diff --git a/.bazelignore b/.bazelignore index 541477a1d..446a903e1 100644 --- a/.bazelignore +++ b/.bazelignore @@ -1,9 +1,7 @@ -examples/library-usage -examples/bd-example-extension-go -npm-package +npm-package/node_modules website node_modules -.claude +.claude/worktrees .worktrees .beads .dolt diff --git a/.bazelrc b/.bazelrc index 9d514ce3e..0ac5774bf 100644 --- a/.bazelrc +++ b/.bazelrc @@ -1,8 +1,27 @@ -# Bazel configuration for beads (side-by-side with the Go toolchain; `go build` -# and `go test` are unaffected). Bzlmod only; Bazel version is pinned in -# .bazelversion. +# Bazel configuration for beads. Bazel is beads' build and test system: CI +# gates on the `bazel test` lanes in .github/workflows/bazel.yml, and +# `make test`/`make check` run the same commands (engdocs/TESTING.md +# "Building and Testing"). Plain `go build`/`go test` still work as an +# inner-loop convenience but are not what CI enforces. Where actions run is +# per machine, never committed here: contributors read the anonymous, +# read-only cache with --config=fork-cache (defined below); maintainers with +# an rbe-west client certificate execute remotely with --config=remote-exec. +# Make either the default with a `build --config=...` line in the gitignored +# .bazelrc.local. Bzlmod only; Bazel version is pinned in .bazelversion. common --enable_bzlmod common --color=no +# C/C++ (and so cgo, -race and the Go stdlib) builds only with MODULE.bazel's +# pinned LLVM toolchain: no host-detected local_config_cc to fall back to, +# which would key actions to the client's gcc and lld and fail remote links +# on workers without lld (scripts/bazel_hermetic_cc_test.go). +common --repo_env=BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1 + +# The pinned remote-worker host in every action key: //platforms:rbe_worker's +# worker-env exec property is the sha256 of tools/rbe/worker-env.txt, and +# rbe-west's schedulers run an action only on a worker that measured that +# host (platforms/BUILD.bazel). Key-affecting, so unconditional: local, +# fork-cache and remote runs hash alike. +build --extra_execution_platforms=//platforms:rbe_worker # ICU policy (engdocs/ICU-POLICY.md): build go-mysql-server with its pure-Go # regex backend so no target links libicu. MODULE.bazel carries the matching @@ -37,7 +56,7 @@ test:prcore --test_env=BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION=1 # Every tag that belongs to another lane (scripts/bazel_policy_test.go # bazelPRCoreExcludedTags). integration-only targets run zero tests outside # --config=integration. -test:prcore --test_tag_filters=-requires-docker,-dolt-server,-dolt-server-proxied,-dolt-server-integration,-dolt-server-cmd,-embedded,-manual,-integration-only +test:prcore --test_tag_filters=-dolt-server,-dolt-server-proxied,-dolt-server-integration,-dolt-server-cmd,-embedded,-manual,-integration-only test:ci --config=prcore test:ci --keep_going --test_summary=terse @@ -50,29 +69,6 @@ test:ci --remote_download_regex=.*/test\.xml$ # bazel.yml publishes the non-race bd as pr.yml's ci-build-artifacts. test:ci --remote_download_regex=.*/bin/cmd/bd/bd_for_tests/bd$ -# Docker lane: only the requires-docker targets (pr.yml's container-backed -# jobs "Test (storage domain + uow)" and "Contract corpus"), on a host with a -# docker daemon. Race like the domain+uow job (//cmd/bd/protocol's variant -# opts out, like the non-race Contract corpus job), but no -short and no -# BEADS_TEST_SKIP=dolt, which would keep the containers from starting. Those -# targets are also tagged no-remote-exec, so they run on the host even with -# --config=remote-exec; their builds may still run remotely. -test.v in -# test.xml, as in test:ci, lets equivalence.py see which tests ran. -test:docker --@rules_go//go/config:race -test:docker --test_tag_filters=requires-docker -test:docker --build_tests_only -test:docker --keep_going -test:docker --test_env=GO_TEST_WRAP_TESTV=1 -# Those jobs pass no -p/-parallel, so go test uses GOMAXPROCS, ubuntu-latest's -# 4 vCPUs, for both. Match that on any host: 4 test processes (hence at most -# 4 dolt containers starting at once) and -test.parallel=4. -test:docker --local_test_jobs=4 -test:docker --test_arg=-test.parallel=4 -# The variants depend on host state no action key sees (the docker daemon, -# the pulled dolt image, the network), so a cached result proves nothing about -# this host: always run them, like the jobs' `go test -count=1`. -test:docker --nocache_test_results - # Embedded-Dolt tier: PR Risk's embedded jobs ("Test (Embedded Dolt Cmd # N/20)", "Test (Embedded Dolt Storage N/5)", "Test (Embedded Dolt # Conformance - core/audit)"), as the `embedded`-tagged variants of bd_test @@ -99,52 +95,64 @@ test:embedded --test_arg=-test.parallel=4 test:embedded --test_env=GO_TEST_WRAP_TESTV=1 test:embedded --remote_download_regex=.*/test\.xml$ # Since D2 step 1 this lane is the tier's only pre-merge run on same-repo PRs -# (pr-risk.yml's legacy jobs stand down), and the legacy jobs ran every test -# every time (-test.count=1). A cached PASS would let a stale or poisoned -# farm action-cache entry, or an unreproduced -race finding, stand in for a -# run: always execute, at farm (not runner) cost. -test:embedded --nocache_test_results +# (pr-risk.yml's legacy jobs stand down). Its results are cached like every +# lane's: an unchanged test reuses its recorded PASS, and nightly re-executes +# everything (--config=fresh below). # No whole-invocation retry on a remote cache eviction ("Lost inputs"): # Bazel would re-run every test, and a test that failed in the first # attempt but passes in the retry would report green, unlike the legacy # jobs, which never retried. Evicted inputs fail the step instead; a # visible "Re-run failed jobs" retries it. test:embedded --experimental_remote_cache_eviction_retries=0 +# The race configuration's nogo validations run once, in bazel.yml's `test` +# lane (`bazel test //... --config=ci`), which is a strict superset of every +# race-group lane's RunNogo/ValidateNogo keys. --norun_validations is a +# build-request option, not a configuration flag: it changes no action key +# (compile, link and nogo actions are shared with `test` through the action +# cache; test results are not, since each lane's test actions carry its own +# test env and args) and discards no analysis; it only skips re-running nogo's +# validation actions that the owner lane already runs on this configuration. +# scripts/nogo_lint_policy_test.go's TestNogoConfigurationsHaveOneValidatingLane +# pins `test` as this configuration's sole validating lane. +test:embedded --norun_validations -# Dolt-server lane: the same jobs as the docker lane ("Test (storage domain + -# uow)" and "Contract corpus"), but every dolt sql-server is a child of the -# test process, started from the pinned dolt in the test wrapper's runfiles -# (BEADS_TEST_DOLT_SERVER=local, set by each dolt-server target), so the -# targets run on remote workers and need no docker. Same selection rules as -# test:docker: race (//cmd/bd/protocol's variant opts out, like its job), no -# -short, no BEADS_TEST_SKIP=dolt, -test.parallel=4, and the no--short twins -# of the job's other packages. Results are cacheable: every input (test -# binary, dolt, env) is in the action key, and a server that cannot start -# fails the target (BEADS_TEST_REQUIRE_DOLT_CONTAINER=1) instead of skipping. -# --config=docker stays as the A/B control. test.xml is downloaded for -# tools/bazel/equivalence.py --job, test.log for bazel.yml's failure artifact. +# Dolt-server lane: what pr.yml's retired container-backed jobs ("Test +# (storage domain + uow)" and "Contract corpus") ran, but every dolt +# sql-server is a child of the test process, started from the pinned dolt in +# the test wrapper's runfiles (BEADS_TEST_DOLT_SERVER=local, set by each +# dolt-server target), so the targets run on remote workers and need no +# docker. As those jobs: race (//cmd/bd/protocol's variant opts out, like its +# job), no -short, no BEADS_TEST_SKIP=dolt, -test.parallel=4, and the +# no--short twins of the job's other packages. Results are cacheable: every +# input (test binary, dolt, env) is in the action key, and a server that +# cannot start fails the target (BEADS_TEST_REQUIRE_DOLT_CONTAINER=1) instead +# of skipping. test.xml is downloaded for tools/bazel/equivalence.py --job, +# test.log for bazel.yml's failure artifact. test:doltserver --@rules_go//go/config:race test:doltserver --test_tag_filters=dolt-server test:doltserver --build_tests_only test:doltserver --keep_going test:doltserver --test_env=GO_TEST_WRAP_TESTV=1 test:doltserver --test_arg=-test.parallel=4 -# Locally (fork PRs, rbe=off, no executor): at most 4 test processes, as in -# test:docker; remote workers are not limited by it. +# Locally (rbe=off, no executor): at most 4 test processes, the jobs' 4-vCPU +# runner shape; remote workers are not limited by it. test:doltserver --local_test_jobs=4 test:doltserver --remote_download_regex=.*/test\.(log|xml)$ +# Race-group nogo is owned by the `test` lane; see test:embedded's comment +# above. +test:doltserver --norun_validations # Proxied-server tier: PR Risk's "Test (Proxied Dolt Cmd N/15)" jobs, as -# //cmd/bd:bd_proxied_test (dolt-server-proxied tag). Kept out of +# //cmd/bd:bd_proxied_test and //cmd/bd:bd_managed_local_test (the +# managed-local lifecycle in a loopback-only network namespace) (the +# dolt-server-proxied tag). Kept out of # --config=doltserver because bazel.yml runs that lane locally too (forks, # rbe=off), where 30 concurrent shards, each with a dolt sql-server busy on # ~4 cores, do not fit regardless of any single shard's wall time; bazel.yml # runs this one only with remote execution, in a job of its own # (bazel-proxied). The build is -# --config=doltserver's: race, like PR Risk's /tmp/bd-cmd-test (main.yml's -# twin job runs build-artifacts' non-race bd-cmd-test, so this is the -# stricter of the two); the subprocess bd is the non-race bd_for_tests, like -# the jobs'. Each shard runs its job's +# --config=doltserver's: race, like PR Risk's /tmp/bd-cmd-test; the +# subprocess bd is the non-race bd_for_tests, like the jobs'. Each shard runs its job's # shard script, whose -test.timeout=15m is past "long": the target is # eternal, which rbe-west caps at 1200s. test:doltserver-proxied --@rules_go//go/config:race @@ -159,15 +167,47 @@ test:doltserver-proxied --test_arg=-test.parallel=4 test:doltserver-proxied --local_test_jobs=4 test:doltserver-proxied --remote_download_regex=.*/test\.(log|xml)$ # Since D2 step 2 this lane is the tier's only pre-merge run on same-repo -# PRs: execute every time, like the jobs' -test.count=1, never replay a -# cached result. -test:doltserver-proxied --nocache_test_results +# PRs. Results are cached like every lane's (nightly: --config=fresh). # No whole-invocation retry on a remote cache eviction ("Lost inputs"): # Bazel would re-run every test, and a test that failed in the first # attempt but passes in the retry would report green, unlike the legacy # jobs, which never retried. Evicted inputs fail the step instead; a # visible "Re-run failed jobs" retries it. test:doltserver-proxied --experimental_remote_cache_eviction_retries=0 +# Race-group nogo is owned by the `test` lane; see test:embedded's comment +# above. +test:doltserver-proxied --norun_validations + +# dolt-server + proxied union (item 5): bazel.yml's bazel-dolt-race job runs +# both tiers in one invocation in mode remote, in place of the bazel-doltserver +# and bazel-proxied lanes, which still run --config=doltserver and +# --config=doltserver-proxied in every other mode. Exactly the union of the two +# member configs' lines, with one tag filter naming both tiers +# (scripts/bazel_dolt_race_test.go). Every other flag is the same in both +# members or outside any action key for the other: the race build, +# -test.parallel=4 and GO_TEST_WRAP_TESTV=1 are common; the eternal timeout +# applies to no dolt-server target; the eviction retry count is what +# doltserver gets from --config=sole-run wherever it executes remotely; +# test_summary, local_test_jobs and remote_download_regex are not in any action +# key. So each member target's test action is unchanged (aquery: all 62 +# TestRunner actions byte-identical), and whichever arm the mode picks shares +# cached results with the other. The member configs stay for those modes, make +# and developers. +test:dolt-race --@rules_go//go/config:race +test:dolt-race --test_tag_filters=dolt-server,dolt-server-proxied +test:dolt-race --build_tests_only +test:dolt-race --keep_going +test:dolt-race --test_summary=terse +test:dolt-race --test_timeout=-1,-1,-1,1200 +test:dolt-race --test_env=GO_TEST_WRAP_TESTV=1 +test:dolt-race --test_arg=-test.parallel=4 +test:dolt-race --local_test_jobs=4 +test:dolt-race --remote_download_regex=.*/test\.(log|xml)$ +test:dolt-race --experimental_remote_cache_eviction_retries=0 +# The union carries its members' --norun_validations line +# (TestBazelDoltRaceConfigIsMemberUnion needs no change: both members and the +# union carry the same line). +test:dolt-race --norun_validations # Server-Dolt storage tier: PR Risk's "Test (Server Dolt Conformance)" and # "Test (Server Dolt Full Suite N/16)" jobs, as @@ -195,10 +235,23 @@ test:doltserver-integration --test_env=GO_TEST_WRAP_TESTV=1 test:doltserver-integration --test_arg=-test.parallel=4 test:doltserver-integration --local_test_jobs=4 test:doltserver-integration --remote_download_regex=.*/test\.(log|xml)$ +# F5 S2 Variant A: this configuration (integration, doltserver-integration, +# doltserver-cmd -- the same fingerprint, race=true plus +# tags=gms_pure_go,integration) has no full-lane owner. Its nogo runs once, +# narrowly, in bazel.yml's bazel-integration job: a `bazel build +# --output_groups=nogo_fix` step over //internal/testutil/integration only +# (the configuration's non-test library; the 56 integration-tagged _test.go +# files this loses vet/lint coverage on are listed in +# tools/nogo/unvalidated_integration_tests.txt, f5-spec.md §3/§5 S2). +# --norun_validations is a build-request option, not a configuration flag: +# it changes no action key and discards no analysis; it only skips +# re-running nogo's validation actions, which bazel-integration's nogo-only +# step already runs for this configuration's library files. +# scripts/nogo_lint_policy_test.go's TestNogoConfigurationsHaveOneValidatingLane +# pins the nogo-only step as this configuration's sole validating lane. +test:doltserver-integration --norun_validations # Since D2 step 2 this lane is the tier's only pre-merge run on same-repo -# PRs: execute every time, like the jobs' -test.count=1, never replay a -# cached result. -test:doltserver-integration --nocache_test_results +# PRs. Results are cached like every lane's (nightly: --config=fresh). # No whole-invocation retry on a remote cache eviction ("Lost inputs"): # Bazel would re-run every test, and a test that failed in the first # attempt but passes in the retry would report green, unlike the legacy @@ -209,8 +262,9 @@ test:doltserver-integration --experimental_remote_cache_eviction_retries=0 # cmd/bd Dolt-server tier: //cmd/bd:bd_dolt_server_test (dolt-server-cmd # tag), the whole integration-tagged cmd/bd suite against a hermetic dolt # sql-server, i.e. the Dolt-gated cmd/bd tests every other lane skips -# (BEADS_TEST_SKIP=dolt in --config=prcore/ci and --config=integration, and -# in main.yml's and nightly.yml's go test jobs). The build flags are exactly +# (BEADS_TEST_SKIP=dolt in --config=prcore/ci and --config=integration), and //tests/regression:regression_test +# (the differential regression suite, formerly regression.yml, against the +# catalog-pinned baseline in @bd_releases). The build flags are exactly # --config=integration's, so it compiles nothing bazel-integration does not # (shared through the remote cache). bazel.yml runs it where it runs the # integration lane (remote, or with the read-only cache in mode cache), in a @@ -226,17 +280,72 @@ test:doltserver-cmd --keep_going test:doltserver-cmd --test_summary=terse test:doltserver-cmd --test_timeout=-1,-1,-1,1200 # As in --config=integration: Go's own timeout fires first and dumps every -# goroutine to test.log, which Bazel's kill at 1200s does not. -test:doltserver-cmd --test_arg=-test.timeout=19m +# goroutine to test.log, which Bazel's kill at 1200s does not. Item 5 A2: the +# -test.timeout=19m arg and the BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION env moved +# onto //cmd/bd:bd_dolt_server_test's and //tests/regression:regression_test's +# own args/env (the rules), so --config=dolt-int below does not need them: +# without the move, server-storage's 15m Go timeout would become 19m under +# the union, and the env would leak into server-storage's targets. The final +# argv and environment Bazel assembles (target args, then -test.timeout=19m, +# then this config's own -test.parallel=4 test_arg; same env map either way) +# are unchanged, so the remote action digest -- what RBE's cache keys on -- +# is unaffected and cached results should carry over. This IS a local +# actionKey change for these two targets' 46 actions: --test_env is part of +# the build configuration's own fingerprint, picked up by every target +# analyzed under that configuration, unlike a target's own env attribute, +# which only the target carries. To be confirmed in practice by the first +# merge group's tests_cached == tests_total in ci-analytics, not claimed here +# as already observed. test:doltserver-cmd --test_arg=-test.parallel=4 -test:doltserver-cmd --test_env=BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION=1 test:doltserver-cmd --test_env=GO_TEST_WRAP_TESTV=1 test:doltserver-cmd --local_test_jobs=4 test:doltserver-cmd --remote_download_regex=.*/test\.(log|xml)$ +# F5 S2 Variant A: same configuration as --config=integration / +# doltserver-integration above; see that block's comment for the owner +# (bazel-integration's nogo-only step over //internal/testutil/integration). +test:doltserver-cmd --norun_validations -# Integration lane: main.yml's "Main Linux integration packages (N/6)" and -# "Main Linux integration cmd/bd (N/8)" jobs (and nightly.yml's Full Test -# Suite, which runs the same `go test` over ./... in one job): every package +# server-storage + cmd-dolt union (item 5 A2): bazel.yml's bazel-dolt-int job +# runs both tiers in one invocation in mode remote, in place of the +# bazel-server-storage and bazel-cmd-dolt jobs, which still run +# --config=doltserver-integration and --config=doltserver-cmd in every other +# mode (fork-ro, fork-rw, cache, local): there one client does both tiers' +# work with no in-flight deduplication, so a union would cost the sum of the +# tiers instead of the max. Exactly the union of the two member configs' +# lines above, with one tag filter naming both members' tags +# (scripts/bazel_dolt_int_test.go). Every other flag is the same in both +# members: the race build, tags=gms_pure_go,integration, keep_going, +# test_summary, the eternal 1200s timeout, GO_TEST_WRAP_TESTV=1, +# -test.parallel=4, local_test_jobs, remote_download_regex and +# norun_validations. So each member target's test action is unchanged in the +# sense that matters for caching (aquery: all 63 TestRunner actions' remote +# action digests are byte-identical, the key RBE's cache lookups use), though +# each action's local actionKey differs since these flags now reach the +# target via its own env/args rather than the member's build configuration. +# Cached results carry over both ways regardless. +# New for cmd-dolt here: --experimental_remote_cache_eviction_retries=0. +# server-storage already has it (above); cmd-dolt did not (it has no +# --config=sole-run of its own, unlike doltserver). Adding it to the union is +# stricter for cmd-dolt (no whole-invocation retry on a remote cache +# eviction) and policy-conformant with sole-run semantics; the eviction +# allowlist in pr_risk_bazel_coverage_test.go records the new line. +build:dolt-int --@rules_go//go/config:tags=gms_pure_go,integration +test:dolt-int --@rules_go//go/config:race +test:dolt-int --test_tag_filters=dolt-server-integration,dolt-server-cmd +test:dolt-int --build_tests_only +test:dolt-int --keep_going +test:dolt-int --test_summary=terse +test:dolt-int --test_timeout=-1,-1,-1,1200 +test:dolt-int --test_env=GO_TEST_WRAP_TESTV=1 +test:dolt-int --test_arg=-test.parallel=4 +test:dolt-int --local_test_jobs=4 +test:dolt-int --remote_download_regex=.*/test\.(log|xml)$ +test:dolt-int --norun_validations +test:dolt-int --experimental_remote_cache_eviction_retries=0 + +# Integration lane: the `go test` main.yml's former "Main Linux integration" +# jobs ran on push (this lane replaced them, and nightly.yml's retired Full +# Test Suite, which ran the same `go test` over ./... in one job): every package # built with -tags=integration,gms_pure_go, race, no -short, no -skip, # BEADS_TEST_SKIP=dolt. The tag is set for the whole build, as `go test -tags` # does, not per target: gazelle generates srcs/deps with integration files @@ -252,7 +361,9 @@ test:integration --test_env=BEADS_TEST_SKIP=dolt # keeps every container- or server-backed test skipped, which is what the # untagged base targets already do. scripts/bazel_policy_test.go derives the # required exclusions from the PR-core list, so a new lane tag lands here too. -test:integration --test_tag_filters=-requires-docker,-dolt-server,-dolt-server-proxied,-dolt-server-integration,-dolt-server-cmd,-embedded,-manual +# pr-core-only targets (the historical-release suites: shell tests against +# the release-shaped bd, which the PR-core lane already runs) stay out too. +test:integration --test_tag_filters=-dolt-server,-dolt-server-proxied,-dolt-server-integration,-dolt-server-cmd,-embedded,-manual,-pr-core-only test:integration --build_tests_only test:integration --keep_going test:integration --test_summary=terse @@ -275,6 +386,13 @@ test:integration --test_env=GO_TEST_WRAP_TESTV=1 # equivalence.py / check_testcases.py right after each lane's own # `bazel test`, before the other lane runs (or give the lanes separate jobs). test:integration --remote_download_regex=.*/test\.xml$ +# F5 S2 Variant A: same configuration as --config=doltserver-integration / +# doltserver-cmd above; see that block's comment for the owner +# (bazel-integration's nogo-only step over //internal/testutil/integration). +# The 56 integration-tagged _test.go files this configuration no longer +# validates in any full lane are the accepted loss, listed in +# tools/nogo/unvalidated_integration_tests.txt. +test:integration --norun_validations # Pure-Go lane: pr.yml's "Check pure-Go and js/wasm boundaries # (CGO_ENABLED=0)" job. CGO is off for every Go target (rules_go drops @@ -300,20 +418,60 @@ build:js-wasm --platforms=@rules_go//go/toolchain:js_wasm build:js-wasm --use_target_platform_for_tests build:js-wasm --remote_download_outputs=toplevel +# nogo (//tools/nogo: go test's vet checks plus the golangci-lint linters +# .golangci.yml enables) runs beside every Go compile, so `bazel build`/ +# `bazel test` fails on a finding -- in bazel.yml's one validating (owner) +# lane per configuration (since F5 S1: a race-group non-owner lane reuses +# its owner's nogo results instead of re-running them; see +# scripts/nogo_lint_policy_test.go's nogoConfigurations table). +# --config=nogo asks for the analysis alone (the nogo_fix output group; +# nothing is linked), in the race configuration bazel.yml's unit lane +# (test:ci) builds, so a local run reuses CI's remote cache. make lint, +# scripts/pr-lint and the pre-commit hook use it. +build:nogo --@rules_go//go/config:race +build:nogo --keep_going +build:nogo --output_groups=nogo_fix +# The same analyzers over the files only other platforms compile +# (//go:build windows, darwin, !linux ...): scripts/pr-lint builds +# //tools/bazel:release_cross, every go_library and go_binary split-transitioned +# to rules_go's non-cgo platforms, for its windows/amd64 and darwin/arm64 +# passes (golangci-lint's former GOOS=windows/darwin legs). bazel.yml's pure +# lane builds the same target for every release platform, which validates +# nogo there too. +build:nogo-cross --keep_going +build:nogo-cross --output_groups=nogo_fix + # D2 step 3: bazel.yml's bazel-test, bazel-pure and bazel-doltserver lanes -# add this in mode remote only, where (on same-repo PRs) they are the only -# pre-merge run of pr.yml's legacy PR Core, pure-Go/js-wasm, domain+uow and -# contract corpus jobs, which ran every test every time (`go test -# -count=1`) and never retried. Like the retired PR Risk tiers' configs: -# always execute (a cached PASS would stand in for a run), and no -# whole-invocation retry after a remote cache eviction ("Lost inputs"), -# whose exit code outranks a test failure, so a test that failed in the -# first attempt and passed in the retry would report green. Local and -# cache runs (forks, Dependabot; their legacy jobs still run) keep cached -# results. -test:sole-run --nocache_test_results +# add this in the remote modes, where (on same-repo PRs and merge groups) +# they are the only pre-merge run of pr.yml's legacy PR Core, +# pure-Go/js-wasm, domain+uow and contract corpus jobs, which never retried. +# Like the retired PR Risk tiers' configs: no whole-invocation retry after +# a remote cache eviction ("Lost inputs"), whose exit code outranks a test +# failure, so a test that failed in the first attempt and passed in the +# retry would report green. test:sole-run --experimental_remote_cache_eviction_retries=0 +# Test result caching. Every lane caches its test results (read and write; +# Bazel's default): a test whose action key (test binary, runfiles, test env, +# platform) is unchanged reuses the PASS the farm recorded for it, on a PR +# (any attempt), a merge group or a push to main, so only what a change +# touched runs. Why that is safe: +# - Identical key, identical test: these targets are hermetic (dolt and +# every input are runfiles). +# - A cached failure is never reused: Bazel treats a failed cached action +# as a miss, so whatever failed re-runs. +# - Only rbe-west's workers write the action cache (clients' writes are +# refused), so a cached PASS is a real remote execution, not a client +# upload. +# - What is given up is re-sampling a nondeterministic (-race, timing) +# test on unchanged inputs. nightly.yml passes fresh-test-results: true, +# so bazel.yml appends this config last to every `bazel test` and the +# whole suite re-executes once a night. +# - No retries: --experimental_remote_cache_eviction_retries=0 (the +# retired tiers' configs and sole-run) and no flaky attempts anywhere. +# Policy: scripts/ci_merge_queue_test.go. +test:fresh --nocache_test_results + # Read-only anonymous cache for fork PRs: rbe-west's rbe-cache endpoint serves # action-cache and CAS reads only (writes and Execute are refused by the farm) # and needs no credentials, so it is committed (scripts/bazel_policy_test.go @@ -344,6 +502,9 @@ build:fork-cache --remote_retries=2 build:fork-cache --experimental_circuit_breaker_strategy=failure # The farm admits 16 connections per source IP. build:fork-cache --remote_max_connections=8 +# No --remote_cache_compression here: setup-bazel's write-bazelrc.sh adds it +# for fork-cache while rbe-cache advertises zstd (cache-zstd-probe.sh), so the +# server decides and rollback needs no change here. # Remote execution against any REAPI-compatible service. Only generic tuning # lives here; the executor endpoint and TLS credentials are never committed. @@ -354,7 +515,7 @@ build:remote-exec --remote_download_minimal build:remote-exec --remote_timeout=600 build:remote-exec --remote_retries=3 # Upload only remotely executed results. A locally executed action (a -# no-remote-exec test, a host-dependent docker-lane result) must not seed the +# no-remote-exec test, whose result depends on the host) must not seed the # shared cache that CI and every other developer read. build:remote-exec --noremote_upload_local_results diff --git a/.bazelversion b/.bazelversion index deeb3d66e..b13d146a7 100644 --- a/.bazelversion +++ b/.bazelversion @@ -1 +1 @@ -9.2.0 +9.3.0 diff --git a/.claude/skills/beads-docs/SKILL.md b/.claude/skills/beads-docs/SKILL.md index 52bab8362..a5454d2ea 100644 --- a/.claude/skills/beads-docs/SKILL.md +++ b/.claude/skills/beads-docs/SKILL.md @@ -201,7 +201,8 @@ document what the pinned release does, never main-only features. See ## 9. Verify before you call it done Run the gates in [references/verification.md](references/verification.md). -The short list: `go test ./test/docsync` (nav↔file sync + link conventions), +The short list: `bazel test //test/docsync:docsync_test --config=ci` +(nav↔file sync + link conventions), `./scripts/generate-cli-docs.sh --check` (generated docs fresh), `./scripts/check-doc-freshness.sh` (Last reviewed markers), and a live preview with `make docs-dev` (or `./mint.sh dev`) at `localhost:3000`. diff --git a/.claude/skills/beads-docs/references/simplification.md b/.claude/skills/beads-docs/references/simplification.md index 5152fd2b5..916834ca5 100644 --- a/.claude/skills/beads-docs/references/simplification.md +++ b/.claude/skills/beads-docs/references/simplification.md @@ -39,8 +39,9 @@ don't measure that work by the word delta. *not* simplifying — it buries the real change in the diff. 4. **Loss-check** (below). 5. **Fact-check** (below). -6. **Gates:** `go test ./test/docsync`, every fence parses, no body H1, no - HTML comments (MDX), preview with `make docs-dev`. +6. **Gates:** `bazel test //test/docsync:docsync_test --config=ci`, every + fence parses, no body H1, no HTML comments (MDX), preview with + `make docs-dev`. 7. **Preview, then commit on approval** — one page or section per batch, so the reviewer can steer before a cut compounds across the section. diff --git a/.claude/skills/beads-docs/references/terminology.md b/.claude/skills/beads-docs/references/terminology.md index 3718007bd..e3f46d5dc 100644 --- a/.claude/skills/beads-docs/references/terminology.md +++ b/.claude/skills/beads-docs/references/terminology.md @@ -8,7 +8,7 @@ the binary still prints, the docs now lie. ## The discipline 1. **Survey first.** Count occurrences in `docs/`, `engdocs/`, `README.md`, - `AGENTS.md`, `AGENT_INSTRUCTIONS.md`, and `*.go`. Read enough to tell + every `AGENTS.md` (root and nested), and `*.go`. Read enough to tell *prose* (the concept) from *literals*. 2. **Rename prose only**, with judgment per occurrence — fix articles and grammar so it reads naturally. diff --git a/.claude/skills/beads-docs/references/verification.md b/.claude/skills/beads-docs/references/verification.md index 762154ce5..44aabca76 100644 --- a/.claude/skills/beads-docs/references/verification.md +++ b/.claude/skills/beads-docs/references/verification.md @@ -8,7 +8,7 @@ Run these before considering docs work complete. Ordered cheapest-first. # 1. Docs sync: docs.json nav <-> file consistency, link conventions # (root-relative extensionless in docs/, exact paths in engdocs/ and # curated root files), orphan detection (only CLI_REFERENCE.md is exempt). -go test ./test/docsync +bazel test //test/docsync:docsync_test --config=ci # 2. Generated CLI docs freshness: regenerates from the live command tree # and diffs docs/CLI_REFERENCE.md, docs/cli-reference/, and the CLI @@ -55,7 +55,7 @@ all of: 1. **Redirect** — add an entry to the `redirects` array in `docs/docs.json` from the old route to the new one. 2. **Rewrite inbound links** — grep the whole repo, not just `docs/`: - README.md, AGENTS.md, AGENT_INSTRUCTIONS.md, engdocs/, examples/, + README.md, every AGENTS.md (root and nested), engdocs/, examples/, npm-package/, plugins/, integrations/, scripts, and Go comments. 3. **Check bd's printed output** — if `bd` prints the old path (grep `cmd/` and `internal/templates/` for it), fix the Go source to print the new diff --git a/.claude/test-strategy.md b/.claude/test-strategy.md deleted file mode 100644 index 3b3709ec5..000000000 --- a/.claude/test-strategy.md +++ /dev/null @@ -1,103 +0,0 @@ -# Test Running Strategy for Claude Code - -## Critical Rules - -1. **ALWAYS use `./scripts/test.sh` instead of `go test` directly** - - It automatically skips broken tests from `.test-skip` - - Uses appropriate timeouts (3m default) - - Consistent with human developers and CI/CD - -2. **Use `-run` to target specific tests when developing features** - ```bash - # Good: When working on feature X - ./scripts/test.sh -run TestFeatureX ./cmd/bd/... - - # Avoid: Running full suite unnecessarily - ./scripts/test.sh ./... - ``` - -3. **Understand the bottleneck: COMPILATION not EXECUTION** - - 180s compilation time vs 3.8s actual test execution (cmd/bd) - - Running subset of tests doesn't save much time (still recompiles) - - But use `-run` anyway to avoid seeing unrelated failures - -## Common Commands - -```bash -# Full test suite (what 'make test' runs) -./scripts/test.sh - -# Test specific package -./scripts/test.sh ./cmd/bd/... -./scripts/test.sh ./internal/storage/embeddeddolt/... - -# Test specific feature -./scripts/test.sh -run TestCreate ./cmd/bd/... -./scripts/test.sh -run TestImport - -# Verbose output (when debugging) -./scripts/test.sh -v -run TestSpecificTest -``` - -## When Tests Fail - -1. **Check if it's a known broken test:** - ```bash - cat .test-skip - ``` - -2. **If it's new, investigate:** - - Read the test failure message - - Run with `-v` for more detail - - Check if recent code changes broke it - -3. **If unfixable now:** - - File GitHub issue with details - - Add to `.test-skip` with issue reference - - Document in commit message - -## Package Size Context - -The `cmd/bd` package is LARGE: -- 41,696 lines of code -- 205 files (82 test files) -- 313 individual tests -- Compilation takes ~180 seconds - -This is why: -- Compilation is slow -- Test script uses 3-minute timeout -- Targeting specific tests is important - -## Environment Variables - -Use these when needed: - -```bash -# Custom timeout -TEST_TIMEOUT=5m ./scripts/test.sh - -# Verbose by default -TEST_VERBOSE=1 ./scripts/test.sh - -# Run pattern -TEST_RUN=TestSomething ./scripts/test.sh -``` - -## Quick Reference - -| Task | Command | -|------|---------| -| Run all tests | `make test` or `./scripts/test.sh` | -| Test one package | `./scripts/test.sh ./cmd/bd/...` | -| Test one function | `./scripts/test.sh -run TestName` | -| Verbose output | `./scripts/test.sh -v` | -| Custom timeout | `./scripts/test.sh -timeout 10m` | -| Skip additional test | `./scripts/test.sh -skip TestFoo` | - -## Remember - -- The test script is in `.gitignore` path: `scripts/test.sh` -- Skip list is in repo root: `.test-skip` -- Full documentation: `engdocs/TESTING.md` -- Current broken tests: See GH issues #355, #356 diff --git a/.githooks/pre-commit b/.githooks/pre-commit index b082d26f7..8e4a17732 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Pre-commit hook: auto-format with gofmt and lint with golangci-lint. +# Pre-commit hook: auto-format with gofmt, then lint and vet with nogo. # Installed via: git config core.hooksPath .githooks # See also: make install (sets hooksPath automatically) @@ -9,24 +9,6 @@ set -euo pipefail # the beads section at the bottom must run for non-Go commits too. staged_go_files=$(git diff --cached --name-only --diff-filter=ACM -- '*.go') if [ -n "$staged_go_files" ]; then - # Build golangci-lint from source so it is never a stale global binary, and - # pin the version to the one CI uses (.github/workflows/{pr,main}.yml). - GOLANGCI_LINT="go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.10.1" - - # Build it with the repo's own Go, the way CI does. In CI, actions/setup-go - # installs the go.mod version and exports GOTOOLCHAIN=local. Locally - # GOTOOLCHAIN defaults to "auto", and for a pkg@version build that honours - # golangci-lint's own toolchain directive instead: it downgrades to - # go1.25.12, which then refuses this repo's newer go directive at config - # load ("the Go language version (go1.25) used to build golangci-lint is - # lower than the targeted Go version") and fails every Go commit. Pinning to - # the go directive reproduces CI's resolution on any host toolchain. - go_toolchain="go$(awk '$1 == "go" { print $2; exit }' go.mod)" - if [ "$go_toolchain" = "go" ]; then - echo >&2 "pre-commit: no go directive in go.mod; cannot pin the lint toolchain" - exit 1 - fi - # Auto-format and re-stage, through the go.mod-pinned gofmt. A bare PATH # gofmt belongs to the host toolchain, and on a host newer than the go # directive it rewrites and re-stages files into a form CI's gofmt rejects @@ -35,13 +17,13 @@ if [ -n "$staged_go_files" ]; then echo "$staged_go_files" | xargs "$gofmt_bin" -w echo "$staged_go_files" | xargs git add - # Lint changed code with auto-fix; block on remaining issues. - # CGO_ENABLED=0 avoids typecheck failures from CGO-only dependencies - # (e.g., dolthub/go-icu-regex) that require system headers not always present. - CGO_ENABLED=0 GOTOOLCHAIN="$go_toolchain" $GOLANGCI_LINT run --new-from-rev=HEAD --fix || exit 1 - - # Re-stage any auto-fixes from the linter - echo "$staged_go_files" | xargs git add + # Lint and vet: nogo (//tools/nogo) over the staged files' Bazel packages, + # the analyzers bazel.yml gates on (go test's vet checks plus the + # golangci-lint linters .golangci.yml enables). Findings fail the commit; + # nogo prints a `patch -p1` command for the ones with suggested fixes. + # Needs bazel (or bazelisk) on PATH; the windows/darwin passes run in CI + # and in `make lint`. + make lint-changed LINT_CHANGED_SCOPE=staged || exit 1 fi # --- BEGIN BEADS INTEGRATION v1.3.0 --- diff --git a/.githooks/pre-push b/.githooks/pre-push index 992d7ece3..4a20fb57d 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -1,8 +1,10 @@ #!/usr/bin/env bash -# Pre-push hook: when pushing a release tag (refs/tags/v*), refuse the push if -# version constants disagree. This stops a release from being tagged/published -# with drifted versions (the failure mode that left main red after the 1.0.5 -# release) before it ever reaches CI. +# Pre-push hook: run the Bazel test suite for branch pushes that change Go or +# Bazel inputs (scripts/pre-push-suite.sh), and when pushing a release tag +# (refs/tags/v*), refuse the push if version constants disagree. The version +# check stops a release from being tagged/published with drifted versions (the +# failure mode that left main red after the 1.0.5 release) before it ever +# reaches CI. # # Installed via: git config core.hooksPath .githooks # See also: make install (sets hooksPath automatically) @@ -55,6 +57,39 @@ if [ "$pushing_version_tag" -eq 1 ]; then fi fi +# The push-time test suite (scripts/pre-push-suite.sh): bazel.yml's test lane, +# `bazel test //... --config=ci`, for branch pushes whose new commits change +# Go or Bazel inputs. A tag push, a deletion, or a docs-only push skips it. +# BD_PREPUSH_SUITE=go runs plain go test instead, under a banner. +# +# The decision keys on the remote ref and the shas, never on the local ref's +# shape: for `git push origin HEAD` and `HEAD:refs/heads/x` git passes the +# literal local ref `HEAD`, which a `refs/heads/*` match would skip (#7351). +zero_sha=0000000000000000000000000000000000000000 +suite_needed=0 +while read -r _local_ref local_sha remote_ref remote_sha; do + case "$remote_ref" in + refs/tags/*) continue ;; + esac + if [ "$local_sha" = "$zero_sha" ] || ! git cat-file -e "$local_sha^{commit}" 2>/dev/null; then + continue + fi + base="$remote_sha" + if [ "$base" = "$zero_sha" ] || ! git cat-file -e "$base^{commit}" 2>/dev/null; then + # A new remote branch: compare against main's merge-base. + base="$(git merge-base "$local_sha" origin/main 2>/dev/null || true)" + fi + if [ -z "$base" ] || git diff --name-only "$base" "$local_sha" -- \ + '*.go' 'go.mod' 'go.sum' '*.bazel' '*.bzl' '.bazelrc' '.bazelversion' 'MODULE.bazel.lock' | grep -q .; then + suite_needed=1 + fi +done <<< "$push_refs" + +if [ "$suite_needed" -eq 1 ]; then + repo_root="$(git rev-parse --show-toplevel)" + "$repo_root/scripts/pre-push-suite.sh" -## What +Closes # - +## What changed -## Why + - +## Evidence it works -## Verification + - +## Checklist + +- [ ] The why is documented: in a linked issue (reproduction or motivation, impact, risk) or in this description. +- [ ] `make test` (the Bazel test lane, nogo lint included) and any other lane `engdocs/TESTING.md` selects pass locally. +- [ ] User-facing behavior changes are reflected in `docs/` or the generated CLI reference. +- [ ] If an invariant or rule changed, the owning `AGENTS.md` is updated. diff --git a/.github/actions/setup-bazel/action.yml b/.github/actions/setup-bazel/action.yml index 92dc96635..497ad56ce 100644 --- a/.github/actions/setup-bazel/action.yml +++ b/.github/actions/setup-bazel/action.yml @@ -8,7 +8,9 @@ description: > BAZEL_REMOTE_EXECUTOR, RBE_TLS_CERT and RBE_TLS_KEY in the step env, that rc enables --config=remote-exec for every bazel command; with none of them the job runs locally; with BAZEL_FORK_CACHE=true (and no secrets) it enables - the read-only fork cache (--config=fork-cache); with BAZEL_FORK_REMOTE=true + the read-only fork cache (--config=fork-cache), and with BAZEL_RRC_READ=true + too (the remote repo contents cache readers) Bazel's remote repo contents + cache through rbe-cache while it answers; with BAZEL_FORK_REMOTE=true (fork and Dependabot PRs, bazel.yml modes fork-ro/fork-rw; needs RBE_FORK_PR and RBE_FORK_TIER) it gets a short-lived certificate from rbe-fork-mint (fork-credential.sh, proving the run with a CSR artifact) and @@ -39,15 +41,18 @@ runs: # unverified repo contents cache is off (write-bazelrc.sh) and the Bazel # binary is not cached, so a poisoned entry (a cache written by an # untrusted run) cannot change what executes. v3: v2 also held Bazelisk's - # download and the contents cache. + # download and the contents cache. v4: MODULE.bazel joins the key because + # the lock does not record non-registry repository rules (llvm_dist), so + # v3 kept restoring the 1.94 GB LLVM .tar.xz after the switch to the + # 149 MB slice. - name: Restore Bazel runner cache id: restore uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/bazel-ci-cache - key: bazel-repo-v3-${{ runner.os }}-${{ hashFiles('.bazelversion', 'MODULE.bazel.lock') }} + key: bazel-repo-v4-${{ runner.os }}-${{ hashFiles('.bazelversion', 'MODULE.bazel', 'MODULE.bazel.lock') }} restore-keys: | - bazel-repo-v3-${{ runner.os }}- + bazel-repo-v4-${{ runner.os }}- - name: Install Bazelisk shell: bash @@ -73,6 +78,8 @@ runs: case "$bazel_version/$arch" in 9.2.0/amd64) bazel_sha=7668a95db1250f12c40407251e4e203b4ec8bf39bc495d2f485b2d8c99048694 ;; 9.2.0/arm64) bazel_sha=049dd21f40ad979db11c3ee68c96a42ce75f1185e69ac61ab20de1501427a410 ;; + 9.3.0/amd64) bazel_sha=d302d22ed77ee5658b87857249baa579db84300ecebe0a1e9a357b5b20f80eb8 ;; + 9.3.0/arm64) bazel_sha=615cc2509819047e4930fe6643c5f01ebd705ccadf75e8f0b85f9b83cc6a6ca0 ;; *) echo "setup-bazel: no pinned sha256 for Bazel '$bazel_version' ($arch); add it from the release's .sha256 file" >&2; exit 1 ;; esac { diff --git a/.github/actions/setup-bazel/cache-rrc-probe.sh b/.github/actions/setup-bazel/cache-rrc-probe.sh new file mode 100644 index 000000000..1dc60a233 --- /dev/null +++ b/.github/actions/setup-bazel/cache-rrc-probe.sh @@ -0,0 +1,151 @@ +#!/usr/bin/env bash +# May this fork-cache lane read Bazel's remote repo contents cache through +# rbe-west's anonymous read-only cache (rbe-cache :8443, .bazelrc's +# fork-cache) right now? Exits 0 only when the kill switch below is on, +# rbe-cache answers a REAPI GetCapabilities for instance oss with gRPC status +# 0 and a ServerCapabilities that has cache_capabilities, and then answers a +# GetActionResult for a key no action has, and a ByteStream Read for a blob +# the CAS does not hold, each with NOT_FOUND (gRPC 5): the whole read chain +# (Caddy, nativelink-anon, the action cache and the CAS) is up. Anything else +# exits nonzero: switched off, an HTTP or gRPC error, a refused connection, +# a timeout, an answer that does not parse, no curl or python3. The caller +# then writes no repo contents cache lines, and never fails on it. The +# verdict carries the GetCapabilities TCP connect time without the DNS +# lookup (about one round trip to rbe-cache), for the lane's step summary. +# +# Why a probe: with the startup flag set and the cache unreachable (closed +# by rbe-west's kill switch, or down), Bazel retries every repository +# against it before fetching it itself (engdocs/design/ +# bazel-remote-repo-contents-cache.md, R6), which costs far more than the +# cache saves. Fork pull_request runs see no repository variables, so the +# opt-out is the committed line below and the server's own answer. +# +# Three gRPC calls over curl's HTTP/2, the first answer decoded by +# python3's standard library: no grpcurl, no new action. Nothing goes to +# stdout (callers write their rc from it); one verdict line goes to stderr. A copy lives in gascity +# (tools/rbe/) and beads (.github/actions/setup-bazel/); keep in sync, except +# the kill switch, which is each repository's own. +# +# Tests only: RBE_CACHE_PROBE_URL (a stand-in server) and +# RBE_CACHE_PROBE_MAX_TIME (seconds). +set -uo pipefail + +# Kill switch: off stops this repository's fork-cache lanes reading the +# remote repo contents cache (they fetch external repositories themselves), +# with a one-line pull request; on lets rbe-cache's answer decide. To stop +# every reader of rbe-cache, set it off in both copies (gascity and beads). +# It reaches a lane when the lane's checkout carries it. +fork_rrc_read=on + +url=${RBE_CACHE_PROBE_URL:-https://rbe-cache.ops.gascity.com:8443} +max_time=${RBE_CACHE_PROBE_MAX_TIME:-5} + +rtt= +no() { + echo "rbe-cache rrc probe: $*${rtt:+ ($rtt)}; this lane fetches external repositories itself" >&2 + exit 1 +} +[ "$fork_rrc_read" = on ] || no "switched off (fork_rrc_read=$fork_rrc_read in $(basename "$0"))" +command -v curl >/dev/null 2>&1 || no "no curl" +command -v python3 >/dev/null 2>&1 || no "no python3" +tmp=$(mktemp -d) || no "no temp dir" +trap 'rm -rf "$tmp"' EXIT + +# call WHAT METHOD REQ: one gRPC call (METHOD: service/method); the answer's +# messages go to $tmp/body, its grpc-status to $st, and the TCP connect time +# without the DNS lookup to $tc. Fails the probe (prefixed with WHAT) on a +# transport error or a non-200 answer. +call() { + local what=$1 out code dns + out=$(curl -sS --http2 --connect-timeout 3 --max-time "$max_time" \ + -H 'content-type: application/grpc' -H 'te: trailers' \ + --data-binary @"$3" -D "$tmp/head" -o "$tmp/body" -w '%{http_code} %{time_namelookup} %{time_connect}' \ + "$url/$2" 2>"$tmp/err") || + no "$what$(tr '\n' ' ' <"$tmp/err")" + read -r code dns tc <<<"$out" + tc=$(awk -v d="$dns" -v c="$tc" 'BEGIN { if (c > d) printf "%.6f", c - d }' 2>/dev/null) || tc= + [ "$code" = 200 ] || no "${what}HTTP $code" + # grpc-status is a trailer; curl writes trailers after the headers. + st=$(tr -d '\r' <"$tmp/head" | sed -n 's/^grpc-status: *//Ip' | tail -1) +} + +# GetCapabilitiesRequest{instance_name: "oss"} (fork-cache's +# --remote_instance_name) as one uncompressed gRPC message. +printf '\000\000\000\000\005\012\003oss' >"$tmp/req" || no "cannot write the request" +call "" build.bazel.remote.execution.v2.Capabilities/GetCapabilities "$tmp/req" +rtt=$(awk -v s="$tc" 'BEGIN { if (s > 0) printf "tcp connect %.1f ms", s * 1000 }' 2>/dev/null) || rtt= +[ "$st" = 0 ] || no "gRPC status ${st:-missing}" + +why=$(python3 -I - "$tmp/body" <<'PY' +import sys + + +def varint(b, i): + v = s = 0 + while True: + if i >= len(b) or s > 63: + raise ValueError("truncated varint") + c = b[i] + i += 1 + v |= (c & 0x7F) << s + s += 7 + if c < 0x80: + return v, i + + +def fields(b): + i = 0 + while i < len(b): + key, i = varint(b, i) + num, wire = key >> 3, key & 7 + if wire == 0: + v, i = varint(b, i) + elif wire == 1: + v, i = b[i:i + 8], i + 8 + elif wire == 2: + n, i = varint(b, i) + v, i = b[i:i + n], i + n + elif wire == 5: + v, i = b[i:i + 4], i + 4 + else: + raise ValueError("wire type %d" % wire) + if i > len(b): + raise ValueError("truncated field %d" % num) + yield num, wire, v + + +try: + body = open(sys.argv[1], "rb").read() + if len(body) < 5 or body[0] != 0: + raise ValueError("not an uncompressed gRPC message") + n = int.from_bytes(body[1:5], "big") + if len(body) != 5 + n: + raise ValueError("gRPC length %d, %d bytes" % (n, len(body) - 5)) + # ServerCapabilities.cache_capabilities + cache = [v for num, wire, v in fields(body[5:]) if num == 1 and wire == 2] +except (OSError, ValueError) as e: + print("unreadable answer (%s)" % e) + sys.exit(2) +if not cache: + print("no cache_capabilities in the answer") + sys.exit(1) +PY +) || no "${why:-python3 failed}" + +# GetActionResultRequest{instance_name: "oss", action_digest: {hash: +# sha256("cache-rrc-probe: no action has this key"), size_bytes: 1}}: a key +# no action has, so the action cache behind rbe-cache must say NOT_FOUND. +key=ad12d7a2f1dec188fc1f2c4f5535a4a65eb630fa2f309eca423695e6ec7abee7 +printf '\000\000\000\000\113\012\003oss\022\104\012\100%s\020\001' "$key" >"$tmp/req" || + no "cannot write the request" +call "GetActionResult: " build.bazel.remote.execution.v2.ActionCache/GetActionResult "$tmp/req" +[ "$st" = 5 ] || no "GetActionResult: gRPC status ${st:-missing}, want 5 (NOT_FOUND)" + +# ReadRequest{resource_name: "oss/blobs//1"}: a blob the CAS +# does not hold (its content would have to hash to that key), so the CAS +# behind rbe-cache must say NOT_FOUND. +printf '\000\000\000\000\116\012\114oss/blobs/%s/1' "$key" >"$tmp/req" || + no "cannot write the request" +call "ByteStream Read: " google.bytestream.ByteStream/Read "$tmp/req" +[ "$st" = 5 ] || no "ByteStream Read: gRPC status ${st:-missing}, want 5 (NOT_FOUND)" +echo "rbe-cache rrc probe: rbe-cache answers GetCapabilities, GetActionResult and ByteStream Read${rtt:+ ($rtt)}; this lane reads the remote repo contents cache" >&2 diff --git a/.github/actions/setup-bazel/cache-zstd-probe.sh b/.github/actions/setup-bazel/cache-zstd-probe.sh new file mode 100644 index 000000000..4e74368eb --- /dev/null +++ b/.github/actions/setup-bazel/cache-zstd-probe.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +# Does rbe-west's anonymous read-only cache (rbe-cache :8443, .bazelrc's +# fork-cache) advertise zstd right now? Exits 0 only when its REAPI +# GetCapabilities answer lists ZSTD in cache_capabilities.supported_compressors, +# the field Bazel checks before it accepts --remote_cache_compression (it +# refuses a remote that does not list it). Anything else exits nonzero: not +# listed, an HTTP or gRPC error, a refused connection, a timeout, an answer +# that does not parse, no curl or python3. The caller then leaves the flag +# off, and never fails on it. +# +# So the server decides, at run time: when rbe-west turns zstd on, fork-cache +# runs use it; when it turns it off (rollback), they stop. No repository +# variable (fork pull_request runs see none) and no revert. +# +# One unary gRPC call over curl's HTTP/2, decoded by python3's standard +# library: no grpcurl, no new action. Nothing goes to stdout (callers write +# their rc from it); one verdict line goes to stderr. A byte copy lives in +# gascity (tools/rbe/) and beads (.github/actions/setup-bazel/); keep in sync. +# +# Tests only: RBE_CACHE_PROBE_URL (a stand-in server) and +# RBE_CACHE_PROBE_MAX_TIME (seconds). +set -uo pipefail +url=${RBE_CACHE_PROBE_URL:-https://rbe-cache.ops.gascity.com:8443} +max_time=${RBE_CACHE_PROBE_MAX_TIME:-5} + +no() { + echo "rbe-cache zstd probe: $*; the fork cache stays identity" >&2 + exit 1 +} +command -v curl >/dev/null 2>&1 || no "no curl" +command -v python3 >/dev/null 2>&1 || no "no python3" +tmp=$(mktemp -d) || no "no temp dir" +trap 'rm -rf "$tmp"' EXIT + +# GetCapabilitiesRequest{instance_name: "oss"} (fork-cache's +# --remote_instance_name) as one uncompressed gRPC message. +printf '\000\000\000\000\005\012\003oss' >"$tmp/req" || no "cannot write the request" +code=$(curl -sS --http2 --connect-timeout 3 --max-time "$max_time" \ + -H 'content-type: application/grpc' -H 'te: trailers' \ + --data-binary @"$tmp/req" -D "$tmp/head" -o "$tmp/body" -w '%{http_code}' \ + "$url/build.bazel.remote.execution.v2.Capabilities/GetCapabilities" 2>"$tmp/err") || + no "$(tr '\n' ' ' <"$tmp/err")" +[ "$code" = 200 ] || no "HTTP $code" +# grpc-status is a trailer; curl writes trailers after the headers. +st=$(tr -d '\r' <"$tmp/head" | sed -n 's/^grpc-status: *//Ip' | tail -1) +[ "$st" = 0 ] || no "gRPC status ${st:-missing}" + +why=$(python3 -I - "$tmp/body" <<'PY' +import sys + +ZSTD = 1 # build.bazel.remote.execution.v2.Compressor.Value.ZSTD + + +def varint(b, i): + v = s = 0 + while True: + if i >= len(b) or s > 63: + raise ValueError("truncated varint") + c = b[i] + i += 1 + v |= (c & 0x7F) << s + s += 7 + if c < 0x80: + return v, i + + +def fields(b): + i = 0 + while i < len(b): + key, i = varint(b, i) + num, wire = key >> 3, key & 7 + if wire == 0: + v, i = varint(b, i) + elif wire == 1: + v, i = b[i:i + 8], i + 8 + elif wire == 2: + n, i = varint(b, i) + v, i = b[i:i + n], i + n + elif wire == 5: + v, i = b[i:i + 4], i + 4 + else: + raise ValueError("wire type %d" % wire) + if i > len(b): + raise ValueError("truncated field %d" % num) + yield num, wire, v + + +try: + body = open(sys.argv[1], "rb").read() + if len(body) < 5 or body[0] != 0: + raise ValueError("not an uncompressed gRPC message") + n = int.from_bytes(body[1:5], "big") + if len(body) != 5 + n: + raise ValueError("gRPC length %d, %d bytes" % (n, len(body) - 5)) + compressors = [] + for num, wire, v in fields(body[5:]): + if num != 1 or wire != 2: # ServerCapabilities.cache_capabilities + continue + for cnum, cwire, cv in fields(v): + if cnum != 6: # CacheCapabilities.supported_compressors + continue + if cwire == 0: + compressors.append(cv) + elif cwire == 2: # packed + j = 0 + while j < len(cv): + x, j = varint(cv, j) + compressors.append(x) +except (OSError, ValueError) as e: + print("unreadable answer (%s)" % e) + sys.exit(2) +if ZSTD in compressors: + print("advertises zstd") + sys.exit(0) +print("zstd not advertised (supported_compressors %s)" % compressors) +sys.exit(1) +PY +) || no "${why:-python3 failed}" +echo "rbe-cache zstd probe: $why; the fork cache uses zstd" >&2 diff --git a/.github/actions/setup-bazel/write-bazelrc.sh b/.github/actions/setup-bazel/write-bazelrc.sh index 2436d976d..15671cd37 100644 --- a/.github/actions/setup-bazel/write-bazelrc.sh +++ b/.github/actions/setup-bazel/write-bazelrc.sh @@ -27,7 +27,18 @@ # # BAZEL_FORK_CACHE=true (bazel.yml mode "cache": rbe=cache dispatches, and # fork/Dependabot runs while rbe-fork is closed) appends --config=fork-cache: -# .bazelrc's credential-free, read-only rbe-west cache. +# .bazelrc's credential-free, read-only rbe-west cache. While that cache +# advertises zstd (cache-zstd-probe.sh asks its GetCapabilities; any failure +# means no) it also asks for zstd transfers (--remote_cache_compression). A +# probe, not a repository variable: fork pull_request runs see no vars. No +# other mode ever asks, because only the anonymous cache can advertise zstd, +# and Bazel refuses a remote that does not. With BAZEL_RRC_READ=true too +# (bazel.yml's remote repo contents cache readers alone: the jobs whose +# configs rrc-lane-commands.txt seeds), and while rbe-cache answers +# (cache-rrc-probe.sh, which also holds the committed kill switch), it reads +# Bazel's remote repo contents cache, as those jobs' trusted readers do: the +# trees rrc-seed wrote on main pushes, through rbe-cache's anonymous AC and +# CAS reads. The job's step summary says whether it reads, and why. # # RBE_FORK_CERT_FILE + RBE_FORK_KEY_FILE + RBE_FORK_ENDPOINT + RBE_FORK_INSTANCE # (bazel.yml modes fork-ro/fork-rw: fork-credential.sh's outputs, a @@ -89,6 +100,7 @@ key="${RBE_TLS_KEY:-}" ca="${RBE_TLS_CA:-}" instance="${RBE_INSTANCE:-}" fork_cache="${BAZEL_FORK_CACHE:-}" +rrc_reader="${BAZEL_RRC_READ:-}" fork_cert="${RBE_FORK_CERT_FILE:-}" fork_key="${RBE_FORK_KEY_FILE:-}" fork_endpoint="${RBE_FORK_ENDPOINT:-}" @@ -111,6 +123,13 @@ case "$fork_cache" in exit 1 ;; esac +case "$rrc_reader" in +"" | true) ;; +*) + echo "setup-bazel: BAZEL_RRC_READ must be \"true\" or empty, got \"$rrc_reader\"" >&2 + exit 1 + ;; +esac rc="$secret_dir/ci.bazelrc" umask 077 @@ -222,7 +241,39 @@ elif [[ "$set_fields" -ne 0 ]]; then echo "setup-bazel: remote execution is partially configured; BAZEL_REMOTE_EXECUTOR, RBE_TLS_CERT and RBE_TLS_KEY must be set together (or none, for local execution)" >&2 exit 1 elif [[ "$fork_cache" == true ]]; then - echo "build --config=fork-cache" >>"$rc" + # The remote repo contents cache, read-only, for the jobs that opt in + # (BAZEL_RRC_READ: only their configs are seeded), while rbe-cache + # answers and the probe's kill switch (fork_rrc_read) is on. With the + # startup flag set and the cache unreachable, every repository first + # fails a lookup (gascity engdocs/design/bazel-remote-repo-contents-cache.md, + # R6), so a closed or down rbe-cache gets no lines, and a notice says + # why. That holds at probe time only: after loading, Bazel fetches the + # files lazily, and losing rbe-cache then fails the command (R4). Both + # lines are key neutral, as for the trusted readers; fork-cache uploads + # nothing, and rbe-cache refuses every write. + rrc_read=false + if [[ "$rrc_reader" != true ]]; then + why="not a remote repo contents cache reader (no BAZEL_RRC_READ)" + elif why=$(bash "$(dirname "${BASH_SOURCE[0]}")/cache-rrc-probe.sh" 2>&1); then + rrc_read=true + echo "$why" + else + echo "::notice title=No remote repo contents cache::$why" + fi + echo "Fork cache remote repo contents cache read: **$([[ "$rrc_read" == true ]] && echo on || echo off)** (${why#rbe-cache rrc probe: })" >>"${GITHUB_STEP_SUMMARY:-/dev/null}" + # zstd for the anonymous cache's transfers while it advertises zstd: + # transport only, so action keys are unchanged. The probes never fail + # this script; they only decide the lines. + { + echo "build --config=fork-cache" + if bash "$(dirname "${BASH_SOURCE[0]}")/cache-zstd-probe.sh"; then + echo "build:fork-cache --remote_cache_compression" + fi + if [[ "$rrc_read" == true ]]; then + echo "startup --experimental_remote_repo_contents_cache" + echo "common --loading_phase_threads=64" + fi + } >>"$rc" cache=true echo "setup-bazel: read-only remote cache (rbe-cache); executing locally" else diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 00a9b016f..7cd6744a5 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,138 +1,15 @@ -# GitHub Copilot Instructions for Beads +# GitHub Copilot instructions for beads -## Project Overview +The canonical contributor instructions for this repository are in +[AGENTS.md](../AGENTS.md); area-specific rules are in the nested `AGENTS.md` +files listed in its routing table. Read those, not this file, for workflow, +build, test, and scope rules. -**beads** (command: `bd`) is a Dolt-powered issue tracker designed for AI-supervised coding workflows. Git integration is optional. We dogfood our own tool for all task tracking. +The rules most often missed in review: -**Key Features:** -- Dependency-aware issue tracking -- Auto-sync via Dolt-native replication -- AI-optimized CLI with JSON output -- Dolt server mode for background operations -- MCP server integration for Claude and other AI assistants - -## Tech Stack - -- **Language**: Go 1.21+ -- **Storage**: Dolt (version-controlled SQL database) -- **CLI Framework**: Cobra -- **Testing**: Go standard testing + table-driven tests -- **CI/CD**: GitHub Actions -- **MCP Server**: Python (integrations/beads-mcp/) - -## Coding Guidelines - -### Testing -- Always write tests for new features -- Use `t.TempDir() in Go tests` to avoid polluting production database -- Run `go test -short ./...` before committing -- Never create test issues in production DB (use temporary DB) - -### Code Style -- Run `make ci-pr-lint` before committing changes to Go or lint-controlled files -- Follow existing patterns in `cmd/bd/` for new commands -- Add `--json` flag to all commands for programmatic use -- Update docs when changing behavior - -### Git Workflow -- Install git hooks: `bd hooks install` -- Use `bd dolt push` / `bd dolt pull` for remote sync -- Before implementing related work, opening a PR, or merging/closing a PR, run: - `scripts/pr-preflight.sh --search "" --repo gastownhall/beads` or - `scripts/pr-preflight.sh --repo gastownhall/beads` -- External contributor PRs have priority: build on them when possible, preserve - tests and attribution, and never close or replace them silently. - -## Issue Tracking with bd - -**CRITICAL**: This project uses **bd** for ALL task tracking. Do NOT create markdown TODO lists. - -### Essential Commands - -```bash -# Find work -bd ready --json # Unblocked issues -bd stale --days 30 --json # Forgotten issues - -# Create and manage (ALWAYS include --description) -bd create "Title" --description="Detailed context" -t bug|feature|task -p 0-4 --json -bd update --claim --json -bd close --reason "Done" --json - -# Search -bd list --status open --priority 1 --json -bd show --json - -# Sync (if remote configured) -bd dolt push # Push to Dolt remote -bd dolt pull # Pull from Dolt remote -``` - -### Workflow - -1. **Check ready work**: `bd ready --json` -2. **Claim task**: `bd update --claim` -3. **Work on it**: Implement, test, document -4. **Discover new work?** `bd create "Found bug" --description="What was found and why" -p 1 --deps discovered-from: --json` -5. **Complete**: `bd close --reason "Done" --json` -6. **Sync**: `bd dolt push` (push to Dolt remote if configured) - -**IMPORTANT**: Always include `--description` when creating issues. Issues without descriptions lack context for future work. - -### Priorities - -- `0` - Critical (security, data loss, broken builds) -- `1` - High (major features, important bugs) -- `2` - Medium (default, nice-to-have) -- `3` - Low (polish, optimization) -- `4` - Backlog (future ideas) - -## Project Structure - -``` -beads/ -├── cmd/bd/ # CLI commands (add new commands here) -├── internal/ -│ ├── types/ # Core data types -│ └── storage/ # Storage layer -│ └── dolt/ # Dolt implementation -├── integrations/ -│ └── beads-mcp/ # MCP server (Python) -├── examples/ # Integration examples -├── docs/ # Documentation -└── .beads/ - └── dolt/ # Dolt database (source of truth) -``` - -## Available Resources - -### MCP Server (Recommended) -Use the beads MCP server for native function calls instead of shell commands: -- Install: `pip install beads-mcp` -- Functions: `mcp__beads__ready()`, `mcp__beads__create()`, etc. -- See `integrations/beads-mcp/README.md` - -### Scripts -- `./scripts/bump-version.sh --commit` - Update all version files atomically -- `./scripts/release.sh ` - Complete release workflow -- `./scripts/update-homebrew.sh ` - Update Homebrew formula - -### Key Documentation -- **AGENTS.md** - Comprehensive AI agent guide (detailed workflows, advanced features) -- **AGENT_INSTRUCTIONS.md** - Development procedures, testing, releases -- **README.md** - User-facing documentation -- **docs/CLI_REFERENCE.md** - Complete command reference - -## Important Rules - -- ✅ Use bd for ALL task tracking -- ✅ Always use `--json` flag for programmatic use -- ✅ Use `bd dolt push` / `bd dolt pull` for remote sync -- ✅ Test with `t.TempDir() in Go tests` -- ❌ Do NOT create markdown TODO lists -- ❌ Do NOT create test issues in production DB -- ❌ Do NOT manually modify `.beads/dolt/` - ---- - -**For detailed workflows and advanced features, see [AGENTS.md](../AGENTS.md)** +- A PR must close a documented GitHub issue (filed before or alongside it). +- Build with `make install`, never `go build -o bd ./cmd/bd` or `go install ./cmd/bd`. +- `make ci-pr-lint` must pass with zero issues; choose tests with + [engdocs/TESTING.md](../engdocs/TESTING.md). +- Never create test issues in a production database; use `t.TempDir()`. +- CLI output uses small Unicode status symbols, never emoji icons. diff --git a/.github/scripts/bazel-gate.sh b/.github/scripts/bazel-gate.sh index 07bed3644..0101669b4 100755 --- a/.github/scripts/bazel-gate.sh +++ b/.github/scripts/bazel-gate.sh @@ -41,7 +41,7 @@ case "${1:-}" in skips=() if [[ "$valid" == true ]]; then case "$mode" in - skip) skips+=(BAZEL BAZEL_TEST BAZEL_PURE BAZEL_EMBEDDED BAZEL_INTEGRATION BAZEL_DOLTSERVER BAZEL_PROXIED BAZEL_SERVER_STORAGE BAZEL_CMD_DOLT) ;; + skip) skips+=(BAZEL BAZEL_TEST BAZEL_PURE BAZEL_RELEASE_CROSS BAZEL_EMBEDDED BAZEL_INTEGRATION BAZEL_DOLTSERVER BAZEL_PROXIED BAZEL_SERVER_STORAGE BAZEL_CMD_DOLT) ;; local) skips+=(BAZEL_EMBEDDED BAZEL_INTEGRATION BAZEL_PROXIED BAZEL_SERVER_STORAGE BAZEL_CMD_DOLT) ;; cache) skips+=(BAZEL_EMBEDDED BAZEL_PROXIED BAZEL_SERVER_STORAGE) ;; esac diff --git a/.github/scripts/ci-capability-selector.sh b/.github/scripts/ci-capability-selector.sh deleted file mode 100755 index ca9624153..000000000 --- a/.github/scripts/ci-capability-selector.sh +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env bash -# Report candidate PR Risk capabilities without changing the current gates. - -set -euo pipefail - -embedded_cli=false -proxied_cli=false -embedded_storage=false -embedded_conformance=false -server_conformance=false -full=false -reason="" -diff_file="" - -cleanup() { - if [[ -n "$diff_file" ]]; then - rm -f "$diff_file" - fi -} -trap cleanup EXIT - -set_full() { - embedded_cli=true - proxied_cli=true - embedded_storage=true - embedded_conformance=true - server_conformance=true - full=true - reason="$1" -} - -emit() { - local lines=( - "embedded_cli=$embedded_cli" - "proxied_cli=$proxied_cli" - "embedded_storage=$embedded_storage" - "embedded_conformance=$embedded_conformance" - "server_conformance=$server_conformance" - "full=$full" - "reason=$reason" - ) - printf '%s\n' "${lines[@]}" - if [[ -n "${GITHUB_OUTPUT:-}" ]]; then - printf '%s\n' "${lines[@]}" >> "$GITHUB_OUTPUT" - fi -} - -event_name="${GITHUB_EVENT_NAME:-}" -base_sha="${PR_BASE_SHA:-}" -head_sha="${PR_HEAD_SHA:-}" -case "$event_name" in - pull_request) ;; - push) set_full "push"; emit; exit 0 ;; - merge_group) set_full "merge_group"; emit; exit 0 ;; - *) set_full "unsupported_event"; emit; exit 0 ;; -esac - -if [[ -z "$base_sha" || -z "$head_sha" ]]; then - set_full "missing_bounds" - emit - exit 0 -fi - -diff_file=$(mktemp) -if ! git diff --no-ext-diff --find-renames --name-status -z "$base_sha" "$head_sha" -- > "$diff_file"; then - set_full "diff_failed" - emit - exit 0 -fi - -saw_path=false -saw_cmd=false -saw_embedded=false -saw_server=false -saw_conformance=false - -while :; do - status="" - if ! IFS= read -r -d '' status <&3; then - if [[ -n "$status" ]]; then - set_full "malformed_record" - fi - break - fi - if [[ "$status" != "A" && "$status" != "M" ]]; then - set_full "unsafe_status" - break - fi - path="" - if ! IFS= read -r -d '' path <&3; then - set_full "malformed_record" - break - fi - saw_path=true - if [[ -z "$path" || "$path" == /* || "/$path/" == *"/../"* || "$path" == . || "$path" == .. || "$path" == ./* ]]; then - set_full "unsafe_path" - break - fi - case "$path" in - .github/workflows/*|.github/scripts/*) - set_full "unsafe_control" - break - ;; - .buildflags|go.mod|go.sum|Makefile|default.nix|flake.nix|flake.lock|overlay.nix|packages.nix) - set_full "build_input" - break - ;; - cmd/bd/*) - embedded_cli=true - proxied_cli=true - saw_cmd=true - ;; - internal/storage/embeddeddolt/*) - embedded_cli=true - embedded_storage=true - embedded_conformance=true - saw_embedded=true - ;; - internal/storage/dolt/*) - proxied_cli=true - server_conformance=true - saw_server=true - ;; - backend/conformance/*|test/conformance/*) - embedded_conformance=true - server_conformance=true - saw_conformance=true - ;; - internal/storage/*|backend/*|schema/*) - set_full "cross_cutting_storage" - break - ;; - docs/*.md|docs/*.mdx|docs/*.png|docs/*.jpg|docs/*.jpeg|docs/*.gif|docs/*.svg|docs/*.webp|docs/*.avif|engdocs/*.md|engdocs/*.mdx|engdocs/*.png|engdocs/*.jpg|engdocs/*.jpeg|engdocs/*.gif|engdocs/*.svg|engdocs/*.webp|engdocs/*.avif|README.md|CHANGELOG.md|ARTICLES.md|BENCHMARKS.md|NEWSLETTER.md) - ;; - *) - set_full "unowned_path" - break - ;; - esac -done 3< "$diff_file" - -if [[ "$full" != true ]]; then - if [[ "$embedded_cli" == true && "$proxied_cli" == true && "$embedded_storage" == true && "$embedded_conformance" == true && "$server_conformance" == true ]]; then - full=true - reason="full" - elif [[ "$saw_path" != true ]]; then - reason="empty_diff" - elif [[ "$saw_cmd" == true && "$saw_embedded" != true && "$saw_server" != true && "$saw_conformance" != true ]]; then - reason="cmd_bd" - elif [[ "$saw_embedded" == true && "$saw_cmd" != true && "$saw_server" != true && "$saw_conformance" != true ]]; then - reason="embedded_storage" - elif [[ "$saw_server" == true && "$saw_cmd" != true && "$saw_embedded" != true && "$saw_conformance" != true ]]; then - reason="server_storage" - elif [[ "$saw_conformance" == true && "$saw_cmd" != true && "$saw_embedded" != true && "$saw_server" != true ]]; then - reason="shared_conformance" - elif [[ "$saw_cmd" == false && "$saw_embedded" == false && "$saw_server" == false && "$saw_conformance" == false ]]; then - reason="docs_only" - else - reason="mixed" - fi -fi - -emit diff --git a/.github/scripts/ci-embedded-tier.sh b/.github/scripts/ci-embedded-tier.sh deleted file mode 100755 index 62c943059..000000000 --- a/.github/scripts/ci-embedded-tier.sh +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env bash -# Decide whether CI should run the full embedded Dolt build/storage/cmd matrix. - -set -euo pipefail - -event_name="${GITHUB_EVENT_NAME:-}" -base_sha="${PR_BASE_SHA:-}" -head_sha="${PR_HEAD_SHA:-}" - -full_embedded=false -reason="" -changed_files="" - -write_outputs() { - if [ -n "${GITHUB_OUTPUT:-}" ]; then - { - echo "full_embedded=$full_embedded" - echo "reason=$reason" - } >> "$GITHUB_OUTPUT" - fi -} - -case "$event_name" in - push) - full_embedded=true - reason="push to main runs full embedded Dolt coverage" - write_outputs - echo "$reason" - exit 0 - ;; - merge_group) - full_embedded=true - reason="merge queue runs full embedded Dolt coverage" - write_outputs - echo "$reason" - exit 0 - ;; -esac - -if [ "$event_name" != "pull_request" ]; then - full_embedded=true - reason="non-PR event runs full embedded Dolt coverage" - write_outputs - echo "$reason" - exit 0 -fi - -if [ -z "$base_sha" ] || [ -z "$head_sha" ]; then - full_embedded=true - reason="PR diff bounds unavailable; defaulting to full embedded Dolt coverage" - write_outputs - echo "$reason" - exit 0 -fi - -if ! changed_files="$(git diff --name-only "$base_sha" "$head_sha")"; then - full_embedded=true - reason="PR diff failed; defaulting to full embedded Dolt coverage" - write_outputs - echo "$reason" - exit 0 -fi - -if [ -z "$changed_files" ]; then - reason="no changed files detected; skipping embedded Dolt matrix" - write_outputs - echo "$reason" - exit 0 -fi - -while IFS= read -r path; do - case "$path" in - cmd/*|internal/*|tests/*|scripts/*|.github/scripts/*|.github/workflows/*) - full_embedded=true - reason="changed $path" - break - ;; - *.go|go.mod|go.sum|Makefile|default.nix|flake.nix|flake.lock|packages.nix) - full_embedded=true - reason="changed $path" - break - ;; - AGENTS.md|AGENT_INSTRUCTIONS.md|CONTRIBUTING.md|RELEASING.md) - full_embedded=true - reason="changed $path" - break - ;; - esac -done <<< "$changed_files" - -if [ "$full_embedded" = true ]; then - reason="risk path detected: $reason; running full embedded Dolt coverage" -else - reason="docs/metadata-only PR; skipping embedded Dolt storage/cmd matrix" -fi - -write_outputs - -echo "$reason" -echo "Changed files:" -while IFS= read -r path; do - printf ' %s\n' "$path" -done <<< "$changed_files" diff --git a/.github/scripts/embedded-cmd-test-shards.txt b/.github/scripts/embedded-cmd-test-shards.txt index c3bfa552f..21e6f181d 100644 --- a/.github/scripts/embedded-cmd-test-shards.txt +++ b/.github/scripts/embedded-cmd-test-shards.txt @@ -1,199 +1,17 @@ -# Embedded cmd test shard manifest. -# -# Format: -# -# There is no committed recent duration artifact for these tests. This manifest -# pins a conservative even split for the 20-shard CI matrix while -# embedded-test-shard.sh continues to hash-distribute newly-added tests that are -# not listed here. -20 1 TestEmbeddedBackup -20 2 TestEmbeddedBackupConcurrent -20 3 TestEmbeddedBlocked -20 4 TestEmbeddedBlockedConcurrent -20 5 TestEmbeddedBootstrap -20 6 TestEmbeddedBootstrapConcurrent -20 7 TestEmbeddedBranch -20 8 TestEmbeddedBranchConcurrent -20 9 TestEmbeddedChildren -20 10 TestEmbeddedChildrenConcurrent -20 11 TestEmbeddedCloseBasic -20 11 TestEmbeddedCloseGuardsAndEpics -20 11 TestEmbeddedCloseAlreadyClosed -20 12 TestEmbeddedCloseConcurrent -20 13 TestEmbeddedComments -20 14 TestEmbeddedCommentsCLI -20 15 TestEmbeddedCommentsCLIConcurrent -20 16 TestEmbeddedCompact -20 17 TestEmbeddedCompactConcurrent -20 18 TestEmbeddedConfig -20 19 TestEmbeddedConfigConcurrent -20 20 TestEmbeddedConfigNoWorkspaceStoreFreeCommands -20 1 TestEmbeddedConfigValidateJSONNoWorkspaceWritesStdout -20 2 TestEmbeddedContext -20 3 TestEmbeddedContextConcurrent -20 4 TestEmbeddedContributorCreate -20 5 TestEmbeddedCount -20 6 TestEmbeddedCountConcurrent -20 7 TestEmbeddedCreateScalarAndRelationships -20 7 TestEmbeddedCreateGraphAndBulk -20 8 TestEmbeddedCreateCommitPending -20 9 TestEmbeddedCreateConcurrent -20 10 TestEmbeddedCreateCrossRepo -20 11 TestEmbeddedCreateCrossRepoUninit -20 12 TestEmbeddedCreateCrossRepoWithParent -20 13 TestEmbeddedCreateWithGitRemote -20 14 TestEmbeddedDefer -20 15 TestEmbeddedDeferConcurrent -20 16 TestEmbeddedDelete -20 17 TestEmbeddedDepA -20 17 TestEmbeddedDepB -20 18 TestEmbeddedDepConcurrent -20 19 TestEmbeddedDiff -20 20 TestEmbeddedDiffConcurrent -20 1 TestEmbeddedDoltBlockedAndCommit -20 1 TestEmbeddedDoltRemoteAndPush -20 2 TestEmbeddedDoltConcurrent -20 3 TestEmbeddedDuplicate -20 4 TestEmbeddedDuplicateConcurrent -20 5 TestEmbeddedDuplicates -20 6 TestEmbeddedDuplicatesConcurrent -20 7 TestEmbeddedEpicStatus -20 7 TestEmbeddedEpicCloseEligible -20 7 TestEmbeddedEpicCloseEligibleReasonFlag -20 7 TestEmbeddedEpicCloseEligibleReasonOutput -20 8 TestEmbeddedEpicConcurrent -20 9 TestEmbeddedExportFormats -20 9 TestEmbeddedExportFlags -20 10 TestEmbeddedExportConcurrent -20 11 TestEmbeddedFederationPeers -20 11 TestEmbeddedFederationStatus -20 12 TestEmbeddedFederationConcurrent -20 13 TestEmbeddedFindDuplicates -20 14 TestEmbeddedFindDuplicatesConcurrent -20 15 TestEmbeddedFlatten -20 16 TestEmbeddedFlattenConcurrent -20 17 TestEmbeddedGC -20 18 TestEmbeddedGCConcurrent -20 19 TestEmbeddedGate -20 20 TestEmbeddedGateConcurrent -20 1 TestEmbeddedGateCreate -20 2 TestEmbeddedGetDependencies -20 3 TestEmbeddedGraph -20 4 TestEmbeddedGraphConcurrent -20 5 TestEmbeddedHistory -20 6 TestEmbeddedHistoryConcurrent -20 7 TestEmbeddedHooks -20 8 TestEmbeddedHooksConcurrent -20 9 TestEmbeddedHuman -20 10 TestEmbeddedHumanConcurrent -20 11 TestEmbeddedImportFromSources -20 11 TestEmbeddedImportUpsertAndPrefixSync -20 12 TestEmbeddedImportConcurrent -20 13 TestEmbeddedInfo -20 14 TestEmbeddedInfoConcurrent -20 15 TestEmbeddedInitA -20 15 TestEmbeddedInitB -20 15 TestEmbeddedInitC -20 16 TestEmbeddedInitConcurrent -20 17 TestEmbeddedKV -20 18 TestEmbeddedKVConcurrent -20 19 TestEmbeddedLabelAddRemove -20 19 TestEmbeddedLabelEditReports -20 19 TestEmbeddedLabelPropagateRename -20 20 TestEmbeddedLabelConcurrent -20 1 TestEmbeddedLint -20 2 TestEmbeddedLintConcurrent -20 3 TestEmbeddedListFiltering -20 3 TestEmbeddedListSearchAndOutput -20 4 TestEmbeddedListConcurrent -20 13 TestEmbeddedMaxRowsListBasic -20 13 TestEmbeddedMaxRowsListLimitInteraction -20 11 TestEmbeddedMaxRowsDepTreeAndDuplicates -20 12 TestEmbeddedMaxRowsDoctorAndConfig -20 14 TestEmbeddedMaxRowsGraph -20 15 TestEmbeddedMaxRowsReady -20 16 TestEmbeddedMaxRowsReadyMerge -20 5 TestEmbeddedMemory -20 6 TestEmbeddedMemoryConcurrent -20 7 TestEmbeddedMigrate -20 8 TestEmbeddedMigrateConcurrent -20 9 TestEmbeddedOnboard -20 10 TestEmbeddedOnboardConcurrent -20 11 TestEmbeddedOrphans -20 12 TestEmbeddedOrphansConcurrent -20 13 TestEmbeddedPrime -20 14 TestEmbeddedPrimeConcurrent -20 15 TestEmbeddedPromote -20 16 TestEmbeddedPromoteCLI -20 17 TestEmbeddedPromoteCLIConcurrent -20 18 TestEmbeddedPruneSafetyAndScope -20 18 TestEmbeddedPruneDryRunAndFilters -20 19 TestEmbeddedPurgeBasics -20 19 TestEmbeddedPurgeFiltered -20 20 TestEmbeddedPurgeConcurrent -20 1 TestEmbeddedQuery -20 2 TestEmbeddedQueryConcurrent -20 3 TestEmbeddedQuick -20 4 TestEmbeddedQuickConcurrent -20 5 TestEmbeddedQuickstart -20 6 TestEmbeddedQuickstartConcurrent -20 7 TestEmbeddedReady -20 8 TestEmbeddedReadyConcurrent -20 9 TestEmbeddedRenamePrefixBasic -20 9 TestEmbeddedRenamePrefixEdgeCases -20 10 TestEmbeddedRenamePrefixConcurrent -20 11 TestEmbeddedReopen -20 12 TestEmbeddedReopenConcurrent -20 13 TestEmbeddedRestore -20 14 TestEmbeddedRestoreConcurrent -20 15 TestEmbeddedSearch -20 16 TestEmbeddedSearchConcurrent -20 17 TestEmbeddedSetup -20 18 TestEmbeddedSetupConcurrent -20 19 TestEmbeddedShip -20 20 TestEmbeddedShipConcurrent -20 1 TestEmbeddedShowBasicsAndJSON -20 1 TestEmbeddedShowDetailAndCurrent -20 2 TestEmbeddedShowConcurrent -20 3 TestEmbeddedStale -20 4 TestEmbeddedStaleConcurrent -20 5 TestEmbeddedState -20 6 TestEmbeddedStateConcurrent -20 7 TestEmbeddedStatus -20 8 TestEmbeddedStatusConcurrent -20 9 TestEmbeddedSupersede -20 10 TestEmbeddedSupersedeConcurrent -20 11 TestEmbeddedSwarm -20 12 TestEmbeddedSwarmConcurrent -20 13 TestEmbeddedTodo -20 14 TestEmbeddedTodoConcurrent -20 15 TestEmbeddedTypes -20 16 TestEmbeddedTypesConcurrent -20 17 TestEmbeddedUndefer -20 18 TestEmbeddedUndeferConcurrent -20 19 TestEmbeddedUpdateFields -20 19 TestEmbeddedUpdateLifecycle -20 20 TestEmbeddedUpdateConcurrent -20 1 TestEmbeddedVCStatusAndCommit -20 1 TestEmbeddedVCCommitVariantsAndMerge -20 2 TestEmbeddedVCConcurrent -20 3 TestEmbeddedVersion -20 4 TestEmbeddedVersionConcurrent -20 5 TestEmbeddedWhere -20 6 TestEmbeddedWhereConcurrent - # Embedded-Dolt cmd/bd test shard manifest. # # Format: # -# 50-shard split for the Bazel-only embedded-Dolt cmd tier +# 100-shard split for the Bazel-only embedded-Dolt cmd tier # (bazel-embedded in .github/workflows/bazel.yml), bin-packed -# longest-processing-time-first by measured wall-time from +# longest-first by measured wall-time from # scripts/ci/embedded_cmd_test_durations.json (see that file for provenance -# and its "relative weight, not absolute SLA" caveat). -# Regenerate with scripts/ci/gen_embedded_cmd_shard_manifest.py 50 +# and its "relative weight, not absolute SLA" caveat) onto the shard +# whose estimated wall time grows least: serial tests (no top-level +# t.Parallel) add up, parallel ones share -test.parallel=4. +# Regenerate with scripts/ci/gen_embedded_cmd_shard_manifest.py 100 # --weights=duration --write after adding, splitting or removing -# TestEmbedded* functions in cmd/bd/*_embedded_test.go. --write is +# TestEmbedded* functions in cmd/bd/*_test.go. --write is # incremental: it keeps every already-assigned test on its current shard # and only places newly-discovered names, onto whichever shard is # currently lightest, so two unrelated PRs that each add one test do not @@ -206,294 +24,522 @@ # This file is generated: notes added here are erased by the next # regeneration. Add them to the generator or the durations file instead. -50 1 TestEmbeddedCommentsCLI -50 1 TestEmbeddedDepAddWispSource -50 1 TestEmbeddedListFiltering -50 1 TestEmbeddedPrimeChangeDirDefaultTemplateMatchesTarget +100 1 TestEmbeddedUpdateConcurrent -50 2 TestEmbeddedCreateRepoFromNonBeadsCwd -50 2 TestEmbeddedDeleteJSONDependencyErrorContract -50 2 TestEmbeddedDepBulkNoCycleCheckKeepsWholeGraphGate -50 2 TestEmbeddedHistoryConcurrent -50 2 TestEmbeddedInitA +100 2 TestEmbeddedShowConcurrent -50 3 TestEmbeddedAdminCompactTier2Honesty -50 3 TestEmbeddedMaxRowsListLimitInteraction -50 3 TestEmbeddedOrphans -50 3 TestEmbeddedShowUnresolvableDeps -50 3 TestEmbeddedStale +100 3 TestEmbeddedCloseConcurrent -50 4 TestEmbeddedBootstrapConcurrent -50 4 TestEmbeddedDuplicatesConcurrent -50 4 TestEmbeddedInfo -50 4 TestEmbeddedMaxRowsDoctorAndConfig -50 4 TestEmbeddedRoutedSiblingWritesCommitTargetHead +100 4 TestEmbeddedEpicConcurrent -50 5 TestEmbeddedCreateScalarAndRelationships -50 5 TestEmbeddedDefer -50 5 TestEmbeddedDoltBlockedAndCommit -50 5 TestEmbeddedGCConcurrent -50 5 TestEmbeddedPromote +100 5 TestEmbeddedConfigConcurrent -50 6 TestEmbeddedCreateStorageClassConflicts -50 6 TestEmbeddedGC -50 6 TestEmbeddedGetDependencies -50 6 TestEmbeddedQuickConcurrent +100 6 TestEmbeddedListFilteringBasicAndLabels -50 7 TestEmbeddedCreateCrossRepoDryRunWithParent -50 7 TestEmbeddedEpicStatus -50 7 TestEmbeddedGate -50 7 TestEmbeddedWhere +100 7 TestEmbeddedDepConcurrent -50 8 TestEmbeddedChangeDirOverridesInheritedBeadsDir -50 8 TestEmbeddedMemoryConcurrent -50 8 TestEmbeddedUpdateConcurrent -50 8 TestEmbeddedVCConcurrent +100 8 TestEmbeddedMaxRowsListLimitInteraction -50 9 TestEmbeddedCloseAlreadyClosed -50 9 TestEmbeddedConfigConcurrent -50 9 TestEmbeddedExternalCapabilityReadyAfterShip -50 9 TestEmbeddedPrimeConcurrent +100 9 TestEmbeddedChildrenConcurrent -50 10 TestEmbeddedDepB -50 10 TestEmbeddedHuman -50 10 TestEmbeddedInitExplicitBeadsDirIsAuthoritative -50 10 TestEmbeddedPromoteCLI +100 10 TestEmbeddedCreateScalarAndRelationships -50 11 TestEmbeddedBlockedConcurrent -50 11 TestEmbeddedDepA -50 11 TestEmbeddedMaxRowsDepTreeAndDuplicates -50 11 TestEmbeddedState +100 11 TestEmbeddedKVConcurrent -50 12 TestEmbeddedDirectCommitPathsBatchAutoCommitDoesNotAdvanceHead -50 12 TestEmbeddedPrimeChangeDirPrimesTarget -50 12 TestEmbeddedPromoteCLIConcurrent -50 12 TestEmbeddedSearchConcurrent -50 12 TestEmbeddedTypes +100 12 TestEmbeddedGatedRendering -50 13 TestEmbeddedAutoImportJSONLNoExplicitCommit -50 13 TestEmbeddedDiff -50 13 TestEmbeddedDuplicates -50 13 TestEmbeddedShipConcurrent +100 13 TestEmbeddedListFilteringStatusAndHierarchy -50 14 TestEmbeddedInitConcurrent -50 14 TestEmbeddedOrphansConcurrent -50 14 TestEmbeddedPrimeChangeDirRedirectNoticeFollowsTarget -50 14 TestEmbeddedRoutedMutatingSiblingDeleteClose -50 14 TestEmbeddedSwarm +100 14 TestEmbeddedReopenConcurrent -50 15 TestEmbeddedChildrenConcurrent -50 15 TestEmbeddedConfigValidateJSONNoWorkspaceWritesStdout -50 15 TestEmbeddedCreateDryRunCrossRepoDoesNotMigrateTarget -50 15 TestEmbeddedEpicCloseEligibleReasonFlag -50 15 TestEmbeddedExplicitHierarchicalParentEdges -50 15 TestEmbeddedVersionConcurrent +100 15 TestEmbeddedPurgeWispsPlaneRetention -50 16 TestEmbeddedBlockedLabelFilters -50 16 TestEmbeddedKV -50 16 TestEmbeddedMaxRowsReady -50 16 TestEmbeddedOpen_EmptyDatabaseRejected -50 16 TestEmbeddedRestoreConcurrent -50 16 TestEmbeddedVCCommitVariantsAndMerge -50 16 TestEmbeddedVersion +100 16 TestEmbeddedMemoryConcurrent -50 17 TestEmbeddedCloseGuardsAndEpics -50 17 TestEmbeddedCompact -50 17 TestEmbeddedGateConcurrent -50 17 TestEmbeddedListComments +100 17 TestEmbeddedReopen -50 18 TestEmbeddedContext -50 18 TestEmbeddedContributorCreate -50 18 TestEmbeddedImportClosedChildWhoseParentWasDeleted -50 18 TestEmbeddedReopen -50 18 TestEmbeddedStateConcurrent +100 18 TestEmbeddedLabelPropagateRename +100 18 TestEmbeddedPrune_protectsBeadCitedByCustomStatusBead -50 19 TestEmbeddedAdminBlocked -50 19 TestEmbeddedCreateRepoRelativeExistingWorkspaceUnaffected -50 19 TestEmbeddedDoltConcurrent -50 19 TestEmbeddedMaxRowsListBasic -50 19 TestEmbeddedPruneSafetyAndScope +100 19 TestEmbeddedLabelConcurrent +100 19 TestEmbeddedNewDoltStore_StrictReadOnlyRefusesWritesOnFreshDatabase -50 20 TestEmbeddedCreateStorageClassBatchAndMisc -50 20 TestEmbeddedDepListSingleIDWarnsOnDroppedExternalEdge -50 20 TestEmbeddedKVConcurrent -50 20 TestEmbeddedSetup +100 20 TestEmbeddedInitRoleRoutingRetainedFork +100 20 TestEmbeddedMigrateSchema_IdentityMismatchRefusesBeforeApplying -50 21 TestEmbeddedBackup -50 21 TestEmbeddedCreateCrossRepoUninit -50 21 TestEmbeddedDiffConcurrent -50 21 TestEmbeddedQuick -50 21 TestEmbeddedQuickstart +100 21 TestEmbeddedMaxRowsReady +100 21 TestEmbeddedMigratePersonal_movesIssues -50 22 TestEmbeddedAdminCompactReadOnlyAllowed -50 22 TestEmbeddedCreateRepoProxiedTargetError -50 22 TestEmbeddedDuplicateConcurrent -50 22 TestEmbeddedFlatten -50 22 TestEmbeddedTypesAgreeWithCreate +100 22 TestEmbeddedCount +100 22 TestEmbeddedIfRevisionCloseReplaysMoleculeAutoClose -50 23 TestEmbeddedExportConcurrent -50 23 TestEmbeddedHistory -50 23 TestEmbeddedMaxRowsGraph -50 23 TestEmbeddedSetupConcurrent -50 23 TestEmbeddedShip +100 23 TestEmbeddedCountConcurrent +100 23 TestEmbeddedExportExcludeOwner_flag -50 24 TestEmbeddedCloseBasic -50 24 TestEmbeddedImportUpsertAndPrefixSync -50 24 TestEmbeddedQuery -50 24 TestEmbeddedUpdateRoutedStoreCommitsTargetHead +100 24 TestEmbeddedEventsTailFollowReportsTruncationOnTheStream +100 24 TestEmbeddedUndeferConcurrent +100 24 TestEmbeddedWispGCProtectsActiveWisps -50 25 TestEmbeddedBackupConcurrent -50 25 TestEmbeddedCreateStorageClassBasic -50 25 TestEmbeddedFindDuplicatesConcurrent -50 25 TestEmbeddedInitGitBootstrapRouting -50 25 TestEmbeddedInitHooksRouting +100 25 TestEmbeddedDoltRemoteAdd_LocalOnly_FiresBeforeGuard +100 25 TestEmbeddedMaxRowsListBasic +100 25 TestEmbeddedRemovedBackendHealRejectionPerBackend -50 26 TestEmbeddedCreateCommitPending -50 26 TestEmbeddedInitC -50 26 TestEmbeddedRenamePrefixBasic -50 26 TestEmbeddedRoutedMutatingSiblingAssignTagDep -50 26 TestEmbeddedSupersedeConcurrent +100 26 TestEmbeddedDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr +100 26 TestEmbeddedExternalMutationPolicy +100 26 TestEmbeddedPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace -50 27 TestEmbeddedComments -50 27 TestEmbeddedMaxRowsReadyMerge -50 27 TestEmbeddedPrime -50 27 TestEmbeddedPruneDryRunAndFilters -50 27 TestEmbeddedReopenConcurrent +100 27 TestEmbeddedDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy +100 27 TestEmbeddedNewDoltStoreFromConfig_DottedDBName +100 27 TestEmbeddedShipConcurrent -50 28 TestEmbeddedConfigNoWorkspaceStoreFreeCommands -50 28 TestEmbeddedEpicCloseEligibleReasonOutput -50 28 TestEmbeddedMigrate -50 28 TestEmbeddedStatus -50 28 TestEmbeddedSwarmConcurrent +100 28 TestEmbeddedDoltLocalOnly_RemoteAdd_RefusesExitOne +100 28 TestEmbeddedHistoryConcurrent +100 28 TestEmbeddedImportChunkedRealStoreResumeConverges -50 29 TestEmbeddedClaimPools -50 29 TestEmbeddedCreateGraphAndBulk -50 29 TestEmbeddedCreateJSONEchoesSubSecondTimestamps -50 29 TestEmbeddedHumanConcurrent -50 29 TestEmbeddedInitSelectedExcludeRouting +100 29 TestEmbeddedDoltLocalOnly_RemoteAdd_ErrorOnStderr +100 29 TestEmbeddedEpicCloseEligibleReasonFlag +100 29 TestEmbeddedImportChunkedNoReadyWindowWithReadinessEdgeIntoCycle -50 30 TestEmbeddedAutoImportFallback_ConflictSkip_EmptyDBImportsAll -50 30 TestEmbeddedDepConcurrent -50 30 TestEmbeddedExportFormats -50 30 TestEmbeddedReadyClaimConcurrent -50 30 TestEmbeddedStaleConcurrent +100 30 TestEmbeddedCloseGuardsAndEpics +100 30 TestEmbeddedDoltLocalOnly_Push_ExitsZeroWithMessage +100 30 TestEmbeddedImportChunkedCrossBucketBlocksEdgesResumeBackfills -50 31 TestEmbeddedAutoImportFallback_ConflictSkip_DoesNotClobber -50 31 TestEmbeddedAutoImportJSONLConcurrentWriter -50 31 TestEmbeddedDeferAutoWake -50 31 TestEmbeddedExternalMutationPolicy -50 31 TestEmbeddedShowConcurrent +100 31 TestEmbeddedDoltLocalOnly_ConfigRoundTrip +100 31 TestEmbeddedIfRevisionCloseWarnsOnForcedOpenChildren +100 31 TestEmbeddedInitSelectedExcludeRoutingForkInvalidQuiet -50 32 TestEmbeddedCreateCrossRepo -50 32 TestEmbeddedDuplicate -50 32 TestEmbeddedInitArtifactRouting -50 32 TestEmbeddedShowBasicsAndJSON -50 32 TestEmbeddedUpdateLifecycle +100 32 TestEmbeddedDoctorUnsupportedJSON +100 32 TestEmbeddedIfRevisionAdvertisedOnFourVerbs +100 32 TestEmbeddedListSearchAndOutputFormats -50 33 TestEmbeddedCreateConcurrent -50 33 TestEmbeddedCreateRepoRelativeUninitRefused -50 33 TestEmbeddedEpicCloseEligible -50 33 TestEmbeddedSearch -50 33 TestEmbeddedTodo +100 33 TestEmbeddedBootstrapJSONLAndGitOrigin +100 33 TestEmbeddedDeleteJournalsTheRequestingActor +100 33 TestEmbeddedExportExcludeOwner_verbose -50 34 TestEmbeddedCreateDryRunRepoDoesNotInitializeTarget -50 34 TestEmbeddedGateListScoped -50 34 TestEmbeddedLintConcurrent -50 34 TestEmbeddedPurgeWispsPlaneRetention -50 34 TestEmbeddedReady +100 34 TestEmbeddedCopyIssueRelations_preservesCommentWithTimestamp +100 34 TestEmbeddedEventsTailReportsTruncationToTheCLI +100 34 TestEmbeddedUnclaimBatchAndRefusals +100 34 TestEmbeddedWispGCPurgeClosedDoesNotCascadeIntoLiveSteps -50 35 TestEmbeddedCommentsCLIConcurrent -50 35 TestEmbeddedHooksConcurrent -50 35 TestEmbeddedLabelPropagateRename -50 35 TestEmbeddedListSearchAndOutput -50 35 TestEmbeddedSupersede +100 35 TestEmbeddedAutoPruneRespectsBdConfigSet +100 35 TestEmbeddedEventsReadNoticesADisabledJournal +100 35 TestEmbeddedGateCreateBeadRename +100 35 TestEmbeddedVersionedHistoryEnvIsProcessWideAndOnlyTurnsRecordingOn -50 36 TestEmbeddedDeferConcurrent -50 36 TestEmbeddedFederationPeers -50 36 TestEmbeddedFlattenConcurrent -50 36 TestEmbeddedStatusConcurrent -50 36 TestEmbeddedTodoConcurrent +100 36 TestEmbeddedAutoPruneLeavesAnUnboundedJournalAlone +100 36 TestEmbeddedDoltRemoteResetData_UnknownRemote +100 36 TestEmbeddedGateConcurrent +100 36 TestEmbeddedUnclaimIfAssigneeCLIDifferentSpelling -50 37 TestEmbeddedInfoSuppressGitHooks -50 37 TestEmbeddedInitB -50 37 TestEmbeddedQueryConcurrent -50 37 TestEmbeddedUndeferConcurrent -50 37 TestEmbeddedUpdateBatchAutoCommitDoesNotAdvanceHead +100 37 TestEmbeddedAutoPruneBoundsTheJournalAfterAMutatingCommand +100 37 TestEmbeddedDoltRemoteResetData_CloudRemoteRefused +100 37 TestEmbeddedMaxRowsDepTreeAndDuplicates +100 37 TestEmbeddedSpawnMolecule_SubstitutesTemplatedStepFields -50 38 TestEmbeddedBlocked -50 38 TestEmbeddedCreateCrossRepoWithParent -50 38 TestEmbeddedEpicConcurrent -50 38 TestEmbeddedHooks -50 38 TestEmbeddedUndefer +100 38 TestEmbeddedGraphConcurrent +100 38 TestEmbeddedRoutedCreateJournalsIntoTheTargetWorkspace +100 38 TestEmbeddedUnclaimIfAssigneeFlagValidation -50 39 TestEmbeddedBranchConcurrent -50 39 TestEmbeddedCountIncludeInfra -50 39 TestEmbeddedCreateWithGitRemote -50 39 TestEmbeddedDelete -50 39 TestEmbeddedUpdateFields +100 39 TestEmbeddedIfRevisionRejectsLabelAndParentEdits +100 39 TestEmbeddedMaxRowsGraph +100 39 TestEmbeddedNewDoltStoreFromConfig_NoMetadata -50 40 TestEmbeddedCountConcurrent -50 40 TestEmbeddedCountIncludeEphemeral -50 40 TestEmbeddedCreateFormCommitsLabelOnlyCreate -50 40 TestEmbeddedLabelEditReports -50 40 TestEmbeddedPreviewDoesNotConsumeVersionMarker +100 40 TestEmbeddedIfRevisionOutranksReassignFenceCLI +100 40 TestEmbeddedNewDoltStoreFromConfig_HyphenatedDBName +100 40 TestEmbeddedUpdateLifecycleClaimParentCommit -50 41 TestEmbeddedGateCreate -50 41 TestEmbeddedLabelAddRemove -50 41 TestEmbeddedLabelConcurrent -50 41 TestEmbeddedListConcurrent -50 41 TestEmbeddedTypesConcurrent +100 41 TestEmbeddedDuplicateConcurrent +100 41 TestEmbeddedVersionedHistoryFollowsTheStoreItWritesInto -50 42 TestEmbeddedImportFromSources -50 42 TestEmbeddedReadyConcurrent -50 42 TestEmbeddedRenamePrefixEdgeCases -50 42 TestEmbeddedRestore -50 42 TestEmbeddedSquashWispMoleculeClearsRootEphemeral +100 42 TestEmbeddedInitAForkAutoContributor +100 42 TestEmbeddedUpdateIfGuardsFlagValidation -50 43 TestEmbeddedFindDuplicates -50 43 TestEmbeddedGraph -50 43 TestEmbeddedImportPromotedWispRoundtrip -50 43 TestEmbeddedInfoConcurrent -50 43 TestEmbeddedQuickstartConcurrent +100 43 TestEmbeddedIfRevisionMultiIDRejected +100 43 TestEmbeddedInitExplicitBeadsDirIsAuthoritative -50 44 TestEmbeddedDoltRemoteAndPush -50 44 TestEmbeddedGraphConcurrent -50 44 TestEmbeddedImportConcurrent -50 44 TestEmbeddedInitRoleRouting -50 44 TestEmbeddedWhereConcurrent +100 44 TestEmbeddedIfRevisionComposesWithIfAssigneeIfStatus +100 44 TestEmbeddedStaleConcurrent -50 45 TestEmbeddedChildren -50 45 TestEmbeddedCompactConcurrent -50 45 TestEmbeddedMigrateConcurrent -50 45 TestEmbeddedShowDetailAndCurrent -50 45 TestEmbeddedVCStatusAndCommit +100 45 TestEmbeddedGraph +100 45 TestEmbeddedUpdateIfGuardsCLI -50 46 TestEmbeddedCompactMisdatedChild -50 46 TestEmbeddedCount -50 46 TestEmbeddedCreateDryRunDoesNotMigrate -50 46 TestEmbeddedFederationStatus -50 46 TestEmbeddedStaleLabelFilters +100 46 TestEmbeddedCloseAlreadyClosedClaimNextAndMolecule +100 46 TestEmbeddedIfRevisionMatchAndMismatch -50 47 TestEmbeddedBootstrap -50 47 TestEmbeddedBranch -50 47 TestEmbeddedContextConcurrent -50 47 TestEmbeddedLint -50 47 TestEmbeddedPurgeConcurrent +100 47 TestEmbeddedListSearchAndOutputSearchAndSort +100 47 TestEmbeddedRevisionRemintMatrix -50 48 TestEmbeddedCloseConcurrent -50 48 TestEmbeddedConfig -50 48 TestEmbeddedDepAndLinkBatchAutoCommitDoesNotAdvanceHead -50 48 TestEmbeddedOnboardConcurrent -50 48 TestEmbeddedQuietFlagSuppressesSuccessOutput +100 48 TestEmbeddedDeferConcurrent +100 48 TestEmbeddedReassignFenceCLI -50 49 TestEmbeddedDepNoCycleCheck -50 49 TestEmbeddedFederationConcurrent -50 49 TestEmbeddedMemory -50 49 TestEmbeddedOnboard -50 49 TestEmbeddedPurgeFiltered +100 49 TestEmbeddedBackupRestoreStrictReadonly +100 49 TestEmbeddedInitAPushConsentAndRemoteBootstrap +100 49 TestEmbeddedMigratePersonal_abortOnNoConfirm -50 50 TestEmbeddedAutoImportJSONLSkipsNonEmpty -50 50 TestEmbeddedExportFlags -50 50 TestEmbeddedPurgeBasics -50 50 TestEmbeddedRenamePrefixConcurrent -50 50 TestEmbeddedUnclaim +100 50 TestEmbeddedDiffConcurrent +100 50 TestEmbeddedDoltRemoteAdd_AllowGitOrigin_WarningOnStderr +100 50 TestEmbeddedImportChunkedWaitsForChildImportedLaterStaysBlocked +100 50 TestEmbeddedVersionOutputShape + +100 51 TestEmbeddedDoltRemoteAdd_AllowGitOrigin_Exits0 +100 51 TestEmbeddedHistoryAndShowAsOfReadDoltCommits +100 51 TestEmbeddedImportChunkedStaleRejectedRowKeepsDeferredDepsOut +100 51 TestEmbeddedInitGitBootstrapRoutingFreshQuiet + +100 52 TestEmbeddedConfigSetOtherKeysSkipTheVersionedHistoryScan +100 52 TestEmbeddedDoltLocalOnly_Push_LocalStoreCopy +100 52 TestEmbeddedImportChunkedNoReadyWindowAtAnyFreezePoint +100 52 TestEmbeddedSwarmConcurrent + +100 53 TestEmbeddedDoltLocalOnly_Push_JSON_DisabledStatus +100 53 TestEmbeddedIfRevisionOrdinaryCAS +100 53 TestEmbeddedImportChunkedMixedRegularWispCrossBucketEdgesWired +100 53 TestEmbeddedInitSelectedExcludeRoutingStealthDecoyQuiet + +100 54 TestEmbeddedDiscoveryPinsEnvFileReadonly +100 54 TestEmbeddedFormatJSONAliasMatchesJSON +100 54 TestEmbeddedGraphModeDependencyWorkspaceUnaffected +100 54 TestEmbeddedInitAgentArtifactsGolden +100 54 TestEmbeddedSearchConcurrent +100 54 TestEmbeddedShowAsOfFailureExitCodes + +100 55 TestEmbeddedDoltLocalOnly_Pull_JSON_DisabledStatus +100 55 TestEmbeddedImportChunkedConcurrentUpdateKeepsDeferredDeps +100 55 TestEmbeddedUndefer +100 55 TestEmbeddedVersionedHistorySwitchScansEveryRowNotOnePage + +100 56 TestEmbeddedDepNoCycleCheck +100 56 TestEmbeddedDoltLocalOnly_Pull_ExitsZeroWithMessage +100 56 TestEmbeddedImportChunkedConcurrentUpdateKeepsBlockingDeps +100 56 TestEmbeddedVersionedHistorySwitchRoundTrip + +100 57 TestEmbeddedDoltLocalOnly_DoltStatus_ShowsDisabled +100 57 TestEmbeddedIfRevisionDeletePreflightGoneIsPreconditionFailed +100 57 TestEmbeddedQueryConcurrent +100 57 TestEmbeddedVersionedHistorySwitchRefusesUnversionableMetadata + +100 58 TestEmbeddedDepAAddRejectionsAndBulk +100 58 TestEmbeddedDoctorUnsupportedProse +100 58 TestEmbeddedIfRevisionCascadeDelete +100 58 TestEmbeddedVersionedHistorySwitchRefusesAnUnrecordableGateTimeout + +100 59 TestEmbeddedDeferAutoWake +100 59 TestEmbeddedDoctorSupportedChecks +100 59 TestEmbeddedIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace +100 59 TestEmbeddedVersionedHistorySetManyRefusesUnversionableMetadata + +100 60 TestEmbeddedCommentsCLI +100 60 TestEmbeddedCorruptMetadataFailsLoudUntilRestored +100 60 TestEmbeddedExportExcludeOwner_config +100 60 TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase +100 60 TestEmbeddedWispGCPurgeClosedStillPurgesFullyClosedMolecules + +100 61 TestEmbeddedBootstrapCloneFailureScrubsCredentials +100 61 TestEmbeddedContributorRoutedWritesCommitInPlanning +100 61 TestEmbeddedEventsPruneHonorsRetainRowsFloorFromConfig +100 61 TestEmbeddedUpdateRoutedStoreCommitsTargetHead +100 61 TestEmbeddedVersionedHistoryConfigSetWritesTheStoreRow + +100 62 TestEmbeddedAutoPruneDoesNotRunForReadOnlyCommands +100 62 TestEmbeddedDoltRemoteResetData_GitBacked +100 62 TestEmbeddedGateCheckSkipsTemplateGates +100 62 TestEmbeddedReadyBlockersAndLabels +100 62 TestEmbeddedUnclaimIfAssigneeCLI + +100 63 TestEmbeddedDepAndLinkBatchAutoCommitDoesNotAdvanceHead +100 63 TestEmbeddedGateCheckLimitCountsOnlyLiveGates +100 63 TestEmbeddedIfRevisionDeletePreflightGoneParentIsPreconditionFailed +100 63 TestEmbeddedListPageEdges + +100 64 TestEmbeddedAutoExportExcludeOwner_config +100 64 TestEmbeddedDoltRemoteAdd_NoGitOrigin_ProceedsNormally +100 64 TestEmbeddedGateWaiterCheckLifecycle +100 64 TestEmbeddedPromoteMovesAWispParent +100 64 TestEmbeddedSpawnMolecule_PreservesStepLabels + +100 65 TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb +100 65 TestEmbeddedRemovedBackendHealRoundTrip +100 65 TestEmbeddedSupersede + +100 66 TestEmbeddedCloseBasicIsolatedStores +100 66 TestEmbeddedShowCommentsTail + +100 67 TestEmbeddedAdminCompactReadOnlyAllowed +100 67 TestEmbeddedAutoImportFallback_ConflictSkip_DoesNotClobber +100 67 TestEmbeddedBootstrapConcurrent +100 67 TestEmbeddedCountIncludeInfra +100 67 TestEmbeddedCreateCommitPending +100 67 TestEmbeddedCreateDryRunRepoDoesNotInitializeTarget +100 67 TestEmbeddedCreateRepoFromNonBeadsCwd +100 67 TestEmbeddedCreateRepoRelativeUninitRefused +100 67 TestEmbeddedHooks +100 67 TestEmbeddedOnboard +100 67 TestEmbeddedPrime +100 67 TestEmbeddedPromote +100 67 TestEmbeddedQuickstart +100 67 TestEmbeddedQuickstartConcurrent +100 67 TestEmbeddedWhere +100 67 TestEmbeddedWhereConcurrent + +100 68 TestEmbeddedAutoImportFallback_ConflictSkip_EmptyDBImportsAll +100 68 TestEmbeddedBlocked +100 68 TestEmbeddedCompactConcurrent +100 68 TestEmbeddedContext +100 68 TestEmbeddedCreateJSONEchoesSubSecondTimestamps +100 68 TestEmbeddedDoltBlockedAndCommit +100 68 TestEmbeddedDoltConcurrent +100 68 TestEmbeddedInfo +100 68 TestEmbeddedInfoSuppressGitHooks +100 68 TestEmbeddedOrphans +100 68 TestEmbeddedRoutedMutatingSiblingDeleteCloseDelete +100 68 TestEmbeddedSetupConcurrent +100 68 TestEmbeddedTodoConcurrent +100 68 TestEmbeddedTypes + +100 69 TestEmbeddedCompact +100 69 TestEmbeddedConfigValidateJSONNoWorkspaceWritesStdout +100 69 TestEmbeddedCreateConcurrent +100 69 TestEmbeddedDepBulkNoCycleCheckKeepsWholeGraphGate +100 69 TestEmbeddedDuplicatesSharedFixture +100 69 TestEmbeddedGateListScoped +100 69 TestEmbeddedGetDependencies +100 69 TestEmbeddedInfoConcurrent +100 69 TestEmbeddedRenamePrefixConcurrent +100 69 TestEmbeddedRoutedSiblingWritesCommitTargetHeadNote +100 69 TestEmbeddedTypesConcurrent +100 69 TestEmbeddedUpdateBatchAutoCommitDoesNotAdvanceHead + +100 70 TestEmbeddedExportConcurrent +100 70 TestEmbeddedFlattenConcurrent +100 70 TestEmbeddedGCDryRunAndSkips +100 70 TestEmbeddedImportConcurrent +100 70 TestEmbeddedImportUpsertAndPrefixSync +100 70 TestEmbeddedLabelAddRemoveMultiAndDuplicate +100 70 TestEmbeddedMemory +100 70 TestEmbeddedMigrateConcurrent +100 70 TestEmbeddedPurgeConcurrent +100 70 TestEmbeddedRoutedMutatingSiblingAssignTagDepTag + +100 71 TestEmbeddedCloseJSONReportsMoleculeAutoClose +100 71 TestEmbeddedInitRoleRoutingExplicitDefault +100 71 TestEmbeddedPrimeChangeDirRedirectNoticeFollowsTarget +100 71 TestEmbeddedRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig +100 71 TestEmbeddedSearchRoutesAgree + +100 72 TestEmbeddedContributorCreateMultiple +100 72 TestEmbeddedCreateWithGitRemote +100 72 TestEmbeddedFederationConcurrent +100 72 TestEmbeddedGateCreateRepoErrorsList +100 72 TestEmbeddedHumanConcurrent +100 72 TestEmbeddedImportPromotedWispRoundtrip +100 72 TestEmbeddedPrimeChangeDirPrimesTarget +100 72 TestEmbeddedRoutedMutatingSiblingDeleteCloseClose +100 72 TestEmbeddedRoutedSiblingWritesCommitTargetHeadReopen +100 72 TestEmbeddedUpdateFieldsMappingAndRefs + +100 73 TestEmbeddedCompactMisdatedChild +100 73 TestEmbeddedExportFlags +100 73 TestEmbeddedFederationPeers +100 73 TestEmbeddedGateCreateFlags +100 73 TestEmbeddedGateCreateReady +100 73 TestEmbeddedPrimeChangeDirDefaultTemplateMatchesTarget +100 73 TestEmbeddedQuickConcurrent +100 73 TestEmbeddedRenamePrefixBasic +100 73 TestEmbeddedRoutedMutatingSiblingAssignTagDepDepAdd + +100 74 TestEmbeddedBlockedConcurrent +100 74 TestEmbeddedBranch +100 74 TestEmbeddedCountIncludeEphemeral +100 74 TestEmbeddedDepAddWispSource +100 74 TestEmbeddedMigrate +100 74 TestEmbeddedPrimeConcurrent +100 74 TestEmbeddedRestore +100 74 TestEmbeddedVCConcurrent + +100 75 TestEmbeddedCommentsCLIConcurrent +100 75 TestEmbeddedContextConcurrent +100 75 TestEmbeddedFlatten +100 75 TestEmbeddedInitC +100 75 TestEmbeddedListComments +100 75 TestEmbeddedOpen_EmptyDatabaseRejected +100 75 TestEmbeddedReclaimRunsTheLeaseReclaimerRole +100 75 TestEmbeddedRoutedSiblingWritesCommitTargetHeadComment +100 75 TestEmbeddedVCStatusAndCommit + +100 76 TestEmbeddedCloseAlreadyClosedContinue +100 76 TestEmbeddedCloseAlreadyClosedMultipleIDs +100 76 TestEmbeddedExportFormats +100 76 TestEmbeddedGCForceWithDecay +100 76 TestEmbeddedGCFullAndNoForcePrompts +100 76 TestEmbeddedInitAGitOriginRemote +100 76 TestEmbeddedLabelAddRemoveRemove +100 76 TestEmbeddedOnboardConcurrent + +100 77 TestEmbeddedClaimPools +100 77 TestEmbeddedConfigNoWorkspaceStoreFreeCommands +100 77 TestEmbeddedCreateStorageClassConflicts +100 77 TestEmbeddedExternalCapabilityReadyAfterShip +100 77 TestEmbeddedHumanListStatsRespondDismiss +100 77 TestEmbeddedMemoryCorpusBudget +100 77 TestEmbeddedOrphansConcurrent +100 77 TestEmbeddedStatus + +100 78 TestEmbeddedBranchConcurrent +100 78 TestEmbeddedComments +100 78 TestEmbeddedDepBRemove +100 78 TestEmbeddedLabelAddRemoveAdd +100 78 TestEmbeddedShip +100 78 TestEmbeddedUpdateFieldsNotesOverwrite +100 78 TestEmbeddedVCCommitVariantsAndMerge +100 78 TestEmbeddedVersionConcurrent + +100 79 TestEmbeddedCreateCrossRepoUninit +100 79 TestEmbeddedDeleteJSONDependencyErrorContract +100 79 TestEmbeddedEpicCloseEligibleNotEligible +100 79 TestEmbeddedInitABasic +100 79 TestEmbeddedInitBRemoteSchemaAndCloneFailure +100 79 TestEmbeddedRenamePrefixEdgeCases +100 79 TestEmbeddedUpdateFieldsNotesClearAndDefer + +100 80 TestEmbeddedCreateCrossRepoWithParent +100 80 TestEmbeddedCreateFormCommitsLabelOnlyCreate +100 80 TestEmbeddedCreateStorageClassBasic +100 80 TestEmbeddedRoutedMutatingSiblingAssignTagDepAssign +100 80 TestEmbeddedStatusConcurrent +100 80 TestEmbeddedSwarmCreate +100 80 TestEmbeddedSwarmValidate + +100 81 TestEmbeddedAdminCompactTier2Honesty +100 81 TestEmbeddedBackup +100 81 TestEmbeddedDeleteForceAndBatch +100 81 TestEmbeddedGateCreateBeadCheck +100 81 TestEmbeddedGateList +100 81 TestEmbeddedRestoreConcurrent +100 81 TestEmbeddedStaleLabelFilters +100 81 TestEmbeddedStateConcurrent + +100 82 TestEmbeddedCreateCrossRepoDryRunWithParent +100 82 TestEmbeddedDeleteBasic +100 82 TestEmbeddedDepBTreeAndCycles +100 82 TestEmbeddedDirectCommitPathsBatchAutoCommitDoesNotAdvanceHead +100 82 TestEmbeddedHooksConcurrent +100 82 TestEmbeddedImportFromSources +100 82 TestEmbeddedStale + +100 83 TestEmbeddedAdminBlocked +100 83 TestEmbeddedAutoImportJSONLConcurrentWriter +100 83 TestEmbeddedInitBAutoCommitAndJSONLRemote +100 83 TestEmbeddedLabelEditReportsPrefix +100 83 TestEmbeddedMaxRowsDoctorAndConfig +100 83 TestEmbeddedPurgeFiltered +100 83 TestEmbeddedReadyConcurrent + +100 84 TestEmbeddedDoltRemoteAdd_GitOriginCollision_Exits1 +100 84 TestEmbeddedInitGitBootstrapRoutingDecoyInvalid +100 84 TestEmbeddedInitSelectedExcludeRoutingStealthInvalid +100 84 TestEmbeddedMigratePersonal_preservesComments + +100 85 TestEmbeddedBootstrapExistingDryRunInit +100 85 TestEmbeddedChildrenBasicAndEmpty +100 85 TestEmbeddedCreateGraphAndBulk +100 85 TestEmbeddedCreateRepoRelativeExistingWorkspaceUnaffected +100 85 TestEmbeddedIfRevisionReopenGuardDirect +100 85 TestEmbeddedInitArtifactRouting + +100 86 TestEmbeddedDoltRemoteAdd_DifferentURL_ProceedsNormally +100 86 TestEmbeddedExplicitHierarchicalParentEdges +100 86 TestEmbeddedInitHooksRouting +100 86 TestEmbeddedMigratePersonal_noopWhenEmpty + +100 87 TestEmbeddedCreateRepoProxiedTargetError +100 87 TestEmbeddedGateInheritsDownParentChain +100 87 TestEmbeddedReadyClaimConcurrent +100 87 TestEmbeddedState +100 87 TestEmbeddedSupersedeConcurrent +100 87 TestEmbeddedSwarmCreateForceAndErrors + +100 88 TestEmbeddedChangeDirOverridesInheritedBeadsDir +100 88 TestEmbeddedDepAAddAndList +100 88 TestEmbeddedKV +100 88 TestEmbeddedMaxRowsReadyMerge +100 88 TestEmbeddedPromoteCLI +100 88 TestEmbeddedUnclaimSuccess + +100 89 TestEmbeddedBackupConcurrent +100 89 TestEmbeddedCreateDryRunDoesNotMigrate +100 89 TestEmbeddedGateShowResolve +100 89 TestEmbeddedInitBStealthAndForceReinit +100 89 TestEmbeddedLabelEditReportsNoop +100 89 TestEmbeddedShowBasicsAndJSON + +100 90 TestEmbeddedAutoImportJSONLSkipsNonEmpty +100 90 TestEmbeddedConfig +100 90 TestEmbeddedFindDuplicatesConcurrent +100 90 TestEmbeddedLabelEditReportsListAndTemplate +100 90 TestEmbeddedLintConcurrent +100 90 TestEmbeddedUpdateLifecycleDefer +100 90 TestEmbeddedVersion + +100 91 TestEmbeddedDuplicate +100 91 TestEmbeddedPreviewDoesNotConsumeVersionMarker +100 91 TestEmbeddedPruneDryRunAndFilters +100 91 TestEmbeddedReadOnlyCommandsSpawnNoGit +100 91 TestEmbeddedShowUnresolvableDeps +100 91 TestEmbeddedTypesAgreeWithCreate + +100 92 TestEmbeddedAutoImportJSONLNoExplicitCommit +100 92 TestEmbeddedDefer +100 92 TestEmbeddedDepAAddTypesAndFlags +100 92 TestEmbeddedEpicCloseEligibleClosesEpics +100 92 TestEmbeddedSetup +100 92 TestEmbeddedSwarmStatusList + +100 93 TestEmbeddedCreateStorageClassBatchAndMisc +100 93 TestEmbeddedDeletePreviewAndGuards +100 93 TestEmbeddedDepBRemoveOutputAndRelatesTo +100 93 TestEmbeddedListConcurrent +100 93 TestEmbeddedPruneSafetyAndScope +100 93 TestEmbeddedShowDetailAndCurrentFlags + +100 94 TestEmbeddedCreateDryRunCrossRepoDoesNotMigrateTarget +100 94 TestEmbeddedDepListSingleIDWarnsOnDroppedExternalEdge +100 94 TestEmbeddedEpicCloseEligibleReasonOutput +100 94 TestEmbeddedFederationStatus +100 94 TestEmbeddedGCConcurrent +100 94 TestEmbeddedReadyDefaultJSONAndFlags + +100 95 TestEmbeddedChildrenJSONAndAllStatuses +100 95 TestEmbeddedFindDuplicates +100 95 TestEmbeddedImportClosedChildWhoseParentWasDeleted +100 95 TestEmbeddedInitConcurrent +100 95 TestEmbeddedQuick + +100 96 TestEmbeddedDiff +100 96 TestEmbeddedDuplicatesConcurrent +100 96 TestEmbeddedHistory +100 96 TestEmbeddedShowDetailAndCurrentHistoryAndCurrent +100 96 TestEmbeddedSquashWispMoleculeClearsRootEphemeral + +100 97 TestEmbeddedDuplicatesOwnWorkspaces +100 97 TestEmbeddedHumanPositionalFileAndGuards +100 97 TestEmbeddedPurgeBasics +100 97 TestEmbeddedQuietFlagSuppressesSuccessOutput +100 97 TestEmbeddedSearchStatusLimitSortDatesMetadata + +100 98 TestEmbeddedCloseBasicSharedStore +100 98 TestEmbeddedContributorCreateRoutesToPlanning +100 98 TestEmbeddedGCConditionalMatcherDecode +100 98 TestEmbeddedQuery +100 98 TestEmbeddedTodo + +100 99 TestEmbeddedBlockedLabelFilters +100 99 TestEmbeddedDoltRemoteAndPush +100 99 TestEmbeddedEpicStatus +100 99 TestEmbeddedInitSelectedExcludeRoutingForkDecoyAuto +100 99 TestEmbeddedSearchQueryStatusAssigneeLabels + +100 100 TestEmbeddedContributorCreateShowReadsRouted +100 100 TestEmbeddedCreateCrossRepo +100 100 TestEmbeddedInitGitBootstrapRoutingExistingExplicit +100 100 TestEmbeddedLint +100 100 TestEmbeddedPromoteCLIConcurrent diff --git a/.github/scripts/embedded-storage-test-shards.txt b/.github/scripts/embedded-storage-test-shards.txt index 4d972644d..c3f45aacb 100644 --- a/.github/scripts/embedded-storage-test-shards.txt +++ b/.github/scripts/embedded-storage-test-shards.txt @@ -114,12 +114,12 @@ # # Format: # -# 15-shard split for the Bazel-only embedded-Dolt storage tier +# 40-shard split for the Bazel-only embedded-Dolt storage tier # (bazel-embedded in .github/workflows/bazel.yml), bin-packed # longest-processing-time-first by measured wall-time from # scripts/ci/embedded_storage_test_durations.json (see that file for provenance # and its "relative weight, not absolute SLA" caveat). -# Regenerate with scripts/ci/gen_embedded_storage_shard_manifest.py 15 +# Regenerate with scripts/ci/gen_embedded_storage_shard_manifest.py 40 # --weights=duration --write after adding or removing Test* functions in # internal/storage/embeddeddolt/*_test.go. --write is incremental: it # keeps every already-assigned test on its current shard and only places @@ -134,405 +134,475 @@ # This file is generated: notes added here are erased by the next # regeneration. Add them to the generator or the durations file instead. -15 1 TestBatchApplyContract -15 1 TestEmbeddedClaimerClaimsAnUnassignedOpenIssueAndAnswersTheBareRow -15 1 TestEmbeddedClaimerReclaimsAcrossSpellingWithoutWriting -15 1 TestEmbeddedDependencyEditorWritesTheTargetIntoItsTypedColumn -15 1 TestEmbeddedIssueOperationsCreateParentChildRecomputesWaitsForClosure -15 1 TestEmbeddedIssueOperationsCreateUnderAParentMintsTheNextChildID -15 1 TestEmbeddedIssueOperationsUpdateClaimCASAndTransferMatrix -15 1 TestEmbeddedIssueOperationsUpdateClaimConflictCarriesTheLosingState -15 1 TestEmbeddedMergeAndSettleMetadataConflict -15 1 TestEmbeddedMergeAndSettleRefusesUnknownTable -15 1 TestEmbeddedMigration0047DelegatesToSplitTargetRepairAndConvergesThroughIgnoredChain -15 1 TestEmbeddedReaderListDefaultExclusionsAndTheirOverrides -15 1 TestEmbeddedReaderListSkipCountsDropsTheCardinalitiesAndNothingElse -15 1 TestEmbeddedReaderListWispTypeNarrowsTheAdmittedPlaneRatherThanAdmittingIt -15 1 TestEmbeddedReaderReadyBriefDropsTheFreeFormTextAndNothingElse -15 1 TestEmbeddedRelationsAnswersAWispTargetInTheOutDirection -15 1 TestEmbeddedRelationsLeavesAnExternalTargetOutOfTheAnswer -15 1 TestEmbeddedRoleFixtureKitHooksAreUsable -15 1 TestLifecycleCreateContract -15 1 TestMergeWithStrategy_OursKeepsLocal +40 1 TestLifecycleCloseReopenContract -15 2 TestActiveDatabaseSizeScopesToActiveEmbeddedDatabase -15 2 TestCleanGitRemoteCacheGarbage -15 2 TestDepRekeyMarkerStillInIgnoredSeries -15 2 TestDescendantWalkReachesEveryTargetKindAndStopsOnCycles -15 2 TestDualWriteFixtureKitIsWired -15 2 TestEmbeddedDepRekeyAbortLeavesMarkerUnrecorded -15 2 TestEmbeddedDependencyEditorAppliesParentChildBeforeBlockingEdges -15 2 TestEmbeddedDependencyEditorRefusesACycleThroughAParentChildHop -15 2 TestEmbeddedDependencyEditorRefusesAGhostSource -15 2 TestEmbeddedDependencyEditorRoutesWispSourcedRemovalToTheWispPlane -15 2 TestEmbeddedDependencyEditorSkipPerEdgeCycleCheckDropsOnlyTheProbe -15 2 TestEmbeddedIssueOperationsCreateAggregatesRelations -15 2 TestEmbeddedIssueOperationsUpdateStatusCrossingSettlesDependers -15 2 TestEmbeddedOpenReadOnly_FreshDatabaseNoWrites -15 2 TestEmbeddedReaderListCountsAreBlocksOnlyWhereGetCountsEveryEdge -15 2 TestEmbeddedRelationsDirectionSelectsTheInverseGraph -15 2 TestEmbeddedRelationsLeavesTheCallersRequestAlone -15 2 TestEmbeddedRelationsOrdersNeighborsFromBothPlanesTogether -15 2 TestEmbeddedRemoteMigrateGate_BlocksReopen -15 2 TestGitRefPinsMatchDolt -15 2 TestHeartbeatRejectsWispEmbedded -15 2 TestHookFiringStoreCreateIssuesFiresDependencyUpdatesFromEmbeddedStore -15 2 TestIgnoredCursorHealRespectsOverrideUnderBroaderPattern -15 2 TestLeaseLifecycleEmbedded -15 2 TestLenientGateWarningBody_ShapedDecisions -15 2 TestReadEventsAutoPruneStateResolvesBothHalvesInOneQuery -15 2 TestSchemaAfterInit -15 2 TestStageAndCommitAfterSQLCommitResponseLossIsIndeterminateAndNotReplayed -15 2 TestWithPeerAuth_WarnsWhenStoredPeerSuppressesAmbientPassword +40 2 TestBatchApplyContract -15 3 TestEmbeddedBatchCloserDoesNotMutateTheCallerRequest -15 3 TestEmbeddedBatchCloserOutcomeSnapshotIsTheDocumentedShape -15 3 TestEmbeddedClaimerRefusesAWispIDAsNotFound -15 3 TestEmbeddedConfigCommitStagesConfig -15 3 TestEmbeddedDependencyEditorAcceptsBlockingAcrossIssueTypes -15 3 TestEmbeddedDependencyEditorRefusalWritesNothing -15 3 TestEmbeddedDependencyEditorRemoveIsIdempotent -15 3 TestEmbeddedDependencyEditorVersionsOnlyARealAddOrRemove -15 3 TestEmbeddedIgnoredMigration0023NoopsOnHealthyWorkspace -15 3 TestEmbeddedMergeAndSettleFKCascadeRepair -15 3 TestEmbeddedReaderListParentReachesEveryDescendantAndOnlyItsOwn -15 3 TestEmbeddedReaderListPriorityKeysetWalkOverAnOversizedEqualKeyRunLosesNothingAndRepeatsNothing -15 3 TestEmbeddedReaderReadyLimitBoundary -15 3 TestEmbeddedReadyClaimerFencesTheClaimByEveryLabelSetAndTheParentItWasGiven -15 3 TestEmbeddedRelationsRefusesATypeFilterOverTheColumnLength -15 3 TestEmbeddedRenameKeepsDependencyIDsDeterministic -15 3 TestEventsAutoPruneKeepsAnUnboundedJournalUnbounded -15 3 TestEventsJournalReadRefusesAnInteriorHole -15 3 TestForeignSkipDetailIsBounded -15 3 TestListWisps -15 3 TestMergeAndSettleWithStrategy_ResolvesDeclinedConflict -15 3 TestPushCommitsPendingChangesFirst -15 3 TestUpdateMergeOps_DoltEngine_TwoIssues -15 3 TestWithPeerAuth_RestoresAbsentEnv +40 3 TestActiveDatabaseSizeFailsForMissingEmbeddedDatabase +40 3 TestActiveDatabaseSizeScopesToActiveEmbeddedDatabase +40 3 TestBuildDSN_NoDatabase +40 3 TestBuildDSN_SpacesInPath +40 3 TestBuildDSN_WithDatabase +40 3 TestCleanGitRemoteCacheGarbage +40 3 TestCleanGitRemoteCacheGarbage_NoCacheDir +40 3 TestCleanGitRemoteCacheGarbage_Throttled +40 3 TestCommitAllOutOfBandChangeAndHonestNoOp +40 3 TestCreateBatchEquivalencePartsCoverEveryScenario +40 3 TestCreateBatchFastPathsMatchPerRowLarge_Embedded +40 3 TestCrossRecordInvariantContract +40 3 TestDepRekeyMarkerStillInIgnoredSeries +40 3 TestDoltCommitResponseLossIsIndeterminate +40 3 TestEmbeddedDependencyEditorRefusesADottedChildGatedOnItsOwnParent +40 3 TestEmbeddedDoltStoreIssueLifecycleBuildsOperations +40 3 TestEmbeddedDoltStoreIssueLifecycleRejectsNilStore +40 3 TestEmbeddedOpenReadOnly_FreshDatabaseNoWrites +40 3 TestEmbeddedSQLCommitResponseLossIsIndeterminate +40 3 TestEpochContract +40 3 TestExpectedRevisionContract +40 3 TestGitRefPinsMatchDolt +40 3 TestHasRepository +40 3 TestHelperProcess +40 3 TestLargeBatchApplyStatementCounts712_Embedded +40 3 TestLargeGraphCreateTiming_Embedded +40 3 TestLenientGateWarningBody_BluntRefusalKeepsSharedGuidance +40 3 TestLenientGateWarningBody_ShapedDecisions +40 3 TestLenientGateWarning_ComposedOutput +40 3 TestMain +40 3 TestPushCommitsPendingChangesFirst +40 3 TestRemoteEntryPointsUseVersionControlOps +40 3 TestRetentionContract +40 3 TestStageAndCommitAfterSQLCommitResponseLossIsIndeterminateAndNotReplayed +40 3 TestTransactionCleanupAfterSQLCommitIsIndeterminate +40 3 TestTransactionCleanupBeforeSQLCommitRemainsDefinite +40 3 TestUnknownProvenanceLeaseStaysReclaimable -15 4 TestEmbeddedBatchCloserSettlesTheDependersOfWhatItClosed -15 4 TestEmbeddedBlockedRecheckSettlesWhatTheWriteRecorded -15 4 TestEmbeddedClaimIssueWrapperClaimsTheWispPlane -15 4 TestEmbeddedClaimerRefusesABuiltInIneligibleStatusWithTheStateThatRefusedIt -15 4 TestEmbeddedClaimerTakesAPoolAssignedIssueButRefusesAForeignHolder -15 4 TestEmbeddedCommitToleratesNothingToCommit -15 4 TestEmbeddedDependencyEditorRecordsOneHistoryEntryForAMixedPlaneRequest -15 4 TestEmbeddedDependencyEditorRefusesBlockingEdgeAcrossItsOwnHierarchy -15 4 TestEmbeddedIgnoredMigration0023RepairsForkLineageJournalShape -15 4 TestEmbeddedReaderListEmptyPageIsWellFormed -15 4 TestEmbeddedRelationsFiltersByAnOpenTypeVocabulary -15 4 TestEmbeddedReopenIssueCategorySemantics -15 4 TestEmbeddedRoleFixtureKitCountHistoryMovesWithACommit -15 4 TestEventsAutoPruneThrottleSkipsTheSecondPass -15 4 TestEventsJournalRestartAndRetentionBoundary -15 4 TestIgnoredCursorHealNeverResurrectsRolledBackVersions -15 4 TestMain -15 4 TestMemoriesContract -15 4 TestPromoteClearsNoHistory -15 4 TestRemoteVerbPlainRemoteKeepsAmbientEnv -15 4 TestReopenIssue -15 4 TestWithPeerAuth -15 4 TestWithPeerAuth_EnvFallbackDoesNotObservePeerCredentials +40 4 TestBlockedListerContract +40 4 TestCreateBatchFastPathsMatchPerRowSmallDepAdd_Embedded +40 4 TestEmbeddedIssueOperationsUpdateLabelPatchOrdering +40 4 TestEmbeddedReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay +40 4 TestEmbeddedReaderListFilterFamiliesNarrowToTheirRows +40 4 TestMergeAndSettleWithStrategy_EmptyStrategyMatchesMergeAndSettle -15 5 TestActiveDatabaseSizeFailsForMissingEmbeddedDatabase -15 5 TestBlockingAnnotatorContract -15 5 TestBootstrapperContract -15 5 TestBuildDSN_WithDatabase -15 5 TestCrossRecordInvariantContract -15 5 TestEmbeddedBatchCloserClaimNextSeesAnUnblockingFromItsOwnBatch -15 5 TestEmbeddedClaimerStampsStartedAtOnceAcrossTheTwoWritesItChoosesBetween -15 5 TestEmbeddedDepRekeyConvergesRenameChain -15 5 TestEmbeddedDependencyEditorAcceptsADiamond -15 5 TestEmbeddedDependencyEditorRemoveUnmarksItsSourceAndDescendants -15 5 TestEmbeddedDependencyEditorRetypeRefusalLeavesTheOriginalEdge -15 5 TestEmbeddedDependencyEditorValidationRefusalsWriteNothing -15 5 TestEmbeddedDoltStoreIssueLifecycleRejectsNilStore -15 5 TestEmbeddedIssueOperationsCreateReverseNonBlockingStagesConcreteTables -15 5 TestEmbeddedIssueOperationsPersistenceRollbackWispAndDetachedResults -15 5 TestEmbeddedMergeAndSettleReportsOperatorConflicts -15 5 TestEmbeddedMigration0058AddsOnlyMissingConstraintInMixedPopulation -15 5 TestEmbeddedReaderGetBriefDepsProjectsTheDependencyRows -15 5 TestEmbeddedReaderListKeysetPositionResumesTheCreatedDescIDAscOrder -15 5 TestEmbeddedReaderListMaxRowsIsHonored -15 5 TestEmbeddedReadyClaimerDoesNotMutateTheCallerRequest -15 5 TestEmbeddedRelationsAnswersInThePinnedOrder -15 5 TestEventsAutoPruneBoundsTheJournalToTheFloors -15 5 TestExpectedRevisionContract -15 5 TestGetDependentRecordsForIssuesEmbedded -15 5 TestLargeBatchApplyWallClock_Embedded -15 5 TestLenientGateWarningBody_BluntRefusalKeepsSharedGuidance -15 5 TestOpenReturnsCachedStore -15 5 TestPartitionWispIDs -15 5 TestRetentionContract -15 5 TestWithPeerAuth_KeyMismatchFailsClosed +40 5 TestEmbeddedClaimerRefusesIncompleteRequestsAndAnAbsentIDWithoutTouchingState +40 5 TestEmbeddedIssueOperationsCloseAndReopenAWisp +40 5 TestEmbeddedReaderListKeysetPositionResumesTheCreatedDescIDAscOrder +40 5 TestRecordVersionKeepsSubSecondChangeAt +40 5 TestWithPeerAuth -15 6 TestCreateIssuesRejectStaleUpserts -15 6 TestDecryptPassword_KeyMismatchNamesTheLocalKey -15 6 TestEmbeddedBatchCloserPerItemRefusalIsAResultAndSurvivorsCommit -15 6 TestEmbeddedBatchCloserWispItemClosesAndEarnsTheClaim -15 6 TestEmbeddedBatchCreateFirstVersionCarriesCreationTimeEdges -15 6 TestEmbeddedDependencyEditorClosedChildAddSatisfiesAnAnyChildrenGate -15 6 TestEmbeddedDependencyEditorMaintainsBlockedStateAcrossPlanes -15 6 TestEmbeddedDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion -15 6 TestEmbeddedIssueOperationsUpdateClaimPatchAppliesAfterClaim -15 6 TestEmbeddedReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay -15 6 TestEmbeddedReadyClaimerClaimsTheFrontRowAndReturnsThePostClaimState -15 6 TestEmbeddedReadyClaimerRecordsOneHistoryEntryForAWin -15 6 TestEmbeddedSyncCommitsConfigBeforeMerge -15 6 TestGetIssue -15 6 TestHeartbeatMatchesActorAcrossSpellingEmbedded -15 6 TestHistory_NullTextColumns -15 6 TestIsBlockedBatchEmbedded -15 6 TestLargeBatchApplyStatementCounts356_Embedded -15 6 TestRemoteGitDataRefOnEngine -15 6 TestRenameLabel -15 6 TestRenameLabelMintsOneVersionPerTouchedBead -15 6 TestRunInTransactionPostCommitStageFailureIsIndeterminate -15 6 TestStatsReporterContract -15 6 TestWithPeerAuth_ConcurrentPeersDoNotMixCredentials -15 6 TestWithPeerAuth_RestoresEnvWhenCallbackFails +40 6 TestCreateBatchFastPathsMatchPerRowApplyWaitsFor_Embedded +40 6 TestEmbeddedMergeAndSettleFKCascadeRepair +40 6 TestEmbeddedMergeAndSettleSkipsNonMemoryConfigConflict +40 6 TestEmbeddedReaderListKeysetPositionNarrowsWithoutReplacingTheOtherPredicates +40 6 TestEmbeddedRelationsAnswersAWispTargetInTheOutDirection +40 6 TestPromoteStillWorksWithCollisionGuard +40 6 TestSearchWithMissingWispPlaneTables +40 6 TestVersionedHistoryKeepsNumbersTheStoreDistinguishesApart -15 7 TestCommitAllOutOfBandChangeAndHonestNoOp -15 7 TestConcurrencyMultiProcess -15 7 TestConcurrentOpenReturnsCached -15 7 TestDualWriteContractFlagOff -15 7 TestEmbeddedBatchCloserClaimNextIsNilWhenTheFrontIsEmpty -15 7 TestEmbeddedBatchCloserForceBypassesOnlyClosePolicy -15 7 TestEmbeddedDepRekeyRepairsHalfRekeyedDuplicateEdge -15 7 TestEmbeddedDependencyEditorGateScopeFollowsTheEdgeType -15 7 TestEmbeddedDependencyEditorRoutesWispSourcedEdgeToTheWispPlane -15 7 TestEmbeddedDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp -15 7 TestEmbeddedIssueOperationsUpdateStatusCrossingSettlesAConditionalBlocksDepender -15 7 TestEmbeddedMigration0057ConvertsTextEventsColumnsToLongtext -15 7 TestEmbeddedReaderListReadyFlagAnswersTheBlockerAwareSet -15 7 TestEmbeddedReaderReadyDefaultTypeExclusionsYieldToAnExplicitType -15 7 TestEmbeddedReaderReadySortPoliciesOrderTheSameRows -15 7 TestEmbeddedReadyClaimerAnswersTheQuestionReaderReadyLists -15 7 TestEmbeddedReadyClaimerLeasesADurableWinButNotAnEphemeralOne -15 7 TestEventsJournalAccessor -15 7 TestHistoryPresenceContract -15 7 TestJournalContract -15 7 TestLifecycleCloseReopenContract -15 7 TestReclaimAnyReplicaOverride -15 7 TestTreeWalkerContract -15 7 TestWithPeerAuth_DivergedRemoteURLFailsClosed +40 7 TestConcurrencyMultiProcess +40 7 TestEmbeddedBatchCloserRecordsOneHistoryEntryForWhatLanded +40 7 TestEmbeddedDependencyEditorAcceptsAnExternalTarget +40 7 TestEmbeddedDependencyEditorRelatesToAddLeavesItsSourceUnblocked +40 7 TestEmbeddedIssueOperationsUpdateMetadataReplaceClearsAndValidates +40 7 TestEmbeddedLenientOpenWarning_DataBehind +40 7 TestEmbeddedRelationsLeavesTheCallersRequestAlone +40 7 TestLoseVersionLeavesTheEpochTablesCommitted +40 7 TestMergeAndSettleWithStrategy_ResolvesDeclinedConflict -15 8 TestAddLabel -15 8 TestBuildDSN_NoDatabase -15 8 TestCleanGitRemoteCacheGarbage_NoCacheDir -15 8 TestDoltCommitResponseLossIsIndeterminate -15 8 TestEmbeddedBatchCloserClaimNextHydratesWhenSomethingClosed -15 8 TestEmbeddedBatchCloserClaimNextIsNilWhenNothingClosed -15 8 TestEmbeddedBatchCloserOutcomesMirrorItemsIndexForIndex -15 8 TestEmbeddedClaimerRefusalMessagesCarryTheirFragments -15 8 TestEmbeddedDependencyEditorAddMarksItsSourceInTheSameVerb -15 8 TestEmbeddedDependencyEditorRecordsOneHistoryEntryPerLandedRequest -15 8 TestEmbeddedGuardedUpdateMintsOnceAfterItsPatches -15 8 TestEmbeddedIssueOperationsUpdateFoldsMetadataIntoOneEvent -15 8 TestEmbeddedIssueOperationsUpdateStampsStartedAtOnceOnTheFirstInProgress -15 8 TestEmbeddedLenientOpenWarning_DataBehind -15 8 TestEmbeddedMergeAndSettleSkipsNonMemoryConfigConflict -15 8 TestEmbeddedMigrateRepairedDependenciesIDColumnCommitsAtomicallyWithVersion53_4690 -15 8 TestEmbeddedMigration0058HealsAlreadyAffectedDatabase -15 8 TestEmbeddedOpenReadOnly_SkipsGateAndMigrations -15 8 TestEmbeddedReaderListMaxRowsBoundaryIsLimitPlusOffset -15 8 TestEmbeddedReaderListReadyFlagCarriesTheAssigneeAndPriorityFilters -15 8 TestEmbeddedReaderReadyDeferredAndEphemeralGates -15 8 TestEmbeddedReaderReadyPageIsThePrefixOfTheUnboundedAnswerCountsIncluded -15 8 TestEmbeddedRelationsResolvesTheAnchorIDExactly -15 8 TestEmbeddedSQLCommitResponseLossIsIndeterminate -15 8 TestGetReadyWorkIncludeEphemeralAppliesWispFilters -15 8 TestHasRepository -15 8 TestLenientGateWarning_ComposedOutput -15 8 TestMergeAndSettleWithStrategy_EmptyStrategyMatchesMergeAndSettle -15 8 TestReclaimExpiredLeaseSurvivesRestartEmbedded -15 8 TestRemoteVerbPlainRemoteWithoutAuthPresentsNone -15 8 TestTransactionCleanupAfterSQLCommitIsIndeterminate +40 8 TestDeleterContract +40 8 TestEmbeddedDependencyEditorRoutesWispSourcedRemovalToTheWispPlane +40 8 TestEmbeddedMergeAndSettleDirtyWorkingSetSurvivesRefusedMerge +40 8 TestEmbeddedMintLeavesUpdatedAtWhereHistoryOffDoes +40 8 TestEmbeddedReaderGetBriefDepsProjectsTheDependencyRows +40 8 TestEmbeddedRelationsOrdersNeighborsFromBothPlanesTogether +40 8 TestEmbeddedReopenIssueCategorySemantics +40 8 TestGetIssueCommentsPageEmbedded +40 8 TestListWisps -15 9 TestCommenterContract -15 9 TestEmbeddedBatchCloserBackendFailureReturnsNoOutcomes -15 9 TestEmbeddedClaimerReclaimsItsOwnInProgressIssueWithoutWriting -15 9 TestEmbeddedClaimerRefusesIncompleteRequestsAndAnAbsentIDWithoutTouchingState -15 9 TestEmbeddedDependencyEditorMixedBatchWritesBothPlanes -15 9 TestEmbeddedDependencyEditorRefusesBlockingEdgeAcrossAWispHierarchy -15 9 TestEmbeddedDependencyEditorRelatesToAddLeavesItsSourceUnblocked -15 9 TestEmbeddedDependencyEditorRemovesOnlyTheNamedEdge -15 9 TestEmbeddedIgnoredMigration0019CreatesEventsForFreshClones -15 9 TestEmbeddedIssueOperationsCloseAndReopenAWisp -15 9 TestEmbeddedIssueOperationsUpdateClosedFieldsMatchClose -15 9 TestEmbeddedIssueOperationsUpdateInvalidIssueTypePreservesValidationSentinel -15 9 TestEmbeddedOpenForRemoteSync_OtherRefusalsStayFatal -15 9 TestEmbeddedReaderListLimitBoundaryUnderASortTheDatabaseCanExpress -15 9 TestEmbeddedReaderListReadyFlagRefusesAFilterItCannotCarry -15 9 TestEmbeddedReaderOffsetSkipsTheRowsBeforeThePage -15 9 TestEmbeddedReaderReadyPageWiderThanTheHydrationBatchIsStillThatPrefix -15 9 TestEventsSinceEmbedded -15 9 TestIgnoredCursorHealConvergesFromEveryCrashState -15 9 TestLegacyTrackedIgnoredCursorUnwedgesPull -15 9 TestMetadataCASContract -15 9 TestPromoteStillWorksWithCollisionGuard -15 9 TestReadyWorkWithMissingDeferredParentTables -15 9 TestUpdateMergeOps_DoltEngine +40 9 TestBumpEpochCarryingNeitherCarriesNorServesARowFromAFutureEpoch +40 9 TestEmbeddedDependencyEditorRefusesCrossPlaneCycle +40 9 TestEmbeddedDependencyEditorSameTypeReAddIsIdempotent +40 9 TestEmbeddedDependencyEditorSnapshotsTheRequest +40 9 TestEmbeddedMigration0058AddsOnlyMissingConstraintInMixedPopulation +40 9 TestEmbeddedReaderReadyPageWiderThanTheHydrationBatchIsStillThatPrefix +40 9 TestEmbeddedReadyClaimerHydratesOnlyItsBlocksEdgesIntoTheCardinalities +40 9 TestGetReadyWorkIncludeEphemeralExcludesNonReadyWisps +40 9 TestPristineEmbeddedDoltFixtureRelocatesPrefixes +40 9 TestUpdateMergeOps_DoltEngine -15 10 TestBuildDSN_SpacesInPath -15 10 TestCleanGitRemoteCacheGarbage_Throttled -15 10 TestCreateIssues -15 10 TestCreateRejectsCrossTableIDCollision -15 10 TestDeleterContract -15 10 TestEmbeddedBatchCloserAllIdempotentBatchLandsNothing -15 10 TestEmbeddedDepRekeyMergesFreshDuplicateEdges -15 10 TestEmbeddedDependencyEditorAddedEchoesTheRequestOrder -15 10 TestEmbeddedDependencyEditorRefusesCrossPlaneCycle -15 10 TestEmbeddedDoltStoreIssueLifecycleBuildsOperations -15 10 TestEmbeddedIgnoredMigration0023NoopsWithoutItsTables -15 10 TestEmbeddedIssueOperationsCreateClosedDerivesTheClosedStamp -15 10 TestEmbeddedIssueOperationsCreateEmptyIDPreservesParentAndReverseDependencies -15 10 TestEmbeddedIssueOperationsUpdateParentStagesBlockedStateAndRollsBackFailure -15 10 TestEmbeddedIssueOperationsUpdateRawMetadataTakesTheFunnelsValueShapes -15 10 TestEmbeddedMigrateStepCommitLeavesUntouchedUserDirt_4566 -15 10 TestEmbeddedReaderDoesNotMutateTheCallerRequest -15 10 TestEmbeddedReadyClaimerHydratesOnlyItsBlocksEdgesIntoTheCardinalities -15 10 TestEmbeddedReadyClaimerSkipsIneligibleFrontRows -15 10 TestEmbeddedRecomputeAllBlockedDirtyGraphIsTyped -15 10 TestEmbeddedTempRebuildIntermediatesNeverReachHistory -15 10 TestEmbeddedTransactionWispLifecyclePersistsDurableDependent -15 10 TestEpochContract -15 10 TestGetReadyWorkMoleculeFilter -15 10 TestHelperProcess -15 10 TestIgnoredCursorHealResumeRespectsOperatorOverride -15 10 TestReclaimRefusesForeignReplicaLease -15 10 TestRemoteEntryPointsUseVersionControlOps -15 10 TestTransactionCleanupBeforeSQLCommitRemainsDefinite -15 10 TestVersionReconcilerContract -15 10 TestWithPeerAuth_MissingRemoteFailsClosed +40 10 TestEmbeddedClaimerStampsStartedAtOnceAcrossTheTwoWritesItChoosesBetween +40 10 TestEmbeddedDependencyEditorRemoveIsIdempotent +40 10 TestEmbeddedIssueOperationsUpdateClaimCASAndTransferMatrix +40 10 TestEmbeddedReaderGetResolvesTheExactIDAcrossBothPlanes +40 10 TestEmbeddedReaderReadyEphemeralPageKeepsBothPlanesCountsAtItsBoundary +40 10 TestGraphCounterContract +40 10 TestIgnoredCursorHealRespectsOperatorOverride +40 10 TestRunInTransactionPostCommitStageFailureIsIndeterminate +40 10 TestVersionedHistoryOffMatchesPreStackGolden_Embedded +40 10 TestWithPeerAuth_WarnsWhenStoredPeerSuppressesAmbientPasswordAmbient -15 11 TestCycleDetectorContract -15 11 TestEmbeddedBatchCloserClaimFilterValueFailureIsARequestValidationFailure -15 11 TestEmbeddedBatchCloserIdempotentRecloseIsAPerItemSuccess -15 11 TestEmbeddedCheckedWrappersRouteTheirPreconditions -15 11 TestEmbeddedDependencyEditorAcceptsAForeignRepoTarget -15 11 TestEmbeddedDependencyEditorMixedBatchRefusalRollsBackBothPlanes -15 11 TestEmbeddedDependencyEditorRefusesASamePlaneEdgeClosingACrossPlaneCycle -15 11 TestEmbeddedDependencyEditorSameTypeReAddIsIdempotent -15 11 TestEmbeddedGetMergeBlockersOnAQuietStore -15 11 TestEmbeddedIssueOperationsCreateRoutesInfraTypesToWisps -15 11 TestEmbeddedIssueOperationsUpdateNotesConflictPreservesValidationSentinel -15 11 TestEmbeddedLenientOpenWarning_OtherRefusalsKeepBluntGuidance -15 11 TestEmbeddedPre0058RepairMarchesDriftedWispDependenciesToFinalShape -15 11 TestEmbeddedReaderGetDetailShapeMatchesTheSeededIssue -15 11 TestEmbeddedReaderListNaturalNumericIDSortTrimsAfterTheFetch -15 11 TestEmbeddedReopenCustomDoneFallsBackWhenNormalizedTableMissing -15 11 TestEmbeddedTransactionStandaloneWispMutationDoesNotPublishUnrelatedDurableChanges -15 11 TestGetDependentRecordsEmbedded -15 11 TestGetLabels -15 11 TestGetNextChildID -15 11 TestGraphCounterContract -15 11 TestLargeBatchApplyStatementCountsClassic40_Embedded -15 11 TestPristineEmbeddedDoltFixtureRelocatesPrefixes -15 11 TestReadyWorkPageTotal -15 11 TestUpdateIssueType +40 11 TestABumpUnderOneStoreIDMovesTheEpochSeenThroughEveryStoreID +40 11 TestEmbeddedBatchCreateFirstVersionCarriesCreationTimeEdges +40 11 TestEmbeddedClaimerRefusalMessagesCarryTheirFragments +40 11 TestEmbeddedGuardedUpdateMintsOnceAfterItsPatches +40 11 TestEmbeddedMergeAndSettleRefusesUnknownTable +40 11 TestEmbeddedReaderListMaxRowsBoundaryIsLimitPlusOffset +40 11 TestEmbeddedReadyClaimerRecordsOneHistoryEntryForAWin +40 11 TestEventsJournal_ActorMatrixOnEmbedded +40 11 TestMemoriesContract +40 11 TestWithPeerAuth_WarnsWhenStoredPeerSuppressesAmbientPasswordStored -15 12 TestBatchCreatorContract -15 12 TestDualWriteContract -15 12 TestEmbeddedClaimerTakesAnOpenIssueTheActorAlreadyHolds -15 12 TestEmbeddedDependencyEditorAttributesItsEventsToTheActor -15 12 TestEmbeddedDependencyEditorSnapshotsTheRequest -15 12 TestEmbeddedIgnoredSeriesConvergesWithFreshInitShape -15 12 TestEmbeddedIssueOperationsCreateWithDependenciesSettlesInTheCreatingTransaction -15 12 TestEmbeddedIssueOperationsRequestValuesAreNotMutated -15 12 TestEmbeddedMergeAndSettleMemoryConfigConflict -15 12 TestEmbeddedReaderGetOptionalRowListsAreOffByDefault -15 12 TestEmbeddedReaderGetResolvesTheExactIDAcrossBothPlanes -15 12 TestEmbeddedReaderReadyEphemeralPageKeepsBothPlanesCountsAtItsBoundary -15 12 TestEmbeddedReaderReadyParentScopesToItsTransitiveDescendants -15 12 TestEmbeddedReadyClaimerLeavesEphemeralRowsOutOfTheDefaultReadySet -15 12 TestEmbeddedRecomputeAllBlockedWiring -15 12 TestEmbeddedRelationsResolvesAWispAnchor -15 12 TestEmbeddedTransactionSameStatusDoesNotPublishUnrelatedDurableChanges -15 12 TestLargeBatchApplyStatementCounts712_Embedded -15 12 TestLifecycleUpdateContract -15 12 TestPreviewStoreRefusesLocalMetadataWrite -15 12 TestQuerierContract -15 12 TestReadyWorkPageTotalFilterMatrix -15 12 TestRemoteVerbsPresentStoredPeerCredentials -15 12 TestSearchWithMissingWispPlaneTables -15 12 TestWorkspaceConfigContract +40 12 TestCounterExcludeStatusAcceptsAWorkspaceCustomStatusWithoutIncludeInfra +40 12 TestEmbeddedClaimerAcceptsAConfiguredActiveStatusAndRefusesAConfiguredWipOne +40 12 TestEmbeddedClaimerRefusesAWispIDAsNotFound +40 12 TestEmbeddedDependencyEditorVersionsOnlyARealAddOrRemove +40 12 TestEmbeddedIgnoredMigration0023RepairsForkLineageJournalShape +40 12 TestEmbeddedIssueOperationsCreateUnderAParentMintsTheNextChildID +40 12 TestEmbeddedReadyClaimerAnswersTheQuestionReaderReadyLists +40 12 TestHistoryPresenceContract +40 12 TestLifecycleUpdateContract +40 12 TestReaderListExcludeStatusAcceptsAWorkspaceCustomStatus -15 13 TestCountsIncludeWispDependencies -15 13 TestDecryptPassword_ShortCiphertextClassifiesAsKeyMismatch -15 13 TestEmbeddedBatchCloserDurableHistoryNeverNamesAWisp -15 13 TestEmbeddedBatchCloserRequestValidationReturnsZeroResultAndChangesNothing -15 13 TestEmbeddedClaimerGrantsALiveLeaseOnTheRowItWonAndLeavesARefusedOneAlone -15 13 TestEmbeddedDependencyEditorRefusesAMissingLocalTarget -15 13 TestEmbeddedIssueOperationsUpdateAllScalarAndPointerFieldsReportChanged -15 13 TestEmbeddedIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses -15 13 TestEmbeddedIssueOperationsUpdateMetadataReplaceClearsAndValidates -15 13 TestEmbeddedIssueOperationsUpdateRefusesATypeOutsideTheWorkspaceVocabulary -15 13 TestEmbeddedIssueOperationsUpdateWritesEveryScalarPatchField -15 13 TestEmbeddedMigrateConvergesUnderConcurrentInterruptedRetries_4566 -15 13 TestEmbeddedMigration0058CleansOrphanedAndInvalidWispDependenciesRowsBeforeAddingConstraints -15 13 TestEmbeddedMigration0062FlipsEventsToIgnoredPlane -15 13 TestEmbeddedReaderListIncludeEphemeralMergesThePlanesIntoOneOrder -15 13 TestEmbeddedReaderListKeysetPositionNarrowsWithoutReplacingTheOtherPredicates -15 13 TestEmbeddedReaderListRejectsATypeOutsideTheWorkspaceVocabulary -15 13 TestEmbeddedReaderListStatusAcceptsACommaSeparatedORSet -15 13 TestEmbeddedReaderReadySetOwnsItsStatusPinnedAndTemplateDecisions -15 13 TestEmbeddedRelationsRefusesAnUnusableTypeFilter -15 13 TestEmbeddedRelationsRefusesTheZeroDirection -15 13 TestEventsJournal_EmbeddedConcurrentGaplessNoDup -15 13 TestExternalCapabilityBlocksEmbeddedReadyAndAppearsInTree -15 13 TestIgnoredCursorHealRespectsOperatorOverride -15 13 TestLegacyTrackedIgnoredCursorHealsOnOpen -15 13 TestSweeperContract +40 13 TestEmbeddedDepRekeyConvergesRenameChain +40 13 TestEmbeddedDependencyEditorAppliesParentChildBeforeBlockingEdges +40 13 TestEmbeddedDependencyEditorRefusesAGhostSource +40 13 TestEmbeddedIssueOperationsCreateParentChildRecomputesWaitsForClosure +40 13 TestEmbeddedIssueOperationsUpdateClaimPatchAppliesAfterClaim +40 13 TestEmbeddedIssueOperationsUpdateFoldsMetadataIntoOneEvent +40 13 TestEmbeddedPre0058RepairMarchesDriftedWispDependenciesToFinalShape +40 13 TestEmbeddedRelationsDirectionSelectsTheInverseGraph +40 13 TestGraphWalkPlansHonorJoinHints -15 14 TestAddDependency -15 14 TestCounterContract -15 14 TestCountsWithMissingWispPlaneTables -15 14 TestEmbeddedBlockedRecheckFailureKeepsTheWrite -15 14 TestEmbeddedDepRekeyRefusesToWriteIntoDirtyDependencies -15 14 TestEmbeddedDependencyEditorRecordsNoHistoryForAnAllEphemeralRequest -15 14 TestEmbeddedDirtyTablesGate_BlocksReopenThenWorkingSetReconcileRecovers -15 14 TestEmbeddedEveryAcceptedLifecycleMutationMintsOneVersion -15 14 TestEmbeddedIssueOperationsClaimLeavesBlockedStateAlone -15 14 TestEmbeddedIssueOperationsUpdateIssuePlaneOnlyRefusesWisps -15 14 TestEmbeddedIssueOperationsUpdateLabelPatchValueRules -15 14 TestEmbeddedMergeAndSettleDirtyWorkingSetSurvivesRefusedMerge -15 14 TestEmbeddedOpenForReadOnlyCommand_LenientGate -15 14 TestEmbeddedReaderListBriefDropsTheFreeFormTextAndNothingElse -15 14 TestEmbeddedReaderListKeysetWalkOverAnOversizedGroupLosesNothingAndRepeatsNothing -15 14 TestEmbeddedReadyClaimerClaimsAnEphemeralRowTheFilterAdmits -15 14 TestEmbeddedReadyClaimerRejectsLimitOffsetBriefAndEmptyActor -15 14 TestEventsJournalPruneWhenEveryRowIsOlderThanTheCutoff -15 14 TestMergeWithStrategy_TheirsResolvesAndCommits -15 14 TestMerge_NoStrategyStillErrorsWithEscapeHatchHint -15 14 TestOpenAfterCloseCreatesNewStore -15 14 TestOpenDifferentDirsReturnsDifferentStores -15 14 TestPruneEventsBatchDeletesTheLowestSeqsOnly -15 14 TestReadyCounterContract -15 14 TestUnknownProvenanceLeaseStaysReclaimable +40 14 TestBatchCreatorContract +40 14 TestBlockingAnnotatorContract +40 14 TestCountsIncludeWispDependencies +40 14 TestEmbeddedIssueOperationsPersistenceRollbackWispAndDetachedResults +40 14 TestEmbeddedOpenForRemoteSync_DataBehind +40 14 TestEmbeddedReaderOffsetSkipsTheRowsBeforeThePage +40 14 TestEmbeddedReaderReadyDefaultTypeExclusionsYieldToAnExplicitType +40 14 TestEmbeddedReadyClaimerClaimsTheFrontRowAndReturnsThePostClaimState +40 14 TestEmbeddedReadyClaimerDoesNotMutateTheCallerRequest +40 14 TestHeartbeatIssueCommitsARefusalOnlyWhenItReadTheIssueEmbedded +40 14 TestHistory_NullTextColumns -15 15 TestCreateIssue -15 15 TestEdgeReaderContract -15 15 TestEmbeddedBatchCloserAllRefusedBatchRecordsNoHistory -15 15 TestEmbeddedBatchCloserDuplicateItemRecloseAtItsOwnIndex -15 15 TestEmbeddedBatchCloserRecordsOneHistoryEntryForWhatLanded -15 15 TestEmbeddedBlockedRecheckRecordsUnblockingWrites -15 15 TestEmbeddedClaimerAcceptsAConfiguredActiveStatusAndRefusesAConfiguredWipOne -15 15 TestEmbeddedDependencyEditorAcceptsATypeOutsideTheConstants -15 15 TestEmbeddedDependencyEditorAcceptsAnExternalTarget -15 15 TestEmbeddedDependencyEditorRefusesSelfDependencyWithTheProbeSkipped -15 15 TestEmbeddedDependencyEditorRepeatsWithinOneRequestCollapse -15 15 TestEmbeddedIssueOperationsUpdateLabelPatchOrdering -15 15 TestEmbeddedMigrateSelfHealsAfterMidPassFault_4566 -15 15 TestEmbeddedMoveIssuePersistenceEphemeralNoHistorySmoke -15 15 TestEmbeddedOpenForRemoteSync_DataBehind -15 15 TestEmbeddedReadyClaimerEmptyFrontIsNormal -15 15 TestEmbeddedRelationsSeparatesNoNeighborsFromNoSuchIssue -15 15 TestEmbeddedTransactionStandaloneWispLifecyclePersistsWithoutDoltCommit -15 15 TestEventsJournalPruneNeverSplitsASkewedPair -15 15 TestEventsJournal_ActorMatrixOnEmbedded -15 15 TestGetIssueCommentsPageEmbedded -15 15 TestGetReadyWorkIncludeEphemeralExcludesNonReadyWisps -15 15 TestIgnoredCursorHealIsIdempotent -15 15 TestReadyWorkStatementBudget -15 15 TestReleaserContract +40 15 TestCreateIssuesRejectStaleUpserts +40 15 TestDecryptPassword_ShortCiphertextClassifiesAsKeyMismatch +40 15 TestEmbeddedGetMergeBlockersOnAQuietStore +40 15 TestEmbeddedIgnoredMigration0023NoopsWithoutItsTables +40 15 TestEmbeddedIssueOperationsRequestValuesAreNotMutated +40 15 TestEmbeddedReaderReadyBriefDropsTheFreeFormTextAndNothingElse +40 15 TestEmbeddedRelationsFiltersByAnOpenTypeVocabulary +40 15 TestGetIssue +40 15 TestLegacyTrackedIgnoredCursorHealsOnOpen +40 15 TestMoleculeContract +40 15 TestReadyWorkPageTotalFilterMatrix + +40 16 TestDescendantWalkReachesEveryTargetKindAndStopsOnCycles +40 16 TestEmbeddedDependencyEditorAddedEchoesTheRequestOrder +40 16 TestEmbeddedDependencyEditorRemovesOnlyTheNamedEdge +40 16 TestEmbeddedReaderDoesNotMutateTheCallerRequest +40 16 TestEmbeddedReaderListLimitBoundaryUnderASortTheDatabaseCanExpress +40 16 TestEmbeddedRenameKeepsDependencyIDsDeterministic +40 16 TestExternalCapabilityBlocksEmbeddedReadyAndAppearsInTree +40 16 TestGetReadyWorkIncludeEphemeralAppliesWispFilters +40 16 TestMergeWithStrategy_OursKeepsLocal +40 16 TestWithPeerAuth_DivergedRemoteURLFailsClosed + +40 17 TestAddDependency +40 17 TestEmbeddedBatchCloserWispItemClosesAndEarnsTheClaim +40 17 TestEmbeddedDependencyEditorSameTypeReAddWithChangedThreadMintsOneVersion +40 17 TestEmbeddedIssueOperationsUpdateIssuePlaneOnlyRefusesWisps +40 17 TestEmbeddedIssueOperationsUpdateStatusCrossingSettlesAConditionalBlocksDepender +40 17 TestEmbeddedReaderListRejectsATypeOutsideTheWorkspaceVocabulary +40 17 TestEmbeddedReadyClaimerLeasesADurableWinButNotAnEphemeralOne +40 17 TestHeartbeatMatchesActorAcrossSpellingEmbedded +40 17 TestStatsReporterContract +40 17 TestVersionReconcilerContract + +40 18 TestCreateBatchParticipationGeneration +40 18 TestEmbeddedBatchCloserIdempotentRecloseIsAPerItemSuccess +40 18 TestEmbeddedDependencyEditorMixedBatchWritesBothPlanes +40 18 TestEmbeddedIssueOperationsUpdateRawMetadataTakesTheFunnelsValueShapes +40 18 TestEmbeddedMergeAndSettleMemoryConfigConflict +40 18 TestEmbeddedReaderListIncludeEphemeralMergesThePlanesIntoOneOrder +40 18 TestEmbeddedReaderListParentReachesEveryDescendantAndOnlyItsOwn +40 18 TestMetadataCASContract +40 18 TestOpenDifferentDirsReturnsDifferentStores +40 18 TestPromoteClearsNoHistory +40 18 TestRemoteVerbPlainRemoteWithoutAuthPresentsNone + +40 19 TestEmbeddedDependencyEditorRetypeRefusalLeavesTheOriginalEdge +40 19 TestEmbeddedIssueOperationsUpdateInvalidIssueTypePreservesValidationSentinel +40 19 TestEmbeddedMigration0062FlipsEventsToIgnoredPlane +40 19 TestEmbeddedReaderListMaxRowsIsHonored +40 19 TestEmbeddedRelationsAnswersInThePinnedOrder +40 19 TestIgnoredCursorHealConvergesFromEveryCrashState +40 19 TestOpenAfterCloseCreatesNewStore +40 19 TestOpenReturnsCachedStore +40 19 TestParticipationGenerationFixtureKitIsWired +40 19 TestRemoteVerbsPresentStoredPeerCredentials +40 19 TestRenameLabelMintsOneVersionPerTouchedBead + +40 20 TestBumpEpochCarryingCarriesOnlyTheLineageHoldingTheNewestRow +40 20 TestCreateIssue +40 20 TestEmbeddedCheckedWrappersRouteTheirPreconditions +40 20 TestEmbeddedIssueOperationsCreateRoutesInfraTypesToWisps +40 20 TestEmbeddedMigrateStepCommitLeavesUntouchedUserDirt_4566 +40 20 TestEmbeddedOpenReadOnly_SkipsGateAndMigrations +40 20 TestEmbeddedReadyClaimerClaimsAnEphemeralRowTheFilterAdmits +40 20 TestEventsJournalRestartAndRetentionBoundary +40 20 TestForeignSkipDetailIsBounded +40 20 TestHeartbeatRejectsWispEmbedded +40 20 TestIgnoredCursorHealNeverResurrectsRolledBackVersions + +40 21 TestBumpEpochCarryingCarriesTheLiveRowsOfEveryStoreInTheDatabase +40 21 TestCreateRejectsCrossTableIDCollision +40 21 TestEmbeddedBatchCloserItemsAnswerToTheCloseGuards +40 21 TestEmbeddedDependencyEditorAcceptsATypeOutsideTheConstants +40 21 TestEmbeddedIssueOperationsUpdateParentStagesBlockedStateAndRollsBackFailure +40 21 TestEmbeddedMigration0047DelegatesToSplitTargetRepairAndConvergesThroughIgnoredChain +40 21 TestEmbeddedRelationsLeavesAnExternalTargetOutOfTheAnswer +40 21 TestEmbeddedRemoteMigrateGate_BlocksReopen +40 21 TestEmbeddedRoleFixtureKitCountHistoryMovesWithACommit +40 21 TestEmbeddedTransactionStandaloneWispLifecyclePersistsWithoutDoltCommit +40 21 TestLargeBatchApplyWallClock_Embedded + +40 22 TestEdgeReaderContract +40 22 TestEmbeddedDepRekeyAbortLeavesMarkerUnrecorded +40 22 TestEmbeddedDepRekeyRefusesToWriteIntoDirtyDependencies +40 22 TestEmbeddedDependencyEditorRefusesSelfDependencyWithTheProbeSkipped +40 22 TestEmbeddedReaderListStatusAcceptsACommaSeparatedORSet +40 22 TestEmbeddedReaderReadyLimitBoundary +40 22 TestEventsAutoPruneKeepsAnUnboundedJournalUnbounded +40 22 TestEventsJournalPruneNeverSplitsASkewedPair +40 22 TestLargeBatchApplyStatementCounts356_Embedded +40 22 TestLeaseLifecycleEmbedded +40 22 TestPolicyBlockingAnnotatorForeignOpensAreSublinear + +40 23 TestAsOfReadContract +40 23 TestEmbeddedBatchCloserBackendFailureReturnsNoOutcomes +40 23 TestEmbeddedBatchCloserClaimNextHydratesWhenSomethingClosed +40 23 TestEmbeddedDependencyEditorAcceptsBlockingAcrossIssueTypes +40 23 TestEmbeddedDependencyEditorRecordsNoHistoryForAnAllEphemeralRequest +40 23 TestEmbeddedMigrateConvergesUnderConcurrentInterruptedRetries_4566 +40 23 TestEmbeddedReaderListEmptyPageIsWellFormed +40 23 TestEmbeddedReadyClaimerFencesTheClaimByEveryLabelSetAndTheParentItWasGiven +40 23 TestEmbeddedRoleFixtureKitHooksAreUsable +40 23 TestEventsAutoPruneBoundsTheJournalToTheFloors +40 23 TestJournalContract + +40 24 TestBootstrapperContract +40 24 TestEmbeddedBatchCloserOutcomesMirrorItemsIndexForIndex +40 24 TestEmbeddedClaimerReclaimsAcrossSpellingWithoutWriting +40 24 TestEmbeddedConfigCommitStagesConfig +40 24 TestEmbeddedIgnoredSeriesConvergesWithFreshInitShape +40 24 TestEmbeddedIssueOperationsCreateWithDependenciesSettlesInTheCreatingTransaction +40 24 TestEmbeddedMigrateSelfHealsAfterMidPassFault_4566 +40 24 TestEmbeddedReaderListQueryMatchesTheTitleOrTheID +40 24 TestEmbeddedReaderListWispTypeNarrowsTheAdmittedPlaneRatherThanAdmittingIt +40 24 TestIgnoredCursorHealResumeRespectsOperatorOverride +40 24 TestLargeBatchApplyStatementCountsClassic40_Embedded +40 24 TestReopenIssue + +40 25 TestBatchGetterContract +40 25 TestDatabases +40 25 TestDualWriteFixtureKitIsWired +40 25 TestEmbeddedBatchCloserClaimNextIsNilWhenNothingClosed +40 25 TestEmbeddedIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses +40 25 TestEmbeddedReadyClaimerLeavesEphemeralRowsOutOfTheDefaultReadySet +40 25 TestEmbeddedReadyClaimerRejectsLimitOffsetBriefAndEmptyActor +40 25 TestGetDependentRecordsForIssuesEmbedded +40 25 TestHeartbeaterContract +40 25 TestIgnoredCursorHealIsIdempotent +40 25 TestIsBlockedBatchEmbedded +40 25 TestReadyWorkPageTotal +40 25 TestWithPeerAuth_RestoresAbsentEnv + +40 26 TestEmbeddedIssueOperationsCreateClosedDerivesTheClosedStamp +40 26 TestEmbeddedMigration0058CleansOrphanedAndInvalidWispDependenciesRowsBeforeAddingConstraints +40 26 TestEmbeddedOpenForReadOnlyCommand_LenientGate +40 26 TestEmbeddedReaderListReadyFlagCarriesTheAssigneeAndPriorityFilters +40 26 TestEmbeddedReaderReadyParentScopesToItsTransitiveDescendants +40 26 TestEmbeddedReadyClaimerSkipsIneligibleFrontRows +40 26 TestEmbeddedRecomputeAllBlockedDirtyGraphIsTyped +40 26 TestEmbeddedRelationsRefusesTheZeroDirection +40 26 TestHookFiringStoreCreateIssuesFiresDependencyUpdatesFromEmbeddedStore +40 26 TestReclaimAnyReplicaOverride +40 26 TestWithPeerAuth_EnvFallbackDoesNotObservePeerCredentials + +40 27 TestEmbeddedBatchCloserDurableHistoryNeverNamesAWisp +40 27 TestEmbeddedBatchCloserRequestValidationReturnsZeroResultAndChangesNothing +40 27 TestEmbeddedDependencyEditorAcceptsADiamond +40 27 TestEmbeddedDependencyEditorAddMarksItsSourceInTheSameVerb +40 27 TestEmbeddedMigration0058HealsAlreadyAffectedDatabase +40 27 TestEmbeddedReaderGetOptionalRowListsAreOffByDefault +40 27 TestEmbeddedRelationsRefusesATypeFilterOverTheColumnLength +40 27 TestEventsJournalReadRefusesAnInteriorHole +40 27 TestPartitionWispIDs +40 27 TestRemoteGitDataRefOnEngine +40 27 TestSweeperContract + +40 28 TestBumpEpochCarryingDoesNotCarryALostLineage +40 28 TestEmbeddedBatchCloserForceBypassesOnlyClosePolicy +40 28 TestEmbeddedBatchCloserSettlesTheDependersOfWhatItClosed +40 28 TestEmbeddedClaimerClaimsAnUnassignedOpenIssueAndAnswersTheBareRow +40 28 TestEmbeddedClaimerReclaimsItsOwnInProgressIssueWithoutWriting +40 28 TestEmbeddedClaimerTakesAPoolAssignedIssueButRefusesAForeignHolder +40 28 TestEmbeddedIssueOperationsUpdateLabelPatchValueRules +40 28 TestEmbeddedIssueOperationsUpdateRefusesATypeOutsideTheWorkspaceVocabulary +40 28 TestEmbeddedReaderListReadyFlagAnswersTheBlockerAwareSet +40 28 TestRenameLabel +40 28 TestUpdateIssueType +40 28 TestWithPeerAuth_RestoresEnvWhenCallbackFails + +40 29 TestEmbeddedBatchCloserClaimFilterValueFailureIsARequestValidationFailure +40 29 TestEmbeddedBatchCloserClaimNextIsNilWhenTheFrontIsEmpty +40 29 TestEmbeddedDepRekeyMergesFreshDuplicateEdges +40 29 TestEmbeddedDependencyEditorRecordsOneHistoryEntryPerLandedRequest +40 29 TestEmbeddedMergeAndSettleMetadataConflict +40 29 TestEmbeddedReaderListDefaultExclusionsAndTheirOverrides +40 29 TestEmbeddedReaderListTimeBoundsAreStrictAndWholeSecond +40 29 TestEmbeddedReaderReadySetOwnsItsStatusPinnedAndTemplateDecisions +40 29 TestEmbeddedTransactionSameStatusDoesNotPublishUnrelatedDurableChanges +40 29 TestEventsJournalAccessor +40 29 TestLeaseReclaimerContract +40 29 TestLifecycleCreateContract + +40 30 TestCounterContract +40 30 TestCycleDetectorContract +40 30 TestEmbeddedClaimerTakesAnOpenIssueTheActorAlreadyHolds +40 30 TestEmbeddedCommitToleratesNothingToCommit +40 30 TestEmbeddedEveryAcceptedLifecycleMutationMintsOneVersion +40 30 TestEmbeddedIssueOperationsUpdateClaimConflictCarriesTheLosingState +40 30 TestEmbeddedIssueOperationsUpdateStampsStartedAtOnceOnTheFirstInProgress +40 30 TestEmbeddedReaderReadySortPoliciesOrderTheSameRows +40 30 TestEmbeddedTransactionStandaloneWispMutationDoesNotPublishUnrelatedDurableChanges +40 30 TestLegacyTrackedIgnoredCursorUnwedgesPull +40 30 TestUpdateMergeOps_DoltEngine_TwoIssues + +40 31 TestBumpEpochCarryingWritesOneCarryRowPerLiveIDNamingTheLineageRoot +40 31 TestDualWriteContract +40 31 TestEmbeddedDependencyEditorAcceptsAForeignRepoTarget +40 31 TestEmbeddedDependencyEditorMaintainsBlockedStateAcrossPlanes +40 31 TestEmbeddedDependencyEditorWritesTheTargetIntoItsTypedColumn +40 31 TestEmbeddedMigrateConsent_BehindAndDirtyWorkingSetReconcileRecovers +40 31 TestEmbeddedReaderListPriorityKeysetWalkOverAnOversizedEqualKeyRunLosesNothingAndRepeatsNothing +40 31 TestEmbeddedTransactionWispLifecyclePersistsDurableDependent +40 31 TestEventsSinceEmbedded +40 31 TestGetLabels +40 31 TestReadyCounterContract +40 31 TestWithPeerAuth_KeyMismatchFailsClosed + +40 32 TestCurrentAddressForNeverReseedsAnAbsentStoreEpochRow +40 32 TestEmbeddedClaimerGrantsALiveLeaseOnTheRowItWonAndLeavesARefusedOneAlone +40 32 TestEmbeddedDependencyEditorRefusesAMissingLocalTarget +40 32 TestEmbeddedDirtyTablesGate_BlocksReopenThenWorkingSetReconcileRecovers +40 32 TestEmbeddedIgnoredMigration0019CreatesEventsForFreshClones +40 32 TestEmbeddedIssueOperationsCreateReverseNonBlockingStagesConcreteTables +40 32 TestEmbeddedReadyClaimerEmptyFrontIsNormal +40 32 TestEmbeddedRecomputeAllBlockedWiring +40 32 TestEventsJournal_EmbeddedConcurrentGaplessNoDup +40 32 TestGetNextChildID +40 32 TestRemoteVerbPlainRemoteKeepsAmbientEnv +40 32 TestWithPeerAuth_MissingRemoteFailsClosed + +40 33 TestEmbeddedBatchCloserDuplicateItemRecloseAtItsOwnIndex +40 33 TestEmbeddedDependencyEditorClosedChildAddSatisfiesAnAnyChildrenGate +40 33 TestEmbeddedDependencyEditorValidationRefusalsWriteNothing +40 33 TestEmbeddedIgnoredMigration0023NoopsOnHealthyWorkspace +40 33 TestEmbeddedMoveIssuePersistenceEphemeralNoHistorySmoke +40 33 TestEmbeddedRelationsResolvesTheAnchorIDExactly +40 33 TestEmbeddedSyncCommitsConfigBeforeMerge +40 33 TestEventsAutoPruneThrottleSkipsTheSecondPass +40 33 TestFirstMintLeavesTheEpochTablesCommitted +40 33 TestGetDependentRecordsEmbedded +40 33 TestPruneEventsBatchDeletesTheLowestSeqsOnly +40 33 TestTreeWalkerContract + +40 34 TestAddLabel +40 34 TestBumpEpochCarryingLeavesTheEpochTablesCommitted +40 34 TestDecryptPassword_KeyMismatchNamesTheLocalKey +40 34 TestEmbeddedBlockedRecheckRecordsUnblockingWrites +40 34 TestEmbeddedDependencyEditorAttributesItsEventsToTheActor +40 34 TestEmbeddedDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp +40 34 TestEmbeddedIssueOperationsCreateAggregatesRelations +40 34 TestEmbeddedReaderReadyDeferredAndEphemeralGates +40 34 TestEmbeddedReaderReadyPageIsThePrefixOfTheUnboundedAnswerCountsIncluded +40 34 TestMergeWithStrategy_TheirsResolvesAndCommits +40 34 TestQuerierContract +40 34 TestReadyWorkStatementBudget + +40 35 TestEmbeddedBatchCloserAllIdempotentBatchLandsNothing +40 35 TestEmbeddedClaimIssueWrapperClaimsTheWispPlane +40 35 TestEmbeddedDependencyEditorGateScopeFollowsTheEdgeType +40 35 TestEmbeddedDependencyEditorRefusesASamePlaneEdgeClosingACrossPlaneCycle +40 35 TestEmbeddedDependencyEditorRepeatsWithinOneRequestCollapse +40 35 TestEmbeddedIssueOperationsUpdateAllScalarAndPointerFieldsReportChanged +40 35 TestEmbeddedIssueOperationsUpdateWritesEveryScalarPatchField +40 35 TestMerge_NoStrategyStillErrorsWithEscapeHatchHint +40 35 TestReadEventsAutoPruneStateResolvesBothHalvesInOneQuery +40 35 TestReadyWorkWithMissingDeferredParentTables +40 35 TestReclaimExpiredLeaseSurvivesRestartEmbedded + +40 36 TestBumpEpochCarryingFailsAndRollsBackWhenARowAlreadyExistsAtTheNewEpoch +40 36 TestCommenterContract +40 36 TestConcurrentOpenReturnsCached +40 36 TestEmbeddedBatchCloserAllRefusedBatchRecordsNoHistory +40 36 TestEmbeddedDependencyEditorRefusalWritesNothing +40 36 TestEmbeddedDependencyEditorSkipPerEdgeCycleCheckDropsOnlyTheProbe +40 36 TestEmbeddedMigration0057ConvertsTextEventsColumnsToLongtext +40 36 TestEmbeddedReaderListReadyFlagRefusesAFilterItCannotCarry +40 36 TestEmbeddedRelationsRefusesAnUnusableTypeFilter +40 36 TestGetReadyWorkMoleculeFilter +40 36 TestReleaserContract +40 36 TestSchemaAfterInit + +40 37 TestEmbeddedBatchCloserClaimNextSeesAnUnblockingFromItsOwnBatch +40 37 TestEmbeddedBatchCloserOutcomeSnapshotIsTheDocumentedShape +40 37 TestEmbeddedDependencyEditorRecordsOneHistoryEntryForAMixedPlaneRequest +40 37 TestEmbeddedDependencyEditorRefusesACycleThroughAParentChildHop +40 37 TestEmbeddedDependencyEditorRemoveUnmarksItsSourceAndDescendants +40 37 TestEmbeddedIssueOperationsCreateEmptyIDPreservesParentAndReverseDependencies +40 37 TestEmbeddedLenientOpenWarning_OtherRefusalsKeepBluntGuidance +40 37 TestEmbeddedMergeAndSettleReportsOperatorConflicts +40 37 TestEmbeddedReaderListBriefDropsTheFreeFormTextAndNothingElse +40 37 TestEmbeddedReaderListNaturalNumericIDSortTrimsAfterTheFetch +40 37 TestEpochWritesReportAnUnpublishedCommitAsIndeterminate +40 37 TestIgnoredCursorHealRespectsOverrideUnderBroaderPattern + +40 38 TestCreateIssues +40 38 TestEmbeddedClaimerRefusesABuiltInIneligibleStatusWithTheStateThatRefusedIt +40 38 TestEmbeddedDependencyEditorRefusesBlockingEdgeAcrossItsOwnHierarchy +40 38 TestEmbeddedIssueOperationsUpdateClosedFieldsMatchClose +40 38 TestEmbeddedIssueOperationsUpdateNotesConflictPreservesValidationSentinel +40 38 TestEmbeddedReaderGetDetailShapeMatchesTheSeededIssue +40 38 TestEmbeddedReaderListCountsAreBlocksOnlyWhereGetCountsEveryEdge +40 38 TestEmbeddedReaderListKeysetWalkOverAnOversizedGroupLosesNothingAndRepeatsNothing +40 38 TestEmbeddedTempRebuildIntermediatesNeverReachHistory +40 38 TestEventsJournalPruneWhenEveryRowIsOlderThanTheCutoff +40 38 TestPolicyBlockingAnnotatorBatchEqualsPerItem +40 38 TestWithPeerAuth_ConcurrentPeersDoNotMixCredentials + +40 39 TestDualWriteContractFlagOff +40 39 TestEmbeddedBatchCloserPerItemRefusalIsAResultAndSurvivorsCommit +40 39 TestEmbeddedBlockedRecheckFailureKeepsTheWrite +40 39 TestEmbeddedDependencyEditorMixedBatchRefusalRollsBackBothPlanes +40 39 TestEmbeddedIssueOperationsClaimLeavesBlockedStateAlone +40 39 TestEmbeddedMigrateRepairedDependenciesIDColumnCommitsAtomicallyWithVersion53_4690 +40 39 TestEmbeddedReaderListSkipCountsDropsTheCardinalitiesAndNothingElse +40 39 TestEmbeddedRelationsResolvesAWispAnchor +40 39 TestParticipationGenerationFence +40 39 TestPreviewStoreRefusesLocalMetadataWrite +40 39 TestReclaimRefusesForeignReplicaLease +40 39 TestWorkspaceConfigContract + +40 40 TestCountsWithMissingWispPlaneTables +40 40 TestEmbeddedBatchCloserDoesNotMutateTheCallerRequest +40 40 TestEmbeddedBlockedRecheckSettlesWhatTheWriteRecorded +40 40 TestEmbeddedDepRekeyRepairsHalfRekeyedDuplicateEdge +40 40 TestEmbeddedDependencyEditorRefusesBlockingEdgeAcrossAWispHierarchy +40 40 TestEmbeddedDependencyEditorRoutesWispSourcedEdgeToTheWispPlane +40 40 TestEmbeddedDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion +40 40 TestEmbeddedIssueOperationsUpdateStatusCrossingSettlesDependers +40 40 TestEmbeddedOpenForRemoteSync_OtherRefusalsStayFatal +40 40 TestEmbeddedRelationsSeparatesNoNeighborsFromNoSuchIssue +40 40 TestEmbeddedReopenCustomDoneFallsBackWhenNormalizedTableMissing diff --git a/.github/scripts/embedded-test-shard.sh b/.github/scripts/embedded-test-shard.sh index a89757e69..3b7bdc7e2 100755 --- a/.github/scripts/embedded-test-shard.sh +++ b/.github/scripts/embedded-test-shard.sh @@ -3,7 +3,7 @@ # # Usage: embedded-test-shard.sh # -# Discovers all TestEmbedded* top-level functions from cmd/bd/*_embedded_test.go. +# Discovers all TestEmbedded* top-level functions in cmd/bd/*_test.go. # Tests listed in embedded-cmd-test-shards.txt for the requested shard count use # that committed assignment; newly-added tests fall back to hash(name) % total. # Runs the matching subset using the pre-built test binary at @@ -33,8 +33,12 @@ fi SHARD_INDEX=$(( SHARD_NUMBER - 1 )) MANIFEST="${BEADS_TEST_SHARD_MANIFEST:-.github/scripts/embedded-cmd-test-shards.txt}" -# Discover all top-level TestEmbedded* functions. -ALL_TESTS=$(grep -rh '^func TestEmbedded' cmd/bd/*_embedded_test.go \ +# Discover all top-level TestEmbedded* functions across every cmd/bd test +# file, by name rather than by file glob (as proxied-test-shard.sh does): a +# test gated on BEADS_TEST_EMBEDDED_DOLT runs in this lane or in none, wherever +# it lives. scripts/embedded_lane_coverage_test.go fails on a gated test this +# selection misses. +ALL_TESTS=$(grep -rh '^func TestEmbedded' cmd/bd/*_test.go \ | sed 's/func \(TestEmbedded[A-Za-z0-9_]*\).*/\1/' \ | sort -u) diff --git a/.github/scripts/proxied-cmd-test-shards.txt b/.github/scripts/proxied-cmd-test-shards.txt index 59ca95906..fca167226 100644 --- a/.github/scripts/proxied-cmd-test-shards.txt +++ b/.github/scripts/proxied-cmd-test-shards.txt @@ -2,233 +2,12 @@ # # Format: # -# 15-shard split, bin-packed longest-processing-time-first by -# estimated cost (bd-init count; per-init migration chains dominate), as of -# the test set that existed when this block was last generated. -# Regenerating it (scripts/ci/gen_proxied_shard_manifest.py 15 --write) is -# deliberately NOT part of normal maintenance: this block is frozen for -# pr-risk.yml's/main.yml's legacy fork/push jobs (see engdocs/TESTING.md), -# so every TestProxiedServer*/TestServerMode* function added since it was -# last generated hash-distributes via proxied-test-shard.sh (cksum(name) % -# total) instead of being explicitly listed here. Only reweight it on -# purpose, and expect the shard assignments below to change substantially -# if you do (a fresh run packs every currently-discovered test, not just -# the ones already listed here). -# -# Deliberate exception (Oct 2026): four tests that had been hash-placed -# onto the two shards closest to the 15m -test.timeout are pinned here -# by hand, onto shards whose measured CI job time was lowest; nothing -# that was already listed moved. TestProxiedServerStorageClass and -# TestProxiedServerServeRefusesAStaleCheckpointWithGone (discovered -# from #7129 on) had hashed onto shard 5, which then hit the timeout on -# most Main runs; pinning them returns shard 5 to its earlier test set. -# TestProxiedServerListComments and -# TestProxiedServerServeRefusesAStreamOnADisabledJournal had hashed -# onto shard 3, which runs within about a minute of the timeout. An -# incremental --write keeps pinned lines where they are; a pin is a -# reviewed choice, not a regeneration of this block. -# -# TestProxiedServerOutageReconnectAcceptanceMatrix is pinned to shard 1 -# (the lightest in recent Main runs, ~6.5 min) instead of hashing onto -# shard 14, which already runs ~13.5 min of the 15m timeout. These jobs -# have no socat, so today it skips here; the pin keeps shard 14 safe if -# socat is ever installed. -# -# This file is generated: notes added here are erased by the next -# regeneration. Add them to the generator instead. Known blind spots -# of the cost proxy (it counts inits, not the work done per init): -# -# TestProxiedServerListSortRetiresTheWalk is the most expensive -# entry and one of the cheapest-looking: off a single init it seeds -# 1400 rows and walks the listing three ways. It is the measurement -# behind the claim that sort=priority retires the client-side walk, -# so it has to run on PRs. -# -# TestProxiedServerServeReadParity is the CLI/HTTP read parity -# oracle, the behavioural half of the anti-drift claim. It being in -# this lane, and this lane being required by the PR Risk CI gate, -# is what makes that claim enforced on PRs rather than asserted in -# a doc comment. - -15 1 TestProxiedServerBlocked -15 1 TestProxiedServerCompactDolt -15 1 TestProxiedServerCreate -15 1 TestProxiedServerDep2 -15 1 TestProxiedServerDepConcurrent -15 1 TestProxiedServerListSortRetiresTheWalk -15 1 TestProxiedServerMolLastActivity -15 1 TestProxiedServerOutageReconnectAcceptanceMatrix -15 1 TestProxiedServerReopenConcurrent -15 1 TestProxiedServerServeReadParity -15 1 TestProxiedServerServeRefusesAStreamOnADisabledJournal -15 1 TestProxiedServerUpdateConcurrentClaim - -15 2 TestProxiedServerCompactHistory -15 2 TestProxiedServerCreate2 -15 2 TestProxiedServerDepListSingleIDWarnsOnDroppedExternalEdge -15 2 TestProxiedServerFindDuplicates -15 2 TestProxiedServerListWatchCountsTheOffsetIntoMaxRows -15 2 TestProxiedServerReady2 -15 2 TestProxiedServerSQL -15 2 TestProxiedServerServeReadRevision -15 2 TestProxiedServerUpdateConcurrentMetadata -15 2 TestProxiedServerUpdateIfGuards - -15 3 TestProxiedServerCascadeParity -15 3 TestProxiedServerDoltLifecycle -15 3 TestProxiedServerMolBurn -15 3 TestProxiedServerMolStale -15 3 TestProxiedServerMoleculeFrontDoorDirectServerProxyParity -15 3 TestProxiedServerSQLDatabaseFlag -15 3 TestProxiedServerServeRelatedIssues -15 3 TestProxiedServerTag -15 3 TestProxiedServerUpdate -15 3 TestProxiedServerWispCreateRejectsEnumViolatingVar - -15 4 TestProxiedServerCreateInfraTypeRoutesToWisps -15 4 TestProxiedServerEdit -15 4 TestProxiedServerListComments -15 4 TestProxiedServerMoleculeFrontDoorWriteParity -15 4 TestProxiedServerPour -15 4 TestProxiedServerReassignFence -15 4 TestProxiedServerServeAddComment -15 4 TestProxiedServerServeRelease -15 4 TestProxiedServerUpdate2 -15 4 TestProxiedServerUpdateHooks - -15 5 TestProxiedServerClose -15 5 TestProxiedServerConfigConcurrent -15 5 TestProxiedServerExport -15 5 TestProxiedServerGateLifecycle -15 5 TestProxiedServerMolReadyGated -15 5 TestProxiedServerMultiStatementSQL -15 5 TestProxiedServerServeAddDependencies -15 5 TestProxiedServerServeRemoveDependency -15 5 TestProxiedServerWispCreate - -15 6 TestProxiedServerClose2 -15 6 TestProxiedServerContext -15 6 TestProxiedServerExternalCreate -15 6 TestProxiedServerLink -15 6 TestProxiedServerNote -15 6 TestProxiedServerRelate -15 6 TestProxiedServerServeBatchClose -15 6 TestProxiedServerServeSettingsWrites -15 6 TestProxiedServerWispList - -15 7 TestProxiedServerAssign -15 7 TestProxiedServerBackupRefusedOnExternalTopology -15 7 TestProxiedServerCount -15 7 TestProxiedServerGC -15 7 TestProxiedServerList -15 7 TestProxiedServerOrphans -15 7 TestProxiedServerReady -15 7 TestProxiedServerServeClaim -15 7 TestProxiedServerServeRefusesAStaleCheckpointWithGone -15 7 TestProxiedServerServeUpdate -15 7 TestProxiedServerState - -15 8 TestProxiedServerBatchParity -15 8 TestProxiedServerCountIncludeInfra -15 8 TestProxiedServerDoltRemoteRemove -15 8 TestProxiedServerGateCreateInheritsRepoMetadata -15 8 TestProxiedServerLabel -15 8 TestProxiedServerMolBond -15 8 TestProxiedServerPathHelpers -15 8 TestProxiedServerRecomputeBlocked -15 8 TestProxiedServerServeClaimNext -15 8 TestProxiedServerSetState - -15 9 TestProxiedServerChildren -15 9 TestProxiedServerComment -15 9 TestProxiedServerDeferAutoWake -15 9 TestProxiedServerGateFrontDoorDirectServerProxyParity -15 9 TestProxiedServerMemory -15 9 TestProxiedServerPing -15 9 TestProxiedServerPrune -15 9 TestProxiedServerReopen -15 9 TestProxiedServerServeClose -15 9 TestProxiedServerStale - -15 10 TestProxiedServerCleanDatabases -15 10 TestProxiedServerDeferUndefer -15 10 TestProxiedServerDuplicates -15 10 TestProxiedServerGraph -15 10 TestProxiedServerPourRejectsEnumViolatingVar -15 10 TestProxiedServerSearch -15 10 TestProxiedServerServeCount -15 10 TestProxiedServerShow -15 10 TestProxiedServerStatuses -15 10 TestProxiedServerUpdateWisp - -15 11 TestProxiedServerDelete -15 11 TestProxiedServerDep -15 11 TestProxiedServerGateCheck -15 11 TestProxiedServerGateList -15 11 TestProxiedServerHeartbeat -15 11 TestProxiedServerMolProgress -15 11 TestProxiedServerPriority -15 11 TestProxiedServerPromote -15 11 TestProxiedServerServeCreate -15 11 TestProxiedServerSwarm - -15 12 TestProxiedServerDeleteBlockedJSONSingleDoc -15 12 TestProxiedServerHistory -15 12 TestProxiedServerKV -15 12 TestProxiedServerMolShow -15 12 TestProxiedServerQuery -15 12 TestProxiedServerQuick -15 12 TestProxiedServerServeDelete -15 12 TestProxiedServerShow2 -15 12 TestProxiedServerTypes -15 12 TestProxiedServerUpdateClosePolicy - -15 13 TestProxiedServerDeleteConcurrent -15 13 TestProxiedServerInfo -15 13 TestProxiedServerMolSquash -15 13 TestProxiedServerReadyClaimConcurrent -15 13 TestProxiedServerReadyWisp -15 13 TestProxiedServerServeEdgeCounts -15 13 TestProxiedServerShow3 -15 13 TestProxiedServerStatus -15 13 TestProxiedServerUnclaim -15 13 TestProxiedServerWispGC - -15 14 TestProxiedServerCleanDatabasesPurgeDropped -15 14 TestProxiedServerConfig -15 14 TestProxiedServerConfigSetMany -15 14 TestProxiedServerDeleteForceOrphans -15 14 TestProxiedServerImport -15 14 TestProxiedServerInitIfMissing -15 14 TestProxiedServerMolDistill -15 14 TestProxiedServerPrime -15 14 TestProxiedServerReadyConcurrent -15 14 TestProxiedServerServeLifecycle -15 14 TestProxiedServerStorageClass -15 14 TestProxiedServerUnclaimIfAssigneeParity - -15 15 TestProxiedServerCloseConcurrent -15 15 TestProxiedServerDeleteWisp -15 15 TestProxiedServerEpic -15 15 TestProxiedServerHuman -15 15 TestProxiedServerLint -15 15 TestProxiedServerMolCurrent -15 15 TestProxiedServerReclaim -15 15 TestProxiedServerServeModeGate -15 15 TestProxiedServerTodo -15 15 TestProxiedServerUpdate3 -15 15 TestProxiedServerUpdateConcurrentAppendNotes - -# Proxied-server cmd test shard manifest. -# -# Format: -# -# 30-shard split for the Bazel-only proxied-server tier +# 34-shard split for the Bazel-only proxied-server tier # (bazel-proxied in .github/workflows/bazel.yml), bin-packed # longest-processing-time-first by measured wall-time from # scripts/ci/proxied_test_durations.json (see that file for # provenance and its "relative weight, not absolute SLA" caveat). -# Regenerate with scripts/ci/gen_proxied_shard_manifest.py 30 +# Regenerate with scripts/ci/gen_proxied_shard_manifest.py 34 # --weights=duration --write after adding or removing # TestProxiedServer*/TestServerMode* functions. --write is incremental: # it keeps every already-assigned test on its current shard and only @@ -250,210 +29,260 @@ # regeneration. Add them to the generator or the durations file # instead. -30 1 TestProxiedServerGateList -30 1 TestProxiedServerHuman -30 1 TestProxiedServerReclaim -30 1 TestProxiedServerSQLStatementRouting -30 1 TestProxiedServerServeLifecycle +34 1 TestProxiedServerDep2 +34 1 TestProxiedServerMolProgress +34 1 TestProxiedServerReadyClaimConcurrent +34 1 TestProxiedServerServeActivatesTheEventsJournal +34 1 TestProxiedServerServeRelease -30 2 TestProxiedServerDelete -30 2 TestProxiedServerDeleteForceOrphans -30 2 TestProxiedServerListComments -30 2 TestProxiedServerPromote -30 2 TestProxiedServerTypesAgreeWithCreate +34 2 TestProxiedServerDepListSingleIDWarnsOnDroppedExternalEdge +34 2 TestProxiedServerGateList +34 2 TestProxiedServerList +34 2 TestProxiedServerServeRemoveDependency +34 2 TestProxiedServerUpdateC -30 3 TestProxiedServerDuplicates -30 3 TestProxiedServerReadyWisp -30 3 TestProxiedServerServeDelete -30 3 TestProxiedServerServeModeGate -30 3 TestProxiedServerServeReadRevision +34 3 TestProxiedServerAutoPrune +34 3 TestProxiedServerClose2B +34 3 TestProxiedServerEventsJournalOffByDefault +34 3 TestProxiedServerIfRevisionCloseMismatchRefuses +34 3 TestProxiedServerMolLastActivity +34 3 TestProxiedServerPurgeWispsPlaneRetention +34 3 TestProxiedServerServeLifecycle +34 3 TestProxiedServerStatuses -30 4 TestProxiedServerGateCreateInheritsRepoMetadata -30 4 TestProxiedServerMolBurn -30 4 TestProxiedServerReadyConcurrent -30 4 TestProxiedServerServeAddDependencies -30 4 TestProxiedServerServeRelatedIssues +34 4 TestProxiedServerMolStale +34 4 TestProxiedServerReadyConcurrent +34 4 TestProxiedServerServeRelatedIssues +34 4 TestProxiedServerServeSettingsWrites +34 4 TestProxiedServerShow2 +34 4 TestServerModeServeSkipsPostRunMaintenance -30 5 TestProxiedServerCleanDatabases -30 5 TestProxiedServerCreate -30 5 TestProxiedServerEventsJournal -30 5 TestProxiedServerPour -30 5 TestProxiedServerServeUpdateClaim -30 5 TestServerModeDeferAutoWake +34 5 TestProxiedServerHistoryRemoteRefusalFrontDoorMatrix +34 5 TestProxiedServerInfo +34 5 TestProxiedServerNote +34 5 TestProxiedServerOutageReconnectAcceptanceMatrix +34 5 TestProxiedServerUpdate3 +34 5 TestServerModeDeferAutoWake -30 6 TestProxiedServerBatchParity -30 6 TestProxiedServerHistoryRemoteSupportedFrontDoorParity -30 6 TestProxiedServerMolShow -30 6 TestProxiedServerMultiStatementSQL -30 6 TestProxiedServerReady -30 6 TestProxiedServerServeRemoveDependency +34 6 TestProxiedServerPing +34 6 TestProxiedServerQuick +34 6 TestProxiedServerServeReadsTheJournalItJustWrote +34 6 TestProxiedServerSwarm +34 6 TestProxiedServerUpdate2B +34 6 TestProxiedServerVersionedHistorySwitchRefusesAnUnrecordableGateTimeout +34 6 TestProxiedServerWispList -30 7 TestProxiedServerCleanDatabasesPurgeDropped -30 7 TestProxiedServerCount -30 7 TestProxiedServerCountIncludeInfra -30 7 TestProxiedServerDoltLifecycle -30 7 TestProxiedServerGC -30 7 TestProxiedServerUpdate +34 7 TestProxiedServerCloseConcurrent +34 7 TestProxiedServerCreateInfraTypeRoutesToWisps +34 7 TestProxiedServerDeleteIfRevisionSingleWinner +34 7 TestProxiedServerExternalCreate +34 7 TestProxiedServerIfRevisionGuardDelete +34 7 TestProxiedServerIfRevisionTargetGoneIsPreconditionFailed +34 7 TestProxiedServerLabelC +34 7 TestProxiedServerMoleculeLifecycleAgreesOnEveryRoute +34 7 TestProxiedServerTypesAgreeWithCreate -30 8 TestProxiedServerInitIfMissing -30 8 TestProxiedServerPathHelpers -30 8 TestProxiedServerReopenConcurrent -30 8 TestProxiedServerShow2 -30 8 TestProxiedServerTypes -30 8 TestProxiedServerUpdateClosePolicy -30 8 TestServerModeSharedServeGlobalReportsTheServedDatabase +34 8 TestProxiedServerClose2 +34 8 TestProxiedServerDeleteWisp +34 8 TestProxiedServerExport +34 8 TestProxiedServerFindDuplicates +34 8 TestProxiedServerGateCheck +34 8 TestProxiedServerServeReadParity -30 9 TestProxiedServerCloseConcurrent -30 9 TestProxiedServerDep2 -30 9 TestProxiedServerListWatchCountsTheOffsetIntoMaxRows -30 9 TestProxiedServerMolReadyGated -30 9 TestProxiedServerSQL +34 9 TestProxiedServerCloseSiblingBlockersFanIn +34 9 TestProxiedServerGateLifecycle +34 9 TestProxiedServerHistoryRemoteSupportedFrontDoorParity +34 9 TestProxiedServerIfRevisionGuardReopen +34 9 TestProxiedServerIfRevisionOutranksReassignFence +34 9 TestProxiedServerServeRefusesTheJournalWhenItIsDisabled +34 9 TestProxiedServerUpdate +34 9 TestServerModeServe -30 10 TestProxiedServerAutoPrune -30 10 TestProxiedServerClose2 -30 10 TestProxiedServerPing -30 10 TestProxiedServerServeClose -30 10 TestProxiedServerServeEdgeCounts +34 10 TestProxiedServerContext +34 10 TestProxiedServerCreate2B +34 10 TestProxiedServerGateCheckB +34 10 TestProxiedServerServeRefusesAStreamOnADisabledJournal +34 10 TestProxiedServerTypes +34 10 TestProxiedServerUpdate2C -30 11 TestProxiedServerBatchDefersThenDoltCommitAdvancesHeadOnce -30 11 TestProxiedServerOutageReconnectAcceptanceMatrix -30 11 TestProxiedServerReady2 -30 11 TestProxiedServerServeReadsTheJournalItJustWrote -30 11 TestProxiedServerServeRefusesTheJournalWhenItIsDisabled -30 11 TestProxiedServerShow +34 11 TestProxiedServerBatchParity +34 11 TestProxiedServerCompactHistory +34 11 TestProxiedServerPour +34 11 TestProxiedServerQuery +34 11 TestProxiedServerReady +34 11 TestProxiedServerServeAddDependencies -30 12 TestProxiedServerAssign -30 12 TestProxiedServerConfigSetMany -30 12 TestProxiedServerContext -30 12 TestProxiedServerInitExplicitBeadsDirIsAuthoritative -30 12 TestProxiedServerReadyClaimConcurrent -30 12 TestProxiedServerServeBatchClose +34 12 TestProxiedServerBlocked +34 12 TestProxiedServerChildren +34 12 TestProxiedServerCleanDatabases +34 12 TestProxiedServerReadyB +34 12 TestProxiedServerReadyWisp +34 12 TestProxiedServerReclaim +34 12 TestProxiedServerShowCommentsTail +34 12 TestProxiedServerUnclaim -30 13 TestProxiedServerChildren -30 13 TestProxiedServerConfig -30 13 TestProxiedServerDoltRemoteRemove -30 13 TestProxiedServerExternalMutationPolicy -30 13 TestProxiedServerPriority -30 13 TestProxiedServerServeUpdate +34 13 TestProxiedServerCompactDolt +34 13 TestProxiedServerCreate2 +34 13 TestProxiedServerGraph +34 13 TestProxiedServerHistoryRemoteSupportedDirectParity +34 13 TestProxiedServerMolSquash +34 13 TestProxiedServerPromote +34 13 TestProxiedServerServeRefusesAStaleCheckpointWithGone -30 14 TestProxiedServerInfo -30 14 TestProxiedServerLint -30 14 TestProxiedServerNote -30 14 TestProxiedServerQuery -30 14 TestProxiedServerUpdate3 -30 14 TestProxiedServerWispCreate +34 14 TestProxiedServerAssign +34 14 TestProxiedServerCloseB +34 14 TestProxiedServerDuplicates +34 14 TestProxiedServerHeartbeat +34 14 TestProxiedServerIfRevisionCloseReplaysMoleculeAutoClose +34 14 TestProxiedServerInitIfMissing +34 14 TestProxiedServerMolReadyGated -30 15 TestProxiedServerCompactDolt -30 15 TestProxiedServerMolDistill -30 15 TestProxiedServerMolProgress -30 15 TestProxiedServerServeClaimNext -30 15 TestProxiedServerServeRefusesAStreamOnADisabledJournal -30 15 TestProxiedServerUnclaimIfAssigneeParity +34 15 TestProxiedServerDepConcurrent +34 15 TestProxiedServerImport +34 15 TestProxiedServerMoleculeFrontDoorWriteParity +34 15 TestProxiedServerReopenConcurrent +34 15 TestProxiedServerSQL -30 16 TestProxiedServerCascadeParity -30 16 TestProxiedServerExternalCreate -30 16 TestProxiedServerGraph -30 16 TestProxiedServerLabel -30 16 TestProxiedServerSwarm -30 16 TestProxiedServerTodo -30 16 TestProxiedServerUpdateConcurrentMetadata +34 16 TestProxiedServerBackupRefusedOnExternalTopology +34 16 TestProxiedServerCascadeParity +34 16 TestProxiedServerConfigSetMany +34 16 TestProxiedServerKV +34 16 TestProxiedServerServeCount +34 16 TestProxiedServerServeCreate +34 16 TestProxiedServerUpdateHooks -30 17 TestProxiedServerClose -30 17 TestProxiedServerConfigConcurrent -30 17 TestProxiedServerDeleteConcurrent -30 17 TestProxiedServerSearch -30 17 TestProxiedServerServeReadParity -30 17 TestProxiedServerStatus +34 17 TestProxiedServerDep +34 17 TestProxiedServerMultiStatementSQL +34 17 TestProxiedServerOrphans +34 17 TestProxiedServerPrime +34 17 TestProxiedServerSQLDatabaseFlag +34 17 TestProxiedServerServeModeGate +34 17 TestServerModeServeIgnoresGraphModeDependency -30 18 TestProxiedServerHeartbeat -30 18 TestProxiedServerMolBond -30 18 TestProxiedServerSQLDatabaseFlag -30 18 TestProxiedServerServeCount -30 18 TestProxiedServerUpdate2 -30 18 TestServerModeTypesAgreeWithCreate +34 18 TestProxiedServerClose3 +34 18 TestProxiedServerCount +34 18 TestProxiedServerCountIncludeInfra +34 18 TestProxiedServerDoltRemoteRemove +34 18 TestProxiedServerMolShow +34 18 TestProxiedServerWispCreateRejectsEnumViolatingVar -30 19 TestProxiedServerCreate2 -30 19 TestProxiedServerEdit -30 19 TestProxiedServerPourRejectsEnumViolatingVar -30 19 TestProxiedServerReassignFence -30 19 TestProxiedServerUpdateWisp -30 19 TestServerModeServe +34 19 TestProxiedServerCreate +34 19 TestProxiedServerMolCurrent +34 19 TestProxiedServerServeBatchClose +34 19 TestProxiedServerShow3 +34 19 TestServerModeTypesAgreeWithCreate -30 20 TestProxiedServerExternalPolicyDirectParity -30 20 TestProxiedServerHistory -30 20 TestProxiedServerImport -30 20 TestProxiedServerMemory -30 20 TestProxiedServerMolCurrent -30 20 TestProxiedServerServeStreamsTheJournalItIsWriting +34 20 TestProxiedServerDelete +34 20 TestProxiedServerLint +34 20 TestProxiedServerPriority +34 20 TestProxiedServerShow2B +34 20 TestProxiedServerWispGC +34 20 TestServerModeSharedServeGlobalReportsTheServedDatabase -30 21 TestProxiedServerDeleteWisp -30 21 TestProxiedServerDepConcurrent -30 21 TestProxiedServerListSortRetiresTheWalk -30 21 TestProxiedServerPrime -30 21 TestProxiedServerRelate -30 21 TestProxiedServerSetState -30 21 TestProxiedServerUpdateConcurrentAppendNotes +34 21 TestProxiedServerBatchDepAddRefusesADottedChildGatedOnItsParent +34 21 TestProxiedServerConfig +34 21 TestProxiedServerExternalPolicyDirectParity +34 21 TestProxiedServerMoleculeFrontDoorDirectServerProxyParity +34 21 TestProxiedServerPathHelpers +34 21 TestProxiedServerPrune +34 21 TestProxiedServerServeClose +34 21 TestProxiedServerUnclaimIfAssigneeParity -30 22 TestProxiedServerCompactHistory -30 22 TestProxiedServerGateLifecycle -30 22 TestProxiedServerKV -30 22 TestProxiedServerShow3 -30 22 TestProxiedServerStale -30 22 TestProxiedServerStatuses +34 22 TestProxiedServerGateCreateInheritsRepoMetadata +34 22 TestProxiedServerRecomputeBlocked +34 22 TestProxiedServerServeEdgeCounts +34 22 TestProxiedServerTag +34 22 TestProxiedServerUpdateB +34 22 TestProxiedServerUpdateConcurrentMetadata -30 23 TestProxiedServerBackupRefusedOnExternalTopology -30 23 TestProxiedServerCloseSiblingBlockersFanIn -30 23 TestProxiedServerDeleteBlockedJSONSingleDoc -30 23 TestProxiedServerQuick -30 23 TestProxiedServerStorageClass -30 23 TestProxiedServerUpdateHooks -30 23 TestProxiedServerWispGC +34 23 TestProxiedServerDep2B +34 23 TestProxiedServerIfRevisionGuardUpdate +34 23 TestProxiedServerListWatchCountsTheOffsetIntoMaxRows +34 23 TestProxiedServerMolBurn +34 23 TestProxiedServerSearchRoutesAgree +34 23 TestProxiedServerServeUpdate +34 23 TestProxiedServerUpdateConcurrentClaim +34 23 TestProxiedServerUpdateWisp -30 24 TestProxiedServerCreateInfraTypeRoutesToWisps -30 24 TestProxiedServerEpic -30 24 TestProxiedServerLink -30 24 TestProxiedServerMoleculeFrontDoorDirectServerProxyParity -30 24 TestProxiedServerRecomputeBlocked -30 24 TestServerModeServeSkipsPostRunMaintenance +34 24 TestProxiedServerDeleteBlockedJSONSingleDoc +34 24 TestProxiedServerDeleteForceOrphans +34 24 TestProxiedServerHuman +34 24 TestProxiedServerIfRevisionDeleteMatchAndMismatch +34 24 TestProxiedServerIfRevisionGuardAssign +34 24 TestProxiedServerListComments +34 24 TestProxiedServerListSortRetiresTheWalk +34 24 TestProxiedServerShowWatch +34 24 TestProxiedServerUpdateIfGuards -30 25 TestProxiedServerDeferUndefer -30 25 TestProxiedServerOrphans -30 25 TestProxiedServerServeClaim -30 25 TestProxiedServerShowWatch -30 25 TestProxiedServerUpdateIfGuards -30 25 TestProxiedServerWispCreateRejectsEnumViolatingVar +34 25 TestProxiedServerInitExplicitBeadsDirIsAuthoritative +34 25 TestProxiedServerSetState +34 25 TestProxiedServerShow +34 25 TestProxiedServerShowB +34 25 TestProxiedServerStale +34 25 TestProxiedServerWispCreate -30 26 TestProxiedServerFindDuplicates -30 26 TestProxiedServerGateCheck -30 26 TestProxiedServerGateFrontDoorDirectServerProxyParity -30 26 TestProxiedServerServeAddComment -30 26 TestProxiedServerServeSettingsWrites -30 26 TestProxiedServerState +34 26 TestProxiedServerDeferAutoWake +34 26 TestProxiedServerExternalMutationPolicy +34 26 TestProxiedServerReopenB +34 26 TestProxiedServerSearch +34 26 TestProxiedServerServeClaim +34 26 TestProxiedServerShow3B -30 27 TestProxiedServerBlocked -30 27 TestProxiedServerMolLastActivity -30 27 TestProxiedServerMolStale -30 27 TestProxiedServerMoleculeFrontDoorWriteParity -30 27 TestProxiedServerServeActivatesTheEventsJournal -30 27 TestProxiedServerServeRefusesAStaleCheckpointWithGone +34 27 TestProxiedServerDeferUndefer +34 27 TestProxiedServerGatedRendering +34 27 TestProxiedServerHistory +34 27 TestProxiedServerLabel +34 27 TestProxiedServerLabelB +34 27 TestProxiedServerUpdateClosePolicy -30 28 TestProxiedServerComment -30 28 TestProxiedServerExport -30 28 TestProxiedServerList -30 28 TestProxiedServerReopen -30 28 TestProxiedServerServeCreate -30 28 TestProxiedServerUnclaim +34 28 TestProxiedServerDep2C +34 28 TestProxiedServerDoltLifecycle +34 28 TestProxiedServerIfRevisionCloseWarnsOnForcedOpenChildren +34 28 TestProxiedServerReady2 +34 28 TestProxiedServerReassignFence +34 28 TestProxiedServerSQLStatementRouting +34 28 TestProxiedServerServeClaimNext +34 28 TestProxiedServerUpdateConcurrentAppendNotes -30 29 TestProxiedServerDeferAutoWake -30 29 TestProxiedServerDep -30 29 TestProxiedServerDepListSingleIDWarnsOnDroppedExternalEdge -30 29 TestProxiedServerHistoryRemoteRefusalFrontDoorMatrix -30 29 TestProxiedServerTag -30 29 TestProxiedServerWispList +34 29 TestProxiedServerGateFrontDoorDirectServerProxyParity +34 29 TestProxiedServerMolDistill +34 29 TestProxiedServerReopen +34 29 TestProxiedServerServeDelete +34 29 TestProxiedServerState -30 30 TestProxiedServerEventsJournalOffByDefault -30 30 TestProxiedServerMolSquash -30 30 TestProxiedServerPrune -30 30 TestProxiedServerPurgeWispsPlaneRetention -30 30 TestProxiedServerServeRelease -30 30 TestProxiedServerUpdateConcurrentClaim +34 30 TestProxiedServerDeleteConcurrent +34 30 TestProxiedServerReadyC +34 30 TestProxiedServerServeAddComment +34 30 TestProxiedServerStatus +34 30 TestProxiedServerTodo +34 30 TestProxiedServerUpdate2 +34 30 TestProxiedServerVersionedHistoryServeActivatesTheProviderFromItsOwnRow + +34 31 TestProxiedServerCloseBeadGate +34 31 TestProxiedServerComment +34 31 TestProxiedServerConfigB +34 31 TestProxiedServerEventsJournal +34 31 TestProxiedServerGateAddWaiterConvoy +34 31 TestProxiedServerIfRevisionGuardClose +34 31 TestProxiedServerMolBond + +34 32 TestProxiedServerCleanDatabasesPurgeDropped +34 32 TestProxiedServerConfigConcurrent +34 32 TestProxiedServerDepB +34 32 TestProxiedServerServeStreamsTheJournalItIsWriting +34 32 TestProxiedServerServeUpdateClaim +34 32 TestProxiedServerStorageClass + +34 33 TestProxiedServerBatchDefersThenDoltCommitAdvancesHeadOnce +34 33 TestProxiedServerClose +34 33 TestProxiedServerGC +34 33 TestProxiedServerMemory +34 33 TestProxiedServerPourRejectsEnumViolatingVar +34 33 TestProxiedServerRelate + +34 34 TestProxiedServerClose4 +34 34 TestProxiedServerCreate2C +34 34 TestProxiedServerEdit +34 34 TestProxiedServerEpic +34 34 TestProxiedServerLink +34 34 TestProxiedServerServeReadRevision diff --git a/.github/scripts/rrc-lane-commands.txt b/.github/scripts/rrc-lane-commands.txt new file mode 100644 index 000000000..331e18657 --- /dev/null +++ b/.github/scripts/rrc-lane-commands.txt @@ -0,0 +1,17 @@ +# Every bazel.yml lane's loading and analysis, for the remote repo contents +# cache: rrc-seed runs each line with --nobuild on a push to main (uploading +# the repositories it fetches) and rrc-verify runs each cold every night. +# One `bazel` command per line (no shell quoting); # starts a comment. +# scripts/bazel_rrc_test.go checks that every --config a reading lane's +# bazel command uses appears here. +test //... --config=ci +test //... --config=embedded +test //... --config=integration +test //... --config=doltserver +test //... --config=doltserver-proxied +test //... --config=dolt-race +test //... --config=doltserver-integration +test //... --config=doltserver-cmd +test //... --config=dolt-int +build --config=pure //cmd/bd:bd //cmd/bd:bd_test //internal/storage/embeddeddolt:embeddeddolt_test //internal/tracker:tracker_test +build --config=js-wasm //internal/hooks:hooks_test diff --git a/.github/scripts/rrc-run-lanes.sh b/.github/scripts/rrc-run-lanes.sh new file mode 100755 index 000000000..d5f329a84 --- /dev/null +++ b/.github/scripts/rrc-run-lanes.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Loading and analysis of every bazel.yml lane, for the remote repo contents +# cache (bazel.yml's rrc-seed and rrc-verify jobs). +# +# Usage: rrc-run-lanes.sh [STARTUP_FLAG...] -- [COMMAND_FLAG...] +# +# Runs `bazel STARTUP_FLAG... --nobuild COMMAND_FLAG...` for each +# command line in .github/scripts/rrc-lane-commands.txt (or RRC_LANE_COMMANDS), +# in order, stopping at the first failure. --nobuild: repository rules, +# loading and analysis only, never a build or test action. +# +# Bazel exits 1 after `test --nobuild` even when loading and analysis succeed +# ("Couldn't start the build. Unable to run tests"). A command passes when it +# exits 0, or exits non-zero having printed "Build completed successfully" +# and no ERROR line but that one. +set -euo pipefail + +startup=() +while [ $# -gt 0 ] && [ "$1" != -- ]; do + startup+=("$1") + shift +done +[ $# -gt 0 ] || { + echo "usage: rrc-run-lanes.sh [STARTUP_FLAG...] -- [COMMAND_FLAG...]" >&2 + exit 2 +} +shift +flags=("$@") + +file=${RRC_LANE_COMMANDS:-$(dirname "${BASH_SOURCE[0]}")/rrc-lane-commands.txt} +mapfile -t cmds < <(sed -e 's/#.*//' -e 's/[[:space:]]*$//' "$file" | grep -v '^[[:space:]]*$' || true) +if [ "${#cmds[@]}" -eq 0 ]; then + echo "::error::no lane commands in $file" + exit 1 +fi + +log=$(mktemp) +trap 'rm -f "$log"' EXIT +summary=${GITHUB_STEP_SUMMARY:-/dev/null} +for cmd in "${cmds[@]}"; do + read -r -a args <<<"$cmd" + start=$(date +%s) + rc=0 + bazel ${startup[@]+"${startup[@]}"} "${args[@]}" --nobuild ${flags[@]+"${flags[@]}"} &1 | tee "$log" || rc=$? + if [ "$rc" -ne 0 ] && grep -q '^INFO: Build completed successfully' "$log" && + ! grep '^ERROR:' "$log" | grep -qv "^ERROR: Couldn't start the build. Unable to run tests$"; then + rc=0 + fi + echo "rrc: \`bazel $cmd\`: exit $rc, $(($(date +%s) - start))s" | tee -a "$summary" + [ "$rc" -eq 0 ] || exit "$rc" +done diff --git a/.github/scripts/rrc-writer-credential.sh b/.github/scripts/rrc-writer-credential.sh new file mode 100755 index 000000000..a650c7ddc --- /dev/null +++ b/.github/scripts/rrc-writer-credential.sh @@ -0,0 +1,113 @@ +#!/usr/bin/env bash +# A 30-minute rbe-west client certificate for the remote repo contents cache +# writer (bazel.yml's rrc-seed job; engdocs/design/bazel-remote-repo-contents-cache.md). +# +# The job trades its GitHub Actions OIDC token (audience rbe-rrc-writer) for a +# certificate CN=rbe-rrc-writer from rbe-west's mint. The mint signs only for +# this repository's bazel.yml on a push to main (repository, ref, event_name +# and job_workflow_ref claims); pull_request, fork and Dependabot runs cannot +# get one (no OIDC token, or a refs/pull/N/merge one). On rbe-west that +# certificate reaches only GetCapabilities, the CAS and an action cache front +# (rrc-gate) that admits repo-contents entries and refuses everything else, so +# it can never write an execution result or execute anything. +# +# The key is an EC P-256 key (PKCS#8: Bazel's Netty TLS refuses a SEC1 "EC +# PRIVATE KEY") generated here in BAZEL_CI_SECRET_DIR, outside the workspace; +# it never leaves the runner. The OIDC token is masked. Outputs (to +# $GITHUB_OUTPUT when set, else stdout): cert, key, endpoint, instance; none +# when the mint answers 503 or cannot be reached (seeding switched off on +# rbe-west: infra nativelink-cas/west/README.md "Client contract"), which +# exits 0 with a warning. +# +# Tests only: RBE_RRC_MINT (a stand-in mint) and RBE_RRC_ENDPOINT_RE. +set -euo pipefail +MINT=${RBE_RRC_MINT:-https://rbe-mint.ops.gascity.com:8444} +ENDPOINT_RE=${RBE_RRC_ENDPOINT_RE:-'^grpcs://rbe-west\.ops\.gascity\.com(:443)?$'} +AUDIENCE=rbe-rrc-writer +dir=${BAZEL_CI_SECRET_DIR:?BAZEL_CI_SECRET_DIR is required} +out=${GITHUB_OUTPUT:-/dev/stdout} + +if [ -z "${ACTIONS_ID_TOKEN_REQUEST_URL:-}" ] || [ -z "${ACTIONS_ID_TOKEN_REQUEST_TOKEN:-}" ]; then + echo "::error title=rrc writer::no OIDC token request URL; the job needs permissions: id-token: write" >&2 + exit 1 +fi + +install -d -m 0700 "$dir" +umask 077 + +oidc=$(curl -sS --fail --connect-timeout 5 --max-time 30 --retry 3 --retry-all-errors \ + -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \ + "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=$AUDIENCE" | jq -r '.value // empty') +if [ -z "$oidc" ]; then + echo "::error title=rrc writer::GitHub returned no OIDC token" >&2 + exit 1 +fi +printf '::add-mask::%s\n' "$oidc" + +openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$dir/rrc-writer.key" 2>/dev/null +csr=$(openssl req -new -key "$dir/rrc-writer.key" -subj "/CN=rbe-rrc-writer-request") +body=$(jq -cn --arg csr "$csr" '{csr_pem: $csr}') + +reply="$dir/rrc-mint.json" +code=000 +for attempt in 1 2 3 4; do + # --connect-timeout: a closed gate drops the SYN; fail fast, not in 60 s. + code=$(curl -sS -o "$reply" -w '%{http_code}' --connect-timeout 5 --max-time 60 \ + -H "Authorization: Bearer $oidc" -H 'content-type: application/json' \ + --data "$body" "$MINT/v1/rrc-writer/cert") || code=000 + # Retry what may pass on its own: a rate limit (429), the mint could not + # reach GitHub's JWKS (502), or the network (000). Everything else is an + # answer. + case "$code" in 429 | 502 | 000) ;; *) break ;; esac + [ "$attempt" -eq 4 ] || sleep $((attempt * 10)) +done +case "$code" in +200) ;; +503 | 000) + # The mint's switch is off, its CA is not installed, or rbe-west's fork + # edge is closed: seeding is off, not broken. No outputs, so the seed + # step skips; the push to main never fails on it. + echo "::warning title=rrc writer: seeding off (HTTP $code)::$(jq -r '.error // empty' "$reply" 2>/dev/null || true)" + exit 0 + ;; +*) + echo "::error title=rrc writer mint refused (HTTP $code)::$(jq -r '.error // empty' "$reply" 2>/dev/null || true)" + exit 1 + ;; +esac + +endpoint=$(jq -r '.endpoint // empty' "$reply") +instance=$(jq -r '.instance // empty' "$reply") +[[ $endpoint =~ $ENDPOINT_RE ]] || { + echo "::error::rrc writer mint returned endpoint '$endpoint'" >&2 + exit 1 +} +[ "$instance" = oss ] || { + echo "::error::rrc writer mint returned instance '$instance', want oss" >&2 + exit 1 +} +jq -r '.cert_pem // empty' "$reply" >"$dir/rrc-writer.crt" +subject=$(openssl x509 -in "$dir/rrc-writer.crt" -noout -subject -nameopt RFC2253) || { + echo "::error::rrc writer mint returned no certificate" >&2 + exit 1 +} +rdns=$(tr ',' '\n' <<<"${subject#subject=}") +cn=$(sed -n 's/^CN=//p' <<<"$rdns") +org=$(sed -n 's/^O=//p' <<<"$rdns") +if ! [[ $cn =~ ^rbe-rrc-writer(-[a-z0-9]+)?$ ]] || [ "$org" != gascity ]; then + echo "::error::rrc writer mint returned a certificate for '$subject'" >&2 + exit 1 +fi +# The certificate must belong to the key generated above. +if [ "$(openssl x509 -in "$dir/rrc-writer.crt" -noout -pubkey | openssl sha256)" != "$(openssl pkey -in "$dir/rrc-writer.key" -pubout | openssl sha256)" ]; then + echo "::error::rrc writer mint returned a certificate for another key" >&2 + exit 1 +fi +openssl x509 -in "$dir/rrc-writer.crt" -noout -subject -enddate +rm -f "$reply" +{ + echo "cert=$dir/rrc-writer.crt" + echo "key=$dir/rrc-writer.key" + echo "endpoint=$endpoint" + echo "instance=$instance" +} >>"$out" diff --git a/.github/workflows/bazel-autofix.yml b/.github/workflows/bazel-autofix.yml index 5bfce89e1..acd5b7ff3 100644 --- a/.github/workflows/bazel-autofix.yml +++ b/.github/workflows/bazel-autofix.yml @@ -40,15 +40,20 @@ # the disk) and re-checked once staged (scripts/bazel-autofix-push.sh), so a # hostile patch can at most rewrite BUILD.bazel / MODULE.bazel / # MODULE.bazel.lock on its own PR branch. Pushes are leased to the run's head -# SHA and skipped for heads that are protected or under a ruleset. +# SHA and skipped for heads that are protected or under a ruleset. The App +# private key is a secret of the `autofix` environment, whose deployment- +# branch policy allows only `main`, so only a job running on main can read +# it; the minted token itself is scoped to this one repo with contents:write +# only, so even a hostile patch gains nothing beyond what the job already +# had. # # TOKEN NOTE: pushes made with the default GITHUB_TOKEN do not retrigger PR -# checks. This reuses the DOCS_AUTOFIX_TOKEN repo secret (fine-grained PAT or -# GitHub App token with contents:write on this repo) rather than adding a -# second one; without it the pushed fix still lands but checks need a manual -# re-run. Fork PRs always get the apply-recipe comment - no token we hold can -# push to a fork. workflow_run always runs this file from the default branch, -# so edits take effect only after they merge. +# checks. On same-repo PRs the push step mints a short-lived installation +# token for the gastownhall-autofix GitHub App (contents:write, scoped to +# this repo only) and uses that instead. Fork PRs always get the apply-recipe +# comment - no token we hold can push to a fork, so the mint step is skipped +# for them. workflow_run always runs this file from the default branch, so +# edits take effect only after they merge. name: Bazel Autofix @@ -70,6 +75,10 @@ jobs: github.event.workflow_run.conclusion == 'failure' runs-on: ubuntu-latest timeout-minutes: 10 + # Grants the job read access to this environment's secrets; its + # deployment-branch policy restricts that to jobs running on main + # (workflow_run always does), not to any PR branch. + environment: autofix # Shared with docs-autofix.yml; queue, never cancel (see header). concurrency: group: autofix-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }} @@ -114,6 +123,22 @@ jobs: fi echo "found=true" >> "$GITHUB_OUTPUT" + # Same-repo PRs only: no token we hold can push to a fork, and a fork's + # head_repository can even be absent (deleted fork), so this mints + # nothing for it and the push script falls back to the apply-recipe + # comment. app-token outputs are empty (not failed) when the step is + # skipped, which is what the fallback below relies on. + - name: Mint autofix app token + id: app-token + if: github.event.workflow_run.head_repository.full_name == github.repository + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3 + with: + app-id: ${{ secrets.AUTOFIX_APP_ID }} + private-key: ${{ secrets.AUTOFIX_APP_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + repositories: ${{ github.event.repository.name }} + permission-contents: write + - name: Push sync commit or leave apply recipe if: steps.patch.outputs.found == 'true' env: @@ -127,9 +152,9 @@ jobs: RUN_URL: ${{ github.event.workflow_run.html_url }} # Split tokens: gh api calls (PR lookup, comments) always use the # workflow token, which carries this job's pull-requests:write; the - # optional PAT is used ONLY for the git push, so it needs no more + # App token is used ONLY for the git push, so it needs no more # than contents:write. GH_TOKEN: ${{ github.token }} - PUSH_TOKEN: ${{ secrets.DOCS_AUTOFIX_TOKEN || github.token }} - AUTOFIX_TOKEN_KIND: ${{ secrets.DOCS_AUTOFIX_TOKEN && 'pat' || 'default' }} + PUSH_TOKEN: ${{ steps.app-token.outputs.token || github.token }} + AUTOFIX_TOKEN_KIND: ${{ steps.app-token.outputs.token && 'app' || 'default' }} run: ./scripts/bazel-autofix-push.sh diff --git a/.github/workflows/bazel-farm.yml b/.github/workflows/bazel-farm.yml index 7ab2c0a7b..caeb0ad2f 100644 --- a/.github/workflows/bazel-farm.yml +++ b/.github/workflows/bazel-farm.yml @@ -120,8 +120,18 @@ jobs: name: Bazel Farm needs: authorize if: ${{ needs.authorize.outputs.allowed == 'true' }} + # A called workflow's job gets at most this call's token permissions, and + # GitHub checks them when the run starts, even for a job whose if: skips + # it (startup_failure otherwise; gascity #7478): bazel.yml's rrc-seed asks + # id-token: write (push to main only) and rrc-verify issues: write + # (schedule and dispatch only). Neither runs for this event, every other + # bazel.yml job keeps contents: read, and rbe-west's mint refuses any OIDC + # token but a main-push bazel.yml one + # (scripts/bazel_rrc_test.go, TestBazelWorkflowCallersGrantEveryRequestedPermission). permissions: contents: read + id-token: write + issues: write uses: ./.github/workflows/bazel.yml # Exactly the four RBE secrets: never the rbe-prewarm app private key # (B1, security review of bdef342d5). This pull_request_target run is diff --git a/.github/workflows/bazel.yml b/.github/workflows/bazel.yml index c0162bcdf..b319ab300 100644 --- a/.github/workflows/bazel.yml +++ b/.github/workflows/bazel.yml @@ -1,33 +1,39 @@ -# Bazel side-by-side lane, gated alongside the legacy go test jobs. Runs -# `bazel test //... --config=ci`, the PR Core-parity selection (race, -short, -# dolt skip, -requires-docker), plus one job per mirrored CI job (pure-Go and -# js/wasm, the dolt-server lane, pr-risk.yml's embedded-Dolt, proxied-server -# and server-Dolt storage tiers, main.yml's integration jobs). +# The Bazel lanes: the only CI run of the Linux Go test tiers. Runs +# `bazel test //... --config=ci`, the PR-core selection (race, -short, dolt +# skip), plus one job per tier (pure-Go and js/wasm, the release +# cross-compile, the dolt-server lane, the embedded-Dolt, proxied-server and +# server-Dolt storage tiers that pr-risk.yml used to run, integration, the +# cmd/bd Dolt-server tier). # -# PRs and merge groups run it through pr.yml's `bazel` job (workflow_call), -# in the same run as the legacy jobs it mirrors, which stay required too, -# except where their D2 flag retires them: while the committed -# BAZEL_RETIRES_LEGACY_EMBEDDED / BAZEL_RETIRES_LEGACY_DOLT_SERVER_TIERS / -# BAZEL_RETIRES_LEGACY_PR_LANES flag is "true", on a same-repo, -# non-Dependabot pull_request (whatever the mode), the bazel-coverage job -# stands down pr-risk.yml's embedded-Dolt test jobs (bazel-embedded runs -# the tier), its proxied-server and server-Dolt storage test jobs -# (bazel-proxied, bazel-server-storage), or pr.yml's PR Core, -# build-artifacts, pure-Go/js-wasm, domain+uow and contract corpus jobs -# (bazel-test, bazel-pure, bazel-doltserver; their `bazel test`s then add -# --config=sole-run); pr.yml's ci-gate then requires those lanes to have run -# remotely and passed, so modes skip, local and cache are red there -# (scripts/pr_risk_bazel_coverage_test.go, pr_lanes_bazel_coverage_test.go). +# PRs and merge groups run it through pr.yml's `bazel` job (workflow_call). +# The legacy go test jobs these lanes mirrored are retired (ga-96smfk.22), +# so pr.yml's ci-gate requires the lanes to have run remotely on rbe-west +# and passed on every pull_request and merge group (BAZEL_REMOTE): modes +# skip, local and cache are red there (scripts/pr_risk_bazel_coverage_test.go). +# Where a lane executes remotely its `bazel test`s add --config=sole-run: it +# is the tier's only run, so a remote cache eviction fails it rather than +# re-running the invocation (whose retry could turn a failed test green). +# Test results are cached (read and written) on every run but nightly's: a +# test whose action key is unchanged reuses the PASS the farm recorded for +# it, on a PR, a merge group (merge queue) or a push to main alike, and only +# what changed runs. nightly.yml passes fresh-test-results: true, so every +# `bazel test` here appends --config=fresh (BAZEL_FRESH below; +# --nocache_test_results) and re-executes every test once a night, which +# keeps sampling flaky and -race failures. A cached failure is never reused. +# Policy: scripts/ci_merge_queue_test.go. # This file has no pull_request or merge_group trigger of its own, so a PR # runs the lane once. Every lane reports its job.status as a workflow_call # output (named after the job) from an always() last step. pr.yml's ci-gate # requires the call's aggregate result (BAZEL) and bazel-test, bazel-pure, -# bazel-embedded, bazel-integration, bazel-doltserver, bazel-proxied and -# bazel-server-storage (BAZEL_TEST, BAZEL_PURE, BAZEL_EMBEDDED, -# BAZEL_INTEGRATION, BAZEL_DOLTSERVER, BAZEL_PROXIED, BAZEL_SERVER_STORAGE); +# bazel-release-cross, bazel-embedded, bazel-integration, bazel-doltserver, +# bazel-proxied and bazel-server-storage (BAZEL_TEST, BAZEL_PURE, +# BAZEL_RELEASE_CROSS, BAZEL_EMBEDDED, BAZEL_INTEGRATION, BAZEL_DOLTSERVER, +# BAZEL_PROXIED, BAZEL_SERVER_STORAGE); # bazel-cmd-dolt (the cmd/bd Dolt-server tier, BAZEL_CMD_DOLT) is advisory: # job-level continue-on-error, and pr.yml requires it only while its -# BAZEL_CMD_DOLT_REQUIRED flag is "true"; +# BAZEL_CMD_DOLT_REQUIRED flag is "true" (pr.yml then also passes +# cmd-dolt-required: true, and bazel-integration leaves //cmd/bd:bd_test, +# which bazel-cmd-dolt runs too, to it); # .github/scripts/bazel-gate.sh turns the rbe job's rbe-mode output into the # skips it accepts, so a lane skipped by its `if:` below passes and one that # should have run and failed, was cancelled or reported nothing fails the @@ -40,7 +46,14 @@ # only what the PR changed is built and tested on the runner, and it is # their only PR-time integration run (no legacy job runs it on PRs). Mode # local (rbe=off) still skips it. Direct runs (push to main, -# workflow_dispatch, nightly.yml's call) gate nothing. +# workflow_dispatch, nightly.yml's call) gate nothing. In mode remote the +# dolt-server and proxied-server tiers run as one union job, bazel-dolt-race +# (`bazel test --config=dolt-race`), whose job.status is both the +# bazel-doltserver and the bazel-proxied output; in every other mode +# bazel-doltserver and bazel-proxied run as before and report their own. +# Exactly one of the two arms runs in any mode, so the gate ids +# (BAZEL_DOLTSERVER, BAZEL_PROXIED) and bazel-gate.sh's skips are unchanged +# (engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md, "dolt-race Union Lane"). # # Execution mode, decided once by the rbe job (every other job needs it and # reads its outputs; none re-derives the condition) and passed to @@ -109,9 +122,18 @@ # by every later step and by locally executed Bazel actions, and a .bazelrc # edit can point the BEP or the executor anywhere. Anyone who can push a # branch here can therefore use or copy the certificate and write to the -# farm's cache. Fork PRs never get it, except those bazel-farm.yml -# authorizes (allowlisted author and sender, accepted as same-repo-level -# trust; that workflow's header lists what it adds): pull_request from a +# farm's cache. Fork PRs never get it on their own runs, except those +# bazel-farm.yml authorizes (allowlisted author and sender, accepted as +# same-repo-level trust; that workflow's header lists what it adds), and +# except once queued: a merge_group run loads every workflow file and +# script from the queue entry's commit, so a fork (or Dependabot) PR that a +# maintainer queues runs its own edits to .github/, .bazelrc, tools/bazel, +# MODULE.bazel, BUILD files and CI scripts with all CI secrets, the +# pre-warm app key included, even if the entry is later ejected. That is +# the trust of merging it (push to main would run the same code), so the +# maintainer rule is: review a fork PR's changes to those paths before +# queueing it, as before merging (engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md, +# "Merge Queue"). Otherwise: pull_request from a # fork receives no secrets, bazel-farm.yml is the only pull_request_target # caller (policy-tested), and forks cannot write the runner cache. Nor do # Dependabot PRs, which run as same-repo but get no Actions secrets. Fork @@ -139,7 +161,11 @@ # runs - the only contexts that ever receive RBE_POOL_APP_PRIVATE_KEY - each # reach that shared key for the duration of the mint step alone (nothing # executes from the checked-out repository tree while it, or the token it -# produces, is in scope: see the rbe-prewarm job below). Unlike the RBE +# produces, is in scope: see the rbe-prewarm job below). That holds only for +# this file as committed: a merge_group run uses the queued commit's copy, +# so a queued fork PR that edits this job (or pr.yml) reaches the key with +# whatever it wrote. Queueing a fork PR is therefore merging-level trust; +# review its .github/ changes first (see the header above). Unlike the RBE # client certificate above, this key cannot be rotated or revoked for beads # alone without also breaking gascity's scaler; the kill switch # (RBE_POOL_APP_PRIVATE_KEY unset, or RBE_PREWARM_WORKERS=0) disables @@ -150,14 +176,15 @@ # gates no longer consume this artifact (they build their own bd); it is # kept for the F3.5.3 SHA256SUMS comparison and for debugging. # -# Runner cache: one entry per (.bazelversion, MODULE.bazel.lock) pair, about -# 2 GB (Bazel's content-addressable --repository_cache, re-hashed on every +# Runner cache: one entry per (.bazelversion, MODULE.bazel, MODULE.bazel.lock) +# triple, about 1 GB (Bazel's content-addressable --repository_cache, re-hashed on every # hit; never the Bazel binary or the repo contents cache), written # only by a push to main that missed it. No --disk_cache: remote runs use the # remote cache, and local runs would need about 7 GB more. # # Workflow-file changes suppress pull_request runs under the org approval -# policy; validate edits to this file with workflow_dispatch on the branch. +# policy (merge_group runs are not suppressed: they run the queued copy); +# validate edits to this file with workflow_dispatch on the branch. name: Bazel on: @@ -176,12 +203,11 @@ on: required: false type: boolean default: false - dolt-lane: - description: "Dolt-backed lane: doltserver (hermetic, remote) or docker (testcontainers A/B control)" + fresh-test-results: + description: "Re-execute every test (--config=fresh: no cached test results), as nightly does" required: false - type: choice - default: "doltserver" - options: [ "doltserver", "docker" ] + type: boolean + default: false workflow_call: inputs: rbe: @@ -192,24 +218,43 @@ on: type: boolean required: false default: true - go-test-json-artifact: - description: > - Artifact (from the calling run) holding go-test.json, PR Core's - `go-test -json` on this commit; enables the equivalence skip-parity - check. nightly.yml sets it. - type: string - required: false - default: "" # A string, not a boolean: on push and dispatch inputs.integration is # null, and null == false in GitHub's loose comparison, so a boolean # test would silently stop the lane on main. integration: description: > - "off" skips bazel-integration; anything else (pr.yml and - bazel-farm.yml pass "on") runs it where remote execution is on. + "off" skips bazel-integration, bazel-cmd-dolt and + bazel-server-storage; anything else (pr.yml and bazel-farm.yml + pass "on") runs them where remote execution is on. type: string required: false default: "on" + # true (pr.yml only, policy-tested to equal its committed + # BAZEL_CMD_DOLT_REQUIRED flag): pr.yml's ci-gate requires + # bazel-cmd-dolt, which runs the whole integration-tagged cmd/bd suite + # (//cmd/bd:bd_dolt_server_test wraps the integration build's + # bd_test), so bazel-integration leaves //cmd/bd:bd_test to it and + # each of those tests runs once. A boolean: on push and dispatch it is + # null, which is not == true, so bazel-farm.yml, nightly.yml, push and + # dispatch (bazel-cmd-dolt advisory there) keep bd_test in + # bazel-integration. + cmd-dolt-required: + description: > + true (pr.yml only) drops //cmd/bd:bd_test from bazel-integration: + the required bazel-cmd-dolt lane runs those tests. + type: boolean + required: false + default: false + # true (nightly.yml only): every `bazel test` re-executes every test + # (--config=fresh), the run that samples flaky and -race failures. + # Everyone else reuses cached results for unchanged tests. A boolean: + # null on push, so push to main reuses too. + fresh-test-results: + description: > + true (nightly.yml) re-executes every test: no cached test results. + type: boolean + required: false + default: false build-artifact-name: description: > Name of the uploaded bd artifact (ci-build-artifacts layout). pr.yml @@ -237,9 +282,7 @@ on: required: false default: "off" # "on" (pr.yml only) runs package-mcp and package-npm in this call, - # which waits on nothing but the rbe job (F3: the legacy pr.yml jobs - # those gates used to need: detect-package-gates, build-artifacts, - # bazel-coverage, and the whole bazel call). bazel-farm.yml, nightly.yml + # which waits on nothing but the rbe job. bazel-farm.yml, nightly.yml # and direct runs (push, dispatch) keep the default "off": main.yml # keeps its own package jobs, and a fork-farm run has no bd artifact # consumer waiting on these. @@ -272,9 +315,12 @@ on: # request it, but no caller ever does: pr.yml and nightly.yml pass it # straight through (both are same-repo/trusted triggers only); # bazel-farm.yml's pull_request_target call does not, so no pre-warm - # credential ever reaches a fork-authored run (B1, security review of - # bdef342d5 - accepted risk is same-repo runs reaching the shared - # gascity scaler key, not forks). See + # credential reaches a fork-authored run before a maintainer queues + # it (B1, security review of bdef342d5 - accepted risk is same-repo + # runs reaching the shared gascity scaler key, not forks). Exception: + # a merge_group run executes the queued commit's workflows, so a + # queued fork PR's edits run with this key (merging-level trust; see + # the header). See # engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md, "rbe-west Pre-warm". RBE_POOL_APP_PRIVATE_KEY: required: false @@ -294,24 +340,36 @@ on: bazel-pure: description: "bazel-pure's job.status" value: ${{ jobs.bazel-pure.outputs.result }} + bazel-release-cross: + description: "bazel-release-cross's job.status" + value: ${{ jobs.bazel-release-cross.outputs.result }} bazel-embedded: description: "bazel-embedded's job.status" value: ${{ jobs.bazel-embedded.outputs.result }} bazel-integration: description: "bazel-integration's job.status" value: ${{ jobs.bazel-integration.outputs.result }} + # Mode remote: bazel-dolt-race runs both tiers and the member jobs + # skip; every other mode: the reverse. One side is always empty. bazel-doltserver: - description: "bazel-doltserver's job.status" - value: ${{ jobs.bazel-doltserver.outputs.result }} + description: "the dolt-server tier's job.status: bazel-dolt-race's in mode remote, bazel-doltserver's otherwise" + value: ${{ jobs.bazel-dolt-race.outputs.result || jobs.bazel-doltserver.outputs.result }} bazel-proxied: - description: "bazel-proxied's job.status" - value: ${{ jobs.bazel-proxied.outputs.result }} + description: "the proxied-server tier's job.status: bazel-dolt-race's in mode remote, bazel-proxied's otherwise" + value: ${{ jobs.bazel-dolt-race.outputs.result || jobs.bazel-proxied.outputs.result }} + # Mode remote: bazel-dolt-int runs both tiers and the member jobs + # skip; every other mode: the reverse. One side is always empty + # (item 5 A2). bazel-dolt-int reports its own per-tier classification + # (classify_tier_results.py), not job.status: the job carries no + # continue-on-error, so job.status alone would read failure for both + # tiers on a cmd-dolt-only failure, unlike bazel-cmd-dolt's own + # advisory, continue-on-error nature outside mode remote. bazel-server-storage: - description: "bazel-server-storage's job.status" - value: ${{ jobs.bazel-server-storage.outputs.result }} + description: "the server-Dolt storage tier's result: bazel-dolt-int's server_storage_result in mode remote, bazel-server-storage's job.status otherwise" + value: ${{ jobs.bazel-dolt-int.outputs.server_storage_result || jobs.bazel-server-storage.outputs.result }} bazel-cmd-dolt: - description: "bazel-cmd-dolt's job.status (advisory unless pr.yml's BAZEL_CMD_DOLT_REQUIRED is \"true\")" - value: ${{ jobs.bazel-cmd-dolt.outputs.result }} + description: "the cmd/bd Dolt-server tier's result (advisory unless pr.yml's BAZEL_CMD_DOLT_REQUIRED is \"true\"): bazel-dolt-int's cmd_dolt_result in mode remote, bazel-cmd-dolt's job.status otherwise" + value: ${{ jobs.bazel-dolt-int.outputs.cmd_dolt_result || jobs.bazel-cmd-dolt.outputs.result }} package-mcp: description: "package-mcp's job.status (empty unless package-gates is 'on')" value: ${{ jobs.package-mcp.outputs.result }} @@ -336,16 +394,40 @@ permissions: env: BD_DISABLE_METRICS: "1" BD_DISABLE_EVENT_FLUSH: "1" + # Appended last to every `bazel test` (after the lane's config and + # sole-run): --config=fresh (.bazelrc, --nocache_test_results) only when + # the caller asks for fresh results (nightly.yml, or a dispatch); empty + # otherwise, so results are cached and reused. See the header. + BAZEL_FRESH: ${{ inputs.fresh-test-results && '--config=fresh' || '' }} # Phase B report-only budget for T1/T2 (tools/bazel/critpath.py). BAZEL_BUDGET_SECONDS: "420" jobs: # The one place the execution mode is decided (see the header), so every - # job sees the same answer for the whole run. Its step reads one secret, and - # only to test it for emptiness: the step's env holds a boolean, never the - # value, and the step runs no repository code (no checkout). Fork and - # Dependabot pull_request runs get no secrets: rbe-fork-mint decides - # theirs (fork-ro, fork-rw, or cache while it is closed). + # job sees the same answer for the whole run. Its decide step reads one + # secret, and only to test it for emptiness: the step's env holds a + # boolean, never the value, and the step runs no repository code (it comes + # before the job's checkout). Fork and Dependabot pull_request runs get no + # secrets: rbe-fork-mint decides theirs (fork-ro, fork-rw, or cache while + # it is closed). + # + # Then, only when the lanes will execute remotely (enabled: modes remote, + # fork-ro, fork-rw; merge groups are mode remote), the worker-env preflight: + # rbe-west's pool workers run gascity main's tools/rbe/worker-env and + # advertise its pin, and the schedulers match //platforms:rbe_worker's pin + # exactly, so when gascity re-pins and beads' copy (tools/rbe/worker-env.txt + # and the pin in platforms/BUILD.bazel) falls behind, every remote action + # queues until the lanes time out. tools/rbe/worker-env-sync compares the + # copy with gascity main and, out of step, fails this job: every lane needs + # it, so they all skip and pr.yml's gate is red within a minute, with the + # diff and the pin to commit in this job's summary. A fallback to mode + # cache would not keep the PR green (pr.yml's ci-gate requires a remote + # run, BAZEL_REMOTE) and would only make it slower, so fail fast. gascity + # unreachable (exit 2: unknown) warns and proceeds: GitHub's availability + # never blocks a PR. The steps after decide run repository code (the PR's + # script, sparse-checked-out) but hold no secret and set no output: the + # job's outputs are decide's alone. nightly.yml runs the same check every + # night and opens a ci/infra issue. rbe: name: execution mode # Same-repo PRs (and merge_group/push/dispatch/schedule runs, which are @@ -359,6 +441,7 @@ jobs: enabled: ${{ steps.decide.outputs.enabled }} mode: ${{ steps.decide.outputs.mode }} tier: ${{ steps.decide.outputs.tier }} + rrc: ${{ steps.rrc.outputs.rrc }} steps: # The expressions' == is case-insensitive (RBE_WEST_WORKERS=True counts). # A push, merge_group or dispatch has no pull_request, so FORK is false. @@ -431,6 +514,68 @@ jobs: } >> "$GITHUB_OUTPUT" echo "Bazel execution mode: **$mode** (RBE_WEST_WORKERS on: $RBE_VAR_ON, rbe=off: $RBE_INPUT_OFF, rbe=cache: $RBE_INPUT_CACHE, fork: $FORK, dependabot: $DEPENDABOT, fork farm: $FORK_FARM, executor secret: $HAS_EXECUTOR)" | tee -a "$GITHUB_STEP_SUMMARY" + # Bazel's remote repo contents cache on rbe-west (ga-vnycm2.29, ported + # from gascity's bazel.yml; gascity + # engdocs/design/bazel-remote-repo-contents-cache.md): extracted + # external repositories (go_deps, the Go SDK, the LLVM slice) come from + # rbe-west's action cache instead of being re-fetched by every cold lane + # client. vars.RBE_REPO_CONTENTS_CACHE rolls it out: + # unset/off nothing (the default); + # seed main pushes seed the cache (rrc-seed); no lane reads it; + # canary seed, and bazel-test reads; + # on seed, and every lane in .github/scripts/rrc-lane-commands.txt + # reads. + # Mode remote only: fork pull_request runs see no vars (mode cache + # reads through setup-bazel's rc instead, in the jobs that pass + # BAZEL_RRC_READ, behind its probe of rbe-cache: write-bazelrc.sh). Any other value is off, with a warning, so a typo + # never fails the required gate. Like decide, this step runs no + # repository code (it comes before the checkout). + - name: Remote repo contents cache + id: rrc + env: + RRC: ${{ vars.RBE_REPO_CONTENTS_CACHE }} + MODE: ${{ steps.decide.outputs.mode }} + run: | + rrc=off + case "$RRC" in + "" | off) ;; + seed | canary | on) + if [ "$MODE" = remote ]; then rrc=$RRC; fi ;; + *) echo "::warning title=RBE_REPO_CONTENTS_CACHE::unknown value '$RRC' (want off, seed, canary or on); treated as off" ;; + esac + echo "rrc=$rrc" >> "$GITHUB_OUTPUT" + echo "Remote repo contents cache: **$rrc**" >> "$GITHUB_STEP_SUMMARY" + + # The worker-env preflight (see the job's comment): the PR's own copy, + # so a PR that syncs it passes. Only the two paths it compares. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + if: ${{ steps.decide.outputs.enabled == 'true' }} + with: + ref: ${{ inputs.checkout-sha }} + persist-credentials: false + allow-unsafe-pr-checkout: ${{ inputs.fork-farm == 'authorized' && github.event_name == 'pull_request_target' }} + sparse-checkout: | + tools/rbe + platforms + + - name: worker-env in step with gascity main + if: ${{ steps.decide.outputs.enabled == 'true' }} + env: + MODE: ${{ steps.decide.outputs.mode }} + run: | + rc=0 + tools/rbe/worker-env-sync main || rc=$? + case "$rc" in + 0) ;; + 1) + echo "::error title=Bazel lanes stopped before queueing::beads' worker-env pin is out of step with gascity main, so rbe-west has no worker for this run's remote actions (mode $MODE): copy tools/rbe/worker-env.txt and the worker-env pin in platforms/BUILD.bazel from gastownhall/gascity main (this job's summary has the diff and the line to commit; see tools/rbe/worker-env-sync)." + exit 1 + ;; + *) + echo "::warning title=rbe worker-env not checked::could not compare beads' worker-env pin with gascity main (exit $rc); proceeding in mode $MODE. If the lanes sit at 0 running actions, run tools/rbe/worker-env-sync." + ;; + esac + # Best-effort pre-warm of gastownhall/gascity's rbe-west OSS worker pool # (one Blacksmith-hosted NativeLink worker, rbe-worker-pool.yml) so it is # already booting instead of the lanes below waiting ~120s at "N actions, 0 @@ -536,7 +681,10 @@ jobs: # above): every byte this step executes comes from this workflow # definition, which pull_request_target always loads from the base # branch and which editing suppresses pull_request runs under the - # org's approval policy (see the header). steps.mint.outputs.token + # org's approval policy (see the header). Not on merge_group: a queue + # entry runs its own commit's copy of this file with no approval + # gate, so a queued fork PR's edit here runs with the key (review + # .github/ changes before queueing). steps.mint.outputs.token # appears nowhere else in this file (policy-tested): this is the only # step with the credential in its environment, and no step after it # touches a repository path or runs a local composite action. @@ -555,6 +703,16 @@ jobs: case "$n" in '') n=1 ;; *[!0-9]*) n=1 ;; + # Two or more digits is over the cap unless they are all zeros + # (still the kill switch); deciding it here keeps a string too + # long for the shell's integer compare from slipping past the + # -gt below unclamped. + ??*) + case "$n" in + *[!0]*) n=4 ;; + *) n=0 ;; + esac + ;; esac if [ "$n" -gt 4 ]; then n=4 @@ -571,7 +729,7 @@ jobs: fi active="$(gh run list -R "$POOL_REPO" --workflow "$POOL_WORKFLOW" --limit 50 \ - --json status --jq '[.[] | select(.status != "completed")] | length' 2>/dev/null)" + --json status --jq '[.[] | select(.status != "completed")] | length' 2>/dev/null)" || true case "$active" in '' | *[!0-9]*) echo "::warning title=rbe-west pre-warm::could not read $POOL_REPO/$POOL_WORKFLOW run status; skipping dispatch" @@ -619,9 +777,19 @@ jobs: # and cache runs (forks, rbe=off/cache, no secrets) build everything # they miss on the runner, so they get the larger GitHub-hosted one. # Fork modes (fork-ro/fork-rw) execute remotely but stay GitHub-hosted, - # like every fork job: the runner is only a client. + # like every fork job: the runner is only a client. ubuntu-24.04, not + # ubuntu-latest, in every lane that reads the remote repo contents cache + # in mode cache: the cached trees are Linux x86_64 ones from a 24.04 host + # (design R2), so the image must not move under them. + # + # 8 vCPU, not the other lanes' 4: with every action a remote cache hit, + # this lane's `bazel test //... --config=ci` spent ~63 of 81s in + # client-side loading and analysis (1798 packages, 66k configured + # targets; critical path 7.65s, merge group 37721729916), which Bazel + # parallelizes across the client's cores. Analysis-only, seeded runner + # cache (ga-vnycm2.8): 38.3s on 2 vCPU, 25.6s on 4, 16.3s on 8. needs: rbe - runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} # Remote execution goes to rbe-west (instance "oss", the Blacksmith-backed # worker pool shared with gascity). Skipped only in mode skip (same-repo # runs while RBE_WEST_WORKERS is unset). @@ -630,13 +798,13 @@ jobs: outputs: result: ${{ steps.result.outputs.result }} env: - # D2 step 3: on covered PRs (always mode remote) this lane is the only - # pre-merge run of pr.yml's legacy PR Core job, which ran every test - # every time and never retried: --config=sole-run then executes every - # test (no cached results) and fails on a remote cache eviction - # instead of re-running the whole invocation. Fork modes do the same - # (with BAZEL_COVERS_FORKS "true" it is their only run too). Local and - # cache runs (the legacy jobs still run) keep cached results. + # This lane is the only pre-merge run of the PR-core tests (pr.yml's + # retired PR Core job never retried): where it executes remotely + # (mode remote, and the fork modes) --config=sole-run fails on a + # remote cache eviction instead of re-running the whole invocation + # (whose retry could turn a failed test green). Test results are + # cached and reused like every lane's; only nightly re-executes them + # all (BAZEL_FRESH). BAZEL_SOLE_RUN: ${{ needs.rbe.outputs.enabled == 'true' && '--config=sole-run' || '' }} steps: # inputs.checkout-sha: see the header (empty: the event's default ref). @@ -670,6 +838,22 @@ jobs: - name: Verify restored Go modules run: go mod verify + # The remote repo contents cache, read-only (the rbe job's rrc output: + # canary, bazel-test; on, every lane). Each cached repository costs + # several sequential round trips, resolved on Skyframe's loading + # threads (default: the CPU count), so without 64 of them a cached read + # is slower than fetching. Both lines are key neutral (startup and + # loading only). Reading only: setup-bazel's rc keeps + # --noremote_upload_local_results, so nothing here writes; rrc-seed + # writes, on push to main. Before Set up Bazel: no server starts first. + - name: Remote repo contents cache (read) + if: ${{ needs.rbe.outputs.mode == 'remote' && (needs.rbe.outputs.rrc == 'on' || needs.rbe.outputs.rrc == 'canary') }} + run: | + { + echo 'startup --experimental_remote_repo_contents_cache' + echo 'common --loading_phase_threads=64' + } >> .bazelrc.local + - name: Set up Bazel id: bazel uses: ./.github/actions/setup-bazel @@ -680,6 +864,7 @@ jobs: RBE_TLS_CA: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CA || '' }} RBE_INSTANCE: ${{ needs.rbe.outputs.mode == 'remote' && 'oss' || '' }} BAZEL_FORK_CACHE: ${{ needs.rbe.outputs.mode == 'cache' && 'true' || '' }} + BAZEL_RRC_READ: 'true' # mode cache reads the repo contents cache through rbe-cache BAZEL_FORK_REMOTE: ${{ startsWith(needs.rbe.outputs.mode, 'fork-') && 'true' || '' }} RBE_FORK_TIER: ${{ needs.rbe.outputs.tier }} RBE_FORK_PR: ${{ github.event.pull_request.number }} @@ -712,18 +897,19 @@ jobs: set -o pipefail start=$(date +%s) rc=0 - bazel test //... --config=ci ${BAZEL_SOLE_RUN:+"$BAZEL_SOLE_RUN"} \ + bazel test //... --config=ci ${BAZEL_SOLE_RUN:+"$BAZEL_SOLE_RUN"} ${BAZEL_FRESH:+"$BAZEL_FRESH"} \ --profile="$RUNNER_TEMP/bazel-profile.json" \ --build_event_json_file="$RUNNER_TEMP/bazel-bep.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec.log.zst" \ + --experimental_build_event_upload_strategy=local \ 2>&1 | tee "$RUNNER_TEMP/bazel-test.log" || rc=$? echo "bazel test: exit $rc, $(( $(date +%s) - start ))s wall" | tee -a "$GITHUB_STEP_SUMMARY" echo >> "$GITHUB_STEP_SUMMARY" exit "$rc" - # pr.yml's build-artifacts job, built by Bazel: the same artifact name - # and layout (bd-linux-gms-pure, SHA256SUMS, build-manifest.txt). Where - # build-artifacts stands down (D2 step 3), its other consumers (PR - # Core, domain+uow) stand down there too. F3: the package gates build + # pr.yml's retired build-artifacts job, built by Bazel: the same + # artifact name and layout (bd-linux-gms-pure, SHA256SUMS, + # build-manifest.txt). F3: the package gates build # their own bd and no longer consume this artifact; it is kept for the # F3.5.3 SHA256SUMS comparison and for debugging. The script documents # which binary and how it differs from `go build`'s. @@ -752,18 +938,8 @@ jobs: python3 tools/bazel/critpath.py "$RUNNER_TEMP/bazel-profile.json" \ --tier "$TIER" --log "$RUNNER_TEMP/bazel-test.log" "${budget[@]}" - # nightly.yml's PR Core `go test -json` on the same commit. - - name: Download go-test results - if: ${{ always() && inputs.go-test-json-artifact != '' && steps.test.outcome != 'skipped' }} - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ${{ inputs.go-test-json-artifact }} - path: ${{ runner.temp }}/go-test-json - # Fails on any Go test that `go test` runs and Bazel did not (tag filter, - # manual, missing target, empty shard) unless it is allowlisted. With - # go test results (nightly) it also fails on tests that passed under go - # test and were skipped under Bazel; a PR run cannot see those. + # manual, missing target, empty shard) unless it is allowlisted. # It reads test.xml from bazel-testlogs, which --config=integration # shares with --config=ci (same output directory): if a job ever runs # both lanes, run each lane's equivalence right after its own @@ -773,11 +949,9 @@ jobs: timeout-minutes: 15 env: DETAILS: ${{ inputs.details && '--details' || '' }} - GO_TEST_JSON: ${{ inputs.go-test-json-artifact != '' && format('{0}/go-test-json/go-test.json', runner.temp) || '' }} run: | args=() if [ -n "$DETAILS" ]; then args+=("$DETAILS"); fi - if [ -n "$GO_TEST_JSON" ]; then args+=(--go-test-json "$GO_TEST_JSON"); fi python3 tools/bazel/equivalence.py --bep "$RUNNER_TEMP/bazel-bep.json" "${args[@]}" # Runs last: it rewrites BUILD files in the checkout. main moves BUILD @@ -839,15 +1013,51 @@ jobs: retention-days: 7 # Only a push to main that missed the exact key writes the runner cache. - # Its content (--repository_cache only, never the rc - # or credentials) is fixed by .bazelversion and MODULE.bazel.lock, so one - # entry per lock is enough and later pushes do not churn the quota. + # Its content (--repository_cache only, never the rc or credentials) is + # fixed by .bazelversion, MODULE.bazel and MODULE.bazel.lock, so one + # entry per triple is enough and later pushes do not churn the quota. - name: Save Bazel runner cache if: ${{ always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && steps.bazel.outcome == 'success' && steps.bazel.outputs.cache-hit != 'true' }} uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/bazel-ci-cache - key: bazel-repo-v3-${{ runner.os }}-${{ hashFiles('.bazelversion', 'MODULE.bazel.lock') }} + key: bazel-repo-v4-${{ runner.os }}-${{ hashFiles('.bazelversion', 'MODULE.bazel', 'MODULE.bazel.lock') }} + + # A redacted, schema'd summary of this invocation's BEP, exec log and + # profile: timing, per-mnemonic cache classes, cold actions, test + # results, repo-fetch time. tools/bazel/ci_analytics_extract.py reads + # only a field whitelist and validates every emitted string, so this + # (unlike the raw BEP file) is safe to upload unredacted; see its + # module docstring. Mirrors gascity's ci/analytics-extractor lane step. + - name: CI analytics summary + id: ci-analytics + if: "!cancelled() && steps.test.outcome != 'skipped'" + continue-on-error: true + timeout-minutes: 3 + env: + LANE: test + MODE: ${{ needs.rbe.outputs.mode }} + CHECK_RUN_ID: ${{ job.check_run_id }} + PR_HINT: ${{ github.event.pull_request.number || 0 }} + run: | + [ -f "$RUNNER_TEMP/bazel-bep.json" ] || exit 0 + zstd --version || echo "::warning::zstd missing: no per-mnemonic data in this lane's summary" + python3 tools/bazel/ci_analytics_extract.py \ + --lane "$LANE" --mode "$MODE" --check-run-id "$CHECK_RUN_ID" --pr-hint "$PR_HINT" \ + --invocation test "$RUNNER_TEMP/bazel-bep.json" "$RUNNER_TEMP/bazel-exec.log.zst" "$RUNNER_TEMP/bazel-profile.json" \ + --out "$RUNNER_TEMP/ci-analytics/ci-analytics.json" + + - name: Upload CI analytics summary + if: "!cancelled() && steps.ci-analytics.outcome == 'success'" + continue-on-error: true + timeout-minutes: 2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: ci-analytics-test-${{ github.run_attempt }} + path: ${{ runner.temp }}/ci-analytics/ci-analytics.json + retention-days: 7 + if-no-files-found: ignore # Last step: the job's result as a workflow_call output for pr.yml's # ci-gate. always() runs it after a failure, a timeout or a @@ -859,31 +1069,28 @@ jobs: JOB_STATUS: ${{ job.status }} run: echo "result=$JOB_STATUS" >> "$GITHUB_OUTPUT" - # pr.yml's check-cmd-bd-puregeo-tests job ("Check pure-Go and js/wasm - # boundaries (CGO_ENABLED=0)") with Bazel-built binaries: --config=pure - # builds bd and the job's three pure test binaries and runs its -short - # cmd/bd subset (PURE_CMD_BD_TESTS, kept equal to the job's -run selector by - # scripts/ci_workflow_test.go); --config=js-wasm builds the hooks test for - # js/wasm, which the Go SDK's go_js_wasm_exec runs under node with the job's - # exact pass-count guard. + # The CGO_ENABLED=0 portability boundaries (pr.yml's retired + # check-cmd-bd-puregeo-tests job) with Bazel-built binaries: --config=pure + # builds bd and three pure test binaries and runs the -short cmd/bd subset + # (PURE_CMD_BD_TESTS, pinned by scripts/ci_workflow_test.go); + # --config=js-wasm builds the hooks test for js/wasm, which the Go SDK's + # go_js_wasm_exec runs under node with an exact pass-count guard. bazel-pure: name: pure-Go and js/wasm # Same runner and skip rule as bazel-test. needs: rbe - runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} if: ${{ needs.rbe.outputs.mode != 'skip' }} timeout-minutes: 90 outputs: result: ${{ steps.result.outputs.result }} env: - PURE_CMD_BD_TESTS: '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir|NocgoFactoriesHonorSharedServer|NocgoNewDoltStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoNewReadOnlyStoreFromConfig_ErrorSuggestsCorrectFlag)' - # D2 step 3: on covered PRs (always mode remote) this lane is the only - # pre-merge run of pr.yml's legacy pure-Go and js/wasm job, which ran every test - # every time and never retried: --config=sole-run then executes every - # test (no cached results) and fails on a remote cache eviction - # instead of re-running the whole invocation. Fork modes do the same - # (with BAZEL_COVERS_FORKS "true" it is their only run too). Local and - # cache runs (the legacy jobs still run) keep cached results. + PURE_CMD_BD_TESTS: '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir|NocgoFactoriesHonorSharedServer|NocgoNewDoltStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoNewReadOnlyStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoStoreFactoriesRefuseGraphWorkspace)' + # The only pre-merge run of these boundaries: where it executes + # remotely --config=sole-run fails on a remote cache eviction instead + # of re-running the whole invocation (whose retry could turn a failed + # test green). Test results are cached and reused like every lane's; + # only nightly re-executes them all (BAZEL_FRESH). BAZEL_SOLE_RUN: ${{ needs.rbe.outputs.enabled == 'true' && '--config=sole-run' || '' }} steps: # inputs.checkout-sha: see the header (empty: the event's default ref). @@ -908,6 +1115,15 @@ jobs: with: node-version: '24' + # The remote repo contents cache, read-only, as in bazel-test. + - name: Remote repo contents cache (read) + if: ${{ needs.rbe.outputs.mode == 'remote' && needs.rbe.outputs.rrc == 'on' }} + run: | + { + echo 'startup --experimental_remote_repo_contents_cache' + echo 'common --loading_phase_threads=64' + } >> .bazelrc.local + - name: Set up Bazel id: bazel uses: ./.github/actions/setup-bazel @@ -918,14 +1134,20 @@ jobs: RBE_TLS_CA: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CA || '' }} RBE_INSTANCE: ${{ needs.rbe.outputs.mode == 'remote' && 'oss' || '' }} BAZEL_FORK_CACHE: ${{ needs.rbe.outputs.mode == 'cache' && 'true' || '' }} + BAZEL_RRC_READ: 'true' # mode cache reads the repo contents cache through rbe-cache BAZEL_FORK_REMOTE: ${{ startsWith(needs.rbe.outputs.mode, 'fork-') && 'true' || '' }} RBE_FORK_TIER: ${{ needs.rbe.outputs.tier }} RBE_FORK_PR: ${{ github.event.pull_request.number }} - name: Run js/wasm hook boundary + id: build-wasm run: | set -euo pipefail - bazel build --config=js-wasm //internal/hooks:hooks_test + bazel build --config=js-wasm //internal/hooks:hooks_test \ + --profile="$RUNNER_TEMP/bazel-profile-build-wasm.json" \ + --build_event_json_file="$RUNNER_TEMP/bazel-bep-build-wasm.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec-build-wasm.log.zst" \ + --experimental_build_event_upload_strategy=local bin="$(bazel cquery --config=js-wasm --output=files //internal/hooks:hooks_test)" cd internal/hooks @@ -965,12 +1187,17 @@ jobs: fi - name: Build cmd/bd and pure-Go test binaries (--config=pure) + id: build-pure run: >- bazel build --config=pure //cmd/bd:bd //cmd/bd:bd_test //internal/storage/embeddeddolt:embeddeddolt_test //internal/tracker:tracker_test + --profile="$RUNNER_TEMP/bazel-profile-build-pure.json" + --build_event_json_file="$RUNNER_TEMP/bazel-bep-build-pure.json" + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec-build-pure.log.zst" + --experimental_build_event_upload_strategy=local # `go build` with CGO_ENABLED=0 rejects a pure binary whose imports reach # dolt's cgo-only store/nbs (gozstd). Bazel compiles gozstd's pure stubs @@ -979,28 +1206,81 @@ jobs: # starts in the next step. -test.run=^$ runs no test (TestMain still # runs; BEADS_TEST_SKIP=dolt keeps tracker's from starting a container). - name: Start every pure-Go artifact (gozstd contamination check) + id: test-pure run: | set -euo pipefail + # Not instrumented: no BEP/exec-log/profile is captured for this + # one-off smoke invocation (design's bazel-pure invocation list + # names build-wasm, build-pure, test-pure and test-bd only). bazel run --config=pure //cmd/bd:bd -- version - bazel test --config=pure ${BAZEL_SOLE_RUN:+"$BAZEL_SOLE_RUN"} \ + bazel test --config=pure ${BAZEL_SOLE_RUN:+"$BAZEL_SOLE_RUN"} ${BAZEL_FRESH:+"$BAZEL_FRESH"} \ //internal/storage/embeddeddolt:embeddeddolt_test \ //internal/tracker:tracker_test \ --test_sharding_strategy=disabled \ '--test_arg=-test.run=^$' \ - --test_env=BEADS_TEST_SKIP=dolt + --test_env=BEADS_TEST_SKIP=dolt \ + --profile="$RUNNER_TEMP/bazel-profile-test-pure.json" \ + --build_event_json_file="$RUNNER_TEMP/bazel-bep-test-pure.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec-test-pure.log.zst" \ + --experimental_build_event_upload_strategy=local # One unsharded process, like `go test -run`; the test.xml check keeps a # selector that matches nothing from passing. - name: Run pure-Go cmd/bd test subset (--config=pure) + id: test-bd run: | set -euo pipefail - bazel test --config=pure ${BAZEL_SOLE_RUN:+"$BAZEL_SOLE_RUN"} //cmd/bd:bd_test \ + bazel test --config=pure ${BAZEL_SOLE_RUN:+"$BAZEL_SOLE_RUN"} ${BAZEL_FRESH:+"$BAZEL_FRESH"} //cmd/bd:bd_test \ --test_sharding_strategy=disabled \ - "--test_arg=-test.run=$PURE_CMD_BD_TESTS" + "--test_arg=-test.run=$PURE_CMD_BD_TESTS" \ + --profile="$RUNNER_TEMP/bazel-profile-test-bd.json" \ + --build_event_json_file="$RUNNER_TEMP/bazel-bep-test-bd.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec-test-bd.log.zst" \ + --experimental_build_event_upload_strategy=local n="$(grep -c ' 0 )) + # A redacted, schema'd summary of this job's four BEP-tracked + # invocations (build-wasm, build-pure, test-pure, test-bd; `bazel run + # ... -- version` above is deliberately not tracked, see its comment). + # Same contract as bazel-test's step; see its comment. + - name: CI analytics summary + id: ci-analytics + if: "!cancelled()" + continue-on-error: true + timeout-minutes: 3 + env: + LANE: pure + MODE: ${{ needs.rbe.outputs.mode }} + CHECK_RUN_ID: ${{ job.check_run_id }} + PR_HINT: ${{ github.event.pull_request.number || 0 }} + run: | + args=() + for step in build-wasm build-pure test-pure test-bd; do + bep="$RUNNER_TEMP/bazel-bep-$step.json" + [ -f "$bep" ] || continue + args+=(--invocation "$step" "$bep" "$RUNNER_TEMP/bazel-exec-$step.log.zst" "$RUNNER_TEMP/bazel-profile-$step.json") + done + [ "${#args[@]}" -gt 0 ] || exit 0 + zstd --version || echo "::warning::zstd missing: no per-mnemonic data in this lane's summary" + python3 tools/bazel/ci_analytics_extract.py \ + --lane "$LANE" --mode "$MODE" --check-run-id "$CHECK_RUN_ID" --pr-hint "$PR_HINT" \ + "${args[@]}" \ + --out "$RUNNER_TEMP/ci-analytics/ci-analytics.json" + + - name: Upload CI analytics summary + if: "!cancelled() && steps.ci-analytics.outcome == 'success'" + continue-on-error: true + timeout-minutes: 2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: ci-analytics-pure-${{ github.run_attempt }} + path: ${{ runner.temp }}/ci-analytics/ci-analytics.json + retention-days: 7 + if-no-files-found: ignore + # Last step: the job's result as a workflow_call output for pr.yml's # ci-gate. always() runs it after a failure, a timeout or a # cancellation too. @@ -1011,61 +1291,24 @@ jobs: JOB_STATUS: ${{ job.status }} run: echo "result=$JOB_STATUS" >> "$GITHUB_OUTPUT" - # pr-risk.yml's embedded-Dolt tier ("Test (Embedded Dolt Cmd N/20)", - # "Test (Embedded Dolt Storage N/5)", "Test (Embedded Dolt Conformance - - # core/audit)") as --config=embedded: the embedded-tagged variants of - # //cmd/bd:bd_test and //internal/storage/embeddeddolt:embeddeddolt_test. - # The shard variants run the jobs' own shard scripts and manifests, so Bazel - # shard k runs exactly the tests of job k. A job of its own rather than a - # second invocation in bazel-test: the tier's long race shards stay off - # bazel-test's critical path and budget, and it compiles nothing bazel-test - # does not (same race configuration, shared through the remote cache). - bazel-embedded: - name: embedded Dolt tier - # Remote execution only: skipped unless the rbe job chose remote, - # fork-ro or fork-rw (enabled; not in modes cache, local or skip). - # Locally the tier is 67 race test - # processes (50 cmd/bd shards + 15 embeddeddolt storage shards + 2 - # conformance partitions; ~24k test-seconds measured locally -- see - # scripts/ci/embedded_cmd_test_durations.json and - # scripts/ci/embedded_storage_test_durations.json -- up from an earlier, - # smaller test surface's ~7-10k estimate) on one runner, several hours - # per run on the pool whose job cap this track exists to relieve, and it - # proves nothing pr-risk.yml's embedded jobs (which do run for forks) do - # not. - # - # Shard counts: storage (15) is sized the way both tiers were originally - # meant to be -- the smallest count whose LPT-packed heaviest shard - # (scripts/ci/gen_embedded_storage_shard_manifest.py --weights=duration - # --repack) lands at or below the tier's own heaviest single top-level - # test (211-225s). cmd cannot reach that floor: Bazel hard-caps - # shard_count at 50 per sh_test-like rule ("Having more than 50 shards is - # indicative of poor test organization. Please reduce the number of - # shards." -- a native analysis-time error, not a style lint), and at 50 - # shards the cmd suite's LPT-packed heaviest shard is ~409.6s -- above - # its own single heaviest test's 239.7s, because the suite's total - # duration (~20145 test-seconds across 242 tests) is too large to flatten - # to the single-test floor within 50 bins. Clearing more shards would - # need either further per-test speedups spread across the suite or - # splitting bd_embedded_test into multiple <=50-shard sh_test rules with - # shard-index-offset plumbing through tools/bazel/go_test_manifest_shard.sh - # and check_shard_coverage.py; neither is done here, so this lane's floor - # is cmd's ~409.6s, not the ~240s a 5-minute lane (including this job's - # ~60s fixed cost) would need -- tracked as a follow-up, not silently - # hidden in the shard count. On RBE this makes the tier's wall time ~= - # that floor + fixed cost (checkout, build, shard dispatch), not ~= - # sum(durations)/shard_count the way a CPU-core-bound local sweep is -- - # each shard is its own remote action and runs concurrently with every - # other shard, farm capacity permitting. - # On same-repo pull_requests those jobs stand down (pr-risk.yml's - # bazel-coverage), so this lane is then the tier's only PR run - # and pr.yml's gate requires it to have run here and passed. - # The runs-on expression is the shared one: Blacksmith in mode remote, - # GitHub-hosted in the fork modes (a client only). + # Every release target (scripts/ci/release-targets.txt) on every PR, so a + # platform-gating mistake is caught here instead of at tag time (#5662): + # the whole tree, cgo off, one remote `bazel build --platforms=...` per + # target (the script's header has the coverage boundary: the cgo release + # builds are not compiled here). nogo (//tools/nogo) validates every one of + # those compiles, so this is also the lint and vet gate for files only + # other platforms build (//go:build windows, darwin, !linux ...; + # engdocs/LINTING.md). A job of its own rather than a step of bazel-pure: + # release_cross is a split transition that shares no analysis with the pure + # invocations, and as a step it was about a minute on the longest cached + # lane. Same runner and skip rule as bazel-pure (it runs in every mode but + # skip). + bazel-release-cross: + name: release cross-compile needs: rbe - runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} - if: ${{ needs.rbe.outputs.enabled == 'true' }} - timeout-minutes: 60 + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + if: ${{ needs.rbe.outputs.mode != 'skip' }} + timeout-minutes: 90 outputs: result: ${{ steps.result.outputs.result }} steps: @@ -1092,6 +1335,110 @@ jobs: RBE_FORK_TIER: ${{ needs.rbe.outputs.tier }} RBE_FORK_PR: ${{ github.event.pull_request.number }} + - name: Cross-compile every release target (--config=release-cross) + run: | + set -euo pipefail + ./scripts/ci/bazel-release-cross-compile.sh + + # Last step: the job's result as a workflow_call output for pr.yml's + # ci-gate. always() runs it after a failure, a timeout or a + # cancellation too. + - name: Record job result + id: result + if: ${{ always() }} + env: + JOB_STATUS: ${{ job.status }} + run: echo "result=$JOB_STATUS" >> "$GITHUB_OUTPUT" + + # pr-risk.yml's retired embedded-Dolt tier ("Test (Embedded Dolt Cmd N/20)", + # "Test (Embedded Dolt Storage N/5)", "Test (Embedded Dolt Conformance - + # core/audit)") as --config=embedded: those jobs, and the frozen 20-shard + # cmd block they read, no longer exist (see engdocs/TESTING.md) — this runs + # the embedded-tagged variants of + # //cmd/bd:bd_test and //internal/storage/embeddeddolt:embeddeddolt_test. + # The shard variants run the jobs' own shard scripts and manifests, so Bazel + # shard k runs exactly the tests of job k. A job of its own rather than a + # second invocation in bazel-test: the tier's long race shards stay off + # bazel-test's critical path and budget, and it compiles nothing bazel-test + # does not (same race configuration, shared through the remote cache). + bazel-embedded: + name: embedded Dolt tier + # Remote execution only: skipped unless the rbe job chose remote, + # fork-ro or fork-rw (enabled; not in modes cache, local or skip). + # Locally the tier is 72 race test + # processes (50 cmd/bd shards + 20 embeddeddolt storage shards + 2 + # conformance partitions; ~24k test-seconds measured locally -- see + # scripts/ci/embedded_cmd_test_durations.json and + # scripts/ci/embedded_storage_test_durations.json -- up from an earlier, + # smaller test surface's ~7-10k estimate) on one runner, several hours + # per run on the pool whose job cap this track exists to relieve, and it + # proved nothing pr-risk.yml's embedded jobs (which ran for forks before + # #7353 retired them) did not. + # + # Shard counts: storage (40): its tests are serial, so a shard's wall + # time is the sum of its tests, and CI shards run ~1.3-1.6x the rbe-west + # measurements; 40 is where the LPT-packed heaviest shard + # (scripts/ci/gen_embedded_storage_shard_manifest.py --weights=duration + # --repack) is its heaviest single top-level test, ~71s + # (TestLifecycleCloseReopenContract). cmd is a 100-shard block split + # over two targets, //cmd/bd:bd_embedded_test (shards 1-50) and + # //cmd/bd:bd_embedded_part2_test (51-100), because Bazel caps a rule at + # 50 shards ("Having more than 50 shards is indicative of poor test + # organization. Please reduce the number of shards." -- a native + # analysis-time error, not a style lint); the step below checks that + # the two ranges tile the block exactly once. After its slowest + # functions were split into smaller top-level tests, a cmd shard's wall + # time is its slowest test: ~45s median, and at most the *Concurrent + # stress tests' 65-145s (their bd subprocesses queue on one workspace's + # writer lock, so they cannot be split without changing what they test). On RBE the tier's wall time ~= that floor + # + fixed cost (checkout, build, shard dispatch), not ~= + # sum(durations)/shard_count the way a CPU-core-bound local sweep is -- + # each shard is its own remote action and runs concurrently with every + # other shard, farm capacity permitting. + # This lane is the tier's only PR run (pr-risk.yml's legacy jobs are + # retired) and pr.yml's gate requires it to have run here and passed. + # The runs-on expression is the shared one: Blacksmith in mode remote, + # GitHub-hosted in the fork modes (a client only). + needs: rbe + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + if: ${{ needs.rbe.outputs.enabled == 'true' }} + timeout-minutes: 60 + outputs: + result: ${{ steps.result.outputs.result }} + steps: + # inputs.checkout-sha: see the header (empty: the event's default ref). + # checkout v7 refuses a fork head on pull_request_target unless opted + # in; only bazel-farm.yml's authorized call opts in (false elsewhere). + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.checkout-sha }} + persist-credentials: false + allow-unsafe-pr-checkout: ${{ inputs.fork-farm == 'authorized' && github.event_name == 'pull_request_target' }} + + # The remote repo contents cache, read-only, as in bazel-test. + - name: Remote repo contents cache (read) + if: ${{ needs.rbe.outputs.mode == 'remote' && needs.rbe.outputs.rrc == 'on' }} + run: | + { + echo 'startup --experimental_remote_repo_contents_cache' + echo 'common --loading_phase_threads=64' + } >> .bazelrc.local + + - name: Set up Bazel + id: bazel + uses: ./.github/actions/setup-bazel + env: + BAZEL_REMOTE_EXECUTOR: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_WEST_EXECUTOR || '' }} + RBE_TLS_CERT: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CERT || '' }} + RBE_TLS_KEY: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_KEY || '' }} + RBE_TLS_CA: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CA || '' }} + RBE_INSTANCE: ${{ needs.rbe.outputs.mode == 'remote' && 'oss' || '' }} + BAZEL_FORK_CACHE: ${{ needs.rbe.outputs.mode == 'cache' && 'true' || '' }} + BAZEL_RRC_READ: 'true' # mode cache reads the repo contents cache through rbe-cache + BAZEL_FORK_REMOTE: ${{ startsWith(needs.rbe.outputs.mode, 'fork-') && 'true' || '' }} + RBE_FORK_TIER: ${{ needs.rbe.outputs.tier }} + RBE_FORK_PR: ${{ github.event.pull_request.number }} + # Bazel retries a flaky = True test (up to three attempts) and reports a # later pass as PASSED. The policy test greps BUILD files for it; this # asks Bazel itself, so a macro or a variable cannot hide one. Cheap: @@ -1112,8 +1459,11 @@ jobs: set -o pipefail start=$(date +%s) rc=0 - bazel test //... --config=embedded \ + bazel test //... --config=embedded ${BAZEL_FRESH:+"$BAZEL_FRESH"} \ --build_event_json_file="$RUNNER_TEMP/bazel-bep.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec.log.zst" \ + --profile="$RUNNER_TEMP/bazel-profile.json" \ + --experimental_build_event_upload_strategy=local \ 2>&1 | tee "$RUNNER_TEMP/bazel-test.log" || rc=$? echo "bazel test --config=embedded: exit $rc, $(( $(date +%s) - start ))s wall" | tee -a "$GITHUB_STEP_SUMMARY" exit "$rc" @@ -1125,8 +1475,7 @@ jobs: if: ${{ always() && steps.test.outcome != 'skipped' }} run: python3 tools/bazel/check_testcases.py --bep "$RUNNER_TEMP/bazel-bep.json" - # Since D2 step 1 this lane is the tier's only pre-merge run on - # same-repo PRs. The shard scripts discover tests from source, but each + # This lane is the tier's only pre-merge run. The shard scripts discover tests from source, but each # Bazel binary holds only its target's srcs: a listed test the binary # lacks matches nothing and passes silently. Fail unless every Bazel # shard ran exactly the tests its script lists (list-only mode, cheap), @@ -1138,9 +1487,11 @@ jobs: run: >- python3 tools/bazel/check_shard_coverage.py --bep "$RUNNER_TEMP/bazel-bep.json" - --suite //cmd/bd:bd_embedded_test .github/scripts/embedded-test-shard.sh 50 - --suite //internal/storage/embeddeddolt:embeddeddolt_embedded_test .github/scripts/embedded-storage-test-shard.sh 15 + --suite //cmd/bd:bd_embedded_test .github/scripts/embedded-test-shard.sh 50@0/100 + --suite //cmd/bd:bd_embedded_part2_test .github/scripts/embedded-test-shard.sh 50@50/100 + --suite //internal/storage/embeddeddolt:embeddeddolt_embedded_test .github/scripts/embedded-storage-test-shard.sh 40 --whole //internal/storage/embeddeddolt:embeddeddolt_conformance_core_test + --whole //internal/storage/embeddeddolt:embeddeddolt_conformance_core_slow_test --whole //internal/storage/embeddeddolt:embeddeddolt_conformance_audit_test - name: Upload test logs @@ -1155,6 +1506,56 @@ jobs: if-no-files-found: ignore retention-days: 7 + # The served targets' per-test durations, on every run: their pinned + # shard manifests (backend/http/served_pinned_shards.txt from + # tools/bazel/pin_shards.py, the corpus parts' split) are sized from a + # sharded run of this lane, and the logs above are kept only on failure. + # test.xml only, a few KB each. Telemetry like the CI analytics upload: + # nothing in CI reads it, so an artifact 5xx or stall must not fail or + # hold the lane (scripts TestBazelEmbeddedServedTimingsUploadIsTelemetry). + - name: Upload served test timings + if: ${{ !cancelled() && steps.test.outcome != 'skipped' }} + continue-on-error: true + timeout-minutes: 2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: bazel-embedded-served-testxml + path: bazel-testlogs/backend/http/**/test.xml + if-no-files-found: ignore + retention-days: 7 + + # Same redacted summary as bazel-test's; see its comment. + - name: CI analytics summary + id: ci-analytics + if: "!cancelled() && steps.test.outcome != 'skipped'" + continue-on-error: true + timeout-minutes: 3 + env: + LANE: embedded + MODE: ${{ needs.rbe.outputs.mode }} + CHECK_RUN_ID: ${{ job.check_run_id }} + PR_HINT: ${{ github.event.pull_request.number || 0 }} + run: | + [ -f "$RUNNER_TEMP/bazel-bep.json" ] || exit 0 + zstd --version || echo "::warning::zstd missing: no per-mnemonic data in this lane's summary" + python3 tools/bazel/ci_analytics_extract.py \ + --lane "$LANE" --mode "$MODE" --check-run-id "$CHECK_RUN_ID" --pr-hint "$PR_HINT" \ + --invocation test "$RUNNER_TEMP/bazel-bep.json" "$RUNNER_TEMP/bazel-exec.log.zst" "$RUNNER_TEMP/bazel-profile.json" \ + --out "$RUNNER_TEMP/ci-analytics/ci-analytics.json" + + - name: Upload CI analytics summary + if: "!cancelled() && steps.ci-analytics.outcome == 'success'" + continue-on-error: true + timeout-minutes: 2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: ci-analytics-embedded-${{ github.run_attempt }} + path: ${{ runner.temp }}/ci-analytics/ci-analytics.json + retention-days: 7 + if-no-files-found: ignore + # Last step: the job's result as a workflow_call output for pr.yml's # ci-gate. always() runs it after a failure, a timeout or a # cancellation too. @@ -1166,8 +1567,8 @@ jobs: run: echo "result=$JOB_STATUS" >> "$GITHUB_OUTPUT" # main.yml's "Main Linux integration packages (N/6)" and "Main Linux - # integration cmd/bd (N/8)" jobs (nightly.yml's Full Test Suite runs the - # same go test in one job) as --config=integration: every package with + # integration cmd/bd (N/8)" jobs (and nightly.yml's retired Full Test + # Suite, the same go test in one job) as --config=integration: every package with # -tags=integration,gms_pure_go, race, no -short, BEADS_TEST_SKIP=dolt (see # .bazelrc). A job of its own: ci and integration share bazel-testlogs, so # bazel-test's equivalence step would read this lane's test.xml if both ran @@ -1178,6 +1579,17 @@ jobs: # which no run here has. check_testcases.py still catches a target or # shard that ran no tests. pr.yml's gate requires it (BAZEL_INTEGRATION) # on same-repo PRs; see the header. + # Exactly-once cmd/bd: where the caller says bazel-cmd-dolt is required + # (inputs.cmd-dolt-required true: pr.yml while its + # BAZEL_CMD_DOLT_REQUIRED is "true"), the target set is //... minus + # //cmd/bd:bd_test. bazel-cmd-dolt has this job's `if:`, so it runs in + # every mode this one does (remote, fork-ro, fork-rw, cache; Dependabot + # too), bazel-gate.sh accepts the two lanes' skips in the same modes, and + # its //cmd/bd:bd_dolt_server_test runs that same integration-build + # bd_test without BEADS_TEST_SKIP=dolt (a superset: the skip only skips). + # Rollback: commit BAZEL_CMD_DOLT_REQUIRED "false" and pr.yml's + # cmd-dolt-required: false together (policy-tested equal); bd_test is + # back here on the next run. bazel-integration: name: integration # Remote (modes remote, fork-ro, fork-rw), or local with the read-only @@ -1189,9 +1601,12 @@ jobs: # A caller may turn it off with integration: "off"; pr.yml and # bazel-farm.yml pass "on". needs: rbe - runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} if: ${{ (needs.rbe.outputs.enabled == 'true' || needs.rbe.outputs.mode == 'cache') && inputs.integration != 'off' }} - timeout-minutes: 85 + # F5 S2 Variant A added the "Nogo: integration library files" step after + # `test`; +5 over the previous 85 keeps it headroom without exceeding + # TestBazelIntegrationJob's test-step-timeout+15 ceiling (75+15=90). + timeout-minutes: 90 outputs: result: ${{ steps.result.outputs.result }} steps: @@ -1204,6 +1619,15 @@ jobs: persist-credentials: false allow-unsafe-pr-checkout: ${{ inputs.fork-farm == 'authorized' && github.event_name == 'pull_request_target' }} + # The remote repo contents cache, read-only, as in bazel-test. + - name: Remote repo contents cache (read) + if: ${{ needs.rbe.outputs.mode == 'remote' && needs.rbe.outputs.rrc == 'on' }} + run: | + { + echo 'startup --experimental_remote_repo_contents_cache' + echo 'common --loading_phase_threads=64' + } >> .bazelrc.local + - name: Set up Bazel id: bazel uses: ./.github/actions/setup-bazel @@ -1214,6 +1638,7 @@ jobs: RBE_TLS_CA: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CA || '' }} RBE_INSTANCE: ${{ needs.rbe.outputs.mode == 'remote' && 'oss' || '' }} BAZEL_FORK_CACHE: ${{ needs.rbe.outputs.mode == 'cache' && 'true' || '' }} + BAZEL_RRC_READ: 'true' # mode cache reads the repo contents cache through rbe-cache BAZEL_FORK_REMOTE: ${{ startsWith(needs.rbe.outputs.mode, 'fork-') && 'true' || '' }} RBE_FORK_TIER: ${{ needs.rbe.outputs.tier }} RBE_FORK_PR: ${{ github.event.pull_request.number }} @@ -1227,25 +1652,68 @@ jobs: # make Bazel restart the build ("Lost inputs"), and ~30 with the cache # closed (the farm's kill switch: everything local, cold), which must # still fit so closing the cache does not turn fork PRs red. + # Where bazel-cmd-dolt is required, //cmd/bd:bd_test is excluded (see + # above): on a PR that changes cmd/bd or what it imports, its race + # link and 16 shards were this step's last ~2-3.5 minutes (runs of + # 2026-10-05: 215-314s wall, 113-208s of it after every other test + # had finished). - name: bazel test //... --config=integration id: test timeout-minutes: 75 + env: + EXCLUDE_TARGETS: ${{ inputs.cmd-dolt-required == true && '-//cmd/bd:bd_test' || '' }} run: | set -o pipefail start=$(date +%s) rc=0 - bazel test //... --config=integration \ + if [[ -n "$EXCLUDE_TARGETS" ]]; then + echo "bazel-cmd-dolt is required: excluding $EXCLUDE_TARGETS (it runs there)" | tee -a "$GITHUB_STEP_SUMMARY" + fi + bazel test //... --config=integration ${BAZEL_FRESH:+"$BAZEL_FRESH"} \ --build_event_json_file="$RUNNER_TEMP/bazel-bep.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec.log.zst" \ + --profile="$RUNNER_TEMP/bazel-profile.json" \ + --experimental_build_event_upload_strategy=local \ + ${EXCLUDE_TARGETS:+-- "$EXCLUDE_TARGETS"} \ 2>&1 | tee "$RUNNER_TEMP/bazel-test.log" || rc=$? echo "bazel test --config=integration: exit $rc, $(( $(date +%s) - start ))s wall" | tee -a "$GITHUB_STEP_SUMMARY" exit "$rc" - # As in bazel-embedded. dolt_version_test is a plain sh_test (no Go - # testcases in its test.xml), which --config=integration's tag filter - # keeps, unlike the embedded one. + # As in bazel-embedded. dolt_version_test and the repository guards in + # //scripts/repochecks are plain sh_tests (no Go testcases in their + # test.xml), which --config=integration's tag filter keeps, unlike the + # embedded one. - name: Every target and shard ran tests if: ${{ always() && steps.test.outcome != 'skipped' }} - run: python3 tools/bazel/check_testcases.py --bep "$RUNNER_TEMP/bazel-bep.json" --not-go //tools/bazel:dolt_version_test + run: python3 tools/bazel/check_testcases.py --bep "$RUNNER_TEMP/bazel-bep.json" --not-go //tools/bazel:dolt_version_test --not-go //scripts/repochecks:all + + # F5 S2 Variant A: the integration/doltserver-integration/doltserver-cmd + # configuration (--config=integration plus race) has no full-lane nogo + # owner (every lane above passes --norun_validations, .bazelrc). This + # narrow build keeps full nogo (vet + golangci-lint) on the + # configuration's non-test library package, + # //internal/testutil/integration, which every one of those lanes + # compiles; the 56 integration-tagged _test.go files this does not + # cover are the accepted loss (tools/nogo/unvalidated_integration_tests.txt, + # f5-spec.md §3). --keep_going so one finding does not hide another. + # scripts/nogo_lint_policy_test.go's + # TestNogoConfigurationsHaveOneValidatingLane pins this step as the + # configuration's sole validating lane. + - name: "Nogo: integration library files" + id: nogo-integration + if: ${{ always() && steps.test.outcome != 'skipped' }} + timeout-minutes: 10 + run: | + set -o pipefail + start=$(date +%s) + rc=0 + bazel build --config=integration --@rules_go//go/config:race --keep_going \ + --output_groups=nogo_fix \ + -- //internal/testutil/integration:integration \ + 2>&1 | tee "$RUNNER_TEMP/bazel-nogo-integration.log" || rc=$? + procs=$(grep -oE 'INFO: [0-9]+ process' "$RUNNER_TEMP/bazel-nogo-integration.log" | tail -1 || true) + echo "nogo-integration: exit $rc, $(( $(date +%s) - start ))s wall${procs:+, $procs}" | tee -a "$GITHUB_STEP_SUMMARY" + exit "$rc" - name: Upload test logs if: ${{ failure() && steps.test.outcome != 'skipped' }} @@ -1259,6 +1727,37 @@ jobs: if-no-files-found: ignore retention-days: 7 + # Same redacted summary as bazel-test's; see its comment. + - name: CI analytics summary + id: ci-analytics + if: "!cancelled() && steps.test.outcome != 'skipped'" + continue-on-error: true + timeout-minutes: 3 + env: + LANE: integration + MODE: ${{ needs.rbe.outputs.mode }} + CHECK_RUN_ID: ${{ job.check_run_id }} + PR_HINT: ${{ github.event.pull_request.number || 0 }} + run: | + [ -f "$RUNNER_TEMP/bazel-bep.json" ] || exit 0 + zstd --version || echo "::warning::zstd missing: no per-mnemonic data in this lane's summary" + python3 tools/bazel/ci_analytics_extract.py \ + --lane "$LANE" --mode "$MODE" --check-run-id "$CHECK_RUN_ID" --pr-hint "$PR_HINT" \ + --invocation test "$RUNNER_TEMP/bazel-bep.json" "$RUNNER_TEMP/bazel-exec.log.zst" "$RUNNER_TEMP/bazel-profile.json" \ + --out "$RUNNER_TEMP/ci-analytics/ci-analytics.json" + + - name: Upload CI analytics summary + if: "!cancelled() && steps.ci-analytics.outcome == 'success'" + continue-on-error: true + timeout-minutes: 2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: ci-analytics-integration-${{ github.run_attempt }} + path: ${{ runner.temp }}/ci-analytics/ci-analytics.json + retention-days: 7 + if-no-files-found: ignore + # Last step: the job's result as a workflow_call output for pr.yml's # ci-gate. always() runs it after a failure, a timeout or a # cancellation too. @@ -1269,32 +1768,35 @@ jobs: JOB_STATUS: ${{ job.status }} run: echo "result=$JOB_STATUS" >> "$GITHUB_OUTPUT" - # pr.yml's container-backed jobs, "Test (storage domain + uow)" and - # "Contract corpus", as Bazel's dolt-server lane: --config=doltserver runs - # the dolt-server variants (domain/..., uow in 8 shards, tracker/..., - # doctor/fix, protocol in 8 shards), each of which starts its own dolt - # sql-server from the pinned dolt, so they execute on the remote workers - # like any other test (locally for forks and rbe=off). The docker lane - # (--config=docker: the same suites against testcontainers on this runner, - # no-remote-exec) stays the A/B control: dispatch with dolt-lane=docker. + # pr.yml's retired container-backed jobs, "Test (storage domain + uow)" + # and "Contract corpus", as Bazel's dolt-server lane: --config=doltserver + # runs the dolt-server variants (domain/..., uow in 8 shards, tracker/..., + # doctor/fix, protocol in 8 shards, testutil), each of which starts its + # own dolt sql-server from the pinned dolt, so they execute on the remote + # workers like any other test (locally with rbe=off). + # Not in mode remote: there bazel-dolt-race runs this tier together with + # the proxied-server tier and reports for both (item 5). In the fork + # modes, cache and local there is no in-flight deduplication of one + # client's actions and the client does the work, so a union would cost the + # sum of the two tiers instead of the max: this job runs there as before. bazel-doltserver: name: dolt-server lane - # Same runner and skip rule as bazel-test. + # Same runner as bazel-test; bazel-test's skip rule, plus mode remote + # (bazel-dolt-race's). needs: rbe - runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} - if: ${{ needs.rbe.outputs.mode != 'skip' }} + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} + if: ${{ needs.rbe.outputs.mode != 'skip' && needs.rbe.outputs.mode != 'remote' }} timeout-minutes: 90 outputs: result: ${{ steps.result.outputs.result }} env: - BAZEL_DOLT_LANE: ${{ inputs.dolt-lane || 'doltserver' }} - # D2 step 3: on covered PRs (always mode remote) this lane is the only - # pre-merge run of pr.yml's legacy domain+uow and contract corpus jobs, which ran every test - # every time and never retried: --config=sole-run then executes every - # test (no cached results) and fails on a remote cache eviction - # instead of re-running the whole invocation. Fork modes do the same - # (with BAZEL_COVERS_FORKS "true" it is their only run too). Local and - # cache runs (the legacy jobs still run) keep cached results. + # This lane is the only pre-merge run of these suites (the go test + # jobs it replaced never retried): where it executes remotely + # --config=sole-run fails on a remote cache eviction instead of + # re-running the whole invocation (whose retry could turn a failed + # test green). + # Test results are cached and reused like every lane's; only nightly + # re-executes them all (BAZEL_FRESH). BAZEL_SOLE_RUN: ${{ needs.rbe.outputs.enabled == 'true' && '--config=sole-run' || '' }} steps: # inputs.checkout-sha: see the header (empty: the event's default ref). @@ -1306,6 +1808,15 @@ jobs: persist-credentials: false allow-unsafe-pr-checkout: ${{ inputs.fork-farm == 'authorized' && github.event_name == 'pull_request_target' }} + # The remote repo contents cache, read-only, as in bazel-test. + - name: Remote repo contents cache (read) + if: ${{ needs.rbe.outputs.mode == 'remote' && needs.rbe.outputs.rrc == 'on' }} + run: | + { + echo 'startup --experimental_remote_repo_contents_cache' + echo 'common --loading_phase_threads=64' + } >> .bazelrc.local + - name: Set up Bazel id: bazel uses: ./.github/actions/setup-bazel @@ -1316,16 +1827,11 @@ jobs: RBE_TLS_CA: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CA || '' }} RBE_INSTANCE: ${{ needs.rbe.outputs.mode == 'remote' && 'oss' || '' }} BAZEL_FORK_CACHE: ${{ needs.rbe.outputs.mode == 'cache' && 'true' || '' }} + BAZEL_RRC_READ: 'true' # mode cache reads the repo contents cache through rbe-cache BAZEL_FORK_REMOTE: ${{ startsWith(needs.rbe.outputs.mode, 'fork-') && 'true' || '' }} RBE_FORK_TIER: ${{ needs.rbe.outputs.tier }} RBE_FORK_PR: ${{ github.event.pull_request.number }} - # Docker lane only (the A/B control), as in the mirrored jobs; its - # tests fail rather than skip without the image. - - name: Pull Dolt sql-server image - if: ${{ env.BAZEL_DOLT_LANE == 'docker' }} - run: ./scripts/ci/pull-dolt-image.sh - - name: bazel test //... --config=doltserver id: test timeout-minutes: 80 @@ -1333,8 +1839,13 @@ jobs: set -o pipefail start=$(date +%s) rc=0 - bazel test //... "--config=$BAZEL_DOLT_LANE" ${BAZEL_SOLE_RUN:+"$BAZEL_SOLE_RUN"} 2>&1 | tee "$RUNNER_TEMP/bazel-test.log" || rc=$? - echo "bazel test --config=$BAZEL_DOLT_LANE: exit $rc, $(( $(date +%s) - start ))s wall" | tee -a "$GITHUB_STEP_SUMMARY" + bazel test //... --config=doltserver ${BAZEL_SOLE_RUN:+"$BAZEL_SOLE_RUN"} ${BAZEL_FRESH:+"$BAZEL_FRESH"} \ + --build_event_json_file="$RUNNER_TEMP/bazel-bep.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec.log.zst" \ + --profile="$RUNNER_TEMP/bazel-profile.json" \ + --experimental_build_event_upload_strategy=local \ + 2>&1 | tee "$RUNNER_TEMP/bazel-test.log" || rc=$? + echo "bazel test --config=doltserver: exit $rc, $(( $(date +%s) - start ))s wall" | tee -a "$GITHUB_STEP_SUMMARY" exit "$rc" - name: Upload test logs @@ -1342,13 +1853,44 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: overwrite: true # a job re-run is the same run: replace, not 409 - name: bazel-${{ env.BAZEL_DOLT_LANE }}-testlogs + name: bazel-doltserver-testlogs path: | bazel-testlogs/**/test.log bazel-testlogs/**/test.xml if-no-files-found: ignore retention-days: 7 + # Same redacted summary as bazel-test's; see its comment. + - name: CI analytics summary + id: ci-analytics + if: "!cancelled() && steps.test.outcome != 'skipped'" + continue-on-error: true + timeout-minutes: 3 + env: + LANE: doltserver + MODE: ${{ needs.rbe.outputs.mode }} + CHECK_RUN_ID: ${{ job.check_run_id }} + PR_HINT: ${{ github.event.pull_request.number || 0 }} + run: | + [ -f "$RUNNER_TEMP/bazel-bep.json" ] || exit 0 + zstd --version || echo "::warning::zstd missing: no per-mnemonic data in this lane's summary" + python3 tools/bazel/ci_analytics_extract.py \ + --lane "$LANE" --mode "$MODE" --check-run-id "$CHECK_RUN_ID" --pr-hint "$PR_HINT" \ + --invocation test "$RUNNER_TEMP/bazel-bep.json" "$RUNNER_TEMP/bazel-exec.log.zst" "$RUNNER_TEMP/bazel-profile.json" \ + --out "$RUNNER_TEMP/ci-analytics/ci-analytics.json" + + - name: Upload CI analytics summary + if: "!cancelled() && steps.ci-analytics.outcome == 'success'" + continue-on-error: true + timeout-minutes: 2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: ci-analytics-doltserver-${{ github.run_attempt }} + path: ${{ runner.temp }}/ci-analytics/ci-analytics.json + retention-days: 7 + if-no-files-found: ignore + # Last step: the job's result as a workflow_call output for pr.yml's # ci-gate. always() runs it after a failure, a timeout or a # cancellation too. @@ -1359,30 +1901,33 @@ jobs: JOB_STATUS: ${{ job.status }} run: echo "result=$JOB_STATUS" >> "$GITHUB_OUTPUT" - # Like pr-risk.yml's proxied-server tier, "Test (Proxied Dolt Cmd N/15)", - # as --config=doltserver-proxied: //cmd/bd:bd_proxied_test runs the shard - # script, so shard k runs exactly that manifest entry's tests. This lane - # runs 30 shards of its own (.github/scripts/proxied-cmd-test-shards.txt's - # duration-balanced 30-block; see scripts/ci/proxied_test_durations.json), - # not the legacy jobs' 15 — shard k here is not the same split as their - # shard k. Same build as --config=doltserver (race bd_test, non-race + # Like pr-risk.yml's retired proxied-server tier, "Test (Proxied Dolt Cmd + # N/15)" (that job, and the frozen 15-shard block it read, no longer exist; + # see engdocs/TESTING.md), as --config=doltserver-proxied: + # //cmd/bd:bd_proxied_test runs the shard script, so shard k runs exactly + # that manifest entry's tests. This lane runs 34 shards of its own + # (.github/scripts/proxied-cmd-test-shards.txt's duration-balanced 34-block; + # see scripts/ci/proxied_test_durations.json) — shard k here was never the + # same split as the retired job's shard k. Same build as --config=doltserver + # (race bd_test, non-race # bd_for_tests), shared with bazel-doltserver through the remote cache. - # PR Risk builds its bd-cmd-test with -race, as here; main.yml's - # test-proxied-cmd twin uses build-artifacts' non-race bd-cmd-test, so - # this lane is the stricter of the two. A job of its own, not gated by - # any integration switch: it runs in pr.yml's call and its gate requires - # it (BAZEL_PROXIED). + # The test binary is race, as PR Risk's retired jobs built it. It also runs + # //cmd/bd:bd_managed_local_test, the managed-local proxied lifecycle + # (formerly proxied-local-smoke.yml) in a loopback-only network + # namespace, which needs the workers' unprivileged user namespaces. A job + # of its own, not gated by any integration switch: it runs in pr.yml's + # call and its gate requires it (BAZEL_PROXIED). Fork modes only: in mode + # remote bazel-dolt-race runs this tier (see bazel-doltserver's comment). bazel-proxied: name: proxied-server tier # Remote execution only, like bazel-embedded: 30 concurrent shards, each # running its own dolt sql-server busy on ~4 cores, do not fit a # GitHub-hosted runner regardless of any single shard's wall time. - # On same-repo pull_requests the legacy jobs stand down (pr-risk.yml's - # bazel-coverage; D2 step 2), so this lane is then the tier's only PR - # run and pr.yml's gate requires it to have run here and passed. + # This lane is the tier's only PR run (pr-risk.yml's legacy jobs are + # retired) and pr.yml's gate requires it to have run here and passed. needs: rbe - runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} - if: ${{ needs.rbe.outputs.enabled == 'true' }} + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + if: ${{ needs.rbe.outputs.enabled == 'true' && needs.rbe.outputs.mode != 'remote' }} timeout-minutes: 30 outputs: result: ${{ steps.result.outputs.result }} @@ -1396,6 +1941,15 @@ jobs: persist-credentials: false allow-unsafe-pr-checkout: ${{ inputs.fork-farm == 'authorized' && github.event_name == 'pull_request_target' }} + # The remote repo contents cache, read-only, as in bazel-test. + - name: Remote repo contents cache (read) + if: ${{ needs.rbe.outputs.mode == 'remote' && needs.rbe.outputs.rrc == 'on' }} + run: | + { + echo 'startup --experimental_remote_repo_contents_cache' + echo 'common --loading_phase_threads=64' + } >> .bazelrc.local + - name: Set up Bazel id: bazel uses: ./.github/actions/setup-bazel @@ -1406,6 +1960,7 @@ jobs: RBE_TLS_CA: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CA || '' }} RBE_INSTANCE: ${{ needs.rbe.outputs.mode == 'remote' && 'oss' || '' }} BAZEL_FORK_CACHE: ${{ needs.rbe.outputs.mode == 'cache' && 'true' || '' }} + BAZEL_RRC_READ: 'true' # mode cache reads the repo contents cache through rbe-cache BAZEL_FORK_REMOTE: ${{ startsWith(needs.rbe.outputs.mode, 'fork-') && 'true' || '' }} RBE_FORK_TIER: ${{ needs.rbe.outputs.tier }} RBE_FORK_PR: ${{ github.event.pull_request.number }} @@ -1423,35 +1978,16 @@ jobs: fi # Remote: each shard's Go timeout is its job's 15m, 1200s Bazel cap, - # plus a compile. scripts/ci/proxied_test_durations.json's 176 entries - # are each a clean, single-job (no concurrent heavy bazel/dolt job - # intentionally started on the box; see that file's header for its - # ambient-contention caveat), -test.parallel=4 top-level-test - # duration — the exact config this job uses — from a single fresh, - # manifest-aligned 30-shard sweep's own (errors="0", - # so a failing-but-complete suite's time is still trustworthy); every - # one of the 176 discovered tests completed inside its shard run, so - # no `bazel run` leaf-summation workaround was needed this time. See - # that file's header for the full methodology, including why an - # earlier -test.parallel=1 (serial) capture was replaced: serial - # timings don't model this lane (which always runs parallel=4), and - # an independent re-review measured near-zero correlation (r=0.08) - # between the serial-derived predicted shard load and actual - # parallel=4 wall time. - # - # Measured per-shard wall time for the full 30-shard local sweep that - # produced this data: shards ranged from roughly 32s to 341s, with - # most clustering well under this job's 25m step timeout / 30m job - # timeout. After repacking with these corrected weights, the LPT - # estimate clusters every shard within a few seconds of ~355-360s - # (sum of all 176 measured durations / 30 shards) — no single test or - # small group of tests dominates a shard the way the discarded serial - # data wrongly implied. This is a local, single-job measurement, not - # a verified RBE forecast (this job has only ever run remote); if a - # shard's RBE wall time diverges sharply from this local estimate, - # that is RBE throughput differing from local execution, not - # necessarily a regression — compare against this job's own recent - # run history before assuming a hang. + # plus a compile. The 34-shard block is LPT-packed by + # scripts/ci/proxied_test_durations.json, a rbe-west capture of each + # top-level test's summed leaf-test time (see its header), to ~187 + # cost-seconds per shard; shards are expected around 55-95s (the same + # packed cost has run up to 1.45x the median wall time). Nearly + # all of that is `bd init --proxied-server` against the shard's dolt + # sql-server, ~one per subtest, each as a user scoped to its own + # database (cmd/bd/proxied_shared_harness_test.go); a shard running far + # longer is worth comparing against this job's recent history before + # assuming a hang. - name: bazel test //... --config=doltserver-proxied id: test timeout-minutes: 25 @@ -1459,8 +1995,11 @@ jobs: set -o pipefail start=$(date +%s) rc=0 - bazel test //... --config=doltserver-proxied \ + bazel test //... --config=doltserver-proxied ${BAZEL_FRESH:+"$BAZEL_FRESH"} \ --build_event_json_file="$RUNNER_TEMP/bazel-bep.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec.log.zst" \ + --profile="$RUNNER_TEMP/bazel-profile.json" \ + --experimental_build_event_upload_strategy=local \ 2>&1 | tee "$RUNNER_TEMP/bazel-test.log" || rc=$? echo "bazel test --config=doltserver-proxied: exit $rc, $(( $(date +%s) - start ))s wall" | tee -a "$GITHUB_STEP_SUMMARY" exit "$rc" @@ -1470,15 +2009,14 @@ jobs: if: ${{ always() && steps.test.outcome != 'skipped' }} run: python3 tools/bazel/check_testcases.py --bep "$RUNNER_TEMP/bazel-bep.json" - # Since D2 step 2 this lane is the tier's only pre-merge run on - # same-repo PRs: as in bazel-embedded, every Bazel shard must run + # This lane is the tier's only pre-merge run: as in bazel-embedded, every Bazel shard must run # exactly the tests its shard script lists, and not only skips. - name: Every listed test ran in its shard if: ${{ always() && steps.test.outcome != 'skipped' }} run: >- python3 tools/bazel/check_shard_coverage.py --bep "$RUNNER_TEMP/bazel-bep.json" - --suite //cmd/bd:bd_proxied_test .github/scripts/proxied-test-shard.sh 30 + --suite //cmd/bd:bd_proxied_test .github/scripts/proxied-test-shard.sh 34 - name: Upload test logs if: ${{ failure() && steps.test.outcome != 'skipped' }} @@ -1492,6 +2030,37 @@ jobs: if-no-files-found: ignore retention-days: 7 + # Same redacted summary as bazel-test's; see its comment. + - name: CI analytics summary + id: ci-analytics + if: "!cancelled() && steps.test.outcome != 'skipped'" + continue-on-error: true + timeout-minutes: 3 + env: + LANE: proxied-server + MODE: ${{ needs.rbe.outputs.mode }} + CHECK_RUN_ID: ${{ job.check_run_id }} + PR_HINT: ${{ github.event.pull_request.number || 0 }} + run: | + [ -f "$RUNNER_TEMP/bazel-bep.json" ] || exit 0 + zstd --version || echo "::warning::zstd missing: no per-mnemonic data in this lane's summary" + python3 tools/bazel/ci_analytics_extract.py \ + --lane "$LANE" --mode "$MODE" --check-run-id "$CHECK_RUN_ID" --pr-hint "$PR_HINT" \ + --invocation test "$RUNNER_TEMP/bazel-bep.json" "$RUNNER_TEMP/bazel-exec.log.zst" "$RUNNER_TEMP/bazel-profile.json" \ + --out "$RUNNER_TEMP/ci-analytics/ci-analytics.json" + + - name: Upload CI analytics summary + if: "!cancelled() && steps.ci-analytics.outcome == 'success'" + continue-on-error: true + timeout-minutes: 2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: ci-analytics-proxied-server-${{ github.run_attempt }} + path: ${{ runner.temp }}/ci-analytics/ci-analytics.json + retention-days: 7 + if-no-files-found: ignore + # Last step: the job's result as a workflow_call output for pr.yml's # ci-gate. always() runs it after a failure, a timeout or a # cancellation too. @@ -1502,26 +2071,208 @@ jobs: JOB_STATUS: ${{ job.status }} run: echo "result=$JOB_STATUS" >> "$GITHUB_OUTPUT" + # Item 5 (scripts/bazel_dolt_race_test.go): the dolt-server and + # proxied-server tiers in one `bazel test --config=dolt-race` (.bazelrc: + # exactly the union of --config=doltserver's and + # --config=doltserver-proxied's lines, one tag filter for both), mode + # remote only, in place of bazel-doltserver and bazel-proxied, which run + # in every other mode. One client waits on rbe-west for both tiers' + # shards at once (27 + 35 test actions, under the remote-exec config's 64 + # jobs), so the job ends with the slower tier and saves the other's + # runner. Each member target's test action key is unchanged (aquery- + # verified), so cached results carry over both ways, and a revert of the + # cutover re-executes nothing. Gated: its job.status is both the + # bazel-doltserver and the bazel-proxied workflow_call output (a failure + # in either tier fails both ids, which are both required). Every step has + # a timeout and the job's exceeds their sum by 5 minutes while staying + # under the merge queue's 60-minute check timeout + # (TestBazelDoltRaceJobTimeouts), so a hang fails a named step instead of + # dropping the merge group. The member jobs' configs and the union's must + # stay key-identical: the mode decides which runs (TestBazelDoltRaceConfigIsMemberUnion). + # Its ci-analytics LANE is dolt-race. + bazel-dolt-race: + name: dolt-race + needs: rbe + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + if: ${{ needs.rbe.outputs.mode == 'remote' }} + # At least every step's timeout-minutes plus 5, and below the merge + # queue's 60-minute check timeout so this job alone cannot exhaust it + # (TestBazelDoltRaceJobTimeouts). Not a whole-run bound: the rbe job runs + # first and sibling lanes have longer timeouts. + timeout-minutes: 56 + outputs: + result: ${{ steps.result.outputs.result }} + steps: + # inputs.checkout-sha: see the header (empty: the event's default ref). + # checkout v7 refuses a fork head on pull_request_target unless opted + # in; only bazel-farm.yml's authorized call opts in (false elsewhere). + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + timeout-minutes: 5 + with: + ref: ${{ inputs.checkout-sha }} + persist-credentials: false + allow-unsafe-pr-checkout: ${{ inputs.fork-farm == 'authorized' && github.event_name == 'pull_request_target' }} + + # The remote repo contents cache, read-only, as in bazel-test. + - name: Remote repo contents cache (read) + if: ${{ needs.rbe.outputs.mode == 'remote' && needs.rbe.outputs.rrc == 'on' }} + timeout-minutes: 1 + run: | + { + echo 'startup --experimental_remote_repo_contents_cache' + echo 'common --loading_phase_threads=64' + } >> .bazelrc.local + + - name: Set up Bazel + id: bazel + timeout-minutes: 5 + uses: ./.github/actions/setup-bazel + env: + BAZEL_REMOTE_EXECUTOR: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_WEST_EXECUTOR || '' }} + RBE_TLS_CERT: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CERT || '' }} + RBE_TLS_KEY: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_KEY || '' }} + RBE_TLS_CA: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CA || '' }} + RBE_INSTANCE: ${{ needs.rbe.outputs.mode == 'remote' && 'oss' || '' }} + BAZEL_FORK_CACHE: ${{ needs.rbe.outputs.mode == 'cache' && 'true' || '' }} + BAZEL_RRC_READ: 'true' # mode cache reads the repo contents cache through rbe-cache + BAZEL_FORK_REMOTE: ${{ startsWith(needs.rbe.outputs.mode, 'fork-') && 'true' || '' }} + RBE_FORK_TIER: ${{ needs.rbe.outputs.tier }} + RBE_FORK_PR: ${{ github.event.pull_request.number }} + + # As in bazel-proxied. + - name: No test target is marked flaky + timeout-minutes: 3 + run: | + flaky="$(bazel query 'attr(flaky, 1, tests(//...))')" + if [ -n "$flaky" ]; then + echo "::error::flaky = True on ${flaky//$'\n'/ }: the gated lanes run each test once" + exit 1 + fi + + # Both tiers' shards at once: 27 dolt-server + 35 proxied test actions, + # under the remote-exec config's 64 jobs. No --config=sole-run: its one + # line (no retry on a remote cache eviction) is already in the union. + # Shards are expected around 55-95s on rbe-west (see bazel-proxied's + # test step), the proxied tier's 1200s cap included. The step timeout is + # >= proxied test_timeout 1200 s + about 3 min so Bazel writes TIMEOUT + # logs before GitHub kills the step. + - name: bazel test //... --config=dolt-race + id: test + timeout-minutes: 23 + run: | + set -o pipefail + start=$(date +%s) + rc=0 + bazel test //... --config=dolt-race ${BAZEL_FRESH:+"$BAZEL_FRESH"} \ + --build_event_json_file="$RUNNER_TEMP/bazel-bep.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec.log.zst" \ + --profile="$RUNNER_TEMP/bazel-profile.json" \ + --experimental_build_event_upload_strategy=local \ + 2>&1 | tee "$RUNNER_TEMP/bazel-test.log" || rc=$? + echo "bazel test --config=dolt-race: exit $rc, $(( $(date +%s) - start ))s wall" | tee -a "$GITHUB_STEP_SUMMARY" + exit "$rc" + + # The member lanes' checks, once over the union's BEP: bazel-proxied's + # (the dolt-server lane has none). check_shard_coverage ignores targets + # it does not list; check_testcases checks every target, so it covers + # the dolt-server tier too, which bazel-doltserver does not check: a + # dolt-server shard that runs no test turns this job red. + - name: Every target and shard ran tests + if: ${{ always() && steps.test.outcome != 'skipped' }} + timeout-minutes: 2 + run: python3 tools/bazel/check_testcases.py --bep "$RUNNER_TEMP/bazel-bep.json" + + - name: Every listed test ran in its shard + if: ${{ always() && steps.test.outcome != 'skipped' }} + timeout-minutes: 2 + run: >- + python3 tools/bazel/check_shard_coverage.py + --bep "$RUNNER_TEMP/bazel-bep.json" + --suite //cmd/bd:bd_proxied_test .github/scripts/proxied-test-shard.sh 34 + + - name: Upload test logs + if: ${{ failure() && steps.test.outcome != 'skipped' }} + timeout-minutes: 3 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: bazel-dolt-race-testlogs + path: | + bazel-testlogs/**/test.log + bazel-testlogs/**/test.xml + if-no-files-found: ignore + retention-days: 7 + + # Same redacted summary as bazel-test's; see its comment. + - name: CI analytics summary + id: ci-analytics + if: "!cancelled() && steps.test.outcome != 'skipped'" + continue-on-error: true + timeout-minutes: 2 + env: + LANE: dolt-race + MODE: ${{ needs.rbe.outputs.mode }} + CHECK_RUN_ID: ${{ job.check_run_id }} + PR_HINT: ${{ github.event.pull_request.number || 0 }} + run: | + [ -f "$RUNNER_TEMP/bazel-bep.json" ] || exit 0 + zstd --version || echo "::warning::zstd missing: no per-mnemonic data in this lane's summary" + python3 tools/bazel/ci_analytics_extract.py \ + --lane "$LANE" --mode "$MODE" --check-run-id "$CHECK_RUN_ID" --pr-hint "$PR_HINT" \ + --invocation test "$RUNNER_TEMP/bazel-bep.json" "$RUNNER_TEMP/bazel-exec.log.zst" "$RUNNER_TEMP/bazel-profile.json" \ + --out "$RUNNER_TEMP/ci-analytics/ci-analytics.json" + + - name: Upload CI analytics summary + if: "!cancelled() && steps.ci-analytics.outcome == 'success'" + continue-on-error: true + timeout-minutes: 2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: ci-analytics-dolt-race-${{ github.run_attempt }} + path: ${{ runner.temp }}/ci-analytics/ci-analytics.json + retention-days: 7 + if-no-files-found: ignore + + # Last step: the job's result as the bazel-doltserver and + # bazel-proxied workflow_call outputs for pr.yml's ci-gate. always() + # runs it after a failure, a timeout or a cancellation too. + - name: Record job result + id: result + if: ${{ always() }} + timeout-minutes: 1 + env: + JOB_STATUS: ${{ job.status }} + run: echo "result=$JOB_STATUS" >> "$GITHUB_OUTPUT" + # pr-risk.yml's server-Dolt storage tier, "Test (Server Dolt Conformance)" # and "Test (Server Dolt Full Suite N/16)", as --config=doltserver-integration: # the conformance and 16-shard full-suite variants of # //internal/storage/dolt over a non-race dolt_test build, each shard # running the job's own shard script. --config=doltserver-integration has # exactly --config=integration's build flags, so it compiles nothing - # bazel-integration does not (shared through the remote cache). A job of - # its own, not gated by any integration switch: this is a PR-time tier, - # unlike main.yml's integration jobs, and pr.yml's gate requires it - # (BAZEL_SERVER_STORAGE). + # bazel-integration does not (shared through the remote cache). This is a + # PR-time tier, unlike main.yml's integration jobs, and pr.yml's gate + # requires it (BAZEL_SERVER_STORAGE); it also honors the same + # `integration` input as bazel-integration/bazel-cmd-dolt so an explicit + # "off" skips it too, even though no caller passes that today (pr.yml and + # bazel-farm.yml both pass "on") -- see the `integration` input's own + # description. + # Not in mode remote: there bazel-dolt-int runs this tier together with + # the cmd/bd Dolt-server tier and reports for both (item 5 A2). In the + # fork modes and cache there is no in-flight deduplication of one client's + # actions, so a union would cost the sum of the two tiers instead of the + # max: this job runs there as before. bazel-server-storage: name: server-Dolt storage tier # Remote execution only, like bazel-integration: locally the tagged race - # build of //... alone is most of the timeout. - # On same-repo pull_requests the legacy jobs stand down (pr-risk.yml's - # bazel-coverage; D2 step 2), so this lane is then the tier's only PR - # run and pr.yml's gate requires it to have run here and passed. + # build of //... alone is most of the timeout. Plus mode remote + # (bazel-dolt-int's). + # This lane is the tier's only PR run (pr-risk.yml's legacy jobs are + # retired) and pr.yml's gate requires it to have run here and passed. needs: rbe - runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} - if: ${{ needs.rbe.outputs.enabled == 'true' }} + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + if: ${{ needs.rbe.outputs.enabled == 'true' && needs.rbe.outputs.mode != 'remote' && inputs.integration != 'off' }} timeout-minutes: 30 outputs: result: ${{ steps.result.outputs.result }} @@ -1535,6 +2286,15 @@ jobs: persist-credentials: false allow-unsafe-pr-checkout: ${{ inputs.fork-farm == 'authorized' && github.event_name == 'pull_request_target' }} + # The remote repo contents cache, read-only, as in bazel-test. + - name: Remote repo contents cache (read) + if: ${{ needs.rbe.outputs.mode == 'remote' && needs.rbe.outputs.rrc == 'on' }} + run: | + { + echo 'startup --experimental_remote_repo_contents_cache' + echo 'common --loading_phase_threads=64' + } >> .bazelrc.local + - name: Set up Bazel id: bazel uses: ./.github/actions/setup-bazel @@ -1545,6 +2305,7 @@ jobs: RBE_TLS_CA: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CA || '' }} RBE_INSTANCE: ${{ needs.rbe.outputs.mode == 'remote' && 'oss' || '' }} BAZEL_FORK_CACHE: ${{ needs.rbe.outputs.mode == 'cache' && 'true' || '' }} + BAZEL_RRC_READ: 'true' # mode cache reads the repo contents cache through rbe-cache BAZEL_FORK_REMOTE: ${{ startsWith(needs.rbe.outputs.mode, 'fork-') && 'true' || '' }} RBE_FORK_TIER: ${{ needs.rbe.outputs.tier }} RBE_FORK_PR: ${{ github.event.pull_request.number }} @@ -1570,8 +2331,11 @@ jobs: set -o pipefail start=$(date +%s) rc=0 - bazel test //... --config=doltserver-integration \ + bazel test //... --config=doltserver-integration ${BAZEL_FRESH:+"$BAZEL_FRESH"} \ --build_event_json_file="$RUNNER_TEMP/bazel-bep.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec.log.zst" \ + --profile="$RUNNER_TEMP/bazel-profile.json" \ + --experimental_build_event_upload_strategy=local \ 2>&1 | tee "$RUNNER_TEMP/bazel-test.log" || rc=$? echo "bazel test --config=doltserver-integration: exit $rc, $(( $(date +%s) - start ))s wall" | tee -a "$GITHUB_STEP_SUMMARY" exit "$rc" @@ -1581,8 +2345,7 @@ jobs: if: ${{ always() && steps.test.outcome != 'skipped' }} run: python3 tools/bazel/check_testcases.py --bep "$RUNNER_TEMP/bazel-bep.json" - # Since D2 step 2 this lane is the tier's only pre-merge run on - # same-repo PRs: as in bazel-embedded, every full-suite shard must run + # This lane is the tier's only pre-merge run: as in bazel-embedded, every full-suite shard must run # exactly the tests its shard script lists, and neither it nor the # conformance target only skips. - name: Every listed test ran in its shard @@ -1593,6 +2356,15 @@ jobs: --suite //internal/storage/dolt:dolt_server_full_test .github/scripts/server-storage-test-shard.sh 16 --whole //internal/storage/dolt:dolt_server_conformance_test + # rbe-ci-cost-latency-study.md recommendation 4: this tier's last + # shard has trailed the rest by 4.3-4.5 min in 2 of 8 runs. Warns + # (::warning) when the slowest shard this run is far above the + # median; does not fail the job yet (--fail-on-imbalance switches + # that on once the budget has run clean for a while). + - name: Shard balance + if: ${{ always() && steps.test.outcome != 'skipped' }} + run: python3 tools/bazel/shard_budget.py --bep "$RUNNER_TEMP/bazel-bep.json" + - name: Upload test logs if: ${{ failure() && steps.test.outcome != 'skipped' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 @@ -1605,6 +2377,37 @@ jobs: if-no-files-found: ignore retention-days: 7 + # Same redacted summary as bazel-test's; see its comment. + - name: CI analytics summary + id: ci-analytics + if: "!cancelled() && steps.test.outcome != 'skipped'" + continue-on-error: true + timeout-minutes: 3 + env: + LANE: server-storage + MODE: ${{ needs.rbe.outputs.mode }} + CHECK_RUN_ID: ${{ job.check_run_id }} + PR_HINT: ${{ github.event.pull_request.number || 0 }} + run: | + [ -f "$RUNNER_TEMP/bazel-bep.json" ] || exit 0 + zstd --version || echo "::warning::zstd missing: no per-mnemonic data in this lane's summary" + python3 tools/bazel/ci_analytics_extract.py \ + --lane "$LANE" --mode "$MODE" --check-run-id "$CHECK_RUN_ID" --pr-hint "$PR_HINT" \ + --invocation test "$RUNNER_TEMP/bazel-bep.json" "$RUNNER_TEMP/bazel-exec.log.zst" "$RUNNER_TEMP/bazel-profile.json" \ + --out "$RUNNER_TEMP/ci-analytics/ci-analytics.json" + + - name: Upload CI analytics summary + if: "!cancelled() && steps.ci-analytics.outcome == 'success'" + continue-on-error: true + timeout-minutes: 2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: ci-analytics-server-storage-${{ github.run_attempt }} + path: ${{ runner.temp }}/ci-analytics/ci-analytics.json + retention-days: 7 + if-no-files-found: ignore + # Last step: the job's result as a workflow_call output for pr.yml's # ci-gate. always() runs it after a failure, a timeout or a # cancellation too. @@ -1616,13 +2419,16 @@ jobs: run: echo "result=$JOB_STATUS" >> "$GITHUB_OUTPUT" # The cmd/bd Dolt-server tier, as --config=doltserver-cmd: the whole - # integration-tagged cmd/bd suite (//cmd/bd:bd_dolt_server_test, 16 - # shards) against a hermetic dolt sql-server, i.e. the Dolt-gated cmd/bd + # integration-tagged cmd/bd suite (//cmd/bd:bd_dolt_server_test, 32 + # shards, the slowest tests pinned to 16 of them) against a hermetic dolt sql-server, i.e. the Dolt-gated cmd/bd # tests (TestCLI_*, TestInit*, the store-backed suites) that every other - # lane and legacy job skips with BEADS_TEST_SKIP=dolt or leaves out of its - # manifest. --config=doltserver-cmd has exactly --config=integration's - # build flags, so it shares bazel-integration's compile through the - # remote cache. Runs exactly where bazel-integration runs (the same if): + # lane skips with BEADS_TEST_SKIP=dolt or leaves out of its + # manifest; plus the differential regression suite + # (//tests/regression:regression_test, 14 shards: the candidate + # bd_for_tests against the catalog-pinned v0.49.6 release, formerly + # regression.yml). --config=doltserver-cmd has exactly + # --config=integration's build flags, so it shares bazel-integration's + # compile through the remote cache. Runs exactly where bazel-integration runs (the same if): # remotely (modes remote, fork-ro, fork-rw), or locally with the # read-only cache (mode cache: fork and Dependabot PRs while rbe-fork is # closed), never plain local (rbe=off), and not when a caller passes @@ -1631,12 +2437,17 @@ jobs: # call's aggregate result (BAZEL), and pr.yml's ci-gate requires the # lane's own result (BAZEL_CMD_DOLT) only while pr.yml's committed # BAZEL_CMD_DOLT_REQUIRED flag is "true" (scripts/ci_workflow_test.go, - # TestBazelCmdDoltJob). + # TestBazelCmdDoltJob); pr.yml then passes cmd-dolt-required: true and + # this lane is the integration build's only bd_test run + # (TestBazelIntegrationExcludesBdTestOnlyWhereCmdDoltCovers). bazel-cmd-dolt: name: cmd/bd Dolt-server tier + # Not in mode remote: there bazel-dolt-int runs this tier together with + # the server-Dolt storage tier (item 5 A2). See bazel-server-storage's + # comment above. needs: rbe - runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} - if: ${{ (needs.rbe.outputs.enabled == 'true' || needs.rbe.outputs.mode == 'cache') && inputs.integration != 'off' }} + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} + if: ${{ (needs.rbe.outputs.enabled == 'true' || needs.rbe.outputs.mode == 'cache') && inputs.integration != 'off' && needs.rbe.outputs.mode != 'remote' }} timeout-minutes: 85 continue-on-error: true outputs: @@ -1651,6 +2462,15 @@ jobs: persist-credentials: false allow-unsafe-pr-checkout: ${{ inputs.fork-farm == 'authorized' && github.event_name == 'pull_request_target' }} + # The remote repo contents cache, read-only, as in bazel-test. + - name: Remote repo contents cache (read) + if: ${{ needs.rbe.outputs.mode == 'remote' && needs.rbe.outputs.rrc == 'on' }} + run: | + { + echo 'startup --experimental_remote_repo_contents_cache' + echo 'common --loading_phase_threads=64' + } >> .bazelrc.local + - name: Set up Bazel id: bazel uses: ./.github/actions/setup-bazel @@ -1661,14 +2481,16 @@ jobs: RBE_TLS_CA: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CA || '' }} RBE_INSTANCE: ${{ needs.rbe.outputs.mode == 'remote' && 'oss' || '' }} BAZEL_FORK_CACHE: ${{ needs.rbe.outputs.mode == 'cache' && 'true' || '' }} + BAZEL_RRC_READ: 'true' # mode cache reads the repo contents cache through rbe-cache BAZEL_FORK_REMOTE: ${{ startsWith(needs.rbe.outputs.mode, 'fork-') && 'true' || '' }} RBE_FORK_TIER: ${{ needs.rbe.outputs.tier }} RBE_FORK_PR: ${{ github.event.pull_request.number }} # Remote: a compile shared with bazel-integration plus the longest - # of 16 shards (~3 minutes measured; each shard pays ~30-40 s of - # TestMain and its own dolt sql-server; Go's -test.timeout=19m, - # Bazel's 1200s cap). Mode cache on a 4-CPU runner: the compile hits + # of 32 shards (~1 minute: tools/bazel/go_test_pinned_shard.sh pins + # the slowest tests to shards of their own; each shard pays a few + # seconds of TestMain and its own dolt sql-server; Go's + # -test.timeout=19m, Bazel's 1200s cap). Mode cache on a 4-CPU runner: the compile hits # the read-only cache, and a PR that changes cmd/bd or what it imports # runs every shard locally, four at a time (~2,200 test-seconds # measured unloaded, slower four-up: ~20-30 minutes); with the cache @@ -1680,8 +2502,11 @@ jobs: set -o pipefail start=$(date +%s) rc=0 - bazel test //... --config=doltserver-cmd \ + bazel test //... --config=doltserver-cmd ${BAZEL_FRESH:+"$BAZEL_FRESH"} \ --build_event_json_file="$RUNNER_TEMP/bazel-bep.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec.log.zst" \ + --profile="$RUNNER_TEMP/bazel-profile.json" \ + --experimental_build_event_upload_strategy=local \ 2>&1 | tee "$RUNNER_TEMP/bazel-test.log" || rc=$? echo "bazel test --config=doltserver-cmd: exit $rc, $(( $(date +%s) - start ))s wall" | tee -a "$GITHUB_STEP_SUMMARY" exit "$rc" @@ -1705,6 +2530,37 @@ jobs: if-no-files-found: ignore retention-days: 7 + # Same redacted summary as bazel-test's; see its comment. + - name: CI analytics summary + id: ci-analytics + if: "!cancelled() && steps.test.outcome != 'skipped'" + continue-on-error: true + timeout-minutes: 3 + env: + LANE: cmd-dolt + MODE: ${{ needs.rbe.outputs.mode }} + CHECK_RUN_ID: ${{ job.check_run_id }} + PR_HINT: ${{ github.event.pull_request.number || 0 }} + run: | + [ -f "$RUNNER_TEMP/bazel-bep.json" ] || exit 0 + zstd --version || echo "::warning::zstd missing: no per-mnemonic data in this lane's summary" + python3 tools/bazel/ci_analytics_extract.py \ + --lane "$LANE" --mode "$MODE" --check-run-id "$CHECK_RUN_ID" --pr-hint "$PR_HINT" \ + --invocation test "$RUNNER_TEMP/bazel-bep.json" "$RUNNER_TEMP/bazel-exec.log.zst" "$RUNNER_TEMP/bazel-profile.json" \ + --out "$RUNNER_TEMP/ci-analytics/ci-analytics.json" + + - name: Upload CI analytics summary + if: "!cancelled() && steps.ci-analytics.outcome == 'success'" + continue-on-error: true + timeout-minutes: 2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: ci-analytics-cmd-dolt-${{ github.run_attempt }} + path: ${{ runner.temp }}/ci-analytics/ci-analytics.json + retention-days: 7 + if-no-files-found: ignore + # Last step: the job's result as a workflow_call output for pr.yml's # ci-gate. always() runs it after a failure, a timeout or a # cancellation too; job.status is the steps' status, unaffected by the @@ -1716,9 +2572,294 @@ jobs: JOB_STATUS: ${{ job.status }} run: echo "result=$JOB_STATUS" >> "$GITHUB_OUTPUT" + # Item 5 A2 (scripts/bazel_dolt_int_test.go): the server-Dolt storage and + # cmd/bd Dolt-server tiers in one `bazel test --config=dolt-int` (.bazelrc: + # exactly the union of --config=doltserver-integration's and + # --config=doltserver-cmd's lines, one tag filter for both), mode remote + # only, in place of bazel-server-storage and bazel-cmd-dolt, which run in + # every other mode (there a single client does both tiers' work without + # in-flight deduplication, so a union would cost the sum of the two tiers + # rather than the max). One client waits on rbe-west for both tiers' shards + # at once (17 + 46 = 63 test actions, under the remote-exec config's 64 + # jobs), so the job ends with the slower tier and the other tier's runner + # is saved. cmd-dolt's Go-level -test.timeout=19m arg and its + # BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION env moved from --config=doltserver-cmd + # onto //cmd/bd:bd_dolt_server_test's and //tests/regression:regression_test's + # own args/env (their comments), so the union's tag filter alone decides + # which targets see them: without the move, server-storage's per-shard 15m + # Go timeout would become 19m under the union. The final argv and + # environment either way are identical (aquery-verified for all 4 affected + # targets, item 5 A2 PR), so remote action digests -- what RBE's cache keys + # on -- are unchanged and cached results should carry over; this is a local + # actionKey change for cmd-dolt's 46 actions, not a remote one (--test_env + # is part of the build configuration's own fingerprint, which every target + # under that configuration picks up, unlike a target's own env attribute), + # confirmed in practice by the first merge group's tests_cached == + # tests_total in ci-analytics, not claimed here as already observed. + # + # Unlike dolt-race, the members have different gating categories: + # bazel-server-storage is plain-gated (BAZEL_SERVER_STORAGE), bazel-cmd-dolt + # is flag-gated and advisory (BAZEL_CMD_DOLT, continue-on-error) until + # pr.yml's BAZEL_CMD_DOLT_REQUIRED is "true". This job therefore carries no + # job-level continue-on-error: on push, nightly and dispatch nothing reads + # BAZEL_SERVER_STORAGE off a workflow_call output, so job-level + # continue-on-error (job.status reads success regardless of the test step's + # own result) would let a server-storage failure end such a run green, + # where it must stay red exactly as it does on main today. Instead only the + # `bazel test` step carries continue-on-error, and an always() step + # (tools/bazel/classify_tier_results.py) reads the BEP by target label, + # computes each tier's own result, and fails the job itself iff + # server-storage's tier failed (a cmd-dolt-only test failure leaves the job + # green, as bazel-cmd-dolt's own continue-on-error already does outside + # mode remote) or bazel's exit code was neither 0 nor 3 (a build or infra + # failure is not attributable to one tier, so both are marked failed and + # the job fails regardless). Both members' workflow_call outputs read this + # job's matching per-tier output first, then their own member's; a job that + # dies before the classify step leaves both outputs empty, which mode + # remote's gate (bazel-gate.sh, ci-gate.sh) already treats as skipped and + # fails, same as an empty bazel-server-storage/bazel-cmd-dolt result would. + # Every step has a timeout and the job's exceeds their sum by 5 minutes + # while staying under the merge queue's 60-minute check timeout + # (TestBazelDoltIntJobTimeouts): 58 leaves only about 2 minutes for runner + # pickup and the rbe job inside that 60-minute budget, so a hang that runs + # to this job's own timeout can drop the merge group; accepted, because + # such a run is red anyway and the 58-minute job timeout bounds only this + # job, not the whole run (as #7514's dolt-race job comment). The member + # jobs' configs and the union's must stay key-identical: the mode decides + # which runs (TestBazelDoltIntConfigIsMemberUnion). Its ci-analytics LANE + # is dolt-int. + bazel-dolt-int: + name: dolt-int + needs: rbe + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + if: ${{ needs.rbe.outputs.mode == 'remote' && inputs.integration != 'off' }} + # At least every step's timeout-minutes plus 5, and below the merge + # queue's 60-minute check timeout so this job alone cannot exhaust it + # (TestBazelDoltIntJobTimeouts). 58 leaves only about 2 minutes for + # runner pickup and the rbe job inside the merge queue's 60-minute check; + # a hang that runs to this timeout can therefore drop the group, which is + # accepted because such a run is red anyway and the 58-minute job timeout + # bounds this job, not the whole run (as #7514's dolt-race job comment). + timeout-minutes: 58 + outputs: + server_storage_result: ${{ steps.classify.outputs.server_storage_result }} + cmd_dolt_result: ${{ steps.classify.outputs.cmd_dolt_result }} + steps: + # inputs.checkout-sha: see the header (empty: the event's default ref). + # checkout v7 refuses a fork head on pull_request_target unless opted + # in; only bazel-farm.yml's authorized call opts in (false elsewhere). + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + timeout-minutes: 5 + with: + ref: ${{ inputs.checkout-sha }} + persist-credentials: false + allow-unsafe-pr-checkout: ${{ inputs.fork-farm == 'authorized' && github.event_name == 'pull_request_target' }} + + # The remote repo contents cache, read-only, as in bazel-test. + - name: Remote repo contents cache (read) + if: ${{ needs.rbe.outputs.mode == 'remote' && needs.rbe.outputs.rrc == 'on' }} + timeout-minutes: 1 + run: | + { + echo 'startup --experimental_remote_repo_contents_cache' + echo 'common --loading_phase_threads=64' + } >> .bazelrc.local + + - name: Set up Bazel + id: bazel + timeout-minutes: 5 + uses: ./.github/actions/setup-bazel + env: + BAZEL_REMOTE_EXECUTOR: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_WEST_EXECUTOR || '' }} + RBE_TLS_CERT: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CERT || '' }} + RBE_TLS_KEY: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_KEY || '' }} + RBE_TLS_CA: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CA || '' }} + RBE_INSTANCE: ${{ needs.rbe.outputs.mode == 'remote' && 'oss' || '' }} + BAZEL_FORK_CACHE: ${{ needs.rbe.outputs.mode == 'cache' && 'true' || '' }} + BAZEL_RRC_READ: 'true' # mode cache reads the repo contents cache through rbe-cache + BAZEL_FORK_REMOTE: ${{ startsWith(needs.rbe.outputs.mode, 'fork-') && 'true' || '' }} + RBE_FORK_TIER: ${{ needs.rbe.outputs.tier }} + RBE_FORK_PR: ${{ github.event.pull_request.number }} + + # As in bazel-server-storage and bazel-proxied. + - name: No test target is marked flaky + timeout-minutes: 3 + run: | + flaky="$(bazel query 'attr(flaky, 1, tests(//...))')" + if [ -n "$flaky" ]; then + echo "::error::flaky = True on ${flaky//$'\n'/ }: the gated lanes run each test once" + exit 1 + fi + + # Both tiers' shards at once: 17 server-storage + 46 cmd-dolt test + # actions, under the remote-exec config's 64 jobs. No --config=sole-run: + # its one line (no retry on a remote cache eviction) is already in the + # union. The step timeout is >= the union's eternal-size test_timeout + # cap (1200s, shared by bd_dolt_server_test and regression_test) + about + # 3 min so Bazel writes TIMEOUT logs before GitHub kills the step, plus + # the margin server-storage's own step budgets for a cold compile (its + # own step was 25). continue-on-error: a cmd-dolt-only test failure + # must not fail this step (and so the job) outright; the classify step + # below decides that per-tier, from this step's own exit code (written + # to its "rc" output) and the BEP. + - name: bazel test //... --config=dolt-int + id: test + timeout-minutes: 25 + continue-on-error: true + run: | + set -o pipefail + start=$(date +%s) + rc=0 + bazel test //... --config=dolt-int ${BAZEL_FRESH:+"$BAZEL_FRESH"} \ + --build_event_json_file="$RUNNER_TEMP/bazel-bep.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec.log.zst" \ + --profile="$RUNNER_TEMP/bazel-profile.json" \ + --experimental_build_event_upload_strategy=local \ + 2>&1 | tee "$RUNNER_TEMP/bazel-test.log" || rc=$? + echo "bazel test --config=dolt-int: exit $rc, $(( $(date +%s) - start ))s wall" | tee -a "$GITHUB_STEP_SUMMARY" + echo "rc=$rc" >> "$GITHUB_OUTPUT" + exit "$rc" + + # check_testcases split per tier (should-fix 2, PR #7535 review): a + # single shared step with no continue-on-error would fail this job + # outright on a cmd-dolt-only zero-testcase shard (e.g. TestMain dying + # on dolt server start under BEADS_TEST_REQUIRE_DOLT_CONTAINER=1), + # where main (bazel-cmd-dolt alone) stays green, and the divergence + # would only show up under the documented rollback to + # BAZEL_CMD_DOLT_REQUIRED=false. Each step is --label-scoped to its own + # tier (so a --label typo or a label the run did not test fails + # closed, not open: check_testcases.py's own --label section) and + # carries continue-on-error so neither can fail the job by itself; the + # classify step below folds each step's own outcome into that tier's + # result with --check, so a cmd-dolt failure here reaches + # cmd_dolt_result only, same as a cmd-dolt BEP test failure does. + - name: Every target and shard ran tests (server-storage) + id: check-ss + if: ${{ always() && steps.test.outcome != 'skipped' }} + continue-on-error: true + timeout-minutes: 1 + run: >- + python3 tools/bazel/check_testcases.py + --bep "$RUNNER_TEMP/bazel-bep.json" + --label //internal/storage/dolt:dolt_server_full_test + --label //internal/storage/dolt:dolt_server_conformance_test + + - name: Every target and shard ran tests (cmd-dolt) + id: check-cd + if: ${{ always() && steps.test.outcome != 'skipped' }} + continue-on-error: true + timeout-minutes: 1 + run: >- + python3 tools/bazel/check_testcases.py + --bep "$RUNNER_TEMP/bazel-bep.json" + --label //cmd/bd:bd_dolt_server_test + --label //tests/regression:regression_test + + # bazel-server-storage's own check (cmd-dolt has none): every + # full-suite shard ran exactly the tests its shard script lists, and + # neither it nor the conformance target only skips. + - name: Every listed test ran in its shard + if: ${{ always() && steps.test.outcome != 'skipped' }} + timeout-minutes: 2 + run: >- + python3 tools/bazel/check_shard_coverage.py + --bep "$RUNNER_TEMP/bazel-bep.json" + --suite //internal/storage/dolt:dolt_server_full_test .github/scripts/server-storage-test-shard.sh 16 + --whole //internal/storage/dolt:dolt_server_conformance_test + + # bazel-server-storage's own check, scoped with --label to the one + # target it has always budgeted: cmd-dolt's bd_dolt_server_test and + # regression_test shards are sharded too but no job budgeted them + # before the union, and this script has never judged them (see its + # docstring). + - name: Shard balance + if: ${{ always() && steps.test.outcome != 'skipped' }} + timeout-minutes: 2 + run: >- + python3 tools/bazel/shard_budget.py + --bep "$RUNNER_TEMP/bazel-bep.json" + --label //internal/storage/dolt:dolt_server_full_test + + # failure() alone misses an ordinary test failure here: the `bazel + # test` step carries its own continue-on-error (must-fix 2), so a + # failing test does not make failure() true until the classify step + # (which runs after this one) exits non-zero. steps.test.outcome == + # 'failure' catches that case directly (nit, PR #7535 review). + - name: Upload test logs + if: ${{ (failure() || steps.test.outcome == 'failure') && steps.test.outcome != 'skipped' }} + timeout-minutes: 3 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: bazel-dolt-int-testlogs + path: | + bazel-testlogs/**/test.log + bazel-testlogs/**/test.xml + if-no-files-found: ignore + retention-days: 7 + + # Same redacted summary as bazel-test's; see its comment. + - name: CI analytics summary + id: ci-analytics + if: "!cancelled() && steps.test.outcome != 'skipped'" + continue-on-error: true + timeout-minutes: 2 + env: + LANE: dolt-int + MODE: ${{ needs.rbe.outputs.mode }} + CHECK_RUN_ID: ${{ job.check_run_id }} + PR_HINT: ${{ github.event.pull_request.number || 0 }} + run: | + [ -f "$RUNNER_TEMP/bazel-bep.json" ] || exit 0 + zstd --version || echo "::warning::zstd missing: no per-mnemonic data in this lane's summary" + python3 tools/bazel/ci_analytics_extract.py \ + --lane "$LANE" --mode "$MODE" --check-run-id "$CHECK_RUN_ID" --pr-hint "$PR_HINT" \ + --invocation test "$RUNNER_TEMP/bazel-bep.json" "$RUNNER_TEMP/bazel-exec.log.zst" "$RUNNER_TEMP/bazel-profile.json" \ + --out "$RUNNER_TEMP/ci-analytics/ci-analytics.json" + + - name: Upload CI analytics summary + if: "!cancelled() && steps.ci-analytics.outcome == 'success'" + continue-on-error: true + timeout-minutes: 2 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: ci-analytics-dolt-int-${{ github.run_attempt }} + path: ${{ runner.temp }}/ci-analytics/ci-analytics.json + retention-days: 7 + if-no-files-found: ignore + + # Last step: each tier's own result (not job.status: this job carries + # no continue-on-error, see the job's own comment) as the + # bazel-server-storage and bazel-cmd-dolt workflow_call outputs for + # pr.yml's ci-gate. always() runs it after a failure, a timeout or a + # cancellation too (steps.test.outcome stays "skipped" then, so the + # script's --bep file does not exist; it is only read when the test + # step actually ran). This step's own exit code decides job.status: it + # fails the job iff server-storage's tier failed, or `bazel test`'s + # exit code was neither 0 nor 3 (a build or infra failure, not + # attributable to one tier, fails both and the job). + - name: Classify tier results + id: classify + if: ${{ always() && steps.test.outcome != 'skipped' }} + timeout-minutes: 1 + env: + TEST_RC: ${{ steps.test.outputs.rc }} + CHECK_SS_OUTCOME: ${{ steps.check-ss.outcome }} + CHECK_CD_OUTCOME: ${{ steps.check-cd.outcome }} + run: >- + python3 tools/bazel/classify_tier_results.py + --bep "$RUNNER_TEMP/bazel-bep.json" + --rc "$TEST_RC" + --tier server-storage=//internal/storage/dolt:dolt_server_full_test,//internal/storage/dolt:dolt_server_conformance_test + --tier cmd-dolt=//cmd/bd:bd_dolt_server_test,//tests/regression:regression_test + --gate-tier server-storage + --check "server-storage=$CHECK_SS_OUTCOME" + --check "cmd-dolt=$CHECK_CD_OUTCOME" + --github-output "$GITHUB_OUTPUT" + # F3: moved here from pr.yml so the gate depends on nothing but the rbe - # job's decision (not detect-package-gates, build-artifacts, bazel-coverage - # or the whole bazel call). Only pr.yml opts in (package-gates: "on"); + # job's decision (not the whole bazel call). Only pr.yml opts in (package-gates: "on"); # bazel-farm.yml and nightly.yml keep the default "off" and this job does # not run for them. Same-repo PRs get a Bazel-built bd (no --config=ci: # only test:ci is defined in .bazelrc, so bazel build //cmd/bd:bd_for_tests @@ -1730,9 +2871,12 @@ jobs: package-mcp: name: Package Gate (MCP) needs: rbe - # 4 vCPU on purpose: pytest-xdist -n 8 measured ~2.7-3x on 4 CPUs - # (tools/f3 timing, 2026-10), well past 2 vCPU's ceiling. - runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + # 8 vCPU with 16 xdist workers (BEADS_MCP_PYTEST_WORKERS below): pytest + # was 70s of this job at -n 8 on 4 vCPU (merge group 37721729916), + # dominated by per-test `bd init` fixture setup, which is CPU-bound. + # Was 4 vCPU / -n 8 (tools/f3 timing, 2026-10: ~2.7-3x on 4 CPUs); + # revert to that if the A/B does not save at least 15s. + runs-on: ${{ needs.rbe.outputs.mode == 'remote' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} if: ${{ inputs.package-gates == 'on' }} timeout-minutes: 30 outputs: @@ -1748,8 +2892,8 @@ jobs: - name: Decide applicability id: detect env: - PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} - PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PR_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha }} PUSH_BEFORE_SHA: ${{ github.event.before }} PUSH_AFTER_SHA: ${{ github.sha }} run: ./scripts/ci/detect-package-gates.sh @@ -1777,7 +2921,7 @@ jobs: # bazel-out/k8-fastbuild-ST-.../bin/cmd/bd/bd_for_tests/bd path). - name: bazel build //cmd/bd:bd_for_tests if: ${{ steps.detect.outputs.mcp_package == 'true' && needs.rbe.outputs.mode == 'remote' }} - run: bazel build --@rules_go//go/config:race //cmd/bd:bd_for_tests --remote_download_regex='.*/bin/cmd/bd/bd_for_tests/bd$' + run: bazel build --@rules_go//go/config:race //cmd/bd:bd_for_tests --remote_download_regex='.*/bin/cmd/bd/bd_for_tests/bd$' --norun_validations - name: Package the Bazel-built bd if: ${{ steps.detect.outputs.mcp_package == 'true' && needs.rbe.outputs.mode == 'remote' }} @@ -1786,8 +2930,8 @@ jobs: echo "BEADS_TEST_BD_BINARY=$RUNNER_TEMP/bd-artifacts/bd-linux-gms-pure" >> "$GITHUB_ENV" # Defense in depth: nothing after this step needs the Bazel server # or its RBE client key (uv sync and pytest run PR-controlled - # code). Shutting down also frees the JVM's memory for the 8 - # xdist workers that follow on this 4 vCPU runner. + # code). Shutting down also frees the JVM's memory for the 16 + # xdist workers that follow on this 8 vCPU runner. bazel shutdown rm -rf "$RUNNER_TEMP/bazel-ci-secret" @@ -1833,6 +2977,9 @@ jobs: if: ${{ steps.detect.outputs.mcp_package == 'true' }} env: GOCACHE: ${{ runner.temp }}/go-cache/non-race + # 16 workers on the 8 vCPU Blacksmith runner; package-mcp.sh's + # default 8 on the GitHub-hosted fallback. + BEADS_MCP_PYTEST_WORKERS: ${{ needs.rbe.outputs.mode == 'remote' && '16' || '8' }} run: make ci-package-mcp # Last step: the job's result as a workflow_call output for pr.yml's @@ -1867,8 +3014,8 @@ jobs: - name: Decide applicability id: detect env: - PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} - PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PR_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha }} PUSH_BEFORE_SHA: ${{ github.event.before }} PUSH_AFTER_SHA: ${{ github.sha }} run: ./scripts/ci/detect-package-gates.sh @@ -1896,7 +3043,7 @@ jobs: # bazel-out/k8-fastbuild-ST-.../bin/cmd/bd/bd_for_tests/bd path). - name: bazel build //cmd/bd:bd_for_tests if: ${{ steps.detect.outputs.npm_package == 'true' && needs.rbe.outputs.mode == 'remote' }} - run: bazel build --@rules_go//go/config:race //cmd/bd:bd_for_tests --remote_download_regex='.*/bin/cmd/bd/bd_for_tests/bd$' + run: bazel build --@rules_go//go/config:race //cmd/bd:bd_for_tests --remote_download_regex='.*/bin/cmd/bd/bd_for_tests/bd$' --norun_validations - name: Package the Bazel-built bd if: ${{ steps.detect.outputs.npm_package == 'true' && needs.rbe.outputs.mode == 'remote' }} @@ -1958,3 +3105,138 @@ jobs: env: JOB_STATUS: ${{ job.status }} run: echo "result=$JOB_STATUS" >> "$GITHUB_OUTPUT" + + # The remote repo contents cache's only writer (ga-vnycm2.29, ported from + # gascity's bazel.yml). On a push to main, with the rbe job's rrc not off, + # run every lane's loading and analysis (.github/scripts/rrc-lane-commands.txt, + # --nobuild): only main's repository rules and Starlark run (gazelle's + # fetch_repo, the Go SDK and LLVM downloads, extraction: what every lane + # already runs on its runner), never a build or test action. Bazel uploads + # each reproducible repository's tree (--remote_upload_local_results) with + # a 30-minute rbe-rrc-writer-beads certificate that rbe-west's mint signs + # only for this workflow on a push to main + # (.github/scripts/rrc-writer-credential.sh); rbe-west's rrc-gate admits + # repo-contents entries from it and refuses every other action cache + # write, and the certificate cannot Execute. Cache only (--remote_cache, + # no executor). Not a lane: no result output, never in pr.yml's gate + # (which never sees it anyway: push only), so a failed seed only leaves the + # lanes fetching. setup-bazel runs in local mode (no secrets): its rc, the + # runner cache and the pinned Bazel, nothing else. The only bazel.yml job + # with id-token: write; every caller must grant it (GitHub checks a called + # workflow's job permissions at startup, even for a job that skips), and + # the mint refuses any token but a main-push bazel.yml one. + rrc-seed: + name: repo contents cache seed + needs: rbe + if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.rbe.outputs.mode == 'remote' && needs.rbe.outputs.rrc != 'off' }} + runs-on: blacksmith-8vcpu-ubuntu-2404 + timeout-minutes: 30 + permissions: + contents: read + id-token: write # the rbe-rrc-writer-beads certificate (GitHub OIDC) + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up Bazel + uses: ./.github/actions/setup-bazel + - name: rbe-rrc-writer certificate + id: writer + env: + BAZEL_CI_SECRET_DIR: ${{ runner.temp }}/bazel-ci-secret + run: bash .github/scripts/rrc-writer-credential.sh + - name: Seed the remote repo contents cache + if: ${{ steps.writer.outputs.cert != '' }} + env: + CERT: ${{ steps.writer.outputs.cert }} + KEY: ${{ steps.writer.outputs.key }} + ENDPOINT: ${{ steps.writer.outputs.endpoint }} + INSTANCE: ${{ steps.writer.outputs.instance }} + run: >- + bash .github/scripts/rrc-run-lanes.sh --experimental_remote_repo_contents_cache -- + --loading_phase_threads=64 + "--remote_cache=$ENDPOINT" "--remote_instance_name=$INSTANCE" + "--tls_client_certificate=$CERT" "--tls_client_key=$KEY" + --remote_upload_local_results + - name: Remove the writer key + if: ${{ always() }} + run: rm -f -- "$RUNNER_TEMP/bazel-ci-secret/rrc-writer.key" "$RUNNER_TEMP/bazel-ci-secret/rrc-writer.crt" + + # Nightly check of the remote repo contents cache (gascity design R1/R2). A + # cached repository tree is trusted by every reader, and nothing on the + # reader checks it against what its rule produces. So, from nightly.yml (or + # a dispatch), fetch every lane's repositories cold (rrc-lane-commands.txt + # with --nobuild and no repo contents cache, Bazel set up exactly as a + # lane) and compare each repository's tree and marker with the cached + # entry a lane would read for the same key (tools/bazel/rrc_verify.py, + # reads only, with the lanes' certificate and the endpoint from + # setup-bazel's rc: no secret is referenced outside setup-bazel). A + # mismatch is a poisoned entry or a rule falsely marked reproducible: the + # job fails and opens (or comments on) an rrc-verify issue. Not a lane: + # never gated. The only bazel.yml job with issues: write; every caller + # must grant it, as for rrc-seed's id-token. + rrc-verify: + name: repo contents cache verify + needs: rbe + if: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && needs.rbe.outputs.mode == 'remote' && needs.rbe.outputs.rrc != 'off' }} + runs-on: blacksmith-8vcpu-ubuntu-2404 + timeout-minutes: 45 + permissions: + contents: read + issues: write # the rrc-verify alert issue + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up Bazel + uses: ./.github/actions/setup-bazel + env: + BAZEL_REMOTE_EXECUTOR: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_WEST_EXECUTOR || '' }} + RBE_TLS_CERT: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CERT || '' }} + RBE_TLS_KEY: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_KEY || '' }} + RBE_TLS_CA: ${{ needs.rbe.outputs.mode == 'remote' && secrets.RBE_TLS_CA || '' }} + RBE_INSTANCE: ${{ needs.rbe.outputs.mode == 'remote' && 'oss' || '' }} + - name: Cold fetch (every lane, no repo contents cache) + run: bash .github/scripts/rrc-run-lanes.sh -- --loading_phase_threads=64 + - name: Compare with the cache + id: verify + run: | + set -euo pipefail + secret_dir="$RUNNER_TEMP/bazel-ci-secret" + prefix='build:remote-exec --remote_executor=' + endpoint=$(grep -F -m1 "$prefix" "$secret_dir/ci.bazelrc" || true) + endpoint=${endpoint#"$prefix"} + [ -n "$endpoint" ] || { echo "::error::setup-bazel's rc names no executor"; exit 1; } + python3 tools/bazel/rrc_verify.py \ + --output-base "$(bazel info output_base)" \ + --endpoint "$endpoint" --instance oss \ + --cert "$secret_dir/client.crt" --key "$secret_dir/client.key" \ + --bazel-version "$(tr -d '[:space:]' < .bazelversion)" \ + --json "$RUNNER_TEMP/rrc-verify.json" --summary "$GITHUB_STEP_SUMMARY" + - name: Upload the report + if: ${{ always() && hashFiles(format('{0}/rrc-verify.json', runner.temp)) != '' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + overwrite: true # a job re-run is the same run: replace, not 409 + name: rrc-verify-${{ github.run_attempt }} + path: ${{ runner.temp }}/rrc-verify.json + retention-days: 30 + - name: Alert (rrc-verify issue) + if: ${{ failure() && steps.verify.outcome == 'failure' }} + env: + GH_TOKEN: ${{ github.token }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -euo pipefail + title="rrc-verify: remote repo contents cache differs from a cold fetch" + body="The nightly rrc-verify run found cached repository trees that differ from a cold fetch, or could not check them: $RUN_URL (summary and the rrc-verify report artifact). + + A mismatch is a poisoned entry or a repository rule falsely marked reproducible (gascity engdocs/design/bazel-remote-repo-contents-cache.md, R1/R2). Contain the fork-cache readers first: they see no repository variables, so (1) commit fork_rrc_read=off in both probe scripts, beads .github/actions/setup-bazel/cache-rrc-probe.sh and gascity tools/rbe/cache-rrc-probe.sh (beads has no fresh-merge: an open fork PR keeps the old switch until it is pushed again); (2) for immediate server-side containment, an operator runs rbe-cache-gate close on core, which stops all fork-cache, and fails fork-cache lanes already reading; (3) on a mismatch, set RBE_REPO_CONTENTS_CACHE to seed: the trusted readers read the same entries (rbe-cache serves the oss action cache), and seed stops every one of them while rrc-seed and this check keep running; set it to off only to stop seeding too, which also stops rrc-verify; if this run only says it could not check, leave the variable as it is. Then follow gascity/infra nativelink-cas/west/README.md (remote repo contents cache writer, poisoned entries)." + gh label create rrc-verify -R "$GITHUB_REPOSITORY" --color B60205 \ + --description "Remote repo contents cache verification failures" 2>/dev/null || true + n=$(gh issue list -R "$GITHUB_REPOSITORY" --label rrc-verify --state open --json number --jq '.[0].number // empty') + if [ -n "$n" ]; then + gh issue comment "$n" -R "$GITHUB_REPOSITORY" --body "Again: $RUN_URL" + else + gh issue create -R "$GITHUB_REPOSITORY" --label rrc-verify --title "$title" --body "$body" + fi diff --git a/.github/workflows/ci-measurements.yml b/.github/workflows/ci-measurements.yml deleted file mode 100644 index 0bfdca1dd..000000000 --- a/.github/workflows/ci-measurements.yml +++ /dev/null @@ -1,770 +0,0 @@ -name: CI Measurements - -on: - workflow_call: - inputs: - suite: - description: "Suite to measure" - required: true - type: string - smoke_version: - description: "Optional previous release for cross-version-smoke" - required: false - type: string - default: "" - workflow_dispatch: - inputs: - suite: - description: "Suite to measure" - required: true - type: choice - default: pr-linux - options: - - pr-linux - - macos-short - - macos-candidates - - linux-integration - - linux-integration-sharded - - linux-integration-hybrid-sharded - - linux-integration-hybrid-16-sharded - - linux-integration-hybrid-prebuilt-sharded - - linux-integration-coverage - - cross-version-smoke - - nix - - mcp-package - - npm-package - smoke_version: - description: "Optional previous release for cross-version-smoke" - required: false - default: "" - -permissions: - contents: read - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }}-${{ inputs.suite }} - cancel-in-progress: false - -env: - BD_DISABLE_METRICS: "1" - BD_DISABLE_EVENT_FLUSH: "1" - -jobs: - pr-linux: - name: Measure PR Linux commands - if: ${{ inputs.suite == 'pr-linux' }} - runs-on: ubuntu-latest - timeout-minutes: 30 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - with: - fetch-depth: 0 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Measure commands - run: | - set -euo pipefail - mkdir -p artifacts - source scripts/ci/lib/timing.sh - source ./.buildflags - - ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0 - ci_time "install golangci-lint" -- ./scripts/ci/install-golangci-lint.sh - # install-golangci-lint.sh appends to $GITHUB_PATH, which GitHub - # Actions only applies to *later steps*, not later commands in this - # same run block. Export it here too so the "pr-lint wrapper" call - # below finds golangci-lint on PATH. - export PATH="$RUNNER_TEMP/golangci-lint:$PATH" - status=0 - ci_time "pr-policy wrapper" -- make ci-pr-policy || status=$? - # -timeout=30m keeps this in step with the lane it measures - # (scripts/ci/pr-core.sh). Without it ./cmd/bd can die on `go test`'s - # 10m default and the measurement reports a panic instead of a duration. - ci_time "pr-core gotestsum" -- gotestsum --junitfile artifacts/pr-core-junit.xml --format testdox -- -race -short -timeout=30m -skip '^TestEmbedded' ./... || status=$? - ci_time "pr-lint wrapper" -- make ci-pr-lint || status=$? - exit "$status" - - - name: Upload measurement artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-measure-pr-linux - path: artifacts/ - retention-days: 7 - if-no-files-found: ignore - - macos-short: - name: Measure macOS short Go tests - if: ${{ inputs.suite == 'macos-short' }} - runs-on: macos-latest - timeout-minutes: 30 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Measure commands - run: | - set -euo pipefail - source scripts/ci/lib/timing.sh - source ./.buildflags - - # -timeout=30m matches the macOS lanes this measures (pr.yml, main.yml). - # This is the job that produced the ./cmd/bd duration distribution, and - # at 10m it clips its own longest samples into timeout panics. - ci_time "macos short go test" -- go test -tags=gms_pure_go -v -race -short -timeout=30m -skip '^TestEmbedded' ./... - - macos-candidates: - name: Measure macOS no-short candidates - if: ${{ inputs.suite == 'macos-candidates' }} - runs-on: macos-latest - timeout-minutes: 60 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Measure commands - run: | - set -euo pipefail - source scripts/ci/lib/timing.sh - - status=0 - ci_time "macos no-short go test" -- go test -tags=gms_pure_go -v -race -timeout=30m -skip '^TestEmbedded' ./... || status=$? - ci_time "macos integration go test" -- go test -tags=integration,gms_pure_go -v -race -timeout=30m -skip '^TestEmbedded' ./... || status=$? - exit "$status" - - linux-integration: - name: Measure Linux integration tests - if: ${{ inputs.suite == 'linux-integration' }} - runs-on: ubuntu-latest - timeout-minutes: 45 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Measure commands - run: | - set -euo pipefail - mkdir -p artifacts - source scripts/ci/lib/timing.sh - - ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0 - ci_time "linux integration go test" -- env BEADS_TEST_SKIP=dolt gotestsum --junitfile artifacts/linux-integration-junit.xml --format testdox -- -v -race -tags=integration,gms_pure_go -timeout=30m ./... - - - name: Upload measurement artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-measure-linux-integration - path: artifacts/ - retention-days: 7 - if-no-files-found: ignore - - linux-integration-sharded: - name: Measure Linux integration shard ${{ matrix.shard }}/6 - if: ${{ inputs.suite == 'linux-integration-sharded' }} - runs-on: ubuntu-latest - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Measure shard - env: - SHARD: ${{ matrix.shard }} - TOTAL_SHARDS: 6 - run: | - set -euo pipefail - mkdir -p artifacts - source scripts/ci/lib/timing.sh - - ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0 - - mapfile -t packages < <( - GO_TEST_SHARD_TAGS=integration,gms_pure_go \ - scripts/ci/go-test-shard-packages.sh "$SHARD" "$TOTAL_SHARDS" - ) - package_manifest="artifacts/linux-integration-packages-${SHARD}-of-${TOTAL_SHARDS}.txt" - printf '%s\n' "${packages[@]}" | tee "$package_manifest" - - if [[ "${#packages[@]}" -eq 0 ]]; then - echo "No packages assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test" - exit 0 - fi - - ci_time "linux integration shard ${SHARD}/${TOTAL_SHARDS} go test" -- \ - env BEADS_TEST_SKIP=dolt gotestsum \ - --junitfile "artifacts/linux-integration-shard-${SHARD}-of-${TOTAL_SHARDS}.xml" \ - --format testdox \ - -- -v -race -tags=integration,gms_pure_go -timeout=30m "${packages[@]}" - - - name: Upload measurement artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-measure-linux-integration-shard-${{ matrix.shard }}-of-6 - path: artifacts/ - retention-days: 7 - if-no-files-found: ignore - - linux-integration-hybrid-packages: - name: Measure Linux integration package shard ${{ matrix.shard }}/6 (no cmd/bd) - if: ${{ inputs.suite == 'linux-integration-hybrid-sharded' || inputs.suite == 'linux-integration-hybrid-16-sharded' || inputs.suite == 'linux-integration-hybrid-prebuilt-sharded' }} - runs-on: ubuntu-latest - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Measure shard - env: - SHARD: ${{ matrix.shard }} - TOTAL_SHARDS: 6 - run: | - set -euo pipefail - mkdir -p artifacts - source scripts/ci/lib/timing.sh - - ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0 - - package_manifest="artifacts/linux-integration-hybrid-packages-${SHARD}-of-${TOTAL_SHARDS}.txt" - write_package_manifest() { - GO_TEST_SHARD_TAGS=integration,gms_pure_go \ - GO_TEST_SHARD_EXCLUDE_REGEX="^github.com/steveyegge/beads/cmd/bd$" \ - scripts/ci/go-test-shard-packages.sh "$SHARD" "$TOTAL_SHARDS" > "$package_manifest" - } - ci_time "list integration package shard ${SHARD}/${TOTAL_SHARDS}" -- write_package_manifest - cat "$package_manifest" - mapfile -t packages < "$package_manifest" - - if [[ "${#packages[@]}" -eq 0 ]]; then - echo "No packages assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test" - exit 0 - fi - - ci_time "linux integration package shard ${SHARD}/${TOTAL_SHARDS} go test" -- \ - env BEADS_TEST_SKIP=dolt gotestsum \ - --junitfile "artifacts/linux-integration-hybrid-packages-${SHARD}-of-${TOTAL_SHARDS}.xml" \ - --format testdox \ - -- -v -race -tags=integration,gms_pure_go -timeout=30m "${packages[@]}" - - - name: Upload measurement artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-measure-linux-integration-hybrid-packages-${{ matrix.shard }}-of-6 - path: artifacts/ - retention-days: 7 - if-no-files-found: ignore - - linux-integration-hybrid-cmd-bd: - name: Measure Linux integration cmd/bd shard ${{ matrix.shard }}/8 - if: ${{ inputs.suite == 'linux-integration-hybrid-sharded' }} - runs-on: ubuntu-latest - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Measure shard - env: - SHARD: ${{ matrix.shard }} - TOTAL_SHARDS: 8 - run: | - set -euo pipefail - mkdir -p artifacts - source scripts/ci/lib/timing.sh - - ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0 - - test_manifest="artifacts/linux-integration-cmd-bd-tests-${SHARD}-of-${TOTAL_SHARDS}.txt" - write_test_manifest() { - GO_TEST_SHARD_TAGS=integration,gms_pure_go \ - scripts/ci/go-test-shard-names.sh "$SHARD" "$TOTAL_SHARDS" ./cmd/bd > "$test_manifest" - } - ci_time "list cmd/bd test shard ${SHARD}/${TOTAL_SHARDS}" -- write_test_manifest - cat "$test_manifest" - mapfile -t tests < "$test_manifest" - - if [[ "${#tests[@]}" -eq 0 ]]; then - echo "No tests assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test" - exit 0 - fi - - run_regex="^($(IFS='|'; echo "${tests[*]}"))$" - ci_time "linux integration cmd/bd shard ${SHARD}/${TOTAL_SHARDS} go test" -- \ - env BEADS_TEST_SKIP=dolt gotestsum \ - --junitfile "artifacts/linux-integration-cmd-bd-${SHARD}-of-${TOTAL_SHARDS}.xml" \ - --format testdox \ - -- -v -race -tags=integration,gms_pure_go -timeout=30m -run "$run_regex" ./cmd/bd - - - name: Upload measurement artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-measure-linux-integration-cmd-bd-${{ matrix.shard }}-of-8 - path: artifacts/ - retention-days: 7 - if-no-files-found: ignore - - linux-integration-hybrid-16-cmd-bd: - name: Measure Linux integration cmd/bd shard ${{ matrix.shard }}/16 - if: ${{ inputs.suite == 'linux-integration-hybrid-16-sharded' }} - runs-on: ubuntu-latest - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Measure shard - env: - SHARD: ${{ matrix.shard }} - TOTAL_SHARDS: 16 - run: | - set -euo pipefail - mkdir -p artifacts - source scripts/ci/lib/timing.sh - - ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0 - - test_manifest="artifacts/linux-integration-cmd-bd-tests-${SHARD}-of-${TOTAL_SHARDS}.txt" - write_test_manifest() { - GO_TEST_SHARD_TAGS=integration,gms_pure_go \ - scripts/ci/go-test-shard-names.sh "$SHARD" "$TOTAL_SHARDS" ./cmd/bd > "$test_manifest" - } - ci_time "list cmd/bd test shard ${SHARD}/${TOTAL_SHARDS}" -- write_test_manifest - cat "$test_manifest" - mapfile -t tests < "$test_manifest" - - if [[ "${#tests[@]}" -eq 0 ]]; then - echo "No tests assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test" - exit 0 - fi - - run_regex="^($(IFS='|'; echo "${tests[*]}"))$" - ci_time "linux integration cmd/bd shard ${SHARD}/${TOTAL_SHARDS} go test" -- \ - env BEADS_TEST_SKIP=dolt gotestsum \ - --junitfile "artifacts/linux-integration-cmd-bd-${SHARD}-of-${TOTAL_SHARDS}.xml" \ - --format testdox \ - -- -v -race -tags=integration,gms_pure_go -timeout=30m -run "$run_regex" ./cmd/bd - - - name: Upload measurement artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-measure-linux-integration-cmd-bd-${{ matrix.shard }}-of-16 - path: artifacts/ - retention-days: 7 - if-no-files-found: ignore - - linux-integration-hybrid-prebuilt-bd: - name: Measure Linux integration prebuild cmd/bd binary - if: ${{ inputs.suite == 'linux-integration-hybrid-prebuilt-sharded' }} - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Measure build - run: | - set -euo pipefail - mkdir -p artifacts - source scripts/ci/lib/timing.sh - source ./.buildflags - - ci_time "build cmd/bd subprocess binary" -- go build -tags gms_pure_go -o artifacts/bd ./cmd/bd - - - name: Upload prebuilt bd - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-measure-linux-integration-prebuilt-bd - path: artifacts/bd - retention-days: 7 - if-no-files-found: error - - linux-integration-hybrid-prebuilt-cmd-bd: - name: Measure Linux integration prebuilt cmd/bd shard ${{ matrix.shard }}/8 - if: ${{ inputs.suite == 'linux-integration-hybrid-prebuilt-sharded' }} - needs: linux-integration-hybrid-prebuilt-bd - runs-on: ubuntu-latest - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Download prebuilt bd - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ci-measure-linux-integration-prebuilt-bd - path: prebuilt-bd - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Measure shard - env: - SHARD: ${{ matrix.shard }} - TOTAL_SHARDS: 8 - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/prebuilt-bd/bd - run: | - set -euo pipefail - mkdir -p artifacts - chmod +x "$BEADS_TEST_BD_BINARY" - source scripts/ci/lib/timing.sh - - ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0 - - test_manifest="artifacts/linux-integration-cmd-bd-tests-${SHARD}-of-${TOTAL_SHARDS}.txt" - write_test_manifest() { - GO_TEST_SHARD_TAGS=integration,gms_pure_go \ - scripts/ci/go-test-shard-names.sh "$SHARD" "$TOTAL_SHARDS" ./cmd/bd > "$test_manifest" - } - ci_time "list cmd/bd test shard ${SHARD}/${TOTAL_SHARDS}" -- write_test_manifest - cat "$test_manifest" - mapfile -t tests < "$test_manifest" - - if [[ "${#tests[@]}" -eq 0 ]]; then - echo "No tests assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test" - exit 0 - fi - - run_regex="^($(IFS='|'; echo "${tests[*]}"))$" - ci_time "linux integration prebuilt cmd/bd shard ${SHARD}/${TOTAL_SHARDS} go test" -- \ - env BEADS_TEST_SKIP=dolt gotestsum \ - --junitfile "artifacts/linux-integration-prebuilt-cmd-bd-${SHARD}-of-${TOTAL_SHARDS}.xml" \ - --format testdox \ - -- -v -race -tags=integration,gms_pure_go -timeout=30m -run "$run_regex" ./cmd/bd - - - name: Upload measurement artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-measure-linux-integration-prebuilt-cmd-bd-${{ matrix.shard }}-of-8 - path: artifacts/ - retention-days: 7 - if-no-files-found: ignore - - linux-integration-coverage: - name: Measure Linux integration coverage - if: ${{ inputs.suite == 'linux-integration-coverage' }} - runs-on: ubuntu-latest - timeout-minutes: 45 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Measure commands - run: | - set -euo pipefail - mkdir -p artifacts - source scripts/ci/lib/timing.sh - - ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0 - status=0 - ci_time "linux integration coverage go test" -- env BEADS_TEST_SKIP=dolt gotestsum --junitfile artifacts/linux-integration-coverage-junit.xml --format testdox -- -v -race -tags=integration,gms_pure_go -coverprofile=artifacts/coverage.out -timeout=30m ./... || status=$? - if [[ -f artifacts/coverage.out ]]; then - ci_time "coverage summary" -- go tool cover -func=artifacts/coverage.out || status=$? - else - echo "coverage.out was not generated; skipping coverage summary" - fi - exit "$status" - - - name: Upload measurement artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-measure-linux-integration-coverage - path: artifacts/ - retention-days: 7 - if-no-files-found: ignore - - cross-version-smoke: - name: Measure cross-version smoke - if: ${{ inputs.suite == 'cross-version-smoke' }} - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Configure Git - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - - name: Cache previous release binaries - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v5 - with: - path: ~/.cache/beads-regression - key: smoke-binaries-measure-${{ runner.os }} - - - name: Measure commands - env: - GH_TOKEN: ${{ github.token }} - SMOKE_VERSION: ${{ inputs.smoke_version }} - run: | - set -euo pipefail - source scripts/ci/lib/timing.sh - source ./.buildflags - - ci_time "build candidate binary" -- go build -tags gms_pure_go -o /tmp/bd-candidate ./cmd/bd - export CANDIDATE_BIN=/tmp/bd-candidate - if [[ -z "$SMOKE_VERSION" ]]; then - SMOKE_VERSION="$(gh release list --repo "$GITHUB_REPOSITORY" --limit 1 --json tagName --jq '.[0].tagName')" - fi - if [[ -z "$SMOKE_VERSION" ]]; then - echo "Could not resolve a previous release tag for cross-version smoke" - exit 1 - fi - ci_time "upgrade smoke ${SMOKE_VERSION}" -- ./scripts/upgrade-smoke-test.sh "$SMOKE_VERSION" - - nix: - name: Measure nix build - if: ${{ inputs.suite == 'nix' }} - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Install Nix - uses: DeterminateSystems/determinate-nix-action@527f17dd63d2d60d3e5552934bc84b9a33a14d11 # v3 - - - name: Measure commands - run: | - set -euo pipefail - source scripts/ci/lib/timing.sh - - ci_time "nix build .#default" -- nix build .#default --print-build-logs - - mcp-package: - name: Measure MCP package checks - if: ${{ inputs.suite == 'mcp-package' }} - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Set up Python - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: '3.14' - - - name: Measure commands - run: | - set -euo pipefail - source scripts/ci/lib/timing.sh - - ci_time "install uv" -- pip install uv==0.11.16 - ci_time "mcp package gate" -- make ci-package-mcp - - - name: Upload measurement artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-measure-mcp-package - path: integrations/beads-mcp/dist/ - retention-days: 7 - if-no-files-found: ignore - - npm-package: - name: Measure npm package checks - if: ${{ inputs.suite == 'npm-package' }} - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - - - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v6 - with: - node-version: '24' - - - name: Measure commands - run: | - set -euo pipefail - source scripts/ci/lib/timing.sh - ci_time "npm package gate" -- make ci-package-npm - - - name: Upload measurement artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-measure-npm-package - path: artifacts/ - retention-days: 7 - if-no-files-found: ignore diff --git a/.github/workflows/conformance.yml b/.github/workflows/conformance.yml deleted file mode 100644 index 2ec90e33b..000000000 --- a/.github/workflows/conformance.yml +++ /dev/null @@ -1,108 +0,0 @@ -name: Conformance - -# Runs the same two-tier storage conformance suite developers run locally: -# the in-process store corpus and the real-binary CLI harness. - -on: - pull_request: - branches: [ main, 'release/**' ] - # "Upgrade-relevant code" allowlist (spec-f7.md §2.4): any non-test Go - # change, build input, or this workflow's own inputs. Kept byte-for-byte - # identical (modulo each workflow's own file/script entries) across - # conformance.yml, migration-test.yml and cross-version-smoke.yml, and - # pinned by TestAdvisoryWorkflowPathFilters. - paths: - - '**.go' - - '!**_test.go' - - 'go.mod' - - 'go.sum' - - 'Makefile' - - '.buildflags' - - '.github/workflows/conformance.yml' - - 'scripts/conformance.sh' - - 'test/conformance/**' - - 'internal/storage/embeddeddolt/conformance_test.go' - # F7c review fix S4: TestMain (the fixture that builds the - # pristine embedded-Dolt databases conformance_test.go and every - # other test in this package reuse) lives here, not in - # conformance_test.go itself; a PR editing only the fixture was - # previously excluded by '!**_test.go' with nothing to re-include it. - - 'internal/storage/embeddeddolt/test_fixture_test.go' - - 'backend/conformance/**' - push: - branches: [ main ] - paths: - - '**.go' - - '!**_test.go' - - 'go.mod' - - 'go.sum' - - 'Makefile' - - '.buildflags' - - '.github/workflows/conformance.yml' - - 'scripts/conformance.sh' - - 'test/conformance/**' - - 'internal/storage/embeddeddolt/conformance_test.go' - # F7c review fix S4: TestMain (the fixture that builds the - # pristine embedded-Dolt databases conformance_test.go and every - # other test in this package reuse) lives here, not in - # conformance_test.go itself; a PR editing only the fixture was - # previously excluded by '!**_test.go' with nothing to re-include it. - - 'internal/storage/embeddeddolt/test_fixture_test.go' - - 'backend/conformance/**' - merge_group: - -concurrency: - group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -env: - BD_DISABLE_METRICS: "1" - BD_DISABLE_EVENT_FLUSH: "1" - -jobs: - conformance: - name: Storage backend conformance (embedded Dolt oracle) - timeout-minutes: 45 - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - # F7c review fix N1: fail-closed. setup-go's own implicit cache - # must stay off on Blacksmith (it would try to use a GitHub-hosted - # cache entry Blacksmith can't see, and only the self-keyed - # blacksmith-sg-v1- restore below should feed this job there); the - # prior `!= 'self-hosted'` form fails OPEN (caching turns on) if - # runner.environment is ever empty/unknown for some future runner - # class, instead of staying off until proven github-hosted. - cache: ${{ runner.environment == 'github-hosted' }} - - # F7c review fix S5: this job's own key copy must match main.yml's - # seeder key byte-for-byte (TestBlacksmithSetupGoCacheKeysMatchAcrossSeederAndConsumers), - # which now keys by UTC calendar day instead of github.sha so main - # pushes don't churn a multi-GB cache entry on every commit; this step - # computes that same day value locally so the key expression below - # resolves (steps.* references only resolve within the same job). - - name: Compute cache date - id: cache-date - if: runner.environment == 'self-hosted' - run: echo "today=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT" - - - name: Restore Blacksmith setup-go cache - if: runner.environment == 'self-hosted' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/go/pkg/mod - ~/.cache/go-build - key: blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - restore-keys: | - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}- - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Run conformance (embedded Dolt oracle) - run: ./scripts/conformance.sh diff --git a/.github/workflows/cross-version-smoke.yml b/.github/workflows/cross-version-smoke.yml deleted file mode 100644 index 7dc520fc2..000000000 --- a/.github/workflows/cross-version-smoke.yml +++ /dev/null @@ -1,172 +0,0 @@ -name: Cross-Version Smoke Tests - -on: - # On tag push (release gate): test the last 30 releases for broad regression coverage - push: - tags: - - 'v*' - - # On PR to main or a release branch: test only the last 5 releases for fast - # feedback. Release-targeted PRs are exactly the ones where cross-version - # upgrade breakage is most expensive to discover at tag time. - pull_request: - branches: [ main, 'release/**' ] - # "Upgrade-relevant code" allowlist (spec-f7.md §2.4): kept identical - # (modulo each workflow's own file/script entries) across conformance.yml, - # migration-test.yml and cross-version-smoke.yml, and pinned by - # TestAdvisoryWorkflowPathFilters. - paths: - - '**.go' - - '!**_test.go' - - 'go.mod' - - 'go.sum' - - 'Makefile' - - '.buildflags' - - '.github/workflows/cross-version-smoke.yml' - - 'scripts/upgrade-smoke-test.sh' - - # Allow manual trigger with custom version count - workflow_dispatch: - inputs: - version_count: - description: 'Number of previous releases to test against' - required: false - default: '5' - -concurrency: - group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -env: - BD_DISABLE_METRICS: "1" - BD_DISABLE_EVENT_FLUSH: "1" - -jobs: - # F7c: smoke's old 1-job-per-version matrix (up to 30 on tag push) folded - # into chunks of 5 versions each, resolved by the `versions` job below. Each - # chunk builds the candidate binary once and loops over - # upgrade-smoke-test.sh's own SMOKE_VERSIONS env var (which already - # self-reinvokes per version and collects failures, so a bad version in a - # chunk does not hide the rest). - smoke: - name: Upgrade smoke (chunk ${{ strategy.job-index }}) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 20 - - strategy: - fail-fast: false - matrix: - chunk: ${{ fromJson(needs.versions.outputs.chunks) }} - - needs: versions - - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: ${{ runner.environment == 'github-hosted' }} - - # F7c review fix S5: this job's own key copy must match main.yml's - # seeder key byte-for-byte (TestBlacksmithSetupGoCacheKeysMatchAcrossSeederAndConsumers), - # which now keys by UTC calendar day instead of github.sha so main - # pushes don't churn a multi-GB cache entry on every commit; this step - # computes that same day value locally so the key expression below - # resolves (steps.* references only resolve within the same job). - - name: Compute cache date - id: cache-date - if: runner.environment == 'self-hosted' - run: echo "today=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT" - - - name: Restore Blacksmith setup-go cache - if: runner.environment == 'self-hosted' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/go/pkg/mod - ~/.cache/go-build - key: blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - restore-keys: | - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}- - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Configure Git - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - - name: Compute chunk cache key - id: chunk - env: - CHUNK_JSON: ${{ toJson(matrix.chunk) }} - run: | - versions="$(jq -r '. | join(" ")' <<<"$CHUNK_JSON")" - hash="$(printf '%s' "$versions" | sha256sum | cut -c1-16)" - echo "versions=$versions" >> "$GITHUB_OUTPUT" - echo "hash=$hash" >> "$GITHUB_OUTPUT" - - # actions/cache (bare) auto-saves at job end on any key miss, which - # would let a same-repo PR that changes the chunk's version set write a - # binaries cache entry another PR (or a later run) could then read back - # without re-downloading or re-verifying it. Restore-only here; the - # matching save below is gated off pull_request so only push/dispatch - # runs can populate this cache (B2, F7c implementation report). - - name: Restore previous release binaries cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v5 - with: - path: ~/.cache/beads-regression - key: smoke-binaries-${{ steps.chunk.outputs.hash }}-${{ runner.os }} - - - name: Build candidate binary - run: go build -tags gms_pure_go -o /tmp/bd-candidate ./cmd/bd - - - name: Run upgrade smoke tests - env: - CANDIDATE_BIN: /tmp/bd-candidate - SMOKE_VERSIONS: ${{ steps.chunk.outputs.versions }} - run: ./scripts/upgrade-smoke-test.sh - - - name: Save previous release binaries cache - # Allow-list the two triggers this workflow actually intends to - # write from (push, workflow_dispatch), rather than deny-listing - # pull_request: a deny-list of `!= 'pull_request'` also admits a - # hypothetical future merge_group event, which this job's own - # runs-on expression already resolves to Blacksmith for - exactly - # the same same-repo-writer risk X1 closed for pull_request. Pinned - # by TestBlacksmithReachableAdvisoryJobsNeverSaveACache, which checks - # both the pull_request and merge_group trust contexts independently. - if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v5 - with: - path: ~/.cache/beads-regression - key: smoke-binaries-${{ steps.chunk.outputs.hash }}-${{ runner.os }} - - versions: - name: Resolve versions to test - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 5 - outputs: - chunks: ${{ steps.resolve.outputs.chunks }} - steps: - - name: Resolve release versions - id: resolve - env: - GH_TOKEN: ${{ github.token }} - # Tag push and manual dispatch test more versions; PRs test fewer for speed - VERSION_COUNT: ${{ (github.event_name == 'push' && '30') || (github.event_name == 'workflow_dispatch' && inputs.version_count) || '5' }} - run: | - VERSIONS=$(gh release list \ - --repo gastownhall/beads \ - --limit "$VERSION_COUNT" \ - --json tagName \ - --jq '[.[].tagName]') - # Chunks of 5: PRs (5 versions) get 1 chunk; tag pushes (30 - # versions) get 6. Folds the old 1-job-per-version matrix down to - # one job per chunk in `smoke` above, without dropping any version. - CHUNKS=$(jq -c '[range(0; length; 5) as $i | .[$i:$i+5]]' <<<"$VERSIONS") - echo "chunks=$CHUNKS" >> "$GITHUB_OUTPUT" - echo "Testing versions: $VERSIONS" - echo "Chunks: $CHUNKS" diff --git a/.github/workflows/docs-autofix.yml b/.github/workflows/docs-autofix.yml index 36d992c97..f8dcbfd33 100644 --- a/.github/workflows/docs-autofix.yml +++ b/.github/workflows/docs-autofix.yml @@ -15,18 +15,23 @@ # patch is applied to an index in a bare clone and re-checked once staged # (scripts/docs-autofix-push.sh), so a hostile patch can at most rewrite # generated doc files on its own PR branch. Pushes are leased to the run's -# head SHA and skipped for heads that are protected or under a ruleset. +# head SHA and skipped for heads that are protected or under a ruleset. The +# App private key is a secret of the `autofix` environment, whose deployment- +# branch policy allows only `main`, so only a job running on main can read +# it; the minted token itself is scoped to this one repo with contents:write +# only, so even a hostile patch gains nothing beyond what the job already +# had. # # CONCURRENCY: job-level, shared with bazel-autofix.yml per head branch and # without cancel-in-progress, so the two bots queue instead of racing on one # branch (see bazel-autofix.yml). # # TOKEN NOTE: pushes made with the default GITHUB_TOKEN do not retrigger PR -# checks. Configure a DOCS_AUTOFIX_TOKEN repo secret (fine-grained PAT or -# GitHub App token with contents:write on this repo) for fully hands-off -# operation on same-repo PRs; without it the pushed fix still lands but -# checks need a manual re-run. Fork PRs always get the apply-recipe comment - -# no token we hold can push to a fork. +# checks. On same-repo PRs the push step mints a short-lived installation +# token for the gastownhall-autofix GitHub App (contents:write, scoped to +# this repo only) and uses that instead. Fork PRs always get the apply-recipe +# comment - no token we hold can push to a fork, so the mint step is skipped +# for them. name: Docs Autofix @@ -49,6 +54,10 @@ jobs: runs-on: ubuntu-latest # Bounded: a hung run would hold the shared group for the default 6h. timeout-minutes: 10 + # Grants the job read access to this environment's secrets; its + # deployment-branch policy restricts that to jobs running on main + # (workflow_run always does), not to any PR branch. + environment: autofix # Shared with bazel-autofix.yml; queue, never cancel. concurrency: group: autofix-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }} @@ -92,6 +101,22 @@ jobs: fi echo "found=true" >> "$GITHUB_OUTPUT" + # Same-repo PRs only: no token we hold can push to a fork, and a fork's + # head_repository can even be absent (deleted fork), so this mints + # nothing for it and the push script falls back to the apply-recipe + # comment. app-token outputs are empty (not failed) when the step is + # skipped, which is what the fallback below relies on. + - name: Mint autofix app token + id: app-token + if: github.event.workflow_run.head_repository.full_name == github.repository + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3 + with: + app-id: ${{ secrets.AUTOFIX_APP_ID }} + private-key: ${{ secrets.AUTOFIX_APP_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + repositories: ${{ github.event.repository.name }} + permission-contents: write + - name: Push regen commit or leave apply recipe if: steps.patch.outputs.found == 'true' env: @@ -104,9 +129,9 @@ jobs: RUN_URL: ${{ github.event.workflow_run.html_url }} # Split tokens: gh api calls (PR lookup, comments) always use the # workflow token, which carries this job's pull-requests:write; the - # optional PAT is used ONLY for the git push, so it needs no more + # App token is used ONLY for the git push, so it needs no more # than contents:write. GH_TOKEN: ${{ github.token }} - PUSH_TOKEN: ${{ secrets.DOCS_AUTOFIX_TOKEN || github.token }} - AUTOFIX_TOKEN_KIND: ${{ secrets.DOCS_AUTOFIX_TOKEN && 'pat' || 'default' }} + PUSH_TOKEN: ${{ steps.app-token.outputs.token || github.token }} + AUTOFIX_TOKEN_KIND: ${{ steps.app-token.outputs.token && 'app' || 'default' }} run: ./scripts/docs-autofix-push.sh diff --git a/.github/workflows/docs-mintlify.yml b/.github/workflows/docs-mintlify.yml index 08f430798..171174ee0 100644 --- a/.github/workflows/docs-mintlify.yml +++ b/.github/workflows/docs-mintlify.yml @@ -3,22 +3,15 @@ name: Docs (Mintlify) checks on: pull_request: types: [opened, synchronize, reopened, ready_for_review] + # The Mintlify site and the check itself. The docsync guard (docs nav, + # links and agent-instruction routing over docs/, engdocs/ and the root + # markdown) is //test/docsync:docsync_test, which bazel.yml's --config=ci + # lane runs on every PR; this workflow keeps only Mintlify's own + # broken-link check, which needs the network (npx mint) and the base + # branch's history. paths: - # The docsync guard also validates engdocs/** and the curated root - # markdown files (rootDocFiles in test/docsync/docsync_test.go) — keep - # this filter in sync with that list, or a docs-breaking PR merges - # green and turns main red at the full test run. - 'docs/**' - - 'engdocs/**' - - 'test/docsync/**' - 'mint.sh' - - 'README.md' - - 'AGENTS.md' - - 'AGENT_INSTRUCTIONS.md' - - 'CONTRIBUTING.md' - - 'CLAUDE.md' - - 'RELEASING.md' - - 'PR_MAINTAINER_GUIDELINES.md' - '.github/scripts/docs-render-check.sh' - '.github/workflows/docs-mintlify.yml' @@ -30,47 +23,6 @@ concurrency: cancel-in-progress: true jobs: - docsync: - name: Docs nav/link sync (docsync guard) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 10 - if: github.event.pull_request.draft == false - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: ${{ runner.environment == 'github-hosted' }} - - # F7c review fix S5: this job's own key copy must match main.yml's - # seeder key byte-for-byte (TestBlacksmithSetupGoCacheKeysMatchAcrossSeederAndConsumers), - # which now keys by UTC calendar day instead of github.sha so main - # pushes don't churn a multi-GB cache entry on every commit; this step - # computes that same day value locally so the key expression below - # resolves (steps.* references only resolve within the same job). - - name: Compute cache date - id: cache-date - if: runner.environment == 'self-hosted' - run: echo "today=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT" - - - name: Restore Blacksmith setup-go cache - if: runner.environment == 'self-hosted' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/go/pkg/mod - ~/.cache/go-build - key: blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - restore-keys: | - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}- - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Run docsync guard - run: go test -tags=gms_pure_go ./test/docsync - broken-links: name: Mintlify broken-links (baseline-aware) runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 83873bfcc..c64890e66 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -13,690 +13,26 @@ env: BD_DISABLE_EVENT_FLUSH: "1" jobs: - detect-ci-tier: - name: Detect CI tier - runs-on: ubuntu-latest - outputs: - full_embedded: ${{ steps.tier.outputs.full_embedded }} - reason: ${{ steps.tier.outputs.reason }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - with: - fetch-depth: 0 - - name: Decide embedded Dolt coverage - id: tier - env: - PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} - PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} - run: bash .github/scripts/ci-embedded-tier.sh - - # Same guard as pr.yml's check-migration-hygiene: direct pushes to main - # (and PR merges whose base moved) must not bypass the migration lints. - # BASE_SHA is the pre-push tip; on force pushes or history rewrites the - # script warns and skips the frozen-migrations diff but still runs the - # duplicate-version and nondeterministic-SQL checks. - check-migration-hygiene: - name: Check migration hygiene - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - with: - fetch-depth: 0 - - - name: Run migration hygiene checks - env: - BASE_SHA: ${{ github.event.before }} - run: ./scripts/check-migration-hygiene.sh - - build-artifacts: - name: Build Artifacts - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - with: - fetch-depth: 0 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - id: restore-go-module-cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - # Per `go help cache`, Go's content-addressed build cache includes - # compiler options, so this base-tag directory can serve builds with - # additional tags. Race builds stay separate; Windows native/cgo - # non-race builds share theirs. - - name: Restore non-race Go build cache - id: restore-non-race-go-build-cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/non-race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ github.sha }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race- - - - name: Build reusable Linux artifacts - env: - GOCACHE: ${{ runner.temp }}/go-cache/non-race - run: | - set -euo pipefail - mkdir -p artifacts - source ./.buildflags - go_version="$(go version)" - commit="$(git rev-parse HEAD)" - go build -tags gms_pure_go -o artifacts/bd-linux-gms-pure ./cmd/bd - chmod +x artifacts/bd-linux-gms-pure - go test -tags gms_pure_go -c -o artifacts/bd-cmd-test ./cmd/bd - chmod +x artifacts/bd-cmd-test - ( - cd artifacts - sha256sum bd-linux-gms-pure > SHA256SUMS - ) - { - echo "commit=${commit}" - echo "go_version=${go_version}" - echo "build_tags=${BEADS_BUILD_TAGS}" - echo "artifact=bd-linux-gms-pure" - } > artifacts/build-manifest.txt - - - name: Upload build artifacts - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-build-artifacts - path: artifacts/ - retention-days: 1 - if-no-files-found: error - - # F4.3/F7b: pr.yml's check-doc-freshness-platforms and - # pr-preflight-platforms ubuntu legs compile several ./scripts and - # ./cmd/bd test binaries but, before this, used no GOCACHE at all (every - # run cold-compiled them). This warms the non-race GOCACHE this job - # already saves (below) with exactly those packages, plus the - # allowlisted-go-tests packages scripts-go-checks' allowlisted leg - # needs (--compile-only: the allowlist's own packages, so this can - # never drift from what that leg runs). Shared with - # blacksmith-go-build-cache's non-race leg (the same-repo-PR path's - # seed) so the two paths can never drift apart (F7b spec 4.2). - - name: Warm non-race GOCACHE for preflight/doc-freshness/allowlisted - env: - GOCACHE: ${{ runner.temp }}/go-cache/non-race - run: | - bash scripts/ci/warm-non-race-cache.sh - python3 tools/bazel/run_allowlisted_go_tests.py --compile-only - - - name: Save Go module cache - if: steps.restore-go-module-cache.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - - - name: Save non-race Go build cache - if: steps.restore-non-race-go-build-cache.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/non-race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ github.sha }} - - # F4.7: pr.yml's `windows-test-binaries` job only restores the module cache - # and the Windows cross-compile GOCACHE; PR workflows never save caches - # (forks and same-repo PRs alike would otherwise be able to poison a - # shared key). This is the seeder, mirroring build-artifacts' and test's - # module/GOCACHE save pattern for the one new cache key xcompile added. + # macOS full -race -short suite. Linux runs the same suite under Bazel + # (bazel.yml's `test` lane, on every push to main, executed on rbe-west), + # and Windows uses smoke tests below; rbe-west has no macOS workers, so this + # is the one lane that still runs the suite on a runner. Blacksmith macOS, + # the image pr.yml's same-repo macOS legs use; blacksmith-macos-go-build-cache + # seeds its module and non-race caches, and this job saves only its own race + # cache (keyed per go.sum and UTC day, F7b review fix S7). # - # Two legs, not one: pr.yml's windows-test-binaries job (pr.yml:522) lands - # on `blacksmith-8vcpu-ubuntu-2404` for same-repo PRs/merge_group and - # `ubuntu-latest` for forks/Dependabot. `runner.os`/`runner.arch` alone - # look identical between those two (both report Linux/X64), but Blacksmith - # runners cannot see caches `actions/cache` saved from a GitHub-hosted - # runner (and vice versa): the cache storage is scoped to the runner - # infrastructure, not just the key. A single ubuntu-latest seeder leg would - # therefore only ever warm the fork-PR path and leave every same-repo PR - # (the common case) cold on every run. Seeding from both runner selections, - # with identical keys/paths, covers both consumer legs. The ternary form - # (rather than a literal Blacksmith label in a matrix array) is required - # for actionlint: it resolves literal matrix arrays of runner labels and - # fails on an undeclared self-hosted label, but treats a ternary - # expression as a dynamic value it can't resolve, and skips validation -- - # the same reason every other Blacksmith `runs-on` in this repo uses the - # ternary form. - windows-test-binaries-cache: - name: Save Windows test binaries cache - strategy: - fail-fast: false - matrix: - runner: [blacksmith, github] - runs-on: ${{ matrix.runner == 'blacksmith' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 30 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - id: restore-go-module-cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Install mingw cross-compiler - timeout-minutes: 12 - run: | - updated="" - for attempt in 1 2 3; do - if sudo timeout 120 apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update; then - updated=yes - break - fi - echo "::warning::apt-get update attempt $attempt failed or timed out" - if [ "$attempt" -lt 3 ]; then sleep 10; fi - done - if [ -z "$updated" ]; then - echo "::warning::apt-get update failed after 3 attempts; proceeding with cached index" - fi - sudo timeout 300 apt-get install -y gcc-mingw-w64-x86-64 - - - name: Restore Go build cache (Windows cross-compile) - id: restore-xcompile-go-build-cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/xcompile-windows-amd64 - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-xcompile-windows-amd64-${{ github.sha }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-xcompile-windows-amd64- - - - name: Build Windows test binaries - env: - GOCACHE: ${{ runner.temp }}/go-cache/xcompile-windows-amd64 - run: bash scripts/ci/build-windows-test-binaries.sh "$RUNNER_TEMP/win-bin" - - - name: Save Go module cache - if: ${{ !cancelled() && steps.restore-go-module-cache.outputs.cache-hit != 'true' }} - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - - - name: Save Go build cache (Windows cross-compile) - if: ${{ !cancelled() && steps.restore-xcompile-go-build-cache.outputs.cache-hit != 'true' }} - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/xcompile-windows-amd64 - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-xcompile-windows-amd64-${{ github.sha }} - - # Fast shell/Make guard for direct source-time build-tag declarations. - # Workflow `run` steps are checked structurally in the required policy wrapper. - check-build-tags: - name: Check build-tag policy - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - run: ./scripts/check-build-tags.sh - - run: ./scripts/check-go-install-guidance.sh - - run: ./scripts/check-winget-portable-alias.sh - - # Lock in the cgo-test-contamination fix (mybd-ycx / GH#3683 follow-up). - # cmd/bd carries a mix of cgo-only test helpers (embedded Dolt, sql.DB) and - # pure-Go tests. Untagged test files that reach for cgo-only helpers break - # the entire package's CGO_ENABLED=0 compile, silently neutering pure-Go - # tests (the original symptom in PR #3704). This job compiles the cmd/bd - # test binary with CGO_ENABLED=0 and runs the pure-Go subset, so a - # regression that re-introduces cgo coupling fails fast. - check-cmd-bd-puregeo-tests: - name: Check cmd/bd pure-Go tests compile (CGO_ENABLED=0) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Build cmd/bd (CGO_ENABLED=0, gms_pure_go) - env: - CGO_ENABLED: "0" - run: go build -tags gms_pure_go -o /tmp/bd-puregeo ./cmd/bd - - - name: Compile pure-Go test binaries (CGO_ENABLED=0, gms_pure_go) - env: - CGO_ENABLED: "0" - run: | - go test -tags gms_pure_go -c -o /tmp/bd-cmd-puregeo-test ./cmd/bd - go test -tags gms_pure_go -c -o /tmp/bd-embeddeddolt-puregeo-test ./internal/storage/embeddeddolt - go test -tags gms_pure_go -c -o /tmp/bd-tracker-puregeo-test ./internal/tracker - - - name: Run pure-Go cmd/bd test subset (CGO_ENABLED=0) - env: - CGO_ENABLED: "0" - # Restrict to tests that exercise pure-Go code paths. Tests that - # need a Dolt store skip themselves at runtime when no test server - # is available; the goal here is to catch compile-time contamination, - # not run the full suite. - run: | - go test -tags gms_pure_go -count=1 -short -run '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir|NocgoFactoriesHonorSharedServer|NocgoNewDoltStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoNewReadOnlyStoreFromConfig_ErrorSuggestsCorrectFlag)' ./cmd/bd - - # Fast check to ensure all version files are in sync - check-version-consistency: - name: Check version consistency - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Check all versions match - run: ./scripts/check-versions.sh - - # Catch duplicate migration version numbers before any Go build. - # Two long-lived branches both claiming 'the next number' produce a silent - # under-apply when merged; this job fails at PR time with the conflicting - # filenames so it is caught before any test even compiles. - check-no-duplicate-migrations: - name: Check no duplicate migration versions - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Check for duplicate migration version numbers - run: | - dup=$( - find internal/storage/schema/migrations -maxdepth 1 -name '*.up.sql' -printf '%f\n' \ - | sed 's/^\([0-9]*\)_.*/\1/' \ - | sort | uniq -d - ) - if [ -n "$dup" ]; then - echo "Duplicate migration version(s) detected: $dup" - echo "Conflicting files:" - while IFS= read -r v; do - find internal/storage/schema/migrations -name "${v}_*.up.sql" -print - done <<< "$dup" - echo "Renumber one of the colliding files before merging." - exit 1 - fi - - # Check documentation references match actual CLI flags - check-doc-flags: - name: Check doc flags freshness - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Build bd - run: CGO_ENABLED=0 go build -tags gms_pure_go -o bd ./cmd/bd/ - - - name: Validate docs against CLI - run: | - ./scripts/check-doc-flags.sh ./bd - ./scripts/check-doc-freshness.sh - - detect-package-gates: - name: Detect package gates - runs-on: ubuntu-latest - outputs: - mcp_package: ${{ steps.detect.outputs.mcp_package }} - npm_package: ${{ steps.detect.outputs.npm_package }} - reason: ${{ steps.detect.outputs.reason }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - with: - fetch-depth: 0 - - - name: Decide package gates - id: detect - env: - PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} - PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} - PUSH_BEFORE_SHA: ${{ github.event.before }} - PUSH_AFTER_SHA: ${{ github.sha }} - run: ./scripts/ci/detect-package-gates.sh - - package-mcp: - name: Package Gate (MCP) - runs-on: ubuntu-latest - needs: [detect-package-gates, build-artifacts] - steps: - - name: Check applicability - id: applicability - run: | - echo "run=${{ needs.detect-package-gates.outputs.mcp_package }}" >> "$GITHUB_OUTPUT" - if [[ "${{ needs.detect-package-gates.outputs.mcp_package }}" != "true" ]]; then - echo "MCP package gate is not applicable: ${{ needs.detect-package-gates.outputs.reason }}" - fi - - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - if: steps.applicability.outputs.run == 'true' - - - name: Set up Python - if: steps.applicability.outputs.run == 'true' - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: '3.14' - - - name: Install uv - if: steps.applicability.outputs.run == 'true' - run: python -m pip install uv==0.11.16 - - - name: Download build artifacts - if: steps.applicability.outputs.run == 'true' - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ci-build-artifacts - path: ci-build-artifacts - - - name: Verify build artifacts - if: steps.applicability.outputs.run == 'true' - run: | - set -euo pipefail - cd ci-build-artifacts - sha256sum -c SHA256SUMS - chmod +x bd-linux-gms-pure - - - name: Run MCP package gate - if: steps.applicability.outputs.run == 'true' - env: - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - run: make ci-package-mcp - - package-npm: - name: Package Gate (npm) - runs-on: ubuntu-latest - needs: [detect-package-gates, build-artifacts] - steps: - - name: Check applicability - id: applicability - run: | - echo "run=${{ needs.detect-package-gates.outputs.npm_package }}" >> "$GITHUB_OUTPUT" - if [[ "${{ needs.detect-package-gates.outputs.npm_package }}" != "true" ]]; then - echo "npm package gate is not applicable: ${{ needs.detect-package-gates.outputs.reason }}" - fi - - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - if: steps.applicability.outputs.run == 'true' - - - name: Set up Node.js - if: steps.applicability.outputs.run == 'true' - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v6 - with: - node-version: '24' - - - name: Download build artifacts - if: steps.applicability.outputs.run == 'true' - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ci-build-artifacts - path: ci-build-artifacts - - - name: Verify build artifacts - if: steps.applicability.outputs.run == 'true' - run: | - set -euo pipefail - cd ci-build-artifacts - sha256sum -c SHA256SUMS - chmod +x bd-linux-gms-pure - - - name: Run npm package gate - if: steps.applicability.outputs.run == 'true' - env: - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - run: make ci-package-npm - - - pr-policy-wrapper: - name: PR Policy (wrapper timing) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - with: - fetch-depth: 0 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - # Same cold-fetch exposure as pr.yml's pr-policy-wrapper: setup-go above - # runs with cache: false, so every run pulls the whole module graph from - # the proxy. Retrying it here means a proxy blip costs seconds instead of - # failing a required check. - # - # Deliberately NOT wrapped around the build: `make ci-pr-policy` runs a - # `go build ./cmd/bd` (scripts/ci/pr-policy.sh, build_docs_binary), and a - # compile error is not transient. See pr.yml's copy for the full rationale. - # - # 3 attempts x 120s + 2 backoffs x 10s = 380s worst case. 8m leaves ~100s - # of headroom, matching the bounded apt-get steps in migration-test.yml. - - name: Download modules - timeout-minutes: 8 - run: | - downloaded="" - for attempt in 1 2 3; do - if timeout 120 go mod download; then - downloaded=yes - break - fi - echo "::warning::go mod download attempt $attempt failed or timed out" - # No backoff after the final attempt - there is nothing left to wait for. - if [ "$attempt" -lt 3 ]; then - sleep 10 - fi - done - # Unlike the best-effort apt-get retries elsewhere in this repo, this - # one is load-bearing: nothing downstream can build without the - # modules. Fail here, naming the fetch, so a module outage is not - # reported as a build failure. - if [ -z "$downloaded" ]; then - echo "::error::go mod download failed after 3 attempts - module fetch failure, not a build failure" - exit 1 - fi - - - name: Run PR policy wrapper - run: make ci-pr-policy - - pr-core-wrapper: - name: PR Core (wrapper timing) - runs-on: ubuntu-latest - needs: build-artifacts - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - id: restore-go-module-cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Restore race Go build cache - id: restore-race-go-build-cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ github.sha }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race- - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Download build artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ci-build-artifacts - path: ci-build-artifacts - - - name: Verify build artifacts - run: | - set -euo pipefail - cd ci-build-artifacts - sha256sum -c SHA256SUMS - chmod +x bd-linux-gms-pure - - - name: Run PR core wrapper - env: - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - GOCACHE: ${{ runner.temp }}/go-cache/race - run: make ci-pr-core - - # F7b: pr.yml's pr-lint-wrapper moved to same-repo Blacksmith - # (blacksmith-4vcpu-ubuntu-2404) for same-repo PRs/merge_group, falling back - # to ubuntu-latest for forks/Dependabot. golangci-lint's own cache and this - # leg's lint GOCACHE are both scoped to the runner infrastructure (not just - # the key), so this push-lane saver needs to seed both runner selections — - # the `venue` matrix dimension crossed with the existing `target` dimension - # (6 legs on push) — the same reason windows-test-binaries-cache above seeds - # both `runner: [blacksmith, github]` legs. The ternary form (rather than a - # literal Blacksmith label in a matrix array) is required for actionlint, - # same as every other Blacksmith `runs-on` in this repo. - # F7b review fix (B2): job-level push-to-main-only guard, same rationale as - # blacksmith-go-build-cache above -- applied to the whole job (not just the - # Blacksmith leg) for simplicity, since the github venue leg is also only - # meant to run from main.yml's push trigger. Pinned by - # TestBlacksmithSaverJobsGuardedAgainstPullRequest. - pr-lint-wrapper: - name: PR Lint (${{ matrix.target }}) - runs-on: ${{ matrix.venue == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} - if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'gastownhall/beads' - timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - target: [native, windows, darwin] - venue: [blacksmith, github] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Install golangci-lint - run: ./scripts/ci/install-golangci-lint.sh - - # This push lane is the only saver (§0, F5.2): keyed on file content and - # the leg; a miss on the exact content key falls back to the leg's most - # recent entry, which golangci-lint revalidates against the current - # config and inputs. pr.yml only ever restores. The key omits the sha - # (SF-4) so a save only happens when .golangci.yml or go.sum change, - # not on every push to main. - - name: Restore golangci-lint cache - id: restore-golangci-lint-cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/.cache/golangci-lint - ${{ matrix.target == 'native' && format('{0}/go-cache/lint-{1}', runner.temp, matrix.target) || '' }} - key: beads-golangci-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-v2.10.1-${{ matrix.target }}-${{ hashFiles('.golangci.yml', 'go.sum') }} - restore-keys: beads-golangci-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-v2.10.1-${{ matrix.target }}- - - # No BD_LINT_NEW_FROM_MERGE_BASE here: the push lane sweeps the whole - # tree, including the GOOS=windows and GOOS=darwin cross-lints. pr.yml - # scopes the same wrapper to the PR's own diff. - - name: Run PR lint wrapper - env: - BD_LINT_TARGETS: ${{ matrix.target }} - GOCACHE: ${{ runner.temp }}/go-cache/lint-${{ matrix.target }} - run: make ci-pr-lint - - # !cancelled() (not just a cache-hit check): golangci-lint's own cache is - # content-addressed and GOCACHE is unaffected by lint findings, so it is - # safe -- and worth keeping -- to save even when the lint step itself - # fails (SF-1). Without this, a red lint run on main never warms the - # cache and every PR leg stays cold. - - name: Save golangci-lint cache - if: ${{ !cancelled() && steps.restore-golangci-lint-cache.outputs.cache-hit != 'true' }} - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/.cache/golangci-lint - ${{ matrix.target == 'native' && format('{0}/go-cache/lint-{1}', runner.temp, matrix.target) || '' }} - key: beads-golangci-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-v2.10.1-${{ matrix.target }}-${{ hashFiles('.golangci.yml', 'go.sum') }} - - # Cross-platform test matrix (Linux/macOS only - Windows uses smoke tests) - # - # Both legs run every package in one `./...` invocation, so go test's DEFAULT - # 10m per-package deadline applied — and cmd/bd outgrew it. scripts/test.sh - # already documents the floor for local runs: cmd/bd is the slowest package at - # ~18min wall, which is why TEST_TIMEOUT defaults to 25m there. CI was still on - # the 10m default and rode the edge: on 2026-09-01 main run 33497003321 failed - # twice with `panic: test timed out after 10m0s` in cmd/bd AND, in the same - # coverage pass, internal/storage/uow — different tests only 1-12s in flight - # each attempt (a package-wide crawl on the 2-core coverage-instrumented - # runner, not a hang), while a rerun of the identical tree passed. Match - # scripts/test.sh's 25m per-package deadline and keep it inside one finite job - # budget, the same shape the storage/uow and conformance jobs below use: the go - # deadline fires first and prints goroutine stacks, so a REAL hang is still - # diagnosable rather than being cut off by a bare job kill. + # ./cmd/bd has outgrown `go test`'s 10m per-package default (see + # scripts/test.sh, scripts/ci/pr-core.sh and #6091), and when it trips the + # alarm the panic names whichever test was in flight, so it reads like a + # hang. -timeout=30m sits on the invocation and inside one finite job + # budget: the go deadline fires first and prints goroutine stacks, so a real + # hang is still diagnosable rather than cut off by a bare job kill. test: - name: Test (${{ matrix.os }}) - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - runs-on: ${{ matrix.os }} - needs: build-artifacts + name: Test (macOS) + if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'gastownhall/beads' + runs-on: ${{ 'blacksmith-6vcpu-macos-26' }} timeout-minutes: 45 - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, macos-latest] - include: - # Linux: full test suite with coverage - - os: ubuntu-latest - coverage: true - test-flags: '-v -race -short -coverprofile=coverage.out' - # macOS: full test suite, no coverage (faster) - - os: macos-latest - coverage: false - test-flags: '-v -race -short' steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 @@ -707,6 +43,10 @@ jobs: go-version-file: 'go.mod' cache: false + - name: Compute cache date + id: cache-date + run: echo "today=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT" + - name: Restore Go module cache id: restore-go-module-cache uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 @@ -717,11 +57,10 @@ jobs: - name: Restore non-race Go build cache id: restore-non-race-go-build-cache - if: matrix.os == 'macos-latest' uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/go-cache/non-race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ github.sha }} + key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race- - name: Restore race Go build cache @@ -729,7 +68,7 @@ jobs: uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/go-cache/race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ github.sha }} + key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race- - name: Install Dolt (Linux/macOS) @@ -745,604 +84,25 @@ jobs: dolt config --global --add user.name "CI Bot" dolt config --global --add user.email "ci@beads.test" - - name: Install gotestsum - if: matrix.coverage - run: go install gotest.tools/gotestsum@v1.13.0 - - - name: Download build artifacts - if: matrix.os == 'ubuntu-latest' - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ci-build-artifacts - path: ci-build-artifacts - - - name: Verify build artifacts - if: matrix.os == 'ubuntu-latest' - run: | - set -euo pipefail - cd ci-build-artifacts - sha256sum -c SHA256SUMS - chmod +x bd-linux-gms-pure - - name: Build - if: matrix.os != 'ubuntu-latest' env: GOCACHE: ${{ runner.temp }}/go-cache/non-race run: go build -v -tags gms_pure_go ./cmd/bd - # Both lanes below pass -timeout=30m explicitly. ./cmd/bd has outgrown - # `go test`'s 10m per-package default (see scripts/ci/pr-core.sh and - # #6091), and when it trips the alarm the panic names whichever test was - # in flight, so it reads like a hang rather than the package running out - # of clock. The flag lives on the invocation, not in matrix.test-flags, - # so editing the matrix cannot silently drop it. 30m matches every other - # -race lane here for this same code. - - name: Test (with coverage + JUnit XML) - if: matrix.coverage - env: - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - GOCACHE: ${{ runner.temp }}/go-cache/race - run: | - gotestsum \ - --junitfile junit.xml \ - --format testdox \ - -- -tags gms_pure_go -race -short -timeout=30m -coverprofile=coverage.out -skip '^TestEmbedded' ./... - - name: Test - if: ${{ !matrix.coverage }} env: BEADS_TEST_BD_BINARY: ${{ github.workspace }}/bd GOCACHE: ${{ runner.temp }}/go-cache/race - run: go test -tags gms_pure_go ${{ matrix.test-flags }} -timeout=30m -skip '^TestEmbedded' ./... - - - name: Upload coverage to Codecov - if: matrix.coverage && !cancelled() - uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v6 - continue-on-error: true - with: - files: coverage.out - token: ${{ secrets.CODECOV_TOKEN }} - fail_ci_if_error: false - - - name: Upload test results to Codecov - if: matrix.coverage && !cancelled() - uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v6 - continue-on-error: true - with: - files: junit.xml - token: ${{ secrets.CODECOV_TOKEN }} - report_type: test_results - fail_ci_if_error: false - - # Only the macOS leg owns macOS generations. The Linux leg restores the - # Linux writers above and must never become a second cache publisher. - - name: Save Go module cache - if: ${{ !cancelled() && matrix.os == 'macos-latest' && steps.restore-go-module-cache.outputs.cache-hit != 'true' }} - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - - - name: Save non-race Go build cache - if: ${{ !cancelled() && matrix.os == 'macos-latest' && steps.restore-non-race-go-build-cache.outputs.cache-hit != 'true' }} - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/non-race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ github.sha }} + run: go test -tags gms_pure_go -v -race -short -timeout=30m -skip '^TestEmbedded' ./... + # Restore-only for the module and non-race caches (the macOS saver + # owns them); this job is the race cache's only reader and writer. - name: Save race Go build cache - if: ${{ !cancelled() && matrix.os == 'macos-latest' && steps.restore-race-go-build-cache.outputs.cache-hit != 'true' }} + if: ${{ !cancelled() && steps.restore-race-go-build-cache.outputs.cache-hit != 'true' }} uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/go-cache/race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ github.sha }} - - # Focused job for the hexagonal storage layer (internal/storage/domain/* and - # internal/storage/uow). These packages back the proxied-server init path and - # also live behind the existing ./... matrix, but TestDomainDB requires the - # Dolt sql-server image cached locally (testcontainers checks `docker image - # inspect` and skips otherwise). Pulling the image up front guarantees the - # suite actually runs and surfaces failures here with a clear job name. - test-domain-uow: - name: Test (storage domain + uow) - runs-on: ubuntu-latest - needs: build-artifacts - # The race-enabled storage package has outgrown Go's implicit 10-minute - # timeout. Keep both per-package deadlines inside one finite job budget. - timeout-minutes: 30 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Install Dolt CLI - run: ./scripts/ci/install-dolt.sh - - - name: Verify dolt on PATH - run: dolt version - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Pull Dolt sql-server image - # Keep tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage. - # Without this, RequireDoltContainer reports doltNoImage and TestDomainDB skips. - run: ./scripts/ci/pull-dolt-image.sh - - - name: Download build artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ci-build-artifacts - path: ci-build-artifacts - - - name: Verify build artifacts - run: | - set -euo pipefail - cd ci-build-artifacts - sha256sum -c SHA256SUMS - chmod +x bd-linux-gms-pure - - - name: Test domain + uow + tracker - env: - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - # internal/storage/domain, internal/storage/uow, and internal/tracker - # run as concurrent package test binaries in this one invocation. - # testcontainers-go shares one Ryuk reaper per host; a failed - # handshake in one process can reap a sibling's live Dolt container - # mid-suite (be-2on). The runner is destroyed after the job, so the - # reaper buys nothing here and only costs this race. - TESTCONTAINERS_RYUK_DISABLED: "true" - run: go test -tags gms_pure_go -race -count=1 -timeout 15m -v ./internal/storage/domain/... ./internal/storage/uow/... ./internal/tracker/... - - # The doctor/fix DB-backed suite spins its own Dolt container in - # TestMain. BEADS_FIX_REQUIRE_DOLT=1 turns a missing container into a - # hard failure so the suite can never silently skip in CI again - # (bd-nxt5e: it was dark for months); this job pulls the image above. - - name: Test doctor/fix (Dolt-backed, hard-require container) - env: - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - BEADS_FIX_REQUIRE_DOLT: "1" - # Pinned for consistency with the step above: this single-package - # step has no sibling test binary to race for the reaper (be-2on). - TESTCONTAINERS_RYUK_DISABLED: "true" - run: go test -tags gms_pure_go -race -count=1 -timeout 10m -v ./cmd/bd/doctor/fix/ - - main-linux-integration-packages: - name: Main Linux integration packages (${{ matrix.shard }}/6) - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - runs-on: ubuntu-latest - needs: build-artifacts - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Download build artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ci-build-artifacts - path: ci-build-artifacts - - - name: Verify build artifacts - run: | - set -euo pipefail - cd ci-build-artifacts - sha256sum -c SHA256SUMS - chmod +x bd-linux-gms-pure - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Test package shard - env: - SHARD: ${{ matrix.shard }} - TOTAL_SHARDS: 6 - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - run: | - set -euo pipefail - mkdir -p artifacts - source scripts/ci/lib/timing.sh - - ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0 - - package_manifest="artifacts/main-linux-integration-packages-${SHARD}-of-${TOTAL_SHARDS}.txt" - write_package_manifest() { - GO_TEST_SHARD_TAGS=integration,gms_pure_go \ - GO_TEST_SHARD_EXCLUDE_REGEX="^github.com/steveyegge/beads/cmd/bd$" \ - scripts/ci/go-test-shard-packages.sh "$SHARD" "$TOTAL_SHARDS" > "$package_manifest" - } - ci_time "list integration package shard ${SHARD}/${TOTAL_SHARDS}" -- write_package_manifest - cat "$package_manifest" - mapfile -t packages < "$package_manifest" - - if [[ "${#packages[@]}" -eq 0 ]]; then - echo "No packages assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test" - exit 0 - fi - - ci_time "main linux integration package shard ${SHARD}/${TOTAL_SHARDS} go test" -- \ - env BEADS_TEST_SKIP=dolt gotestsum \ - --junitfile "artifacts/main-linux-integration-packages-${SHARD}-of-${TOTAL_SHARDS}.xml" \ - --format testdox \ - -- -v -race -tags=integration,gms_pure_go -timeout=30m "${packages[@]}" - - - name: Upload integration artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: main-linux-integration-packages-${{ matrix.shard }}-of-6 - path: artifacts/ - retention-days: 7 - if-no-files-found: ignore - - main-linux-integration-cmd-bd: - name: Main Linux integration cmd/bd (${{ matrix.shard }}/8) - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - runs-on: ubuntu-latest - needs: build-artifacts - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Download build artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ci-build-artifacts - path: ci-build-artifacts - - - name: Verify build artifacts - run: | - set -euo pipefail - cd ci-build-artifacts - sha256sum -c SHA256SUMS - chmod +x bd-linux-gms-pure - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Test cmd/bd shard - env: - SHARD: ${{ matrix.shard }} - TOTAL_SHARDS: 8 - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - run: | - set -euo pipefail - mkdir -p artifacts - source scripts/ci/lib/timing.sh - - ci_time "install gotestsum" -- go install gotest.tools/gotestsum@v1.13.0 - - test_manifest="artifacts/main-linux-integration-cmd-bd-tests-${SHARD}-of-${TOTAL_SHARDS}.txt" - write_test_manifest() { - GO_TEST_SHARD_TAGS=integration,gms_pure_go \ - scripts/ci/go-test-shard-names.sh "$SHARD" "$TOTAL_SHARDS" ./cmd/bd > "$test_manifest" - } - ci_time "list cmd/bd test shard ${SHARD}/${TOTAL_SHARDS}" -- write_test_manifest - cat "$test_manifest" - mapfile -t tests < "$test_manifest" - - if [[ "${#tests[@]}" -eq 0 ]]; then - echo "No tests assigned to shard ${SHARD}/${TOTAL_SHARDS}; skipping go test" - exit 0 - fi - - run_regex="^($(IFS='|'; echo "${tests[*]}"))$" - ci_time "main linux integration cmd/bd shard ${SHARD}/${TOTAL_SHARDS} go test" -- \ - env BEADS_TEST_SKIP=dolt gotestsum \ - --junitfile "artifacts/main-linux-integration-cmd-bd-${SHARD}-of-${TOTAL_SHARDS}.xml" \ - --format testdox \ - -- -v -race -tags=integration,gms_pure_go -timeout=30m -run "$run_regex" ./cmd/bd - - - name: Upload integration artifacts - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: main-linux-integration-cmd-bd-${{ matrix.shard }}-of-8 - path: artifacts/ - retention-days: 7 - if-no-files-found: ignore - - # End-to-end coverage for proxied-server CLI subcommands, sharded across the - # CI matrix. Each sub-test drives the bd CLI subprocess against a real dolt - # sql-server started via testcontainers by the shared proxied harness - # (cmd/bd/*_proxied_integration_test.go). - # - # Reuses the cmd/bd test binary compiled once by build-artifacts (bd-cmd-test): - # the proxied tests share the package and are gated at runtime by - # BEADS_TEST_PROXIED_SERVER=1. Shard assignment is committed in - # .github/scripts/proxied-cmd-test-shards.txt; newly-added - # TestProxiedServer*/TestServerMode* tests hash-distribute until listed there. - # Prefer the `TestProxiedServer` naming convention for new entry - # points; server-mode-topology suites named TestServerMode* are also - # discovered among the cmd/bd/*_test.go entry points, so neither family is - # left out of this lane. That glob is non-recursive: a container-gated suite - # added under cmd/bd// is still never selected here whatever it is - # named, so keep new proxied/server-mode entry points at the top level. - test-proxied-cmd: - name: Test (proxied-server cmd ${{ matrix.shard }}/15) - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - runs-on: ubuntu-latest - needs: build-artifacts - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Download build artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ci-build-artifacts - path: ci-build-artifacts - - - name: Verify build artifacts - run: | - set -euo pipefail - cd ci-build-artifacts - sha256sum -c SHA256SUMS - chmod +x bd-linux-gms-pure bd-cmd-test - - - name: Install Dolt CLI - # TestProxiedServerExternalCreate needs the dolt binary on PATH; the - # shared harness itself uses the dolt sql-server container image. - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Pull Dolt sql-server image - # The shared proxied harness requires the image cached locally - # (isDoltImageCached); without it every proxied test self-skips. Keep the - # tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage. - run: ./scripts/ci/pull-dolt-image.sh - - - name: Test proxied-server cmd shard - # Timeout ordering, same as pr-risk.yml's twin: the test binary's own - # -test.timeout=15m (proxied-test-shard.sh) fires first and dumps - # goroutines, this 16m step timeout only backstops a wedged binary, and - # the 30m job budget absorbs the download/install/pull steps. Without - # the step timeout, slow setup alone can exhaust the job budget and kill - # a healthy test run with nothing to diagnose. - timeout-minutes: 16 - env: - BEADS_TEST_PROXIED_SERVER: "1" - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - BEADS_TEST_CMD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-cmd-test - run: bash .github/scripts/proxied-test-shard.sh ${{ matrix.shard }} 15 - - # Embedded Dolt tests - test the in-process Dolt engine (no server required) - # - # Split into: build → storage tests + parallel cmd test shards. - # cmd/bd embedded tests use a committed shard manifest; newly-added tests - # still auto-distribute via hash fallback until the manifest is updated. - - build-embedded: - name: Build (Embedded Dolt) - needs: detect-ci-tier - if: needs.detect-ci-tier.outputs.full_embedded == 'true' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - id: restore-go-module-cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Restore race Go build cache - id: restore-race-go-build-cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ github.sha }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race- - - - name: Build embedded bd binary - env: - GOCACHE: ${{ runner.temp }}/go-cache/race - run: go build -tags gms_pure_go -race -o /tmp/bd-embedded-test ./cmd/bd/ - - - name: Build embedded storage test binary - env: - GOCACHE: ${{ runner.temp }}/go-cache/race - run: go test -tags gms_pure_go -race -c -o /tmp/embeddeddolt-test ./internal/storage/embeddeddolt/ - - - name: Build embedded cmd test binary - env: - GOCACHE: ${{ runner.temp }}/go-cache/race - run: go test -tags gms_pure_go -race -c -o /tmp/bd-cmd-test ./cmd/bd/ - - - name: Upload binaries - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: embedded-test-binaries - path: | - /tmp/bd-embedded-test - /tmp/embeddeddolt-test - /tmp/bd-cmd-test - retention-days: 1 - - - name: Save race Go build cache - if: steps.restore-race-go-build-cache.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ github.sha }} - - test-embedded-storage: - name: Test (Embedded Dolt Storage ${{ matrix.shard }}/${{ strategy.job-total }}) - needs: [detect-ci-tier, build-embedded] - if: needs.detect-ci-tier.outputs.full_embedded == 'true' - runs-on: ubuntu-latest - # The shard script's -test.timeout=20m plus setup. At 15m the 1000-item - # batch-apply cap cancelled shard 2/5: TestBatchApplyContract took 604s - # under -race (97s at the 100-item cap, main run 35862663577) and the - # shard hit 15m twice (PR Risk run 36807191489). The manifest now pins - # the heavy tests apart; the heaviest shard projects to ~13m. - timeout-minutes: 25 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Download binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: embedded-test-binaries - path: /tmp/ - - - name: Fix permissions - run: chmod +x /tmp/embeddeddolt-test - - - name: Configure Git - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - - name: Test - env: - BEADS_TEST_EMBEDDED_DOLT: "1" - BEADS_TEST_EMBEDDED_TEST_BINARY: /tmp/embeddeddolt-test - # Manifest-driven shard of the storage suite (mirrors test-embedded-cmd - # / embedded-test-shard.sh). Conformance runs separately in the - # dedicated test-embedded-conformance job below (mirrors pr-risk.yml); - # embedded-storage-test-shard.sh excludes TestConformance from - # discovery, so it never lands in one of these shards. - run: bash .github/scripts/embedded-storage-test-shard.sh ${{ matrix.shard }} 5 - - test-embedded-conformance: - name: Test (Embedded Dolt Conformance - ${{ matrix.partition }}) - needs: [detect-ci-tier, build-embedded] - if: needs.detect-ci-tier.outputs.full_embedded == 'true' - runs-on: ubuntu-latest - timeout-minutes: 35 - strategy: - fail-fast: false - matrix: - partition: [core, audit] - env: - BEADS_TEST_EMBEDDED_DOLT: "1" - BEADS_TEST_EMBEDDED_TEST_BINARY: /tmp/embeddeddolt-test - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Download binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: embedded-test-binaries - path: /tmp/ - - - name: Fix permissions - run: chmod +x /tmp/embeddeddolt-test - - - name: Configure Git - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - - name: Test core conformance - if: matrix.partition == 'core' - # RunAll has a natural Audit seam. Run everything except Audit in the - # core shard and Audit alone in the other shard. The combined suite has - # exceeded 30m under runner variance; each half currently takes ~15m. - # Keep the Go timeout below the job timeout so a real stall still emits - # a diagnostic goroutine dump before Actions stops the job. - run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=30m -test.run '^TestConformance$' -test.skip '^TestConformance$/^Audit$' - - - name: Test audit conformance - if: matrix.partition == 'audit' - run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=30m -test.run '^TestConformance$/^Audit$' - - test-embedded-cmd: - name: Test (Embedded Dolt Cmd ${{ matrix.shard }}/${{ strategy.job-total }}) - needs: [detect-ci-tier, build-embedded] - if: needs.detect-ci-tier.outputs.full_embedded == 'true' - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Download binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: embedded-test-binaries - path: /tmp/ - - - name: Fix permissions - run: chmod +x /tmp/bd-embedded-test /tmp/embeddeddolt-test /tmp/bd-cmd-test - - - name: Configure Git - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - - name: Test - env: - BEADS_TEST_EMBEDDED_DOLT: "1" - BEADS_TEST_BD_BINARY: /tmp/bd-embedded-test - run: bash .github/scripts/embedded-test-shard.sh ${{ matrix.shard }} 20 + key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} # Windows smoke tests only - full test suite times out (see bd-bmev) # Linux/macOS run comprehensive tests; Windows just verifies binary works @@ -1350,34 +110,22 @@ jobs: # Windows uses -tags gms_pure_go to avoid the ICU regex dependency. # go-icu-regex's regex_windows.go also uses Go stdlib regexp (build tag: windows). # CGO is still required for gozstd (bundled C source) and the embedded dolt engine. - # F7b: pr.yml's standalone Windows jobs (test-windows-liveness, - # worktree-remove-windows, etc.) moved to same-repo Blacksmith - # (blacksmith-*vcpu-windows-2025); this job's own module/non-race GOCACHE - # saves already cover the fork/github path (windows-latest), but Blacksmith - # runners cannot see caches `actions/cache` saved from a GitHub-hosted - # runner (and vice versa) even for an identical key, so the `venue` matrix - # dimension here seeds the Blacksmith selection too -- same reasoning as - # pr-lint-wrapper/go-vet-cache above and windows-test-binaries-cache's - # `runner` matrix. + # pr.yml's Windows jobs (test-windows-liveness, worktree-remove-windows, + # etc.) run on Blacksmith Windows for every PR, forks included + # (ga-96smfk.22), so this job seeds their module and non-race GOCACHEs on + # that one runner selection: Blacksmith runners cannot see caches + # `actions/cache` saved from a GitHub-hosted runner, and no GitHub-hosted + # Windows consumer is left. test-windows: - name: Test (Windows - smoke, ${{ matrix.venue }}) - # F7b review fix (B2): added the repository check to match - # blacksmith-go-build-cache/pr-lint-wrapper/go-vet-cache's convention - # above (this job's push-to-main guard predates F7b and already had the - # event/ref check; the repository check closes the same fork gap F7c's - # own blacksmith-setup-go-cache guard closes). Pinned by + name: Test (Windows - smoke) + # F7b review fix (B2): push-to-main, same-repo only, like every saver + # here (the repository check closes the fork gap). Pinned by # TestBlacksmithSaverJobsGuardedAgainstPullRequest. if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'gastownhall/beads' - runs-on: ${{ matrix.venue == 'blacksmith' && 'blacksmith-4vcpu-windows-2025' || 'windows-latest' }} - # F7b review fix (S8): this job now runs on paid Blacksmith Windows - # (4x billing) for its blacksmith venue leg; it previously had no - # timeout-minutes at all. 20 matches test-windows-liveness's timeout - # (S6) for consistency. + runs-on: ${{ 'blacksmith-4vcpu-windows-2025' }} + # F7b review fix (S8): paid Blacksmith Windows (4x billing). 20 matches + # test-windows-liveness's timeout (S6) for consistency. timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - venue: [blacksmith, github] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 @@ -1388,19 +136,17 @@ jobs: go-version-file: 'go.mod' cache: false - # F7b review fix (S7/Speed): see blacksmith-go-build-cache's identical - # step above for the full rationale. + # F7b review fix (S7/Speed): cache keys are bucketed by go.sum and UTC + # day, not per commit, so ordinary push traffic writes at most one + # entry per day (TestBlacksmithSaverCacheKeysAreNotPerCommit). - name: Compute cache date id: cache-date shell: bash run: echo "today=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT" # F7b review fix (S9): same Windows toolchain diagnostic as pr.yml's - # moved Windows jobs, run here on the Blacksmith leg too (the venue - # this job's github leg already exercises on windows-latest every push - # without issue, so only the blacksmith leg's image is unverified). + # Windows jobs. - name: Check Windows toolchain diagnostics - if: matrix.venue == 'blacksmith' shell: bash run: go env CGO_ENABLED CC GOOS GOARCH @@ -1442,11 +188,8 @@ jobs: # (blacksmith-4vcpu-windows-2025), so their cold `cmd/bd` test compiles # (the real long pole; see pr-preflight-platforms' S2 comment) get a # true cache hit. Confirmed to run under Git Bash on Windows (reviewer - # verification); Blacksmith-leg only -- the github (windows-latest) - # venue leg has no PR-side consumer for this namespace, so warming it - # there would be wasted GitHub-hosted cache churn for no reader. + # verification). - name: Warm non-race GOCACHE (Windows preflight/liveness consumers) - if: matrix.venue == 'blacksmith' shell: bash env: GOCACHE: ${{ runner.temp }}/go-cache/non-race @@ -1466,41 +209,24 @@ jobs: path: ${{ runner.temp }}/go-cache/non-race key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - fmt-check: - name: Check formatting - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Check gofmt - run: make fmt-check - - # Warms the vet cache pr.yml's scripts-go-checks vet leg restores (F5.3). - # `go vet` caches successful vet actions, so a warm cache re-vets only - # changed packages and their dependents. Restore-only in pr.yml (§0); this - # push job is the only saver, on an exact-key miss. - # F7b: pr.yml's scripts-go-checks vet leg moved to same-repo Blacksmith; this - # seed needs both runner selections for the same reason pr-lint-wrapper - # above does (Blacksmith and GitHub-hosted runners cannot see each other's - # actions/cache entries, even for an identical key). - # F7b review fix (B2): job-level push-to-main-only guard, same rationale and - # convention as pr-lint-wrapper above. Pinned by - # TestBlacksmithSaverJobsGuardedAgainstPullRequest. - go-vet-cache: - name: Warm go vet cache - runs-on: ${{ matrix.venue == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + # macOS saver: pr.yml's pr-preflight-platforms and + # check-doc-freshness-platforms macOS legs run on blacksmith-6vcpu-macos-26 + # for every PR, forks included (ga-96smfk.22). This job is their only + # seeder (and also seeds the `test` job's module and non-race caches), and runs only the shared warm-up those legs compile + # (warm-non-race-cache.sh, the same script the Windows seeder uses) + # plus the non-test ./cmd/bd build -- no tests, so it stays a few minutes of + # macOS time per push. Same push-to-main-only job guard (B2) and go.sum + + # UTC-day cache keys (S7) as test-windows, so a PR can never + # write this namespace and ordinary push traffic writes at most one + # non-race entry per day. Pinned by + # TestBlacksmithSaverJobsGuardedAgainstPullRequest, + # TestBlacksmithSaverCacheKeysAreNotPerCommit and + # TestBlacksmithMacOSSaverMatchesPRLegs. + blacksmith-macos-go-build-cache: + name: Warm macOS Go build cache + runs-on: ${{ 'blacksmith-6vcpu-macos-26' }} if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'gastownhall/beads' timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - venue: [blacksmith, github] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 @@ -1511,9 +237,6 @@ jobs: go-version-file: 'go.mod' cache: false - # F7b review fix (S7/Speed): see blacksmith-go-build-cache's identical - # step above for the full rationale -- bounds this saver's writes to at - # most once per UTC calendar day per go.sum, not once per push. - name: Compute cache date id: cache-date run: echo "today=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT" @@ -1526,293 +249,42 @@ jobs: key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - name: Restore vet Go build cache - id: restore-vet-go-build-cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/vet - key: beads-go-vet-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-vet-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - # The non-race build cache fallback this used to list can never hit: - # actions/cache versions an entry by its path list, and that cache - # saves to a different path (.../go-cache/non-race), so the prefix - # match is always filtered out (SF-5). - restore-keys: beads-go-vet-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-vet- - - - name: Go vet with go test's checks - env: - GOCACHE: ${{ runner.temp }}/go-cache/vet - run: bash scripts/ci/go-test-vet.sh - - # build-artifacts is the module cache's sole saver (same key); this job - # only restores it to warm the vet run, and only saves its own cache. - # !cancelled(): go vet's cache is content-addressed, so it is safe to - # save even when the vet step itself fails (SF-1). - - name: Save vet Go build cache - if: ${{ !cancelled() && steps.restore-vet-go-build-cache.outputs.cache-hit != 'true' }} - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/vet - key: beads-go-vet-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-vet-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - - # F7b: pr.yml's scripts-go-checks moved to same-repo Blacksmith - # (blacksmith-4vcpu-ubuntu-2404); this is that path's saver for the race and - # non-race GOCACHEs its scripts-test and allowlisted legs restore (the vet - # leg is already covered by go-vet-cache's venue matrix above). Mirrors - # build-artifacts (non-race, fork/github path) and build-embedded (race, - # fork/github path): Blacksmith runners cannot see caches `actions/cache` - # saved from a GitHub-hosted runner (and vice versa) even for an identical - # key, so without this every same-repo PR's scripts-go-checks race/non-race - # legs would stay cold forever. - # - # Unlike pr-lint-wrapper/go-vet-cache above, this job has no `venue` matrix - # dimension and runs on Blacksmith only: build-artifacts/build-embedded - # already seed the ubuntu-latest (fork) leg's non-race/race caches - # respectively, so a second ubuntu-latest leg here would be a redundant, - # wasted run. `${{ '...' }}` (rather than a bare literal) is required for - # actionlint: a literal self-hosted label in `runs-on` fails validation, - # but actionlint treats any `${{ }}` expression, even one it could in - # principle resolve to a constant, as dynamic and skips the check — the - # same reason every other Blacksmith `runs-on` in this repo uses this form. - # main.yml only triggers on push to main (already trusted), so this - # intentionally has no fork/dependabot fallback branch. - # - # F7b review fix (B2): pin push-to-main-only at the job level too, not just - # via this workflow's current `on: push` trigger (same defense-in-depth - # rationale as F7c review fix S2's blacksmith-setup-go-cache guard above -- - # if main.yml ever gained a pull_request/merge_group trigger, a bare - # `on: push` assumption would silently let this job, and the unguarded - # saver below it, run on a same-repo PR, making every same-repo PR a writer - # of this Blacksmith cache namespace). Pinned by - # TestBlacksmithSaverJobsGuardedAgainstPullRequest. - blacksmith-go-build-cache: - name: Warm Blacksmith Go build cache (${{ matrix.flavor }}) - runs-on: ${{ 'blacksmith-4vcpu-ubuntu-2404' }} - if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'gastownhall/beads' - timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - flavor: [race, non-race] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - # F7b review fix (S7/Speed): bounds this saver's writes to at most once - # per UTC calendar day per go.sum, not once per push to main. The old - # ${{ github.sha }} suffix wrote a brand-new multi-GB race+non-race - # build-cache entry on every single push regardless of whether go.sum - # changed; on Blacksmith's 25 GB/week/repo quota (LRU eviction, no - # per-repo exemption the way GitHub-hosted actions/cache effectively - # has) that churn (measured ~1.74GB/push for this job's two flavors - # alone) could exhaust the week's budget in a single day of ordinary - # push traffic and evict every other Blacksmith-reachable job's cache. - # Same convention as F7c review fix S5's blacksmith-setup-go-cache - # (main.yml, above). Pinned by TestBlacksmithSaverCacheKeysAreNotPerCommit. - - name: Compute cache date - id: cache-date - run: echo "today=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT" - - - name: Restore Go module cache - id: restore-go-module-cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Restore race Go build cache - id: restore-race-go-build-cache - if: matrix.flavor == 'race' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race- - - name: Restore non-race Go build cache id: restore-non-race-go-build-cache - if: matrix.flavor == 'non-race' uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/go-cache/non-race key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race- - # scripts-go-checks' scripts-test leg's exact compile set. -run '^$' - # selects no tests (only compiles), so this needs no Dolt/test-env setup. - - name: Warm race GOCACHE (scripts-go-checks scripts-test leg) - if: matrix.flavor == 'race' - env: - GOCACHE: ${{ runner.temp }}/go-cache/race - run: go test -race -run '^$' -tags gms_pure_go ./scripts/... + # Records the toolchain in the log so an image drift is visible next + # to the cache it seeds. + - name: Check macOS toolchain diagnostics + run: | + sw_vers + go env GOOS GOARCH CGO_ENABLED CC + bash --version | head -n 1 - # scripts-go-checks' allowlisted leg (run_allowlisted_go_tests.py - # --compile-only: the allowlist's own packages, so this can never drift - # from what that leg actually runs) plus pr-preflight-platforms'/ - # check-doc-freshness-platforms' ubuntu legs via warm-non-race-cache.sh, - # shared with build-artifacts' identical steps so the two paths can - # never drift apart (F7b spec 4.2). - - name: Warm non-race GOCACHE (scripts-go-checks allowlisted leg + preflight/doc-freshness) - if: matrix.flavor == 'non-race' + - name: Build env: GOCACHE: ${{ runner.temp }}/go-cache/non-race - run: | - bash scripts/ci/warm-non-race-cache.sh - python3 tools/bazel/run_allowlisted_go_tests.py --compile-only + run: go build -tags gms_pure_go -o /dev/null ./cmd/bd - - name: Save race Go build cache - if: ${{ !cancelled() && matrix.flavor == 'race' && steps.restore-race-go-build-cache.outputs.cache-hit != 'true' }} + - name: Warm non-race GOCACHE for macOS preflight/doc-freshness + env: + GOCACHE: ${{ runner.temp }}/go-cache/non-race + run: bash scripts/ci/warm-non-race-cache.sh + + - name: Save Go module cache + if: ${{ !cancelled() && steps.restore-go-module-cache.outputs.cache-hit != 'true' }} uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: - path: ${{ runner.temp }}/go-cache/race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} + path: ~/go/pkg/mod + key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - name: Save non-race Go build cache - if: ${{ !cancelled() && matrix.flavor == 'non-race' && steps.restore-non-race-go-build-cache.outputs.cache-hit != 'true' }} + if: ${{ !cancelled() && steps.restore-non-race-go-build-cache.outputs.cache-hit != 'true' }} uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/go-cache/non-race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - - test-nix: - name: Test Nix Flake - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - uses: DeterminateSystems/determinate-nix-action@527f17dd63d2d60d3e5552934bc84b9a33a14d11 # v3 - - name: Run bd help via Nix - id: nix_help - run: | - nix run .#default -- --help > help.txt - # Every flake check for the runner's own system (today: hook-timeout- - # backends, checks.nix). `nix flake check` rather than a spelled-out - # `.#checks.x86_64-linux.`: no hardcoded system, and a check added - # to checks.nix is run without a workflow edit. - - name: Run the flake checks - run: | - nix flake check -L - - name: Verify help text - if: steps.nix_help.outcome == 'success' - run: | - FIRST_LINE=$(head -n 1 help.txt) - EXPECTED="Issues chained together like beads. A lightweight issue tracker with first-class dependency support." - if [ "$FIRST_LINE" != "$EXPECTED" ]; then - echo "First line of help.txt doesn't match expected output" - echo "Expected: $EXPECTED" - echo "Got: $FIRST_LINE" - exit 1 - fi - echo "Help text first line is correct" - - # F7c: Blacksmith cannot see GitHub-hosted cache entries, so the advisory - # workflows that moved onto a same-repo-PR Blacksmith runner (Conformance, - # Regression's PR run, Migration Test Harness, Cross-Version Smoke, Docs - # docsync, Proxied Local) need a Blacksmith-side writer for their Go build - # cache. This job is push-to-main only (always trusted), so it is the ONLY - # writer: it always restores whatever is available, unconditionally re-runs - # every warm-up command (not gated on a cache hit), and then always saves - # under a key suffixed with this push's commit SHA. Every PR-side consumer - # uses `actions/cache/restore` only (never saves) with the same key - # prefix/restore-keys below, so a same-repo PR can read this cache but can - # never write an entry another PR or main would later read back unverified - # (B2, F7c implementation report). This also means the key format is one we - # define ourselves (`blacksmith-sg-v1-...`), not setup-go's own implicit - # key, so there is no dependency on Blacksmith's `$ImageOS` resolving the - # same way setup-go's own cache-action would have assumed. - # - # Precondition (spec-f7.md §3): an org admin must confirm Blacksmith's - # "branch-protected caches" toggle is ON before this seed is trusted to - # feed PR-scoped restores; a mismatched or OFF setting only degrades PR - # jobs to a cold cache (restore-only, so there is no correctness risk - # either way) -- see the F7c implementation report. - blacksmith-setup-go-cache: - name: Seed setup-go cache (Blacksmith) - # A literal (non-expression) Blacksmith label is actionlint's unknown- - # runner-label check; every other same-repo Blacksmith job in this repo - # routes through a conditional expression instead (actionlint only - # validates literal runs-on strings). This job is push-to-main only - # (always trusted, so there is nothing to gate on), but it still wraps - # the label in a trivial expression to keep actionlint clean and match - # repo convention. - runs-on: ${{ 'blacksmith-4vcpu-ubuntu-2404' }} - # F7c review fix S2: pin push-to-main-only at the job level, not just via - # this workflow's current `on: push` trigger. If main.yml ever gained a - # pull_request (or merge_group) trigger in the future, a bare - # `github.repository == ...` guard would let this job - and the bare, - # always-saving cache below it - run on a PR, making every same-repo PR a - # writer of the Blacksmith setup-go cache namespace every advisory - # consumer trusts. Pinned exactly by - # TestBlacksmithSeederGuardedAgainstPullRequest. - if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'gastownhall/beads' - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - # F7c review fix S5: the old key suffix was ${{ github.sha }}, so every - # single push to main - whether or not go.sum changed - saved a brand - # new multi-GB ~/go/pkg/mod + ~/.cache/go-build entry under this - # namespace. On a cache store with LRU eviction (Blacksmith), that churn - # risked evicting F7a's own beads-go-mod-v2-*/beads-go-build-v2-* cache - # entries. Keying per UTC day instead still bounds staleness (a go.sum - # change is picked up on save on the very next push, and a same-day - # restore-keys fallback to yesterday's entry is only ever a prefix - # away), while capping writes to at most once per calendar day instead - # of once per push. Pinned by TestBlacksmithSeederCacheKeyIsNotPerCommit. - - name: Compute cache date - id: cache-date - run: echo "today=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT" - - - name: Restore Blacksmith setup-go cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/go/pkg/mod - ~/.cache/go-build - key: blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - restore-keys: | - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}- - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - # Unconditional (not gated on a cache hit): this job's entire purpose is - # to keep the Blacksmith-side cache warm, so it must always repopulate - # GOCACHE/GOMODCACHE even when the restore step above already found a - # usable entry (a stale or partial restore should still self-heal here). - - name: Build bd - run: make build - - - name: Compile regression tests - run: go test -c -tags regression,gms_pure_go ./tests/regression - - - name: Compile embedded Dolt conformance tests - run: go test -c -tags gms_pure_go ./internal/storage/embeddeddolt - - - name: Compile e2e conformance tests - run: go test -c -tags 'gms_pure_go e2e' ./test/conformance - - # Always save (even if a warm-up step above failed) under a fresh, - # commit-specific key: the content is still a valid, newer GOCACHE/ - # GOMODCACHE snapshot than whatever was restored, and `cache/save` is a - # pure write with no read-back of PR-controlled state, so there is no - # poisoning concern in saving unconditionally here. - - name: Save Blacksmith setup-go cache - if: always() - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/go/pkg/mod - ~/.cache/go-build - key: blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} + key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} \ No newline at end of file diff --git a/.github/workflows/migration-test.yml b/.github/workflows/migration-test.yml deleted file mode 100644 index f35d686bf..000000000 --- a/.github/workflows/migration-test.yml +++ /dev/null @@ -1,264 +0,0 @@ -name: Migration Test Harness - -on: - pull_request: - # "Upgrade-relevant code" allowlist (spec-f7.md §2.4): kept identical - # (modulo each workflow's own file/script entries) across conformance.yml, - # migration-test.yml and cross-version-smoke.yml, and pinned by - # TestAdvisoryWorkflowPathFilters. - paths: - - '**.go' - - '!**_test.go' - - 'go.mod' - - 'go.sum' - - 'Makefile' - - '.buildflags' - - '.github/workflows/migration-test.yml' - - 'scripts/migration-test/**' - - 'scripts/migrate-legacy-to-current.sh' - push: - tags: ['v*'] - workflow_dispatch: - -permissions: - contents: read - -env: - BD_DISABLE_METRICS: "1" - BD_DISABLE_EVENT_FLUSH: "1" - DOLT_TEST_RUNTIME_VERSION: v2.1.8 - DOLT_TEST_RUNTIME_SHA256: f66318f08ed66e409fc39363ae0fff8ce6fbf6dba9f5bac632b91527b9632a74 - -jobs: - historical-upgrades: - name: Historical ${{ matrix.shard }} shard → candidate - # v0.55.4 is dynamically linked against the ICU version shipped by Ubuntu - # 24.04's libicu74 package. blacksmith-*-ubuntu-2404 IS 24.04, so the pin - # holds there. The non-Blacksmith fallback below is pinned to the literal - # `ubuntu-24.04` label (NOT `ubuntu-latest`) for the same reason: - # actions/runner-images#14748 schedules `ubuntu-latest` to move from 24.04 - # to 26.04 starting 2026-10-19, and 26.04 drops libicu74 entirely, which - # would break the "Install test dependencies" step below and the v0.55.4 - # fixture's ICU ABI even if it didn't. Do not change this fallback to - # `ubuntu-latest`; see sameRepoBlacksmith4vcpuNoble in ci_workflow_test.go. - # F7c: 14 matrix legs (one per historical version) folded into 3 shards. - # Each shard builds the candidate once, installs its own dependencies - # once, then loops over `run.sh --version` for every version it owns, - # collecting failures so one bad version does not hide the rest (see - # "Verify explicit historical upgrades" below). - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} - timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - include: - # src: the one version built from source against Go 1.25, instead - # of installed as a pinned binary. - - shard: src - versions: '["v0.9.1"]' - cache-hash: 453aa2e25bbad328 - # pre-dolt: historical versions that predate the separate Dolt - # runtime oracle (no "Install Dolt test runtime" step needed). - - shard: pre-dolt - versions: '["v0.17.0","v0.49.6","v0.50.3","v0.63.3","v1.0.0"]' - cache-hash: 03cccab45291ead3 - # dolt-runtime: versions that need the pinned Dolt runtime binary - # as a read-only oracle (the old per-version `contains(...)` list). - - shard: dolt-runtime - versions: '["v0.55.4","v0.56.1","v0.57.0","v0.62.0","v1.0.1","v1.1.0","v1.1.2","v1.2.2"]' - cache-hash: a8579bd64e9a0926 - # The v1.1.2 tree re-tagged by the recovery release, so it adds no - # new storage regime — but it is the tag field upgrades actually - # start from, and it was never in this corpus. - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: ${{ runner.environment == 'github-hosted' }} - - # Blacksmith runners cannot see GitHub-hosted setup-go cache entries, so - # setup-go's own `cache: true` (used above on ubuntu-24.04/ubuntu-latest) - # is disabled here and this job restores from the Blacksmith-side cache - # main.yml's blacksmith-setup-go-cache job seeds on every push to main. - # Restore-only by design (see B2 in the F7c implementation report): a - # same-repo PR can read this cache but never write to it, so a PR cannot - # poison what main's seeder or other PRs read. - # F7c review fix S5: this job's own key copy must match main.yml's - # seeder key byte-for-byte (TestBlacksmithSetupGoCacheKeysMatchAcrossSeederAndConsumers), - # which now keys by UTC calendar day instead of github.sha so main - # pushes don't churn a multi-GB cache entry on every commit; this step - # computes that same day value locally so the key expression below - # resolves (steps.* references only resolve within the same job). - - name: Compute cache date - id: cache-date - if: runner.environment == 'self-hosted' - run: echo "today=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT" - - - name: Restore Blacksmith setup-go cache - if: runner.environment == 'self-hosted' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/go/pkg/mod - ~/.cache/go-build - key: blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - restore-keys: | - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}- - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Install test dependencies - # Backstop for a hang that escapes the inner `timeout` calls, so it has - # to sit ABOVE what those calls can legitimately consume: 3 update - # attempts x 120s + 2 backoffs x 10s + 180s install = 560s worst case. - # 11m leaves ~100s of headroom and stays under the job's 20m budget, so - # a stuck step fails as a step instead of cancelling the whole job. - timeout-minutes: 11 - run: | - updated="" - for attempt in 1 2 3; do - if sudo timeout 120 apt-get \ - -o Acquire::Retries=3 \ - -o Acquire::http::Timeout=30 \ - -o Acquire::https::Timeout=30 \ - update; then - updated=yes - break - fi - echo "::warning::apt-get update attempt $attempt failed or timed out" - # No backoff after the final attempt - there is nothing left to wait for. - if [ "$attempt" -lt 3 ]; then - sleep 10 - fi - done - # Deliberate best-effort: a stale index still installs these packages - # from the runner image cache far more often than not, and failing the - # job here would turn a transient mirror outage into a red build. The - # warning is what makes the degraded path visible in the job log. - if [ -z "$updated" ]; then - echo "::warning::apt-get update failed after 3 attempts; proceeding with cached index" - fi - sudo timeout 180 apt-get install -y jq libicu74 - - - name: Install Dolt test runtime - # v0.55.4-v0.62.0 host their fixture on this server; v1.0.1-v1.1.2 use - # the same pinned binary as a read-only oracle over the wisp plane, - # which has no `bd dolt sql` equivalent. This is exactly the - # dolt-runtime shard's version list. - if: matrix.shard == 'dolt-runtime' - run: | - archive="$RUNNER_TEMP/dolt-linux-amd64.tar.gz" - runtime="$RUNNER_TEMP/dolt-runtime" - install_root="$GITHUB_WORKSPACE/.tools/dolt" - curl -fsSL --retry 3 --retry-all-errors --retry-delay 2 \ - "https://github.com/dolthub/dolt/releases/download/${DOLT_TEST_RUNTIME_VERSION}/dolt-linux-amd64.tar.gz" \ - -o "$archive" - echo "${DOLT_TEST_RUNTIME_SHA256} $archive" | sha256sum -c - - mkdir -p "$runtime" "$install_root/bin" - tar -xzf "$archive" -C "$runtime" - install -m 0755 "$runtime/dolt-linux-amd64/bin/dolt" "$install_root/bin/dolt" - "$install_root/bin/dolt" version - - - name: Configure Git - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - # F7c review fix X1: a bare actions/cache here would auto-save on any - # key miss. On Blacksmith, same-repo PRs are the only ones that ever - # run this job (tag push and workflow_dispatch land on ubuntu-24.04, - # not Blacksmith), so a bare save would make every historical-dolt-* - # entry a same-repo-PR-only write - exactly what B2 forbids elsewhere. - # The checksum verification lib/binary.sh does on every extracted - # archive is not a sufficient mitigation: `tar -P` extraction plus - # `cp -f` following a planted `verified//bd` symlink can still - # write outside ~/.cache/beads-regression (e.g. over the checked-out - # workspace or the candidate binary itself) before the checksum check - # ever runs. Restore-only here, same split as smoke-binaries-*/ - # regression-baseline-* below: only push/dispatch (always GitHub-hosted - # for this job) may save. - - name: Restore pinned historical release cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/.cache/beads-regression - key: historical-dolt-${{ matrix.shard }}-${{ matrix.cache-hash }}-${{ runner.os }}-${{ runner.arch }} - - - name: Build candidate - run: make build - - - name: Set up Go 1.25 for v0.9.1 source build - if: matrix.shard == 'src' - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version: '1.25.0' - # No Blacksmith restore step for this narrow one-off (src shard - # only, a single version): accepting a cold build here rather than - # adding a second seeded cache keyspace for one matrix leg. - cache: ${{ runner.environment == 'github-hosted' }} - - # Each version runs as its own `run.sh` subprocess: the underlying - # historical-dolt-upgrade-test.sh uses `set -euo pipefail` and aborts at - # its first failure within one process, so a single multi-version - # invocation could silently hide every version queued after the first - # failure. Looping subprocess calls here, guarded by `if !`, is what - # lets "all versions run, and the job fails if any failed" (spec-f7.md - # §2.3.7) hold for shards with more than one version. - - name: Verify explicit historical upgrades - env: - CANDIDATE_BIN: ./bd - GIT_CONFIG_NOSYSTEM: "1" - DOLT_BIN: ${{ github.workspace }}/.tools/dolt/bin/dolt - SHARD_VERSIONS: ${{ matrix.versions }} - SHARD: ${{ matrix.shard }} - run: | - set -euo pipefail - mapfile -t versions < <(jq -r '.[]' <<<"$SHARD_VERSIONS") - # Fail closed: `jq -r '.[]'` over an empty array, a non-array - # scalar, or unparsable JSON all produce zero lines rather than a - # non-zero exit under process substitution, so mapfile would - # otherwise silently succeed with an empty $versions and this step - # would report green having verified nothing. - if [ "${#versions[@]}" -eq 0 ]; then - echo "::error::shard $SHARD resolved to zero versions from SHARD_VERSIONS=$SHARD_VERSIONS; failing closed instead of reporting a false pass" - exit 1 - fi - failed=0 - failed_versions=() - for v in "${versions[@]}"; do - echo "::group::Historical upgrade: $v" - # 8m per version plus a 30s SIGKILL grace: observed real runs take - # well under a minute, so this only trips on a genuine hang, and - # bounds the damage to one version's budget instead of a stuck - # subprocess silently consuming the rest of the job's 20m timeout - # and hiding every version queued after it. - if ! timeout --kill-after=30s 8m ./scripts/migration-test/run.sh --version "$v"; then - echo "::error::historical upgrade failed for $v" - failed=1 - failed_versions+=("$v") - fi - echo "::endgroup::" - done - if [ "${#failed_versions[@]}" -gt 0 ]; then - { - echo "### Failed historical upgrades (shard $SHARD)" - printf -- '- %s\n' "${failed_versions[@]}" - } >> "$GITHUB_STEP_SUMMARY" - fi - exit "$failed" - - - name: Save pinned historical release cache - # Allow-list push/workflow_dispatch rather than deny-list - # pull_request: a deny-list also admits a hypothetical future - # merge_group event, which this job's runs-on expression already - # resolves to Blacksmith for - exactly the same same-repo-writer - # risk X1 closed for pull_request. Pinned by - # TestBlacksmithReachableAdvisoryJobsNeverSaveACache (checks both the - # pull_request and merge_group trust contexts independently). - if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/.cache/beads-regression - key: historical-dolt-${{ matrix.shard }}-${{ matrix.cache-hash }}-${{ runner.os }}-${{ runner.arch }} diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index fad96547a..7bd190a2d 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,110 +1,42 @@ -name: Nightly Full Tests +name: Nightly +# Every nightly test runs under Bazel on rbe-west: the `bazel` call below is +# the full suite with no cached test results. Nothing here runs go test on a +# runner (ga-96smfk.22). on: schedule: # Run at 2am UTC daily - cron: '0 2 * * *' workflow_dispatch: - inputs: - suite: - description: "Nightly suite or measurement suite" - required: true - type: choice - default: full-test - options: - - full-test - - pr-linux - - macos-short - - macos-candidates - - linux-integration - - linux-integration-sharded - - linux-integration-hybrid-sharded - - linux-integration-hybrid-16-sharded - - linux-integration-hybrid-prebuilt-sharded - - linux-integration-coverage - - cross-version-smoke - - nix - - mcp-package - - npm-package - - bazel - smoke_version: - description: "Optional previous release for cross-version-smoke" - required: false - default: "" + +permissions: + contents: read env: BD_DISABLE_METRICS: "1" BD_DISABLE_EVENT_FLUSH: "1" jobs: - measure: - name: Measure selected CI suite - if: ${{ github.event_name == 'workflow_dispatch' && inputs.suite != 'full-test' && inputs.suite != 'bazel' }} - uses: ./.github/workflows/ci-measurements.yml - with: - suite: ${{ inputs.suite }} - smoke_version: ${{ inputs.smoke_version }} - - # PR Core's go test (scripts/ci/pr-core.sh) with -json output, so the Bazel - # job below can compare per-test status: a test that passes here and skips - # under Bazel fails the equivalence check unless allowlisted. - bazel-go-test-json: - name: Bazel equivalence (go-test side) - if: ${{ github.event_name == 'schedule' || inputs.suite == 'bazel' }} - runs-on: ubuntu-latest - timeout-minutes: 60 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Run PR core go-test (JSON) - env: - BEADS_PR_CORE_GO_TEST_JSON: ${{ runner.temp }}/go-test.json - run: make ci-pr-core - - # Uploaded even when tests fail: the status comparison still applies. - - name: Upload go-test results - if: ${{ always() }} - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: bazel-equivalence-go-test-json - path: ${{ runner.temp }}/go-test.json - if-no-files-found: error - retention-days: 7 - - # Bazel lane with the full go test equivalence listing and the skip-parity - # check (reported here; PRs gate on it through pr.yml). Remote execution - # when the repo secrets are present; bazel.yml gets the four RBE secrets - # plus rbe-prewarm's bazel-allocator app private key (same-repo/scheduled - # trigger only, so pre-warming is safe here - see bazel.yml's - # "rbe-west Pre-warm" header and engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md). + # Bazel lane with the full equivalence listing (package and test-name sets; + # PRs gate on it through pr.yml). Remote execution when the repo secrets + # are present; bazel.yml gets the four RBE secrets plus rbe-prewarm's + # bazel-allocator app private key (same-repo/scheduled trigger only, so + # pre-warming is safe here - see bazel.yml's "rbe-west Pre-warm" header and + # engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md). bazel: - name: Bazel equivalence (full detail) - needs: bazel-go-test-json - if: ${{ !cancelled() && (github.event_name == 'schedule' || inputs.suite == 'bazel') }} + name: Bazel (fresh, full detail) + # A called workflow's job gets at most this call's token permissions, and + # GitHub checks them when the run starts, even for a job whose if: skips + # it (startup_failure otherwise; gascity #7478): bazel.yml's rrc-seed asks + # id-token: write (push to main only) and rrc-verify issues: write + # (schedule and dispatch only). rrc-verify runs here (its alert issue); + # rrc-seed never does, every other bazel.yml job keeps contents: read, + # and rbe-west's mint refuses any OIDC token but a main-push bazel.yml one + # (scripts/bazel_rrc_test.go, TestBazelWorkflowCallersGrantEveryRequestedPermission). + permissions: + contents: read + id-token: write + issues: write uses: ./.github/workflows/bazel.yml secrets: RBE_WEST_EXECUTOR: ${{ secrets.RBE_WEST_EXECUTOR }} @@ -114,92 +46,46 @@ jobs: RBE_POOL_APP_PRIVATE_KEY: ${{ secrets.RBE_POOL_APP_PRIVATE_KEY }} with: details: true - go-test-json-artifact: bazel-equivalence-go-test-json + # The one run that re-executes every test (no cached test results): + # PRs, merge groups and pushes to main reuse unchanged tests' PASSes, + # so this keeps sampling flaky and -race failures every night. + fresh-test-results: true - full-test: - name: Full Test Suite - if: ${{ github.event_name == 'schedule' || inputs.suite == 'full-test' }} + # rbe-west's pool workers are gascity's and advertise the sha256 of + # gascity's worker-env manifest; beads' tools/rbe/worker-env.txt is a + # byte-for-byte copy and platforms/BUILD.bazel carries the same pin. A copy + # that falls behind queues every remote action (bazel.yml's rbe job runs + # the same check before each remote run and fails it fast), so check every + # night and, out of step, open or update a ci/infra issue with the diff and + # the pin to commit (tools/rbe/worker-env-sync-issue). The only job here + # with issues: write, and only its last step uses the token. gascity + # unreachable (exit 2) fails the job without an issue. + rbe-worker-env-sync: + name: rbe worker-env in step with gascity runs-on: ubuntu-latest - timeout-minutes: 45 + timeout-minutes: 5 + permissions: + contents: read + issues: write steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version-file: 'go.mod' + persist-credentials: false - - name: Install Dolt - run: | - ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Build - run: go build -v -tags gms_pure_go ./cmd/bd - - - name: Full Test Suite (including integration tests) + - name: Compare the worker-env manifest and pin with gascity's main + id: sync env: - # Skip Docker-based Dolt testcontainer tests — they hang in - # GitHub Actions (known issue, see scripts/repro-dolt-hang/). - # Non-Docker integration tests still run via the installed dolt binary. - BEADS_TEST_SKIP: dolt - run: go test -v -race -tags=integration,gms_pure_go -coverprofile=coverage.out -timeout=30m ./... - - # The suite above never sets BEADS_TEST_EMBEDDED_DOLT, so every - # skipUnlessEmbeddedDolt-gated test in internal/storage/embeddeddolt - # (including TestBatchApplyContract, the 1000-item case of - # TestLargeBatchApplyWallClock_Embedded, and — F1 — the 712-item case of - # TestLargeBatchApplyStatementCounts712_Embedded) is skipped there, on - # every lane, not just this one. This step is their only non-race - # coverage of a real 1000-item apply through the embedded backend, and - # (F1) the only coverage at all of the 712-item shape's pinned - # statement-count regression baseline on a per-PR race lane: the race - # lanes (main.yml, pr-risk.yml) shrink/skip those cases under - # raceEnabled — see - # internal/storage/embeddeddolt/large_batch_apply_measure_test.go — and - # the PR-conditional server-Dolt full suite (full_embedded in - # .github/scripts/ci-embedded-tier.sh) covers the SAME write body - # (internal/storage/issueops.ApplyBatchInTx) through a different - # backend, not this one. Non-race here because the embedded engine's - # own goroutine/lock machinery runs inside this test binary and the - # race detector dramatically inflates its wall-clock (see - # race_detector_on_test.go), which is exactly what - # TestLargeBatchApplyWallClock_Embedded is measuring and exactly why - # TestLargeBatchApplyStatementCounts712_Embedded's 712-item case takes - # ~260-300s under -race (genuine engine-internal race overhead, not - # test logic — see that test's doc comment). - - name: Embedded Dolt batch-apply suite (non-race) - if: ${{ !cancelled() }} - env: - BEADS_TEST_EMBEDDED_DOLT: "1" - run: go test -tags gms_pure_go -timeout 20m -run '^(TestBatchApplyContract|TestLargeBatchApplyWallClock_Embedded|TestLargeBatchApplyStatementCounts712_Embedded)$' ./internal/storage/embeddeddolt - - - name: Check coverage threshold + WORKER_ENV_SYNC_REPORT: ${{ runner.temp }}/worker-env-sync.md run: | - COVERAGE=$(go tool cover -func=coverage.out | grep total | awk '{print $3}' | sed 's/%//') - echo "Coverage: $COVERAGE%" - # Threshold is lower (30%) because Docker-based Dolt integration - # tests are skipped in CI (BEADS_TEST_SKIP=dolt). With Docker - # tests included, coverage would be ~50%+. - if (( $(echo "$COVERAGE < 30" | bc -l) )); then - echo "❌ Coverage is below 30% threshold" - exit 1 - elif (( $(echo "$COVERAGE < 40" | bc -l) )); then - echo "⚠️ Coverage is below 40% (warning threshold)" - else - echo "✅ Coverage meets threshold" - fi + rc=0 + tools/rbe/worker-env-sync main || rc=$? + echo "rc=$rc" >> "$GITHUB_OUTPUT" + exit "$rc" - - name: Upload coverage - uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v6 - if: success() - continue-on-error: true - with: - file: ./coverage.out - fail_ci_if_error: false + - name: Open or update the out-of-step issue + if: ${{ failure() && steps.sync.outputs.rc == '1' }} + env: + GH_TOKEN: ${{ github.token }} + REPORT: ${{ runner.temp }}/worker-env-sync.md + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: tools/rbe/worker-env-sync-issue "$REPORT" "$RUN_URL" diff --git a/.github/workflows/pr-risk.yml b/.github/workflows/pr-risk.yml index 3a632f71b..155b3b944 100644 --- a/.github/workflows/pr-risk.yml +++ b/.github/workflows/pr-risk.yml @@ -2,8 +2,16 @@ name: PR Risk on: pull_request: - branches: [ main, 'release/**' ] + branches: [ main, 'release/**', 'hotfix/**' ] + # Merge queue (engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md, "Merge Queue"): + # the ruleset's required gate must also report on each queue entry's + # merge-group commit, or a queued PR waits until the queue times it out. + # checks_requested is the queue asking for those checks; pinned + # explicitly (scripts/ci_merge_queue_test.go). The concurrency group + # below keys a merge group on its own gh-readonly-queue/* ref, so queue + # runs never cancel each other or a PR's own runs. merge_group: + types: [ checks_requested ] concurrency: group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} @@ -12,548 +20,17 @@ concurrency: env: BD_DISABLE_METRICS: "1" BD_DISABLE_EVENT_FLUSH: "1" - # D2: "true" retires a PR Risk legacy tier on same-repo, non-Dependabot - # pull_requests; pr.yml's gated Bazel lane(s) for it are then the tier's - # only pre-merge run, and pr.yml's gate goes red unless they ran remotely - # and passed. Committed, not repo variables, so a re-run can never change - # them; each must equal pr.yml's / pr-risk.yml's copy - # (scripts/pr_risk_bazel_coverage_test.go). Revert: commit "false" in both - # workflows (in-flight PRs pick it up on their next push or merge of main). - # Step 1: the embedded-Dolt test jobs (Bazel `embedded Dolt tier`). - BAZEL_RETIRES_LEGACY_EMBEDDED: "true" - # Step 2: the proxied-server and server-Dolt storage test jobs (Bazel - # `proxied-server tier` and `server-Dolt storage tier`). - BAZEL_RETIRES_LEGACY_DOLT_SERVER_TIERS: "true" - # Step 3: pr.yml's own legacy jobs whose Bazel lanes run in the same pr.yml - # run: PR Core, build-artifacts, the pure-Go/js-wasm check, domain+uow and - # contract corpus (Bazel `test`, `pure-Go and js/wasm`, `dolt-server - # lane`). pr-risk.yml retires nothing for it; its copy only keeps the - # shared bazel-coverage job identical. - BAZEL_RETIRES_LEGACY_PR_LANES: "true" - # Fork and Dependabot PRs: "true" covers them like same-repo PRs (the - # flags above then retire their legacy tiers too): rbe-west's mint - # (rbe-fork) gives their Bazel lanes remote execution, instance oss-fork - # or, for allowlisted authors, oss, and a run the mint does not serve - # (mode cache) is red. "false": they keep the legacy tiers, and the Bazel - # lanes run remotely beside them whenever rbe-fork is open (bazel.yml - # modes fork-ro/fork-rw), else locally with the read-only cache as before. - BAZEL_COVERS_FORKS: "false" + +# The legacy Go test tiers this workflow used to run (embedded Dolt storage, +# conformance and cmd shards; proxied-server cmd shards; server-Dolt storage +# and full suite) are pr.yml's Bazel lanes on rbe-west now: `embedded Dolt +# tier`, `proxied-server tier` (`dolt-race`, with the dolt-server lane, in +# mode remote) and `server-Dolt storage tier` (bazel.yml), which pr.yml's `CI Gate / Required` requires to have run remotely and +# passed on every pull_request and merge group, fork and Dependabot PRs +# included (ga-96smfk.22). What remains is the Nix packaging check, which no +# Bazel target can stand in for: it builds the package Nix users install. jobs: - detect-ci-tier: - name: Detect CI tier - # F3: same-repo PRs and merge_group get the org's Blacksmith pool; forks, - # Dependabot and any other event stay GitHub-hosted. This job restores no - # GitHub-saved cache. - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} - # F3: now on Blacksmith for same-repo PRs; a hang used to burn only the - # default 360 minutes of a free GitHub-hosted runner, now Blacksmith - # minutes too. - timeout-minutes: 10 - outputs: - full_embedded: ${{ steps.tier.outputs.full_embedded }} - reason: ${{ steps.tier.outputs.reason }} - shadow_embedded_cli: ${{ steps.shadow-selector.outputs.embedded_cli }} - shadow_proxied_cli: ${{ steps.shadow-selector.outputs.proxied_cli }} - shadow_embedded_storage: ${{ steps.shadow-selector.outputs.embedded_storage }} - shadow_embedded_conformance: ${{ steps.shadow-selector.outputs.embedded_conformance }} - shadow_server_conformance: ${{ steps.shadow-selector.outputs.server_conformance }} - shadow_full: ${{ steps.shadow-selector.outputs.full }} - shadow_reason: ${{ steps.shadow-selector.outputs.reason }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - with: - fetch-depth: 0 - - - name: Decide embedded Dolt coverage - id: tier - env: - PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} - PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} - run: bash .github/scripts/ci-embedded-tier.sh - - - name: Shadow CI capability selector - id: shadow-selector - continue-on-error: true - env: - GITHUB_EVENT_NAME: ${{ github.event_name }} - PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} - PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} - run: | - set -o pipefail - selection="$(bash .github/scripts/ci-capability-selector.sh)" - printf '%s\n' "$selection" - { - echo '### Shadow CI capability selector' - printf '%s\n' "$selection" | sed 's/^/- `/' | sed 's/$/`/' - } >> "$GITHUB_STEP_SUMMARY" - - # D2: which legacy tiers below stand down because pr.yml's gated Bazel - # lanes run them instead: `embedded` (the test-embedded-* jobs; Bazel - # `embedded Dolt tier`) and `dolt_server` (test-proxied-cmd and the - # test-server-storage* jobs; Bazel `proxied-server tier` and `server-Dolt - # storage tier`), plus `pr_lanes`, which only pr.yml reads (its own PR - # Core, build-artifacts, pure-Go, domain+uow and contract corpus jobs). - # Each is true only with its committed BAZEL_RETIRES_LEGACY_* flag, on a same-repo (not fork) pull_request whose actor is not - # Dependabot. pr.yml runs this same job (policy-tested identical) and its - # gate goes red unless the lanes then ran remotely and passed, so neither - # the kill switch (mode skip) nor a missing executor secret (mode cache) - # can silently drop a tier. Forks and Dependabot (no secrets), merge_group - # and every other event keep the legacy tiers. The step reads no secret or - # variable and runs no repository code. - bazel-coverage: - name: Bazel tier coverage - # F3: same-repo PRs and merge_group get the org's Blacksmith pool; forks, - # Dependabot and any other event stay GitHub-hosted. This job restores no - # GitHub-saved cache, so Blacksmith's inability to see one does not cost - # it anything. Must stay byte-identical to pr.yml's copy - # (TestPRRiskBazelCoverageJob) and to the TestSameRepoBlacksmithRunners - # pin. - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 5 - outputs: - embedded: ${{ steps.decide.outputs.embedded }} - dolt_server: ${{ steps.decide.outputs.dolt_server }} - pr_lanes: ${{ steps.decide.outputs.pr_lanes }} - steps: - # GitHub's == is case-insensitive. FORK is bazel.yml's rbe job's - # expression, verbatim. Nothing mutable is read: not RBE_WEST_WORKERS - # and not the executor secret (either, evaluated per run, would let one - # workflow's re-run disagree with the other's). A same-repo PR whose run - # lacks the secret is covered anyway, so pr.yml's gate goes red (mode - # cache) instead of a tier silently moving back. Fork and Dependabot - # runs get no Actions secrets by design: they are covered only while - # BAZEL_COVERS_FORKS is "true" (rbe-fork gives their lanes remote - # execution), and then a closed rbe-fork turns them red the same way; - # it never moves them back to a legacy tier silently. github.actor - # (unlike triggering_actor) stays the PR's actor on a re-run. - - name: Decide which legacy tiers the Bazel lanes cover - id: decide - env: - RETIRED_EMBEDDED: ${{ env.BAZEL_RETIRES_LEGACY_EMBEDDED == 'true' }} - RETIRED_DOLT_SERVER: ${{ env.BAZEL_RETIRES_LEGACY_DOLT_SERVER_TIERS == 'true' }} - RETIRED_PR_LANES: ${{ env.BAZEL_RETIRES_LEGACY_PR_LANES == 'true' }} - COVERS_FORKS: ${{ env.BAZEL_COVERS_FORKS == 'true' }} - PULL_REQUEST: ${{ github.event_name == 'pull_request' }} - FORK: ${{ github.event.pull_request.head.repo.fork == true }} - DEPENDABOT: ${{ github.actor == 'dependabot[bot]' }} - run: | - for v in RETIRED_EMBEDDED RETIRED_DOLT_SERVER RETIRED_PR_LANES COVERS_FORKS PULL_REQUEST FORK DEPENDABOT; do - case "${!v}" in - true|false) ;; - *) echo "::error::$v is '${!v}', want true or false"; exit 1 ;; - esac - done - # Covered: the Bazel lanes are this run's only run of the retired - # tiers. Same-repo PRs (the CI secrets); fork and Dependabot PRs - # too while BAZEL_COVERS_FORKS is "true". - covered=false - if [ "$PULL_REQUEST" = true ]; then - if [ "$FORK" = false ] && [ "$DEPENDABOT" = false ]; then - covered=true - elif [ "$COVERS_FORKS" = true ]; then - covered=true - fi - fi - embedded=false - if [ "$covered" = true ] && [ "$RETIRED_EMBEDDED" = true ]; then - embedded=true - fi - dolt_server=false - if [ "$covered" = true ] && [ "$RETIRED_DOLT_SERVER" = true ]; then - dolt_server=true - fi - pr_lanes=false - if [ "$covered" = true ] && [ "$RETIRED_PR_LANES" = true ]; then - pr_lanes=true - fi - { - echo "embedded=$embedded" - echo "dolt_server=$dolt_server" - echo "pr_lanes=$pr_lanes" - } >> "$GITHUB_OUTPUT" - echo "Legacy tiers retired in favour of the Bazel lanes: embedded Dolt **$embedded**, proxied and server Dolt **$dolt_server**, pr.yml's PR Core/build/pure-Go/domain+uow/contract jobs **$pr_lanes** (pull_request: $PULL_REQUEST, fork: $FORK, dependabot: $DEPENDABOT, forks covered: $COVERS_FORKS, retired embedded: $RETIRED_EMBEDDED, retired proxied/server: $RETIRED_DOLT_SERVER, retired pr.yml jobs: $RETIRED_PR_LANES)" | tee -a "$GITHUB_STEP_SUMMARY" - - # End-to-end coverage for proxied-server CLI subcommands, sharded across the - # CI matrix. Each sub-test drives the bd CLI subprocess against a real dolt - # sql-server started via testcontainers by the shared proxied harness - # (cmd/bd/*_proxied_integration_test.go). - # - # Reuses the cmd/bd test binary compiled once by build-embedded: the proxied - # tests live in the same package and are gated at runtime by - # BEADS_TEST_PROXIED_SERVER=1, so no separate build is needed. Shard - # assignment is committed in .github/scripts/proxied-cmd-test-shards.txt; - # newly-added TestProxiedServer*/TestServerMode* tests hash-distribute until - # listed there. Stands down, with the test-server-storage* jobs, where - # bazel-coverage's dolt_server says pr.yml's gated Bazel `proxied-server - # tier` lane runs it (D2 step 2). - test-proxied-cmd: - name: Test (Proxied Dolt Cmd ${{ matrix.shard }}/${{ strategy.job-total }}) - needs: [detect-ci-tier, bazel-coverage, build-embedded] - if: needs.detect-ci-tier.outputs.full_embedded == 'true' && needs.bazel-coverage.outputs.dolt_server != 'true' - runs-on: ubuntu-latest - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Download binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: embedded-test-binaries - path: /tmp/ - - - name: Fix permissions - run: chmod +x /tmp/bd-proxied /tmp/bd-cmd-test - - - name: Install Dolt CLI - # TestProxiedServerExternalCreate needs the dolt binary on PATH; the - # shared harness itself uses the dolt sql-server container image. - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Pull Dolt sql-server image - # The shared proxied harness requires the image cached locally - # (isDoltImageCached); without it every proxied test self-skips. Keep the - # tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage. - run: ./scripts/ci/pull-dolt-image.sh - - - name: Test proxied-server cmd shard - timeout-minutes: 16 - env: - BEADS_TEST_PROXIED_SERVER: "1" - BEADS_TEST_BD_BINARY: /tmp/bd-proxied - BEADS_TEST_CMD_BINARY: /tmp/bd-cmd-test - run: bash .github/scripts/proxied-test-shard.sh ${{ matrix.shard }} 15 - - # Embedded Dolt tests - test the in-process Dolt engine (no server required) - # - # Split into: build → storage tests + parallel cmd test shards. - # cmd/bd embedded tests use a committed shard manifest; newly-added tests - # still auto-distribute via hash fallback until the manifest is updated. - # - # The storage, conformance and cmd test jobs stand down when - # bazel-coverage says pr.yml's gated Bazel `embedded Dolt tier` lane runs - # them instead (its `embedded` output); the proxied and server Dolt jobs - # when its Bazel `proxied-server tier` and `server-Dolt storage tier` lanes - # do (`dolt_server`). build-embedded's embedded-test-binaries artifact - # feeds all six (and nothing else), so it stands down only when both do. - - build-embedded: - name: Build (Embedded Dolt) - needs: [detect-ci-tier, bazel-coverage] - if: needs.detect-ci-tier.outputs.full_embedded == 'true' && (needs.bazel-coverage.outputs.embedded != 'true' || needs.bazel-coverage.outputs.dolt_server != 'true') - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Restore race Go build cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ github.sha }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race- - - - name: Restore non-race Go build cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/non-race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ github.sha }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race- - - - name: Build embedded bd binary - env: - GOCACHE: ${{ runner.temp }}/go-cache/race - run: go build -tags gms_pure_go -race -o /tmp/bd-embedded-test ./cmd/bd/ - - - name: Build embedded storage test binary - env: - GOCACHE: ${{ runner.temp }}/go-cache/race - run: go test -tags gms_pure_go -race -c -o /tmp/embeddeddolt-test ./internal/storage/embeddeddolt/ - - - name: Build embedded cmd test binary - env: - GOCACHE: ${{ runner.temp }}/go-cache/race - run: go test -tags gms_pure_go -race -c -o /tmp/bd-cmd-test ./cmd/bd/ - - # Non-race bd used as the proxied-server test subprocess. The proxied - # tests spawn bd many times per sub-test; a -race subprocess would slow - # every invocation, so build a plain binary for BEADS_TEST_BD_BINARY. - - name: Build proxied bd subprocess binary - env: - GOCACHE: ${{ runner.temp }}/go-cache/non-race - run: go build -tags gms_pure_go -o /tmp/bd-proxied ./cmd/bd/ - - # Server-Dolt conformance binary. No -race: the Dolt server runs - # out-of-process in a container, and omitting it keeps the run inside the - # job's timeout. The dolt package self-skips without the docker image, so - # the binary is harmless if its job is gated off. - - name: Build server Dolt conformance test binary - env: - GOCACHE: ${{ runner.temp }}/go-cache/non-race - run: go test -tags=integration,gms_pure_go -c -o /tmp/dolt-conformance-test ./internal/storage/dolt/ - - - name: Upload binaries - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: embedded-test-binaries - path: | - /tmp/bd-embedded-test - /tmp/embeddeddolt-test - /tmp/bd-cmd-test - /tmp/bd-proxied - /tmp/dolt-conformance-test - retention-days: 1 - - test-embedded-storage: - name: Test (Embedded Dolt Storage ${{ matrix.shard }}/${{ strategy.job-total }}) - needs: [detect-ci-tier, bazel-coverage, build-embedded] - if: needs.detect-ci-tier.outputs.full_embedded == 'true' && needs.bazel-coverage.outputs.embedded != 'true' - runs-on: ubuntu-latest - # The shard script's -test.timeout=20m plus setup. At 15m the 1000-item - # batch-apply cap cancelled shard 2/5: TestBatchApplyContract took 604s - # under -race (97s at the 100-item cap, main run 35862663577) and the - # shard hit 15m twice (run 36807191489). The manifest now pins the heavy - # tests apart; the heaviest shard projects to ~13m. - timeout-minutes: 25 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Download binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: embedded-test-binaries - path: /tmp/ - - - name: Fix permissions - run: chmod +x /tmp/embeddeddolt-test - - - name: Configure Git - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - - name: Test - env: - BEADS_TEST_EMBEDDED_DOLT: "1" - BEADS_TEST_EMBEDDED_TEST_BINARY: /tmp/embeddeddolt-test - # Manifest-driven shard of the storage suite (mirrors test-embedded-cmd - # / embedded-test-shard.sh). Conformance runs separately in the - # dedicated test-embedded-conformance job; embedded-storage-test-shard.sh - # excludes TestConformance from discovery, so it never lands in one of - # these shards. - run: bash .github/scripts/embedded-storage-test-shard.sh ${{ matrix.shard }} 5 - - test-embedded-conformance: - name: Test (Embedded Dolt Conformance - ${{ matrix.partition }}) - needs: [detect-ci-tier, bazel-coverage, build-embedded] - if: needs.detect-ci-tier.outputs.full_embedded == 'true' && needs.bazel-coverage.outputs.embedded != 'true' - runs-on: ubuntu-latest - timeout-minutes: 35 - strategy: - fail-fast: false - matrix: - partition: [core, audit] - env: - BEADS_TEST_EMBEDDED_DOLT: "1" - BEADS_TEST_EMBEDDED_TEST_BINARY: /tmp/embeddeddolt-test - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Download binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: embedded-test-binaries - path: /tmp/ - - - name: Fix permissions - run: chmod +x /tmp/embeddeddolt-test - - - name: Configure Git - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - - name: Test core conformance - if: matrix.partition == 'core' - # RunAll has a natural Audit seam. Run everything except Audit in the - # core shard and Audit alone in the other shard. The combined suite has - # exceeded 30m under runner variance; each half currently takes ~15m. - # Keep the Go timeout below the job timeout so a real stall still emits - # a diagnostic goroutine dump before Actions stops the job. - run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=30m -test.run '^TestConformance$' -test.skip '^TestConformance$/^Audit$' - - - name: Test audit conformance - if: matrix.partition == 'audit' - run: /tmp/embeddeddolt-test -test.v -test.count=1 -test.timeout=30m -test.run '^TestConformance$/^Audit$' - - test-server-storage: - name: Test (Server Dolt Conformance) - needs: [detect-ci-tier, bazel-coverage, build-embedded] - if: needs.detect-ci-tier.outputs.full_embedded == 'true' && needs.bazel-coverage.outputs.dolt_server != 'true' - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Download binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: embedded-test-binaries - path: /tmp/ - - - name: Fix permissions - run: chmod +x /tmp/dolt-conformance-test - - - name: Configure Git - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Dolt - run: | - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - dolt version - - - name: Pull Dolt sql-server image - # Presence of this image flips isDoltImageCached() true, so the suite - # exercises server Dolt instead of self-skipping. Keep the tag in sync - # with internal/testutil/testdoltcommon.go:DoltDockerImage. - run: ./scripts/ci/pull-dolt-image.sh - - - name: Test - # Server twin of test-embedded-conformance: same conformance.RunAll, but - # against the container-backed server-mode Dolt backend. No -short / no - # BEADS_TEST_SKIP=dolt, so TestMain starts the shared server and the - # suite runs instead of self-skipping. - run: /tmp/dolt-conformance-test -test.v -test.count=1 -test.timeout=15m -test.run '^TestConformance$' - - test-server-storage-full: - name: Test (Server Dolt Full Suite ${{ matrix.shard }}/${{ strategy.job-total }}) - needs: [detect-ci-tier, bazel-coverage, build-embedded] - if: needs.detect-ci-tier.outputs.full_embedded == 'true' && needs.bazel-coverage.outputs.dolt_server != 'true' - runs-on: ubuntu-latest - timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Download binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: embedded-test-binaries - path: /tmp/ - - - name: Fix permissions - run: chmod +x /tmp/dolt-conformance-test - - - name: Configure Git - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Dolt - run: | - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - dolt version - - - name: Pull Dolt sql-server image - # Presence of this image flips isDoltImageCached() true, so the suite - # exercises server Dolt instead of self-skipping. Keep the tag in sync - # with internal/testutil/testdoltcommon.go:DoltDockerImage. - run: ./scripts/ci/pull-dolt-image.sh - - - name: Test - # build-embedded's dolt-conformance-test binary compiles every - # top-level test in internal/storage/dolt, not just conformance -- - # test-server-storage above only ever runs the ^TestConformance$ - # subset. Everything else in that binary (TestCreateGuard_*, - # federation/create-guard/concurrent suites, and diff-owned tests such - # as TestBenchDBPurgeDoesNotLeak on PR #5792) was reached by no - # PR-triggered lane and silently SKIPped for lack of a live server. - # This sibling job reuses the same artifact and server setup and runs - # everything else instead, so a SKIP there gets a real PASS/FAIL. - # - # Manifest-driven shard of the full suite (mirrors test-embedded-storage - # / server-storage-test-shard.sh): 1126 tests in one 15m-Go-timeout job - # never finished (job 95616282508 died at 256/1126 tests, 15m28s in, - # zero failures -- it just ran out of time). server-storage-test-shard.sh - # excludes TestConformance from discovery, so it never lands in one of - # these shards. - env: - BEADS_TEST_ENV_RUN_DOLT: "1" - run: bash .github/scripts/server-storage-test-shard.sh ${{ matrix.shard }} 16 - - test-embedded-cmd: - name: Test (Embedded Dolt Cmd ${{ matrix.shard }}/${{ strategy.job-total }}) - needs: [detect-ci-tier, bazel-coverage, build-embedded] - if: needs.detect-ci-tier.outputs.full_embedded == 'true' && needs.bazel-coverage.outputs.embedded != 'true' - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Download binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: embedded-test-binaries - path: /tmp/ - - - name: Fix permissions - run: chmod +x /tmp/bd-embedded-test /tmp/embeddeddolt-test /tmp/bd-cmd-test - - - name: Configure Git - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - - name: Test - env: - BEADS_TEST_EMBEDDED_DOLT: "1" - BEADS_TEST_BD_BINARY: /tmp/bd-embedded-test - run: bash .github/scripts/embedded-test-shard.sh ${{ matrix.shard }} 20 - test-nix: name: Test Nix Flake # F7a: cache-free (no GitHub-saved cache restored/saved here) same-repo @@ -568,10 +45,11 @@ jobs: id: nix_help run: | nix run .#default -- --help > help.txt - # Every flake check for the runner's own system (today: hook-timeout- - # backends, checks.nix). `nix flake check` rather than a spelled-out - # `.#checks.x86_64-linux.`: no hardcoded system, and a check added - # to checks.nix is run without a workflow edit. + # A packaging check, not a test: evaluates every flake output (packages, + # apps, devShells, overlay) for every system the flake declares. The + # flake has no `checks`: its one check, hook-timeout-backends, runs + # under Bazel as //tests/hook_timeout_backends:hook_timeout_backends_test + # in bazel.yml's PR-core lane. - name: Run the flake checks run: | nix flake check -L @@ -601,15 +79,6 @@ jobs: # minutes too. timeout-minutes: 10 needs: - - detect-ci-tier - - bazel-coverage - - build-embedded - - test-embedded-storage - - test-embedded-conformance - - test-server-storage - - test-server-storage-full - - test-embedded-cmd - - test-proxied-cmd - test-nix if: ${{ always() }} steps: @@ -619,47 +88,6 @@ jobs: env: CI_GATE_NAME: PR risk gate CI_GATE_REQUIRED: >- - DETECT_CI_TIER - BAZEL_COVERAGE - BUILD_EMBEDDED - TEST_EMBEDDED_STORAGE - TEST_EMBEDDED_CONFORMANCE - TEST_SERVER_STORAGE - TEST_SERVER_STORAGE_FULL - TEST_EMBEDDED_CMD - TEST_PROXIED_CMD TEST_NIX - FULL_EMBEDDED: ${{ needs.detect-ci-tier.outputs.full_embedded }} - BAZEL_COVERS_EMBEDDED: ${{ needs.bazel-coverage.outputs.embedded }} - BAZEL_COVERS_DOLT_SERVER: ${{ needs.bazel-coverage.outputs.dolt_server }} - DETECT_CI_TIER: ${{ needs.detect-ci-tier.result }} - BAZEL_COVERAGE: ${{ needs.bazel-coverage.result }} - BUILD_EMBEDDED: ${{ needs.build-embedded.result }} - TEST_EMBEDDED_STORAGE: ${{ needs.test-embedded-storage.result }} - TEST_EMBEDDED_CONFORMANCE: ${{ needs.test-embedded-conformance.result }} - TEST_SERVER_STORAGE: ${{ needs.test-server-storage.result }} - TEST_SERVER_STORAGE_FULL: ${{ needs.test-server-storage-full.result }} - TEST_EMBEDDED_CMD: ${{ needs.test-embedded-cmd.result }} - TEST_PROXIED_CMD: ${{ needs.test-proxied-cmd.result }} TEST_NIX: ${{ needs.test-nix.result }} - run: | - skipped_ok="" - if [[ "$FULL_EMBEDDED" != "true" ]]; then - skipped_ok="BUILD_EMBEDDED TEST_EMBEDDED_STORAGE TEST_EMBEDDED_CONFORMANCE TEST_SERVER_STORAGE TEST_SERVER_STORAGE_FULL TEST_EMBEDDED_CMD TEST_PROXIED_CMD" - fi - # The legacy tiers' test jobs stand down only where pr.yml's gated - # Bazel lanes run the tier (bazel-coverage), and build-embedded, - # whose artifact only they consume, only where all of them do; any - # other skip of them, or a failed or missing decision, fails the - # gate. - if [[ "$BAZEL_COVERS_EMBEDDED" == "true" ]]; then - skipped_ok="$skipped_ok TEST_EMBEDDED_STORAGE TEST_EMBEDDED_CONFORMANCE TEST_EMBEDDED_CMD" - fi - if [[ "$BAZEL_COVERS_DOLT_SERVER" == "true" ]]; then - skipped_ok="$skipped_ok TEST_PROXIED_CMD TEST_SERVER_STORAGE TEST_SERVER_STORAGE_FULL" - fi - if [[ "$BAZEL_COVERS_EMBEDDED" == "true" ]] && [[ "$BAZEL_COVERS_DOLT_SERVER" == "true" ]]; then - skipped_ok="$skipped_ok BUILD_EMBEDDED" - fi - export CI_GATE_SKIPPED_OK="$skipped_ok" - bash .github/scripts/ci-gate.sh + run: bash .github/scripts/ci-gate.sh diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 54fa45d04..22dc8c23e 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -5,8 +5,16 @@ on: # release/** is here because release-prep and release-fix PRs are based on # the release branch, not on main. Without it they run almost no CI and the # first full signal is the tag build, where a failure burns the tag. - branches: [ main, 'release/**' ] + branches: [ main, 'release/**', 'hotfix/**' ] + # Merge queue (engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md, "Merge Queue"): + # the ruleset's required gate must also report on each queue entry's + # merge-group commit, or a queued PR waits until the queue times it out. + # checks_requested is the queue asking for those checks; pinned + # explicitly (scripts/ci_merge_queue_test.go). The concurrency group + # below keys a merge group on its own gh-readonly-queue/* ref, so queue + # runs never cancel each other or a PR's own runs. merge_group: + types: [ checks_requested ] concurrency: group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} @@ -15,146 +23,48 @@ concurrency: env: BD_DISABLE_METRICS: "1" BD_DISABLE_EVENT_FLUSH: "1" - # D2: "true" retires a PR Risk legacy tier on same-repo, non-Dependabot - # pull_requests; pr.yml's gated Bazel lane(s) for it are then the tier's - # only pre-merge run, and pr.yml's gate goes red unless they ran remotely - # and passed. Committed, not repo variables, so a re-run can never change - # them; each must equal pr.yml's / pr-risk.yml's copy - # (scripts/pr_risk_bazel_coverage_test.go). Revert: commit "false" in both - # workflows (in-flight PRs pick it up on their next push or merge of main). - # Step 1: the embedded-Dolt test jobs (Bazel `embedded Dolt tier`). - BAZEL_RETIRES_LEGACY_EMBEDDED: "true" - # Step 2: the proxied-server and server-Dolt storage test jobs (Bazel - # `proxied-server tier` and `server-Dolt storage tier`). - BAZEL_RETIRES_LEGACY_DOLT_SERVER_TIERS: "true" - # Step 3: pr.yml's own legacy jobs whose Bazel lanes run in the same pr.yml - # run: PR Core, build-artifacts, the pure-Go/js-wasm check, domain+uow and - # contract corpus (Bazel `test`, `pure-Go and js/wasm`, `dolt-server - # lane`). pr-risk.yml retires nothing for it; its copy only keeps the - # shared bazel-coverage job identical. - BAZEL_RETIRES_LEGACY_PR_LANES: "true" - # F4 side-by-side rollout: "false" keeps the native windows-latest jobs - # (test-windows-liveness, worktree-remove-windows) as the required pair and - # their Linux-cross-built "-prebuilt" twins (test-windows-liveness-prebuilt, - # worktree-remove-windows-prebuilt) advisory-only. Both pairs run and report - # on every PR regardless of this flag; flipping it to "true" swaps which - # pair ci-gate enforces (the other pair moves to CI_GATE_SKIPPED_OK) without - # touching ci-gate.needs or the env map below -- see the "Evaluate CI gate" - # step's run script. Committed, not a repo variable, for the same reason as - # the BAZEL_RETIRES_LEGACY_* flags above: a re-run can never change it. - WINDOWS_PREBUILT_REQUIRED: "true" - # Fork and Dependabot PRs: "true" covers them like same-repo PRs (the - # flags above then retire their legacy tiers too): rbe-west's mint - # (rbe-fork) gives their Bazel lanes remote execution, instance oss-fork - # or, for allowlisted authors, oss, and a run the mint does not serve - # (mode cache) is red. "false": they keep the legacy tiers, and the Bazel - # lanes run remotely beside them whenever rbe-fork is open (bazel.yml - # modes fork-ro/fork-rw), else locally with the read-only cache as before. - BAZEL_COVERS_FORKS: "false" + # step's run script. Committed, not a repo variable, so a re-run can never + # change it. # bazel.yml's bazel-cmd-dolt lane (the cmd/bd Dolt-server tier: the # Dolt-gated cmd/bd tests no other lane runs) is advisory while this is # "false": it runs and reports in the bazel call (continue-on-error, so a # failure never turns the call's aggregate red), and ci-gate ignores its # BAZEL_CMD_DOLT result. "true" adds BAZEL_CMD_DOLT to CI_GATE_REQUIRED in # the "Evaluate CI gate" step's run script; bazel-gate.sh still accepts - # its skip in modes skip and local. Committed, not a repo variable, for - # the same reason as the flags above. - BAZEL_CMD_DOLT_REQUIRED: "false" + # its skip in modes skip and local. Committed, not a repo variable, so a + # re-run can never change it. The `bazel` job's cmd-dolt-required + # input must equal it (a `with:` cannot read env; policy-tested): "true" + # also drops //cmd/bd:bd_test from bazel-integration, because the required + # lane runs the same integration-build bd_test without the dolt skip, so + # each cmd/bd test runs once. Rollback: commit "false" here and false in + # that input together; bazel-integration runs bd_test again on the next run. + BAZEL_CMD_DOLT_REQUIRED: "true" jobs: - # D2 step 3: stands down where bazel-coverage says pr_lanes (same-repo, - # non-Dependabot PRs while BAZEL_RETIRES_LEGACY_PR_LANES is "true"): its - # consumers then stand down too. F3: the package gates (package-mcp, - # package-npm) are no longer among those consumers - they moved into - # bazel.yml and build their own bd (Bazel-built on same-repo PRs, `go - # build` otherwise), needing only the call's rbe job. - build-artifacts: - name: Build Artifacts - runs-on: ubuntu-latest - needs: bazel-coverage - if: needs.bazel-coverage.outputs.pr_lanes != 'true' - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - with: - fetch-depth: 0 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Restore non-race Go build cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/non-race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ github.sha }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race- - - - name: Build reusable Linux artifacts - env: - GOCACHE: ${{ runner.temp }}/go-cache/non-race - run: | - set -euo pipefail - mkdir -p artifacts - source ./.buildflags - go_version="$(go version)" - commit="$(git rev-parse HEAD)" - go build -tags gms_pure_go -o artifacts/bd-linux-gms-pure ./cmd/bd - chmod +x artifacts/bd-linux-gms-pure - ( - cd artifacts - sha256sum bd-linux-gms-pure > SHA256SUMS - ) - { - echo "commit=${commit}" - echo "go_version=${go_version}" - echo "build_tags=${BEADS_BUILD_TAGS}" - echo "artifact=bd-linux-gms-pure" - } > artifacts/build-manifest.txt - - - name: Upload build artifacts - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: ci-build-artifacts - path: artifacts/ - retention-days: 1 - if-no-files-found: error - - # F7a: fold of five independent, no-cache pr.yml checks that previously ran - # as five separate ubuntu-latest jobs (check-build-tags, - # check-version-consistency, check-migration-hygiene, - # check-no-beads-changes, fmt-check) into one Blacksmith job with five - # steps. Each step gets its own id and `if: ${{ !cancelled() }}` so one - # check's failure does not block the others from running, and the job - # exposes each step's outcome as a job output so ci-gate can still red the - # exact same CI_GATE_REQUIRED token it did before the fold - - # TestPRCIGateFastChecksTokens pins the mapping. FAST_CHECKS (the job's own - # `result`) is an added backstop token: if the whole job is lost (e.g. a - # cancelled runner) before any step sets its output, the per-check outputs - # read empty and the CI_GATE_REQUIRED fallback below treats that as - # "skipped" - which is NOT skipped_ok, so the gate still reds, but - # FAST_CHECKS gives ci-gate.sh one clear error line ("FAST_CHECKS=cancelled") - # instead of five confusing ones. + # The checks that need the PR's base commit, so no hermetic Bazel target + # can hold them: check-migration-hygiene.sh's delta half (C: shipped + # migrations are frozen, D: ignored-plane twins, E: no prepared DML in new + # migrations, all over `git diff `) and the .beads/issues.jsonl + # guard. Everything else this job ran is a Bazel test in bazel.yml's `test` + # lane (ga-96smfk.20): //scripts/repochecks:build_tags_test, + # :go_install_guidance_test, :winget_portable_alias_test, + # :migration_hygiene_test (checks A and B) and :fmt_test, and + # //internal/versioncheck:versioncheck_test for check-versions.sh. No Go: + # both steps are bash and git. + # + # Each step has its own id and `if: ${{ !cancelled() }}`, so one failure + # does not hide the other, and its outcome is a job output that ci-gate + # requires (TestPRCIGateFastChecksTokens). FAST_CHECKS (the job's own + # `result`) is the backstop token for a job lost before any step set its + # output. fast-checks: - name: Fast checks (build tags, versions, migrations, beads diff, fmt) + name: Fast checks (frozen migrations, .beads diff) runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} timeout-minutes: 10 outputs: - build-tags: ${{ steps.build-tags.outcome }} - version-consistency: ${{ steps.version-consistency.outcome }} migration-hygiene: ${{ steps.migration-hygiene.outcome }} no-beads-changes: ${{ steps.no-beads-changes.outcome }} - fmt: ${{ steps.fmt.outcome }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 with: @@ -162,52 +72,38 @@ jobs: # the base branch; a shallow checkout starves both. fetch-depth: 0 - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - # Fast shell/Make guard for direct source-time build-tag declarations. - # Workflow `run` steps are checked structurally in the required policy - # wrapper. - - name: Check build-tag policy - id: build-tags - if: ${{ !cancelled() }} - run: | - ./scripts/check-build-tags.sh - ./scripts/check-go-install-guidance.sh - ./scripts/check-winget-portable-alias.sh - - # Fast check to ensure all version files are in sync - - name: Check all versions match - id: version-consistency - if: ${{ !cancelled() }} - run: ./scripts/check-versions.sh - - # Migration hygiene: duplicate version numbers, nondeterministic SQL - # (UUID()/NOW()/RAND(), the #4259 root-cause class), and edits to - # migration files that already exist on the base branch (shipped - # migrations are frozen; fix forward with a new version). Fails at PR - # time, before any test even compiles. Details: + # Migration hygiene, delta half: edits to migration files that already + # exist on the base branch (shipped migrations are frozen; fix forward + # with a new version), and the twin and prepared-DML rules for new + # migrations. Checks A and B (duplicate versions, nondeterministic SQL) + # read only the tree and run in Bazel. Details: # scripts/check-migration-hygiene.sh. - name: Run migration hygiene checks id: migration-hygiene if: ${{ !cancelled() }} env: BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }} + MIGRATION_HYGIENE_SCOPE: delta run: ./scripts/check-migration-hygiene.sh # Fast check to catch accidental .beads/issues.jsonl changes from - # contributors. pull_request-only, same as before the fold: merge_group - # has no base_ref to diff against, so the step (and therefore this - # token) is skipped there, and merge_group's CI_GATE_SKIPPED_OK - # allow-lists exactly that skip below. + # contributors. Runs on both PR triggers: a pull_request diffs against + # origin/ (GITHUB_BASE_REF), a merge group (which has no + # base_ref) against the queue's merge_group.base_sha, the commit the + # group's head is built on (fetch-depth 0 above fetches it). - name: Check for .beads/issues.jsonl changes id: no-beads-changes - if: ${{ !cancelled() && github.event_name == 'pull_request' }} + if: ${{ !cancelled() }} + env: + MERGE_GROUP_BASE_SHA: ${{ github.event.merge_group.base_sha }} run: | - if git diff --name-only origin/${{ github.base_ref }}...HEAD | grep -q "^\.beads/issues\.jsonl$"; then + base="${MERGE_GROUP_BASE_SHA:-origin/${GITHUB_BASE_REF:-main}}" + # Fail closed: a pipe into grep -q would pass on a failed diff. + if ! git rev-parse --verify --quiet "$base^{commit}" >/dev/null; then + echo "::error::diff base $base is unavailable" + exit 1 + fi + if git diff --name-only "$base"...HEAD | grep -q "^\.beads/issues\.jsonl$"; then echo "This PR includes changes to .beads/issues.jsonl" echo "" echo "This file is the project's issue database and should not be modified in PRs." @@ -221,161 +117,6 @@ jobs: fi echo "No .beads/issues.jsonl changes detected" - - name: Check gofmt - id: fmt - if: ${{ !cancelled() }} - run: make fmt-check - - # Lock in two CGO-disabled portability boundaries. cmd/bd carries a mix of - # cgo-only test helpers (embedded Dolt, sql.DB) and pure-Go tests; compiling - # and running its pure-Go subset prevents test contamination (mybd-ycx / - # GH#3683 follow-up). internal/hooks also declares a js/wasm boundary where - # process execution must fail explicitly, so this required leaf job compiles - # the complete package test binary and executes that exact contract under - # Node rather than allowing a missing platform implementation to recur. - # - # D2 step 3: stands down where bazel-coverage says pr_lanes; Bazel's - # `pure-Go and js/wasm` lane (bazel-pure) runs the same boundaries, and - # check-release-target-cross-compilation still `go build`s ./... with - # CGO_ENABLED=0 on every PR. - check-cmd-bd-puregeo-tests: - name: Check pure-Go and js/wasm boundaries (CGO_ENABLED=0) - runs-on: ubuntu-latest - needs: bazel-coverage - if: needs.bazel-coverage.outputs.pr_lanes != 'true' - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v6 - with: - node-version: '24' - - - name: Run js/wasm hook boundary - env: - CGO_ENABLED: "0" - GOARCH: wasm - GOOS: js - run: | - set -euo pipefail - - # This required lane owns the exact js/wasm refusal contract. If the - # wasm test surface grows, widen this selector and its count guard - # together rather than assuming compilation executes new tests. - test_status=0 - test_output="$(go test -tags gms_pure_go -count=1 -timeout=2m \ - -exec="$(go env GOROOT)/lib/wasm/go_js_wasm_exec" \ - -run '^TestRunHookReportsUnsupportedExecution$' \ - -v ./internal/hooks 2>&1)" || test_status=$? - printf '%s\n' "$test_output" - (( test_status == 0 )) || exit "$test_status" - - run_count=0 - pass_count=0 - nonpass_count=0 - pass_pattern='^--- PASS: TestRunHookReportsUnsupportedExecution \([0-9.]+s\)$' - nonpass_pattern='^[[:space:]]*--- (FAIL|SKIP): ' - while IFS= read -r line; do - if [[ "$line" == "=== RUN TestRunHookReportsUnsupportedExecution" ]]; then - ((run_count += 1)) - fi - if [[ "$line" =~ $pass_pattern ]]; then - ((pass_count += 1)) - fi - if [[ "$line" =~ $nonpass_pattern ]]; then - ((nonpass_count += 1)) - fi - done <<< "$test_output" - if (( run_count != 1 || pass_count != 1 || nonpass_count != 0 )); then - printf 'expected one exact js/wasm hook test run and pass with no failures or skips; got runs=%s passes=%s nonpasses=%s\n' \ - "$run_count" "$pass_count" "$nonpass_count" >&2 - exit 1 - fi - - - name: Build cmd/bd (CGO_ENABLED=0, gms_pure_go) - env: - CGO_ENABLED: "0" - run: go build -tags gms_pure_go -o /tmp/bd-puregeo ./cmd/bd - - - name: Compile pure-Go test binaries (CGO_ENABLED=0, gms_pure_go) - env: - CGO_ENABLED: "0" - run: | - go test -tags gms_pure_go -c -o /tmp/bd-cmd-puregeo-test ./cmd/bd - go test -tags gms_pure_go -c -o /tmp/bd-embeddeddolt-puregeo-test ./internal/storage/embeddeddolt - go test -tags gms_pure_go -c -o /tmp/bd-tracker-puregeo-test ./internal/tracker - - - name: Run pure-Go cmd/bd test subset (CGO_ENABLED=0) - env: - CGO_ENABLED: "0" - # Restrict to tests that exercise pure-Go code paths. Tests that - # need a Dolt store skip themselves at runtime when no test server - # is available; the goal here is to catch compile-time contamination, - # not run the full suite. - run: | - go test -tags gms_pure_go -count=1 -short -run '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir|NocgoFactoriesHonorSharedServer|NocgoNewDoltStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoNewReadOnlyStoreFromConfig_ErrorSuggestsCorrectFlag)' ./cmd/bd - - # Compile every shipped release target on every PR, so a platform-gating - # mistake is caught here instead of at tag time (#5662). - # - # Coverage boundary, recorded so the green is not over-read: every leg below - # builds CGO_ENABLED=0, but .goreleaser.yml builds bd-linux-amd64, - # bd-linux-arm64 and bd-windows-amd64 with CGO_ENABLED=1, and the darwin pair - # is built natively at CGO_ENABLED=1 by release.yml's goreleaser-macos job. - # Five of these eight legs are therefore a weaker proxy than the binary they - # stand for: the cgo half of the tree (beads_cgo.go -> - # internal/storage/embeddeddolt) is never compiled here, so a break confined - # to it still passes this check. Only android/arm64, windows/arm64 and - # freebsd/amd64 replicate their release configuration exactly. - # - # The build scope is deliberately ./... and not the ./cmd/bd that every - # .goreleaser.yml build id declares as main:. Compiling the whole tree per - # platform is intentional extra coverage, not an oversight. - # - # F7a: folded from 8 per-target jobs into 2 per-group jobs. The target list - # moved out of this matrix and into scripts/ci/release-targets.txt, which - # scripts/ci/check-release-cross-compile.sh reads and - # TestReleaseTargetCrossCompilationMatrixMatchesGoreleaser pins against - # .goreleaser.yml, so the manifest (not this YAML) is now the single - # source of truth for the target set. Moved to Blacksmith for same-repo - # PRs/merge_group: this job restores no GitHub-saved build cache (only a - # best-effort module-cache restore, whose misses are cheap network - # fetches, not lost compute). Runner choice must match the - # TestSameRepoBlacksmithRunners pin. - check-release-target-cross-compilation: - name: Check release target cross-compilation (${{ matrix.group }}) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - group: [unix, desktop] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Build complete release target tree for group ${{ matrix.group }} - run: ./scripts/ci/check-release-cross-compile.sh ${{ matrix.group }} - # The lingering-handle liveness regression test is //go:build windows: the # Ubuntu job above selects it by name but compiles it out, and main.yml's # Windows job runs only on pushes to main (build/smoke, no go test). Run @@ -383,26 +124,18 @@ jobs: # regressions actually execute at PR time. The init credential shell # fixtures are a separate concern and run natively in # pr-preflight-platforms, not here. - # F7b: same-repo Blacksmith (blacksmith-4vcpu-windows-2025) for same-repo - # PRs/merge_group, falling back to windows-latest for forks/Dependabot -- - # same pattern as the Linux same-repo jobs above, with the Windows-2025 - # label instead (public beta; GitHub's windows-2025 image minus the full - # Visual Studio IDE/EdgeDriver/WinAppDriver, VS Build Tools 2022 present, - # no Linux Docker). - # - # RISK (unverified from this sandbox, flagged in the F7b report): the first - # step below builds and runs ./cmd/bd with CGO_ENABLED=1 (embedded Dolt). - # windows-latest's cgo build works today via the toolchain GitHub documents - # for that image; Blacksmith's windows-2025 docs only confirm "VS Build - # Tools 2022" is present, not which cgo toolchain (MSVC/clang-cl vs an - # installed mingw-w64) backs `go build` with CGO_ENABLED=1 there. The - # fork-PR path (windows-latest) is an unaffected, always-on canary for this - # job; if the same-repo leg fails here specifically with a cgo/link error, - # that is the toolchain gap to roll back on (revert this runs-on line to - # the literal `windows-latest`). + # Blacksmith Windows (blacksmith-4vcpu-windows-2025: GitHub's windows-2025 + # image minus the full Visual Studio IDE/EdgeDriver/WinAppDriver, VS Build + # Tools 2022 present, no Linux Docker) for every PR and merge group, forks + # and Dependabot included (ga-96smfk.22): Windows and macOS jobs run on + # Blacksmith, everything Linux under Bazel on rbe-west. The first step + # builds ./cmd/bd with CGO_ENABLED=1 (embedded Dolt); the toolchain + # diagnostic step below prints which cgo toolchain backs it. Since + # ga-96smfk.22 this job (not a cross-compiled "-prebuilt" twin) is the + # required run of these tests. test-windows-liveness: name: Test (Windows) cmd/bd liveness regression - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-windows-2025' || 'windows-latest' }} + runs-on: ${{ 'blacksmith-4vcpu-windows-2025' }} # F7b review fix (S6): raised from 15 to 20, matching open PR #7143's own # measurement on this exact job (retained runs take about 8m; one run's # own step timing showed 451s total with a 403s compile step) and @@ -514,12 +247,12 @@ jobs: # on the second step only ensures it still runs after the first fails, # giving both packages' results in one log instead of stopping at the # first failure. No aggregator step is needed. - # F7b: same-repo Blacksmith (blacksmith-2vcpu-windows-2025); both steps + # Blacksmith Windows (blacksmith-2vcpu-windows-2025) for every PR; both steps # build with CGO_ENABLED=0 (or no cgo at all for doltversion), so this job # carries none of test-windows-liveness's cgo-toolchain risk. test-windows-small: name: Test (Windows) small packages (doltversion, dbproxy server) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-2vcpu-windows-2025' || 'windows-latest' }} + runs-on: ${{ 'blacksmith-2vcpu-windows-2025' }} timeout-minutes: 15 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 @@ -555,13 +288,12 @@ jobs: # Destructive worktree removal depends on native Windows path identity. # This focused process suite requires NTFS per-directory case sensitivity # and fails (rather than skips) when the runner cannot provide it. - # F7b: same-repo Blacksmith (blacksmith-4vcpu-windows-2025). CGO_ENABLED=0 - # below, so no cgo-toolchain risk; this leg's non-race GOCACHE restore-keys - # prefix now gets a hit from main.yml's test-windows job, whose `venue` - # matrix extension (F7b) saves that same key on this exact runner - # selection (restore-keys falls back to the most recent prefix match - # regardless of the exact sha, same as build-artifacts already does for - # the Linux preflight/doc-freshness legs). + # Blacksmith Windows (blacksmith-4vcpu-windows-2025) for every PR. + # CGO_ENABLED=0 below, so no cgo-toolchain risk; its non-race GOCACHE + # restore-keys prefix gets a hit from main.yml's test-windows job, which + # saves that key on this exact runner selection (restore-keys falls back + # to the most recent prefix match regardless of the exact sha). Since + # ga-96smfk.22 this job is the required run of these tests. # # RISK (F7b review: not flagged in the original implementation -- # cmd/bd/worktree_remove_git_windows_test.go:233 shells out to @@ -572,12 +304,11 @@ jobs: # does not treat an unsupported fsutil call as a skip condition). The # diagnostic step below surfaces that gap in this job's own log instead of # a bare test failure deep in the suite; if it reports the feature missing, - # roll back this job's runs-on to the literal `windows-latest` (same - # rollback as test-windows-liveness's cgo risk above) until Blacksmith - # confirms/enables it. + # roll back this job's runs-on to the literal `windows-latest` until + # Blacksmith confirms/enables it. worktree-remove-windows: name: Worktree remove boundary (Windows) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-windows-2025' || 'windows-latest' }} + runs-on: ${{ 'blacksmith-4vcpu-windows-2025' }} timeout-minutes: 15 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 @@ -624,205 +355,16 @@ jobs: GOCACHE: ${{ runner.temp }}/go-cache/non-race run: go test -tags gms_pure_go -count=1 -run '^TestWorktreeRemove' ./cmd/bd - # F4 side-by-side rollout (advisory phase): cross-compiles the Windows test - # binaries this file's native Windows jobs need, from a committed manifest - # (scripts/ci/windows-test-binaries.txt), on a Linux runner via mingw-w64 -- - # the same toolchain release.yml's goreleaser job uses for the shipped - # bd-windows-amd64 binary (CC=x86_64-w64-mingw32-gcc; see .goreleaser.yml). - # The "-prebuilt" twin jobs below download this artifact and run it - # natively on windows-latest instead of compiling there, so the CGO build - # that otherwise runs once per Windows job runs here once instead. - # - # Deliberately advisory only: the native `test-windows-liveness` and - # `worktree-remove-windows` jobs above are untouched and still the only - # required pair while WINDOWS_PREBUILT_REQUIRED (top of this file) is - # "false". ci-gate does wait on this job's two twins below (they are in its - # `needs`), but neither twin's result is in CI_GATE_REQUIRED yet -- the - # side-by-side phase runs both paths on every PR so a policy test - # (TestWindowsTestBinariesSelectSameTestsAsNativeJobs, in - # scripts/windows_test_binaries_manifest_test.go) can confirm they select - # the same tests before anyone flips WINDOWS_PREBUILT_REQUIRED to "true". - # - # Manifest is intentionally partial in this phase: it covers only the two - # cmd/bd-backed jobs twinned below. Forks and Dependabot PRs get no - # secrets here, same as every job in this file -- cross-compiling and - # uploading an artifact needs none. - windows-test-binaries: - name: Build Windows test binaries (cross-compile) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 30 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Verify Go module checksums - run: go mod verify - - - name: Install mingw cross-compiler - timeout-minutes: 12 - run: | - updated="" - for attempt in 1 2 3; do - if sudo timeout 120 apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update; then - updated=yes - break - fi - echo "::warning::apt-get update attempt $attempt failed or timed out" - if [ "$attempt" -lt 3 ]; then sleep 10; fi - done - if [ -z "$updated" ]; then - echo "::warning::apt-get update failed after 3 attempts; proceeding with cached index" - fi - sudo timeout 300 apt-get install -y gcc-mingw-w64-x86-64 - - - name: Restore Go build cache (Windows cross-compile) - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/xcompile-windows-amd64 - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-xcompile-windows-amd64-${{ github.sha }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-xcompile-windows-amd64- - - - name: Build Windows test binaries - env: - GOCACHE: ${{ runner.temp }}/go-cache/xcompile-windows-amd64 - run: bash scripts/ci/build-windows-test-binaries.sh "$RUNNER_TEMP/win-bin" - - - name: Upload Windows test binaries - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: windows-test-binaries - path: ${{ runner.temp }}/win-bin - retention-days: 1 - compression-level: 1 - if-no-files-found: error - - # Advisory twin of test-windows-liveness: runs the identical test selection, - # flags, and env on windows-latest, but against the binary - # windows-test-binaries cross-compiled instead of compiling here. Step - # names, -run patterns, -count, and the PASS/FAIL parsing block are kept - # byte-for-byte equivalent to the native job on purpose -- - # TestWindowsTestBinariesSelectSameTestsAsNativeJobs checks the -run - # literals stay in sync. - # F7b: same-repo Blacksmith (blacksmith-2vcpu-windows-2025). This leg only - # runs a prebuilt binary (cross-compiled on Linux by windows-test-binaries - # via mingw-w64) rather than compiling with cgo on the Windows runner - # itself, so it carries none of test-windows-liveness's cgo-toolchain risk. - test-windows-liveness-prebuilt: - name: Test (Windows, prebuilt) cmd/bd liveness regression - needs: windows-test-binaries - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-2vcpu-windows-2025' || 'windows-latest' }} - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Download Windows test binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: windows-test-binaries - path: ${{ runner.temp }}/win-bin - - - name: Verify downloaded binaries - shell: bash - run: | - cd "$RUNNER_TEMP/win-bin" - sha256sum -c SHA256SUMS - - # F7b review fix (S9): these binaries are cgo-linked on Linux via - # mingw-w64 (windows-test-binaries), not compiled on this runner, so - # the risk here is specifically whether a cross-compiled binary loads - # and runs at all on Blacksmith's windows-2025 image (missing runtime - # DLLs, etc.), not the cgo-toolchain risk test-windows-liveness - # carries. `-run '^$'` loads/links the binary and matches no tests, so - # a load failure surfaces here instead of inside the real test step. - - name: Check prebuilt Windows binary loads - shell: bash - run: bash scripts/ci/run-go-test-binary.sh "$RUNNER_TEMP/win-bin/cmd-bd-cgo.test.exe" ./cmd/bd -run '^$' -count=1 - - - name: Run native Windows global Prime override (prebuilt) - shell: bash - run: | - export BEADS_TEST_PREBUILT_TEST_BINARY="$RUNNER_TEMP/win-bin/cmd-bd-cgo.test.exe" - export BEADS_TEST_BD_BINARY="$RUNNER_TEMP/win-bin/bd.exe" - go_path=$(command -v go) - [[ "$("$go_path" env GOHOSTOS GOOS)" == $'windows\nwindows' ]] - test_status=0 - test_output=$(./scripts/test.sh -v -timeout 5m -run '^TestPrimeBinaryPortfolio$/^TestPrime_HookJSON_GlobalPrimeOverride$' -count=1 ./cmd/bd) || test_status=$? - printf '%s\n' "$test_output" - ((test_status == 0)) - pass_pattern='^[[:space:]]*--- PASS: TestPrimeBinaryPortfolio/TestPrime_HookJSON_GlobalPrimeOverride \(' - nonpass_pattern='^[[:space:]]*--- (FAIL|SKIP): ' - pass_count=0 - while IFS= read -r line; do - if [[ "$line" =~ $pass_pattern ]]; then - ((pass_count += 1)) - fi - if [[ "$line" =~ $nonpass_pattern ]]; then - exit 1 - fi - done <<<"$test_output" - ((pass_count == 1)) - - - name: Run Windows liveness regression test (prebuilt) - shell: bash - run: bash scripts/ci/run-go-test-binary.sh "$RUNNER_TEMP/win-bin/cmd-bd-cgo.test.exe" ./cmd/bd -run '^TestIsServerProbablyRunning' -count=1 - - # Advisory twin of worktree-remove-windows: same package, -run pattern, and - # CGO_ENABLED=0 selection as the native job, but against the cgo=0 binary - # windows-test-binaries cross-compiled instead of compiling here. - # F7b: same-repo Blacksmith (blacksmith-2vcpu-windows-2025); same prebuilt- - # binary rationale as test-windows-liveness-prebuilt above. - worktree-remove-windows-prebuilt: - name: Worktree remove boundary (Windows, prebuilt) - needs: windows-test-binaries - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-2vcpu-windows-2025' || 'windows-latest' }} - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Download Windows test binaries - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: windows-test-binaries - path: ${{ runner.temp }}/win-bin - - - name: Verify downloaded binaries - shell: bash - run: | - cd "$RUNNER_TEMP/win-bin" - sha256sum -c SHA256SUMS - - # F7b review fix (S9): see test-windows-liveness-prebuilt's identical - # step for the full rationale. - - name: Check prebuilt Windows binary loads - shell: bash - run: bash scripts/ci/run-go-test-binary.sh "$RUNNER_TEMP/win-bin/cmd-bd-nocgo.test.exe" ./cmd/bd -run '^$' -count=1 - - - name: Run native Windows worktree removal boundary tests (prebuilt) - shell: bash - run: bash scripts/ci/run-go-test-binary.sh "$RUNNER_TEMP/win-bin/cmd-bd-nocgo.test.exe" ./cmd/bd -run '^TestWorktreeRemove' -count=1 - # Check documentation references match actual CLI flags # + # Stays a job: the generated CLI docs describe the release pinned in + # docs/cli-docs.pin, and check-doc-flags.sh validates them against bd built + # from that tag (scripts/resolve-docs-bd.sh: git fetch the tag, pure-Go go + # build), attributing drift against the merge-base. Neither input can enter + # a Bazel action key: releases publish no pure-Go linux binary to pin, and + # the attribution needs the PR's base. check-doc-freshness.sh, which this + # job also ran, is //scripts/repochecks:doc_freshness_test. + # # F7a: moved to Blacksmith for same-repo PRs/merge_group. This job's module # cache restore step was already absent before the fold (every run cold- # builds bd), so there is no GitHub-saved cache to lose here. @@ -849,9 +391,13 @@ jobs: - name: Validate docs against CLI env: DOC_DRIFT_PATCH_OUT: ${{ runner.temp }}/cli-docs-freshness.patch - run: | - ./scripts/check-doc-flags.sh ./bd - ./scripts/check-doc-freshness.sh + # Merge queue: a merge group has no GITHUB_BASE_REF, and without a + # diff base check-cli-docs-drift.sh fails on any drift, including + # drift already on main that the PR run attributed away, which + # would eject every queued PR. Diff against the queue's base + # commit instead (empty on pull_request: origin/$GITHUB_BASE_REF). + BD_DOCS_DIFF_BASE: ${{ github.event.merge_group.base_sha }} + run: ./scripts/check-doc-flags.sh ./bd # When the drift check fails, it writes the exact regenerated-docs fix # (produced with CI's canonical build) so contributors can apply it with @@ -866,42 +412,34 @@ jobs: path: ${{ runner.temp }}/cli-docs-freshness.patch if-no-files-found: ignore - # F7b: same-repo Blacksmith for the Linux/Windows legs via the "matrix - # marker" form (spec F7/F7b §2.1): Actions does not expand `${{ }}` inside a - # matrix array/include value, so each leg's `include` entry instead carries - # a plain string `runner` marker, and the job's `runs-on` is a single - # chained ternary (sameRepoPlatformsMatrixMarkerRunsOn in - # scripts/ci_blacksmith_runner_test.go) that resolves per-marker, falling - # back to `matrix.os` for forks/Dependabot (each marker's own same-repo - # condition false) or any leg with no marker. Every leg now restores a - # non-race Go build cache seeded by main.yml's push-to-main savers on the - # exact same runner selection (S2 below). - # - # F7b review fix (S3): the macOS leg stays on GitHub-hosted macos-latest - # unconditionally -- never Blacksmith -- because Blacksmith bills macOS - # runners at roughly 20x its Linux/Windows rate and no push-to-main - # Blacksmith-macOS cache saver exists (main.yml's `test` job's macOS leg, - # which this job's restore step reads from, already runs on GitHub-hosted - # macos-latest). The `runner: same-repo-macos` marker is kept only so this - # job's matrix shape stays uniform across all three OSes; its branch in the - # chained ternary is a plain `'macos-latest'`, not a same-repo conditional. + # The Linux leg is Bazel's (ga-96smfk.20): //scripts:doc_freshness_required_test + # (integration lane: the doc-freshness suite under -required-suite) and + # //scripts/gitattributespolicy:gitattributespolicy_required_host_test + # (-required-host -expected-goos linux), both on rbe-west's Linux workers. + # The macOS and Windows legs stay here, on Blacksmith for every PR and + # merge group, forks and Dependabot included (ga-96smfk.22). Each leg's + # `include` entry names its Blacksmith label in `runner` (`os` keeps the + # check names stable and selects the Windows-only steps). Every leg + # restores a non-race Go build cache seeded by main.yml's push-to-main + # savers on the exact same label (S2 below): test-windows for Windows, + # blacksmith-macos-go-build-cache for macOS. The macOS label is pinned to + # macos-26 (Apple Silicon, the image GitHub's macos-latest resolves to); + # 6 vCPU is enough for a leg dominated by one incremental ./cmd/bd test + # compile. check-doc-freshness-platforms: name: Check doc freshness (${{ matrix.os }}) - runs-on: ${{ matrix.runner == 'same-repo-linux' && ((github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest') || matrix.runner == 'same-repo-windows' && ((github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-windows-2025' || 'windows-latest') || matrix.runner == 'same-repo-macos' && 'macos-latest' || matrix.os }} + runs-on: ${{ matrix.runner }} timeout-minutes: 10 strategy: fail-fast: false matrix: include: - - os: ubuntu-latest - expected_goos: linux - runner: same-repo-linux - os: macos-latest expected_goos: darwin - runner: same-repo-macos + runner: blacksmith-6vcpu-macos-26 - os: windows-latest expected_goos: windows - runner: same-repo-windows + runner: blacksmith-4vcpu-windows-2025 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 @@ -942,10 +480,14 @@ jobs: GOCACHE: ${{ runner.temp }}/go-cache/non-race run: go test '-tags=integration,gms_pure_go' -count=1 ./scripts/gitattributespolicy -args -required-host -expected-goos '${{ matrix.expected_goos }}' - # F7b: same-repo Blacksmith via the "matrix marker" form (see - # check-doc-freshness-platforms above for the full explanation; - # sameRepoPlatformsMatrixMarkerRunsOn in scripts/ci_blacksmith_runner_test.go - # is this same chained ternary). + # Blacksmith macOS and Windows legs, labels in the matrix (see + # check-doc-freshness-platforms above). The Linux leg is retired + # (ga-96smfk.22): every Linux step's tests run under Bazel on rbe-west + # (//scripts:scripts_test, //cmd/bd:bd_test, //internal/config:config_test). + # Only the two + # tests of go test's own bd build fallback + # (tools/bazel/equivalence_allowlist.txt) skip under Bazel; they keep + # running here on macOS and Windows. # # F7b review (S1): an earlier revision of this job split the Windows leg # into two `shard` entries on the theory that it would turn one ~9-minute @@ -957,23 +499,29 @@ jobs: # cold `cmd/bd` test compile in "Exercise generated Git hook timeout # process boundary" (250-300s); see S2 below (the restore-non-race-cache # step) for the fix that actually targets it. Reverted to one leg per OS. + # + # Windows leg budget with the caches warm (merge group 37710264475 and PR + # runs, 2026-10-07/08): 45-115s setup (setup-go, then the two cache + # restores, mostly tar extraction), 33-71s for TestPRPreflight (Git Bash + # process creation, now parallel subtests), 27-58s to compile and link + # ./cmd/bd's test binary, and about 25s for the rest. A second Windows leg + # would pay the setup again to save about 20s, so it stays one leg. An + # 8 vCPU Windows leg was tried (#7381): cache restores still hit, but it + # queued 63s for the larger runner and finished at 144s vs 129s here. pr-preflight-platforms: name: PR preflight process (${{ matrix.os }}) - runs-on: ${{ matrix.runner == 'same-repo-linux' && ((github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest') || matrix.runner == 'same-repo-windows' && ((github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-windows-2025' || 'windows-latest') || matrix.runner == 'same-repo-macos' && 'macos-latest' || matrix.os }} + runs-on: ${{ matrix.runner }} timeout-minutes: 20 strategy: fail-fast: false matrix: include: - - os: ubuntu-latest - expected_goos: linux - runner: same-repo-linux - os: macos-latest expected_goos: darwin - runner: same-repo-macos + runner: blacksmith-6vcpu-macos-26 - os: windows-latest expected_goos: windows - runner: same-repo-windows + runner: blacksmith-4vcpu-windows-2025 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 @@ -992,15 +540,14 @@ jobs: restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- # F7b review (S2): restore-only non-race Go build cache, seeded by the - # push-to-main saver on the exact same runner selection (Linux: - # main.yml's blacksmith-go-build-cache non-race leg; Windows: - # main.yml's test-windows Blacksmith leg; macOS: main.yml's test job's - # macOS leg) so the cold cmd/bd compile below (the real long pole, - # 250-300s uncached) gets a true cache hit instead of starting cold. - # GOCACHE must match the seeder's exactly, and CGO_ENABLED is left at - # its platform default (same as the seeder) so the key families line - # up; see mainBlacksmithGoBuildCacheRunsOn / mainVenueBlacksmithWindows4vcpuRunsOn - # in ci_workflow_test.go for the seeder side of this contract. + # push-to-main saver on the exact same Blacksmith label (Windows: + # main.yml's test-windows; macOS: main.yml's + # blacksmith-macos-go-build-cache) so the cold cmd/bd compile below + # (the real long pole, 250-300s uncached) gets a true cache hit instead + # of starting cold. GOCACHE must match the seeder's exactly, and + # CGO_ENABLED is left at its platform default (same as the seeder) so + # the key families line up; see mainBlacksmithWindows4vcpuRunsOn in + # ci_workflow_test.go for the seeder side of this contract. - name: Restore non-race Go build cache uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: @@ -1027,14 +574,30 @@ jobs: GOCACHE: ${{ runner.temp }}/go-cache/non-race run: go test '-tags=gms_pure_go' -count=1 -run '^TestTestScriptPrebuiltBinaryContract$' ./scripts - - name: Exercise generated Git hook timeout process boundary + # One go test of ./cmd/bd runs the generated hook timeout boundary and + # plain go test's own bd build fallback (BEADS_TEST_BD_BINARY unset), + # which Bazel never takes, on every OS developers run go test on: the + # tests tools/bazel/equivalence_allowlist.txt lists as skipped under + # Bazel. They were two steps; each go test of ./cmd/bd re-hashes its + # ~1500 packages and relinks the test binary, which cost 5-9s on + # Windows for a fallback run of under one second. + - name: Exercise generated Git hook timeout process boundary and go test's bd build fallback shell: bash env: GOCACHE: ${{ runner.temp }}/go-cache/non-race - run: go test '-tags=gms_pure_go' -count=1 -run '^TestGeneratedHookTimeoutProcessBoundary$' ./cmd/bd + run: go test '-tags=gms_pure_go' -count=1 -run '^(TestGeneratedHookTimeoutProcessBoundary|TestGOMODCACHENotUnderTestHome|TestGoBuildBDCommandIsCWDIndependent)$' ./cmd/bd + # This step recompiles ./cmd/bd's test binary. It must share the restored + # GOCACHE with the hook-timeout/bd-build-fallback step above (same tags, same platform + # default CGO_ENABLED, see the script's header) so it is a relink rather + # than a second cold compile: without GOCACHE here it fell back to the + # runner's empty default cache and cold-compiled all of ./cmd/bd on every + # PR (210-240s on macos-latest, ~120s on Windows; the leg's long pole). + # TestPRPreflightPlatformsRunStepsUseRestoredGoBuildCache pins this. - name: Exercise native init gateway credential shell shell: bash + env: + GOCACHE: ${{ runner.temp }}/go-cache/non-race run: bash scripts/ci/test-init-gateway-credential.sh "$RUNNER_OS" - name: Exercise credential command fixtures on Windows @@ -1042,6 +605,7 @@ jobs: shell: pwsh env: CGO_ENABLED: "0" + GOCACHE: ${{ runner.temp }}/go-cache/non-race run: | $go = (Get-Command go -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source $hostInfo = @(& $go env GOHOSTOS GOOS) @@ -1078,300 +642,16 @@ jobs: - name: Check benchmark environment scrubbing if: matrix.os == 'windows-latest' shell: bash + env: + GOCACHE: ${{ runner.temp }}/go-cache/non-race run: go test -tags gms_pure_go -count=1 -run '^(TestCleanEnvUsesHostKeySemantics|TestBenchmarkCommandBuildersStripDoltEnvOverrides)$' ./scripts/repro-dolt-prod-timeouts - name: Check shared environment key semantics if: matrix.os == 'windows-latest' shell: bash - run: bash scripts/ci/test-windows-env-helpers.sh - - # F3: package-mcp and package-npm (and the detect job that fed them) moved - # into bazel.yml, which pr.yml calls with package-gates: "on" below. They - # now depend on nothing but the rbe job's decision, so they no longer wait - # on build-artifacts, bazel-coverage or the rest of the bazel call. - # - # F7a: moved to Blacksmith for same-repo PRs/merge_group. setup-go runs with - # cache: false and the module download step below always hits the network, - # so this job restores no GitHub-saved cache. - pr-policy-wrapper: - name: PR Policy (wrapper timing) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - with: - fetch-depth: 0 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - # The module fetch is the only part of this job that talks to the network, - # and setup-go above runs with cache: false, so every run pulls the whole - # module graph from the proxy. Doing it here, retried, means a proxy blip - # costs seconds instead of failing a required check. - # - # Deliberately NOT wrapped around the build: `make ci-pr-policy` runs a - # `go build ./cmd/bd` (scripts/ci/pr-policy.sh, build_docs_binary), and a - # compile error is not transient. Retrying it would make a genuinely broken - # build take three attempts to report and look like a slow one. The fetch - # has a legitimate transient failure mode; the build does not. - # - # 3 attempts x 120s + 2 backoffs x 10s = 380s worst case. 8m leaves ~100s - # of headroom, matching the bounded apt-get steps in migration-test.yml. - - name: Download modules - timeout-minutes: 8 - run: | - downloaded="" - for attempt in 1 2 3; do - if timeout 120 go mod download; then - downloaded=yes - break - fi - echo "::warning::go mod download attempt $attempt failed or timed out" - # No backoff after the final attempt - there is nothing left to wait for. - if [ "$attempt" -lt 3 ]; then - sleep 10 - fi - done - # Unlike the best-effort apt-get retries elsewhere in this repo, this - # one is load-bearing: nothing downstream can build without the - # modules. Fail here, naming the fetch, so a module outage is not - # reported as a build failure. - if [ -z "$downloaded" ]; then - echo "::error::go mod download failed after 3 attempts - module fetch failure, not a build failure" - exit 1 - fi - - - name: Run PR policy wrapper - run: make ci-pr-policy - - # D2 step 3: stands down where bazel-coverage says pr_lanes; Bazel / - # test (`bazel test //... --config=ci`, the same selection, checked by its - # equivalence step) runs it, and scripts-go-checks runs what Bazel does not - # (./scripts/... and the allowlisted tests under go test, go test's vet). - pr-core-wrapper: - name: PR Core (wrapper timing) - runs-on: ubuntu-latest - needs: [build-artifacts, bazel-coverage] - if: needs.bazel-coverage.outputs.pr_lanes != 'true' - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Restore race Go build cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ github.sha }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race- - - - name: Install Dolt - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Download build artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ci-build-artifacts - path: ci-build-artifacts - - - name: Verify build artifacts - run: | - set -euo pipefail - cd ci-build-artifacts - sha256sum -c SHA256SUMS - chmod +x bd-linux-gms-pure - - - name: Run PR core wrapper - env: - BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION: '1' - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - GOCACHE: ${{ runner.temp }}/go-cache/race - run: make ci-pr-core - - # PR Core's duties the Bazel lanes do not take over (D2 step 3), on every - # PR whatever bazel-coverage says, in PR Core's environment (dolt, git and - # dolt identity, scripts/ci/lib/test-env.sh): - # - `go test ./scripts/...` with PR Core's flags: the repository policy - # tests, several of which check part or all of their rules under go test - # only (scripts/bazel_skip_allowlist_test.go keeps such parts there); - # - go test's own vet checks over ./... (rules_go's go_test runs none); - # - the Go tests `bazel test --config=ci` does not run or skips - # (tools/bazel/equivalence_allowlist.txt), each required to pass. - # F7b: same-repo Blacksmith (blacksmith-4vcpu-ubuntu-2404) for same-repo - # PRs/merge_group, falling back to ubuntu-latest for forks/Dependabot, same - # pattern as advisory-reports/pr-policy-wrapper/pr-core-wrapper above. - # main.yml's blacksmith-go-build-cache job seeds this leg's race and - # non-race GOCACHEs; go-vet-cache's venue matrix seeds the vet leg's. - scripts-go-checks: - name: Go checks (${{ matrix.check }}) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - check: [scripts-test, vet, allowlisted] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Restore race Go build cache - if: matrix.check == 'scripts-test' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race-${{ github.sha }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-race- - - - name: Restore vet Go build cache - if: matrix.check == 'vet' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/vet - key: beads-go-vet-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-vet-${{ github.sha }} - # The non-race build cache fallback this used to list can never hit: - # actions/cache versions an entry by its path list, and that cache - # saves to a different path (.../go-cache/non-race), so the prefix - # match is always filtered out (SF-5). - restore-keys: beads-go-vet-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-vet- - - - name: Restore non-race Go build cache - if: matrix.check == 'allowlisted' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ runner.temp }}/go-cache/non-race - key: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race-${{ github.sha }} - restore-keys: beads-go-build-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-base-gms_pure_go-non-race- - - - name: Install Dolt - if: matrix.check == 'scripts-test' || matrix.check == 'allowlisted' - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - if: matrix.check == 'scripts-test' || matrix.check == 'allowlisted' - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Go test the scripts packages - if: matrix.check == 'scripts-test' - env: - BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION: '1' - GOCACHE: ${{ runner.temp }}/go-cache/race - run: bash scripts/ci/scripts-go-test.sh - - - name: Go vet with go test's checks - if: ${{ !cancelled() && steps.setup-go.outcome == 'success' && matrix.check == 'vet' }} - env: - GOCACHE: ${{ runner.temp }}/go-cache/vet - run: bash scripts/ci/go-test-vet.sh - - - name: Run the Go tests the Bazel lane skips - if: ${{ !cancelled() && steps.setup-go.outcome == 'success' && matrix.check == 'allowlisted' }} env: GOCACHE: ${{ runner.temp }}/go-cache/non-race - run: bash scripts/ci/allowlisted-go-tests.sh - - # F7b: same-repo Blacksmith (blacksmith-4vcpu-ubuntu-2404) for same-repo - # PRs/merge_group, falling back to ubuntu-latest for forks/Dependabot. - # main.yml's pr-lint-wrapper `venue` matrix seeds this leg's golangci-lint - # and lint-native GOCACHEs. - pr-lint-wrapper: - name: PR Lint (${{ matrix.target }}) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 20 - permissions: - contents: read - strategy: - fail-fast: false - matrix: - target: [native, windows, darwin] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - with: - # --new-from-merge-base below walks real history. - fetch-depth: 0 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Restore Go module cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/go/pkg/mod - key: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.mod', 'go.sum') }} - restore-keys: beads-go-mod-v2-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Install golangci-lint - run: ./scripts/ci/install-golangci-lint.sh - - # Keyed on file content and the leg; a miss on the exact content key - # falls back to the leg's most recent entry, which golangci-lint - # revalidates against the current config and inputs. pr.yml never saves - # this cache (§0); main.yml's pr-lint-wrapper matrix is the only saver, - # on an exact-key miss. The key omits the sha (SF-4) so main.yml only - # saves when .golangci.yml or go.sum change. - - name: Restore golangci-lint cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/.cache/golangci-lint - ${{ matrix.target == 'native' && format('{0}/go-cache/lint-{1}', runner.temp, matrix.target) || '' }} - key: beads-golangci-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-v2.10.1-${{ matrix.target }}-${{ hashFiles('.golangci.yml', 'go.sum') }} - restore-keys: beads-golangci-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-v2.10.1-${{ matrix.target }}- - - # Scope the wrapper's lint to what this PR introduces, matching the - # (now-deleted) `lint` job's only-new-issues scope. main.yml runs the - # same wrapper with this unset, so the whole tree is still swept on - # every push to main. Both PR triggers (pull_request, merge_group) - # target main. - - name: Run PR lint wrapper - env: - BD_LINT_NEW_FROM_MERGE_BASE: origin/main - BD_LINT_TARGETS: ${{ matrix.target }} - GOCACHE: ${{ runner.temp }}/go-cache/lint-${{ matrix.target }} - run: make ci-pr-lint + run: bash scripts/ci/test-windows-env-helpers.sh # F7a: fold of build-examples + complexity-report, the two pr.yml jobs that # are advisory-only (not in ci-gate's needs/CI_GATE_REQUIRED) and restore no @@ -1496,136 +776,6 @@ jobs: retention-days: 7 if-no-files-found: error - # Focused job for the hexagonal storage layer (internal/storage/domain/* and - # internal/storage/uow). These packages back the proxied-server init path and - # also live behind the existing ./... matrix, but TestDomainDB requires the - # Dolt sql-server image cached locally (testcontainers checks `docker image - # inspect` and skips otherwise). Pulling the image up front guarantees the - # suite actually runs and surfaces failures here with a clear job name. - # - # D2 step 3: stands down where bazel-coverage says pr_lanes; Bazel's - # `dolt-server lane` runs the same packages against a local dolt - # sql-server, which test-dolt-server-fingerprint (every PR) keeps equal to - # the container this job uses. - test-domain-uow: - name: Test (storage domain + uow) - runs-on: ubuntu-latest - needs: [build-artifacts, bazel-coverage] - if: needs.bazel-coverage.outputs.pr_lanes != 'true' - # The race-enabled storage package has outgrown Go's implicit 10-minute - # timeout. Keep both per-package deadlines inside one finite job budget. - timeout-minutes: 30 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Install Dolt CLI - run: ./scripts/ci/install-dolt.sh - - - name: Verify dolt on PATH - run: dolt version - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Pull Dolt sql-server image - # Keep tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage. - # Without this, RequireDoltContainer reports doltNoImage and TestDomainDB skips. - run: ./scripts/ci/pull-dolt-image.sh - - - name: Download build artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 - with: - name: ci-build-artifacts - path: ci-build-artifacts - - - name: Verify build artifacts - run: | - set -euo pipefail - cd ci-build-artifacts - sha256sum -c SHA256SUMS - chmod +x bd-linux-gms-pure - - - name: Test domain + uow + tracker - env: - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - # internal/storage/domain, internal/storage/uow, and internal/tracker - # run as concurrent package test binaries in this one invocation. - # testcontainers-go shares one Ryuk reaper per host; a failed - # handshake in one process can reap a sibling's live Dolt container - # mid-suite (be-2on). The runner is destroyed after the job, so the - # reaper buys nothing here and only costs this race. - TESTCONTAINERS_RYUK_DISABLED: "true" - run: go test -tags gms_pure_go -race -count=1 -timeout 15m -v ./internal/storage/domain/... ./internal/storage/uow/... ./internal/tracker/... - - # The doctor/fix DB-backed suite spins its own Dolt container in - # TestMain. BEADS_FIX_REQUIRE_DOLT=1 turns a missing container into a - # hard failure so the suite can never silently skip in CI again - # (bd-nxt5e: it was dark for months); this job pulls the image above. - - name: Test doctor/fix (Dolt-backed, hard-require container) - env: - BEADS_TEST_BD_BINARY: ${{ github.workspace }}/ci-build-artifacts/bd-linux-gms-pure - BEADS_FIX_REQUIRE_DOLT: "1" - # Pinned for consistency with the step above: this single-package - # step has no sibling test binary to race for the reaper (be-2on). - TESTCONTAINERS_RYUK_DISABLED: "true" - run: go test -tags gms_pure_go -race -count=1 -timeout 10m -v ./cmd/bd/doctor/fix/ - - # Compares the Dolt sql-server container image the container-backed tests - # use and the local test server backend (the pinned dolt CLI, what every - # Bazel dolt-server lane starts) against the one checked-in fingerprint, - # so an image bump cannot drift the container side unnoticed. REQUIRE - # makes the container half fail, not skip. Every PR, whatever bazel-coverage - # says: it was test-domain-uow's first step, and the Bazel lanes that - # replace that job (D2 step 3) have no docker. - # - # F7a: moved to Blacksmith for same-repo PRs/merge_group. Restores no - # GitHub-saved cache (Dolt CLI and the sql-server image are fetched fresh - # every run via scripts/ci/install-dolt.sh and pull-dolt-image.sh). - test-dolt-server-fingerprint: - name: Test (Dolt server fingerprint) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Install Dolt CLI - run: ./scripts/ci/install-dolt.sh - - - name: Verify dolt on PATH - run: dolt version - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Pull Dolt sql-server image - # Keep tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage. - run: ./scripts/ci/pull-dolt-image.sh - - - name: Test Dolt server fingerprint (container + local) - env: - BEADS_TEST_REQUIRE_DOLT_CONTAINER: "1" - run: go test -tags gms_pure_go -count=1 -timeout 5m -v -run '^TestDoltServerFingerprint$' ./internal/testutil/ - # `test-macos` / "Test (macos-latest)" used to run here and is deliberately # removed (F4, PR CI -> 5 min). It was a non-required, PR-side mirror of # main.yml's `test` job's macOS leg (full `go test -race -short ./...`), @@ -1646,66 +796,6 @@ jobs: # they are not a substitute. If this tradeoff turns out to be wrong, # reinstate a PR-side mirror rather than relying on main.yml alone. - # Producer-side guard for the Beads<->consumer CLI contract. Runs the whole - # cmd/bd/protocol package: the golden corpus (regenerated from this branch's - # bd and byte-compared to the committed testdata/corpus/, so an unreviewed - # wire change is a hard failure — run `make corpus-regen`), the double-run - # determinism check, and the TestProtocol_/TestJSONContract_ behavioral - # conformance suite that pins the CLI's JSON payloads and semantics. - # - # Run the PACKAGE, never a -run subset: a filter here is what let the - # conformance tests sit red on main for ~3 months while every CI run was - # green (they matched no job's -run, and every broad ./... job skips them - # for want of a Dolt store). Package scope means a newly added protocol test - # is gated the moment it lands. - # - # Needs the Dolt sql-server image (the protocol harness spins a container). - # ~10 min: each test builds an isolated Dolt-backed workspace. If that ever - # becomes unacceptable on PRs, shard this job by an exhaustive `go test - # -list` partition — do not reintroduce a hand-written -run regex. - # - # D2 step 3: stands down where bazel-coverage says pr_lanes; Bazel's - # `dolt-server lane` runs the package (//cmd/bd/protocol:protocol_dolt_test). - contract-corpus: - name: Contract corpus (golden + determinism + conformance) - runs-on: ubuntu-latest - needs: bazel-coverage - if: needs.bazel-coverage.outputs.pr_lanes != 'true' - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: false - - - name: Install Dolt CLI - run: ./scripts/ci/install-dolt.sh - - - name: Configure Git and Dolt identity - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - - - name: Pull Dolt sql-server image - # Keep tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage. - run: ./scripts/ci/pull-dolt-image.sh - - - name: Protocol conformance + corpus golden + determinism - # Require a live Dolt store here: this is the gate that must exercise the - # conformance, golden and double-run checks, so a failed container is a - # hard failure, not a silent skip (see requireDoltStore in the - # cmd/bd/protocol tests). - # - # -timeout is explicit because the package runs well past `go test`'s - # 10m default; without it a slow runner reports a panic, not a verdict. - env: - BEADS_PROTOCOL_REQUIRE_DOLT: "1" - run: go test -tags gms_pure_go -count=1 -timeout 30m ./cmd/bd/protocol - # F7a: fold of a 3-host matrix (native, msys2, cygwin) into one sequential # job on a single windows-latest runner. Review SF-1 (2026-10-03): only the # Cygwin *setup* step keeps `continue-on-error: true` (a flaky installer @@ -1716,10 +806,8 @@ jobs: # steps keeps `if: ${{ !cancelled() }}` (plus a check that its own leg's # setup succeeded) so a failure in one leg does not stop the later legs # from attempting to run - the fail-fast: false behavior the matrix used to - # give for free. windows-make-shell is not a Windows job F4 touches (it - # does not intersect test-windows-liveness, worktree-remove-windows, the - # preflight/doc-freshness matrices, or the twins). - # F7b: same-repo Blacksmith (blacksmith-4vcpu-windows-2025). + # give for free. + # Blacksmith Windows (blacksmith-4vcpu-windows-2025) for every PR. # # RISK (unverified from this sandbox, flagged in the F7b report): the # native-Make step below assumes Chocolatey is preinstalled (`choco @@ -1730,12 +818,11 @@ jobs: # is not independently confirmed. The msys2/setup-msys2 and # cygwin/cygwin-install-action steps download their own tooling and do not # depend on any preinstalled image contents, so they carry no equivalent - # risk. The fork-PR path (windows-latest) remains an always-on canary; if - # only the same-repo leg's native-Make step fails here, that is the gap to - # roll back on (revert this runs-on line to the literal `windows-latest`). + # risk. If only the native-Make step fails here, that is the gap to roll + # back on (revert this runs-on line to the literal `windows-latest`). windows-make-shell: name: Windows Make shell (native, msys2, cygwin) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-windows-2025' || 'windows-latest' }} + runs-on: ${{ 'blacksmith-4vcpu-windows-2025' }} timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 @@ -1769,8 +856,7 @@ jobs: # disables that implicit save on Blacksmith (fail-closed: only the # literal "github-hosted" value keeps caching on, matching the # fail-closed convention F7c review fix N1 set for actions/setup-go's - # own `cache` input) while leaving the always-on fork-PR - # (windows-latest) leg's caching behavior unchanged. Pinned by + # own `cache` input). Pinned by # TestBlacksmithReachablePRJobsDisableDefaultCachingActions. - name: Set up MSYS2 GNU Make id: install-msys2 @@ -2242,35 +1328,37 @@ jobs: throw 'Cygwin Make shell smoke failed' } - # The Bazel lane (bazel.yml), gated alongside the legacy jobs it mirrors - # (PR Core, build-artifacts, the pure-Go/js-wasm check, domain+uow and - # contract corpus, and pr-risk.yml's embedded-Dolt, proxied-server and - # server-Dolt storage tiers), all of which stay required ids, but stand - # down on same-repo PRs with a non-Dependabot actor while their D2 flag - # is "true" (bazel-coverage): pr-risk.yml's embedded-Dolt test jobs - # (BAZEL_RETIRES_LEGACY_EMBEDDED, step 1), its proxied-server and - # server-Dolt storage test jobs (BAZEL_RETIRES_LEGACY_DOLT_SERVER_TIERS, - # step 2), and this workflow's PR Core, build-artifacts, pure-Go/js-wasm, - # domain+uow and contract corpus jobs (BAZEL_RETIRES_LEGACY_PR_LANES, - # step 3). ci-gate then requires this call's lanes for them (embedded; - # proxied and server-storage; test, pure and doltserver) to have run - # remotely and passed. bazel.yml has no pull_request/merge_group trigger + # The Bazel lanes (bazel.yml): the only pre-merge run of every Linux Go + # test tier (PR core, pure-Go and js/wasm, the release cross-compile, the + # dolt-server lane, the embedded-Dolt, proxied-server and server-Dolt + # storage tiers that pr-risk.yml used to run, integration and the cmd/bd + # Dolt-server tier). + # ci-gate requires each of them to have run remotely on rbe-west and + # passed, on every pull_request and merge group: same-repo PRs and merge + # groups in mode remote, fork and Dependabot PRs through rbe-west's mint + # (rbe-fork, modes fork-ro/fork-rw). Mode skip (the farm switch off) or + # cache (no secret, or rbe-fork closed or refusing) is red, never a silent + # pass with fewer tests. bazel.yml has no pull_request/merge_group trigger # of its own: this call is its only PR run. It gets the four RBE secrets - # and nothing else; its rbe job decides remote, cache (forks, Dependabot: - # local execution with the anonymous read-only cache, no embedded, - # proxied or server-storage lane) or skip, and exports that for ci-gate. - # Its bazel-integration lane (main.yml's integration jobs, which run only - # on push to main) is on and required here in modes remote and cache: - # same-repo PRs run it remotely, fork and Dependabot PRs locally with the - # read-only cache. Its bd artifact is renamed - # (bazel-ci-build-artifacts) so it cannot collide with build-artifacts' - # upload. F3: the package gates build their own bd (via this call's rbe - # job) and do not consume this artifact; it is kept for the F3.5.3 - # SHA256SUMS comparison and for debugging. + # and the pre-warm app key and nothing else. Test results are cached: a PR + # or merge group re-runs only tests whose inputs changed (nightly re-runs + # everything; .bazelrc test:fresh). Its bd artifact + # (bazel-ci-build-artifacts) is kept for debugging; F3: the package gates + # build their own bd via this call's rbe job. bazel: name: Bazel + # A called workflow's job gets at most this call's token permissions, and + # GitHub checks them when the run starts, even for a job whose if: skips + # it (startup_failure otherwise; gascity #7478): bazel.yml's rrc-seed asks + # id-token: write (push to main only) and rrc-verify issues: write + # (schedule and dispatch only). Neither runs for this event, every other + # bazel.yml job keeps contents: read, and rbe-west's mint refuses any OIDC + # token but a main-push bazel.yml one + # (scripts/bazel_rrc_test.go, TestBazelWorkflowCallersGrantEveryRequestedPermission). permissions: contents: read + id-token: write + issues: write uses: ./.github/workflows/bazel.yml secrets: RBE_WEST_EXECUTOR: ${{ secrets.RBE_WEST_EXECUTOR }} @@ -2281,89 +1369,13 @@ jobs: with: build-artifact-name: bazel-ci-build-artifacts integration: "on" + # Must equal BAZEL_CMD_DOLT_REQUIRED (top of this file; policy-tested): + # true leaves //cmd/bd:bd_test to the then-required bazel-cmd-dolt. + cmd-dolt-required: true # F3: only pr.yml opts in; the package-mcp/package-npm jobs run inside # this call, needing only its rbe job. package-gates: "on" - # D2: pr-risk.yml's bazel-coverage job, verbatim (policy-tested - # identical). Where it says a tier is covered, PR Risk skips that tier's - # legacy test jobs (embedded, dolt_server), or this workflow skips its own - # (pr_lanes: build-artifacts, PR Core, the pure-Go/js-wasm check, - # domain+uow and contract corpus), so ci-gate requires the tier's Bazel - # lanes to have run remotely and passed in this run. - bazel-coverage: - name: Bazel tier coverage - # F3: same-repo PRs and merge_group get the org's Blacksmith pool; forks, - # Dependabot and any other event stay GitHub-hosted. This job restores no - # GitHub-saved cache, so Blacksmith's inability to see one does not cost - # it anything. Must stay byte-identical to pr-risk.yml's copy - # (TestPRRiskBazelCoverageJob) and to the TestSameRepoBlacksmithRunners - # pin. - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 5 - outputs: - embedded: ${{ steps.decide.outputs.embedded }} - dolt_server: ${{ steps.decide.outputs.dolt_server }} - pr_lanes: ${{ steps.decide.outputs.pr_lanes }} - steps: - # GitHub's == is case-insensitive. FORK is bazel.yml's rbe job's - # expression, verbatim. Nothing mutable is read: not RBE_WEST_WORKERS - # and not the executor secret (either, evaluated per run, would let one - # workflow's re-run disagree with the other's). A same-repo PR whose run - # lacks the secret is covered anyway, so pr.yml's gate goes red (mode - # cache) instead of a tier silently moving back. Fork and Dependabot - # runs get no Actions secrets by design: they are covered only while - # BAZEL_COVERS_FORKS is "true" (rbe-fork gives their lanes remote - # execution), and then a closed rbe-fork turns them red the same way; - # it never moves them back to a legacy tier silently. github.actor - # (unlike triggering_actor) stays the PR's actor on a re-run. - - name: Decide which legacy tiers the Bazel lanes cover - id: decide - env: - RETIRED_EMBEDDED: ${{ env.BAZEL_RETIRES_LEGACY_EMBEDDED == 'true' }} - RETIRED_DOLT_SERVER: ${{ env.BAZEL_RETIRES_LEGACY_DOLT_SERVER_TIERS == 'true' }} - RETIRED_PR_LANES: ${{ env.BAZEL_RETIRES_LEGACY_PR_LANES == 'true' }} - COVERS_FORKS: ${{ env.BAZEL_COVERS_FORKS == 'true' }} - PULL_REQUEST: ${{ github.event_name == 'pull_request' }} - FORK: ${{ github.event.pull_request.head.repo.fork == true }} - DEPENDABOT: ${{ github.actor == 'dependabot[bot]' }} - run: | - for v in RETIRED_EMBEDDED RETIRED_DOLT_SERVER RETIRED_PR_LANES COVERS_FORKS PULL_REQUEST FORK DEPENDABOT; do - case "${!v}" in - true|false) ;; - *) echo "::error::$v is '${!v}', want true or false"; exit 1 ;; - esac - done - # Covered: the Bazel lanes are this run's only run of the retired - # tiers. Same-repo PRs (the CI secrets); fork and Dependabot PRs - # too while BAZEL_COVERS_FORKS is "true". - covered=false - if [ "$PULL_REQUEST" = true ]; then - if [ "$FORK" = false ] && [ "$DEPENDABOT" = false ]; then - covered=true - elif [ "$COVERS_FORKS" = true ]; then - covered=true - fi - fi - embedded=false - if [ "$covered" = true ] && [ "$RETIRED_EMBEDDED" = true ]; then - embedded=true - fi - dolt_server=false - if [ "$covered" = true ] && [ "$RETIRED_DOLT_SERVER" = true ]; then - dolt_server=true - fi - pr_lanes=false - if [ "$covered" = true ] && [ "$RETIRED_PR_LANES" = true ]; then - pr_lanes=true - fi - { - echo "embedded=$embedded" - echo "dolt_server=$dolt_server" - echo "pr_lanes=$pr_lanes" - } >> "$GITHUB_OUTPUT" - echo "Legacy tiers retired in favour of the Bazel lanes: embedded Dolt **$embedded**, proxied and server Dolt **$dolt_server**, pr.yml's PR Core/build/pure-Go/domain+uow/contract jobs **$pr_lanes** (pull_request: $PULL_REQUEST, fork: $FORK, dependabot: $DEPENDABOT, forks covered: $COVERS_FORKS, retired embedded: $RETIRED_EMBEDDED, retired proxied/server: $RETIRED_DOLT_SERVER, retired pr.yml jobs: $RETIRED_PR_LANES)" | tee -a "$GITHUB_STEP_SUMMARY" - ci-gate: name: CI Gate / Required # F3: same-repo PRs and merge_group get the org's Blacksmith pool; forks, @@ -2377,27 +1389,14 @@ jobs: # minutes too. timeout-minutes: 10 needs: - - build-artifacts - fast-checks - - check-cmd-bd-puregeo-tests - - check-release-target-cross-compilation - test-windows-liveness - worktree-remove-windows - - test-windows-liveness-prebuilt - - worktree-remove-windows-prebuilt - check-doc-flags - check-doc-freshness-platforms - pr-preflight-platforms - - pr-policy-wrapper - - pr-core-wrapper - - scripts-go-checks - - pr-lint-wrapper - - test-domain-uow - - test-dolt-server-fingerprint - - contract-corpus - windows-make-shell - bazel - - bazel-coverage if: ${{ always() }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 @@ -2406,67 +1405,43 @@ jobs: env: CI_GATE_NAME: PR baseline gate CI_GATE_REQUIRED: >- - BUILD_ARTIFACTS FAST_CHECKS - CHECK_BUILD_TAGS - CHECK_VERSION_CONSISTENCY CHECK_MIGRATION_HYGIENE CHECK_NO_BEADS_CHANGES - FMT_CHECK - CHECK_CMD_BD_PUREGEO_TESTS - CHECK_RELEASE_TARGET_CROSS_COMPILATION CHECK_DOC_FLAGS CHECK_DOC_FRESHNESS_PLATFORMS PR_PREFLIGHT_PLATFORMS PACKAGE_MCP PACKAGE_NPM - PR_POLICY_WRAPPER - PR_CORE_WRAPPER - SCRIPTS_GO_CHECKS - PR_LINT_WRAPPER - TEST_DOMAIN_UOW - TEST_DOLT_SERVER_FINGERPRINT - CONTRACT_CORPUS + TEST_WINDOWS_LIVENESS + WORKTREE_REMOVE_WINDOWS WINDOWS_MAKE_SHELL BAZEL BAZEL_TEST BAZEL_PURE + BAZEL_RELEASE_CROSS BAZEL_EMBEDDED BAZEL_INTEGRATION BAZEL_DOLTSERVER BAZEL_PROXIED BAZEL_SERVER_STORAGE - BAZEL_COVERAGE - BAZEL_EMBEDDED_RETIRED - BAZEL_DOLT_SERVER_RETIRED - BAZEL_PR_LANES_RETIRED - BUILD_ARTIFACTS: ${{ needs.build-artifacts.result }} - # F7a: fast-checks folds five formerly-separate jobs into one job - # with five steps; each token below now reads that step's outcome - # (via the job's outputs) instead of a sibling job's result, with a - # 'skipped' fallback for a lost job (see FAST_CHECKS below). - # TestPRCIGateFastChecksTokens pins this mapping. - CHECK_BUILD_TAGS: ${{ needs.fast-checks.outputs.build-tags || 'skipped' }} - CHECK_VERSION_CONSISTENCY: ${{ needs.fast-checks.outputs.version-consistency || 'skipped' }} + BAZEL_REMOTE + # fast-checks' two base-diff steps; each token reads that step's + # outcome (via the job's outputs), with a 'skipped' fallback for a + # lost job (see FAST_CHECKS below). TestPRCIGateFastChecksTokens + # pins this mapping. The repository guards the job used to run + # (build tags, versions, migration checks A and B, gofmt) are Bazel + # tests and gate through BAZEL_TEST. CHECK_MIGRATION_HYGIENE: ${{ needs.fast-checks.outputs.migration-hygiene || 'skipped' }} CHECK_NO_BEADS_CHANGES: ${{ needs.fast-checks.outputs.no-beads-changes || 'skipped' }} - FMT_CHECK: ${{ needs.fast-checks.outputs.fmt || 'skipped' }} # Backstop: if fast-checks itself is lost (e.g. a cancelled runner) - # before any step sets an output, the five tokens above all read - # 'skipped' (none are in CI_GATE_SKIPPED_OK by default, so the gate - # still reds) - FAST_CHECKS gives ci-gate.sh one clear line naming - # the job instead of five step-shaped ones. + # before any step sets an output, the two tokens above read + # 'skipped' (neither is in CI_GATE_SKIPPED_OK, so the gate still + # reds) - FAST_CHECKS gives ci-gate.sh one clear line naming the + # job. FAST_CHECKS: ${{ needs.fast-checks.result }} - CHECK_CMD_BD_PUREGEO_TESTS: ${{ needs.check-cmd-bd-puregeo-tests.result }} - CHECK_RELEASE_TARGET_CROSS_COMPILATION: ${{ needs.check-release-target-cross-compilation.result }} TEST_WINDOWS_LIVENESS: ${{ needs.test-windows-liveness.result }} WORKTREE_REMOVE_WINDOWS: ${{ needs.worktree-remove-windows.result }} - # F4 side-by-side rollout: always evaluated, like the native pair - # above; WINDOWS_PREBUILT_REQUIRED (top of this file) decides below - # which pair is in CI_GATE_REQUIRED and which is in - # CI_GATE_SKIPPED_OK. - TEST_WINDOWS_LIVENESS_PREBUILT: ${{ needs.test-windows-liveness-prebuilt.result }} - WORKTREE_REMOVE_WINDOWS_PREBUILT: ${{ needs.worktree-remove-windows-prebuilt.result }} CHECK_DOC_FLAGS: ${{ needs.check-doc-flags.result }} CHECK_DOC_FRESHNESS_PLATFORMS: ${{ needs.check-doc-freshness-platforms.result }} PR_PREFLIGHT_PLATFORMS: ${{ needs.pr-preflight-platforms.result }} @@ -2476,19 +1451,13 @@ jobs: # here). PACKAGE_MCP: ${{ needs.bazel.outputs.package-mcp || 'skipped' }} PACKAGE_NPM: ${{ needs.bazel.outputs.package-npm || 'skipped' }} - PR_POLICY_WRAPPER: ${{ needs.pr-policy-wrapper.result }} - PR_CORE_WRAPPER: ${{ needs.pr-core-wrapper.result }} - SCRIPTS_GO_CHECKS: ${{ needs.scripts-go-checks.result }} - PR_LINT_WRAPPER: ${{ needs.pr-lint-wrapper.result }} - TEST_DOMAIN_UOW: ${{ needs.test-domain-uow.result }} - TEST_DOLT_SERVER_FINGERPRINT: ${{ needs.test-dolt-server-fingerprint.result }} - CONTRACT_CORPUS: ${{ needs.contract-corpus.result }} WINDOWS_MAKE_SHELL: ${{ needs.windows-make-shell.result }} # bazel.yml's lanes report their job.status as outputs; a lane that # did not report (skipped, or lost before its last step) reads as # skipped, which passes only in the modes bazel-gate.sh allows. BAZEL_TEST: ${{ needs.bazel.outputs.bazel-test || 'skipped' }} BAZEL_PURE: ${{ needs.bazel.outputs.bazel-pure || 'skipped' }} + BAZEL_RELEASE_CROSS: ${{ needs.bazel.outputs.bazel-release-cross || 'skipped' }} BAZEL_EMBEDDED: ${{ needs.bazel.outputs.bazel-embedded || 'skipped' }} BAZEL_INTEGRATION: ${{ needs.bazel.outputs.bazel-integration || 'skipped' }} BAZEL_DOLTSERVER: ${{ needs.bazel.outputs.bazel-doltserver || 'skipped' }} @@ -2503,33 +1472,8 @@ jobs: BAZEL_CALL: ${{ needs.bazel.result }} BAZEL_RBE_MODE: ${{ needs.bazel.outputs.rbe-mode }} BAZEL_RBE_ENABLED: ${{ needs.bazel.outputs.rbe-enabled }} - # D2: which legacy tiers PR Risk, or this workflow (pr_lanes), - # retired for this PR (BAZEL_*_RETIRED below). - BAZEL_COVERAGE: ${{ needs.bazel-coverage.result }} - BAZEL_COVERS_EMBEDDED: ${{ needs.bazel-coverage.outputs.embedded }} - BAZEL_COVERS_DOLT_SERVER: ${{ needs.bazel-coverage.outputs.dolt_server }} - BAZEL_COVERS_PR_LANES: ${{ needs.bazel-coverage.outputs.pr_lanes }} run: | skipped_ok="" - if [[ "$GITHUB_EVENT_NAME" == "merge_group" ]]; then - skipped_ok="CHECK_NO_BEADS_CHANGES" - fi - # F4 side-by-side rollout: WINDOWS_PREBUILT_REQUIRED (top of this - # file) flips which pair of Windows jobs ci-gate enforces with a - # single committed flag, instead of three edits per job - # (ci-gate.needs, CI_GATE_REQUIRED, and this step's env map) done - # twice. Both pairs are unconditionally in ci-gate.needs and always - # evaluated above (neither is in the static CI_GATE_REQUIRED list); - # only which pair is added to CI_GATE_REQUIRED (enforced) vs. - # skipped_ok (merely advisory -- a failure there cannot redden the - # gate) changes here. - if [[ "$WINDOWS_PREBUILT_REQUIRED" == "true" ]]; then - CI_GATE_REQUIRED="$CI_GATE_REQUIRED TEST_WINDOWS_LIVENESS_PREBUILT WORKTREE_REMOVE_WINDOWS_PREBUILT" - skipped_ok="$skipped_ok TEST_WINDOWS_LIVENESS WORKTREE_REMOVE_WINDOWS" - else - CI_GATE_REQUIRED="$CI_GATE_REQUIRED TEST_WINDOWS_LIVENESS WORKTREE_REMOVE_WINDOWS" - skipped_ok="$skipped_ok TEST_WINDOWS_LIVENESS_PREBUILT WORKTREE_REMOVE_WINDOWS_PREBUILT" - fi # The cmd/bd Dolt-server tier (bazel.yml's bazel-cmd-dolt) is # advisory until BAZEL_CMD_DOLT_REQUIRED (top of this file) is # "true"; it is never in the static list above. @@ -2545,38 +1489,19 @@ jobs: skipped_ok="$skipped_ok $(bash .github/scripts/bazel-gate.sh skips)" BAZEL="$(bash .github/scripts/bazel-gate.sh aggregate)" export BAZEL - # D2 step 3: this workflow's legacy jobs that stand down where - # bazel-coverage says pr_lanes (exactly "true"); their Bazel lanes - # are then required below. - if [[ "$BAZEL_COVERS_PR_LANES" == "true" ]]; then - skipped_ok="$skipped_ok BUILD_ARTIFACTS CHECK_CMD_BD_PUREGEO_TESTS PR_CORE_WRAPPER TEST_DOMAIN_UOW CONTRACT_CORPUS" + # The Bazel lanes are the only run of every Linux Go test tier + # (there is no legacy job to fall back to), so on every pull_request + # and merge group they must have run remotely on rbe-west: mode + # remote, or fork-ro/fork-rw through rbe-fork for a PR without the + # CI secrets; mode skip (the farm switch off) or cache (no + # secret, or rbe-fork closed or refusing) is red whatever + # bazel-gate.sh's skip list allows; each lane's own result is + # required above. + BAZEL_REMOTE=success + if [[ ! "$BAZEL_RBE_MODE" =~ ^(remote|fork-ro|fork-rw)$ ]]; then + BAZEL_REMOTE=not-run-remotely + echo "::error::The Bazel lanes did not run remotely on rbe-west (mode '${BAZEL_RBE_MODE:-none}'); they are this PR's only run of the Linux Go test tiers. In mode cache on a PR without the CI secrets, rbe-fork was closed or refused this run: re-run all jobs later." fi - # Where a legacy tier is retired (by PR Risk or by this - # workflow), this run's Bazel lanes for it are the tier's only - # pre-merge run: each must have run remotely (mode remote, or - # fork-ro/fork-rw with an rbe-fork certificate where - # BAZEL_COVERS_FORKS covers a PR without the CI secrets) and - # passed. Mode skip (the farm switch off), cache (no secret, or - # rbe-fork closed or refusing), or any other result, is red - # whatever bazel-gate.sh allows. - # retired ID FLAG COVERED TIER LANE...: set and export ID. - retired() { - local id="$1" flag="$2" covered="$3" tier="$4" result=success lane - shift 4 - if [[ "$covered" == "true" ]]; then - [[ "$BAZEL_RBE_MODE" =~ ^(remote|fork-ro|fork-rw)$ ]] || result="not-run-remotely" - for lane in "$@"; do - [[ "${!lane:-}" == "success" ]] || result="not-run-remotely" - done - if [[ "$result" != "success" ]]; then - echo "::error::The legacy $tier is retired ($flag) and its Bazel lanes ($*) did not all run remotely and pass (mode '${BAZEL_RBE_MODE:-none}'). In mode cache on a PR without the CI secrets, rbe-fork was closed or refused this run: re-run all jobs later. If remote execution is off on purpose, commit $flag: \"false\" (or BAZEL_COVERS_FORKS: \"false\" for forks) in pr.yml and pr-risk.yml and push this PR again." - fi - fi - printf -v "$id" '%s' "$result" - export "${id?}" - } - retired BAZEL_EMBEDDED_RETIRED BAZEL_RETIRES_LEGACY_EMBEDDED "$BAZEL_COVERS_EMBEDDED" "PR Risk embedded Dolt tier" BAZEL_EMBEDDED - retired BAZEL_DOLT_SERVER_RETIRED BAZEL_RETIRES_LEGACY_DOLT_SERVER_TIERS "$BAZEL_COVERS_DOLT_SERVER" "PR Risk proxied-server and server-Dolt storage tiers" BAZEL_PROXIED BAZEL_SERVER_STORAGE - retired BAZEL_PR_LANES_RETIRED BAZEL_RETIRES_LEGACY_PR_LANES "$BAZEL_COVERS_PR_LANES" "PR Core, build-artifacts, pure-Go/js-wasm, domain+uow and contract corpus jobs" BAZEL_TEST BAZEL_PURE BAZEL_DOLTSERVER + export BAZEL_REMOTE export CI_GATE_SKIPPED_OK="$skipped_ok" bash .github/scripts/ci-gate.sh diff --git a/.github/workflows/proxied-local-smoke.yml b/.github/workflows/proxied-local-smoke.yml deleted file mode 100644 index dbfad62e5..000000000 --- a/.github/workflows/proxied-local-smoke.yml +++ /dev/null @@ -1,189 +0,0 @@ -# Managed-local proxied lifecycle lane. -# -# The proxied shards in main.yml exercise command behavior against an -# EXTERNALLY managed Dolt testcontainer. This lane covers the production -# local-first path those shards cannot: bd launches its own loopback proxy, -# the proxy launches a locally installed `dolt sql-server`, and the whole -# lifecycle (create/read, loopback-only listeners, idle shutdown, -# transparent restart with persistence), identity failures, orphan recovery, -# and start/stop convergence run INSIDE a network namespace with only -# loopback up — proving no outbound network is needed once the binaries are -# installed. Linux first; the test lane defines Windows/macOS parity but does -# not implement those OS-specific observation helpers yet. - -name: Proxied Local Lifecycle - -on: - workflow_dispatch: - merge_group: - push: - branches: [main] - paths: - - 'cmd/bd/proxied_local_*' - - 'cmd/bd/proxied_server*.go' - - 'cmd/bd/dolt*.go' - - 'cmd/bd/*_proxied_server.go' - - 'cmd/bd/backup*.go' - - 'cmd/bd/purge*.go' - - 'cmd/bd/*managed_local*' - - 'cmd/bd/proxied_outage_reconnect_integration_test.go' - - 'cmd/bd/db_proxy_child.go' - - 'cmd/bd/init*.go' - - 'cmd/bd/proxied_integration_helpers_test.go' - - 'cmd/bd/store_factory*.go' - - 'cmd/bd/test_dolt_server_cgo_test.go' - - 'cmd/bd/tracker_proxy_uow_conformance_integration_test.go' - - 'cmd/bd/uow_factory.go' - - 'internal/configfile/**' - - 'internal/doltserver/**' - - 'internal/storage/dbproxy/**' - - 'internal/storage/uow/**' - - 'internal/tracker/conformance/**' - - 'internal/tracker/uow_store.go' - - 'internal/tracker/engine.go' - - 'internal/tracker/store.go' - - 'go.mod' - - 'go.sum' - - '.github/workflows/proxied-local-smoke.yml' - pull_request: - paths: - - 'cmd/bd/proxied_local_*' - - 'cmd/bd/proxied_server*.go' - - 'cmd/bd/dolt*.go' - - 'cmd/bd/*_proxied_server.go' - - 'cmd/bd/backup*.go' - - 'cmd/bd/purge*.go' - - 'cmd/bd/*managed_local*' - - 'cmd/bd/proxied_outage_reconnect_integration_test.go' - - 'cmd/bd/db_proxy_child.go' - - 'cmd/bd/init*.go' - - 'cmd/bd/proxied_integration_helpers_test.go' - - 'cmd/bd/store_factory*.go' - - 'cmd/bd/test_dolt_server_cgo_test.go' - - 'cmd/bd/tracker_proxy_uow_conformance_integration_test.go' - - 'cmd/bd/uow_factory.go' - - 'internal/configfile/**' - - 'internal/doltserver/**' - - 'internal/storage/dbproxy/**' - - 'internal/storage/uow/**' - - 'internal/tracker/conformance/**' - - 'internal/tracker/uow_store.go' - - 'internal/tracker/engine.go' - - 'internal/tracker/store.go' - - 'go.mod' - - 'go.sum' - - '.github/workflows/proxied-local-smoke.yml' - -permissions: - contents: read - -jobs: - managed-local-smoke: - name: Managed-local proxied lifecycle (Linux, offline) - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 25 - env: - CGO_ENABLED: "1" - # Pinned so the lane tests a known dolt CLI, not whatever the installer - # resolves on a given day. Bump deliberately, and only in lockstep with - # the measured pin in scripts/ci/install-dolt.sh (see "Which Dolt - # version to install" in docs/architecture/dolt.md). - DOLT_VERSION: 2.2.0 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - - - name: Set up Go - id: setup-go - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: ${{ runner.environment == 'github-hosted' }} - - # F7c review fix S5: this job's own key copy must match main.yml's - # seeder key byte-for-byte (TestBlacksmithSetupGoCacheKeysMatchAcrossSeederAndConsumers), - # which now keys by UTC calendar day instead of github.sha so main - # pushes don't churn a multi-GB cache entry on every commit; this step - # computes that same day value locally so the key expression below - # resolves (steps.* references only resolve within the same job). - - name: Compute cache date - id: cache-date - if: runner.environment == 'self-hosted' - run: echo "today=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT" - - - name: Restore Blacksmith setup-go cache - if: runner.environment == 'self-hosted' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/go/pkg/mod - ~/.cache/go-build - key: blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - restore-keys: | - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}- - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Install pinned Dolt CLI - run: | - curl -fsSL "https://github.com/dolthub/dolt/releases/download/v${DOLT_VERSION}/dolt-linux-amd64.tar.gz" -o /tmp/dolt.tar.gz - tar -xzf /tmp/dolt.tar.gz -C /tmp - sudo install /tmp/dolt-linux-amd64/bin/dolt /usr/local/bin/dolt - dolt version - - - name: Build bd and compile the test binary (online) - run: | - go build -tags gms_pure_go -o /tmp/bd-under-test ./cmd/bd - go test -tags gms_pure_go -c -o /tmp/proxied-local-smoke.test ./cmd/bd - - - name: Assert the managed-local lifecycle tests are compiled in - run: | - listed="$( - BEADS_TEST_PROXIED_LOCAL=1 \ - BEADS_TEST_SKIP=dolt \ - /tmp/proxied-local-smoke.test \ - -test.list '^TestManagedLocalProxied' - )" - for test_name in \ - TestManagedLocalProxiedLifecycleSmoke \ - TestManagedLocalProxiedForeignListenerNotAdopted \ - TestManagedLocalProxiedReusedPidNeverKilled \ - TestManagedLocalProxiedLegacyRecordFailClosed \ - TestManagedLocalProxiedOrphanBackendReaped \ - TestManagedLocalProxiedNProcessColdStartConvergence \ - TestManagedLocalProxiedStopStartInterleave \ - TestManagedLocalProxiedDoltStatusReportsLiveTopology \ - TestManagedLocalProxiedDoltStartRefusesOverLiveProxy \ - TestManagedLocalProxiedDoltStartRefusesWithProxyDown \ - TestManagedLocalProxiedDoltLifecycleLeavesOtherTopologiesAlone \ - TestManagedLocalProxiedTrackerUOWConformance \ - TestManagedLocalProxiedBackupRoundTrip \ - TestManagedLocalProxiedAutoBackup \ - TestManagedLocalProxiedBackupRestoreRefusedWhileAttached \ - TestManagedLocalProxiedPurgeWispsPlaneRetention \ - TestManagedLocalProxiedBackendCleanExitRetiresProxy - do - if ! grep -qx "$test_name" <<<"$listed"; then - echo "managed-local lifecycle test $test_name is missing; got: '$listed'" >&2 - exit 1 - fi - done - - - name: Run managed-local lifecycle lane offline (loopback-only netns) - run: | - sudo env \ - "PATH=$PATH" \ - BEADS_TEST_PROXIED_LOCAL=1 \ - BEADS_TEST_SKIP=dolt \ - BEADS_TEST_BD_BINARY=/tmp/bd-under-test \ - unshare --net -- bash -euxc ' - ip link set lo up - # Prove the namespace really has no outbound network before - # trusting anything the test reports. - if timeout 3 bash -c "exec 3<>/dev/tcp/1.1.1.1/443" 2>/dev/null; then - echo "outbound network unexpectedly available inside the netns" >&2 - exit 1 - fi - cd cmd/bd - /tmp/proxied-local-smoke.test \ - -test.run "^TestManagedLocalProxied" \ - -test.v -test.timeout 15m - ' diff --git a/.github/workflows/regression.yml b/.github/workflows/regression.yml deleted file mode 100644 index a304df6d8..000000000 --- a/.github/workflows/regression.yml +++ /dev/null @@ -1,177 +0,0 @@ -name: Regression Tests - -on: - # Run on merges to main - push: - branches: [main] - pull_request: - branches: [main, 'release/**'] - # Allow manual trigger - workflow_dispatch: - -env: - BD_DISABLE_METRICS: "1" - BD_DISABLE_EVENT_FLUSH: "1" - -jobs: - regression: - name: Differential Regression (v0.49.6 baseline) - # F7c: detect-regression-need folded in as this job's own first step - # (id: detect). A non-applicable PR now costs one short Blacksmith-sized - # job instead of two GitHub-hosted jobs; every later step is gated on - # steps.detect.outputs.run_regression instead of a separate job's output. - runs-on: ${{ (github.event_name == 'merge_group' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]')) && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} - timeout-minutes: 45 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - with: - fetch-depth: 0 - - - name: Decide whether to run differential regression tests - id: detect - env: - EVENT_NAME: ${{ github.event_name }} - PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} - PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} - run: | - set -euo pipefail - - if [[ "$EVENT_NAME" != "pull_request" ]]; then - echo "run_regression=true" >> "$GITHUB_OUTPUT" - echo "reason=$EVENT_NAME event always runs regression tests" >> "$GITHUB_OUTPUT" - exit 0 - fi - - labels="$(jq -r '.pull_request.labels[].name // empty' "$GITHUB_EVENT_PATH")" - if grep -Fxq "run-regression" <<<"$labels"; then - echo "run_regression=true" >> "$GITHUB_OUTPUT" - echo "reason=run-regression label present" >> "$GITHUB_OUTPUT" - exit 0 - fi - if grep -Fxq "skip-regression" <<<"$labels"; then - echo "run_regression=false" >> "$GITHUB_OUTPUT" - echo "reason=skip-regression label present" >> "$GITHUB_OUTPUT" - exit 0 - fi - - changed="$(git diff --name-only "$PR_BASE_SHA" "$PR_HEAD_SHA")" - echo "Changed files:" - printf '%s\n' "$changed" - - regression_candidates="$( - printf '%s\n' "$changed" | - grep -Ev '^(cmd/bd|internal/storage|internal/types)/.*_test\.go$' || - true - )" - - risky_pattern='^(\.github/workflows/regression\.yml|Makefile|go\.(mod|sum)|cmd/bd/|internal/storage/|internal/types/|tests/regression/)' - if grep -Eq "$risky_pattern" <<<"$regression_candidates"; then - echo "run_regression=true" >> "$GITHUB_OUTPUT" - echo "reason=PR changes CLI, storage, types, regression, or build inputs" >> "$GITHUB_OUTPUT" - exit 0 - fi - - echo "run_regression=false" >> "$GITHUB_OUTPUT" - echo "reason=PR does not touch regression-sensitive paths" >> "$GITHUB_OUTPUT" - - - name: Show regression trigger reason - if: steps.detect.outputs.run_regression == 'true' - run: echo "${{ steps.detect.outputs.reason }}" - - - name: Set up Go - id: setup-go - if: steps.detect.outputs.run_regression == 'true' - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: 'go.mod' - cache: ${{ runner.environment == 'github-hosted' }} - - # F7c review fix S5: this job's own key copy must match main.yml's - # seeder key byte-for-byte (TestBlacksmithSetupGoCacheKeysMatchAcrossSeederAndConsumers), - # which now keys by UTC calendar day instead of github.sha so main - # pushes don't churn a multi-GB cache entry on every commit; this step - # computes that same day value locally so the key expression below - # resolves (steps.* references only resolve within the same job). - - name: Compute cache date - id: cache-date - if: steps.detect.outputs.run_regression == 'true' && runner.environment == 'self-hosted' - run: echo "today=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT" - - - name: Restore Blacksmith setup-go cache - if: steps.detect.outputs.run_regression == 'true' && runner.environment == 'self-hosted' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v5 - with: - path: | - ~/go/pkg/mod - ~/.cache/go-build - key: blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}-${{ steps.cache-date.outputs.today }} - restore-keys: | - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('go.sum') }}- - blacksmith-sg-v1-${{ runner.os }}-${{ runner.arch }}-go-${{ steps.setup-go.outputs.go-version }}- - - - name: Configure Git - if: steps.detect.outputs.run_regression == 'true' - run: | - git config --global user.name "CI Bot" - git config --global user.email "ci@beads.test" - - - name: Install Dolt - if: steps.detect.outputs.run_regression == 'true' - run: ./scripts/ci/install-dolt.sh - - - name: Configure Dolt - if: steps.detect.outputs.run_regression == 'true' - run: | - dolt config --global --add user.name "CI Bot" - dolt config --global --add user.email "ci@beads.test" - dolt version - - - name: Pull Dolt sql-server image - # Without this, isDoltImageCached() returns false in TestMain and the - # regression suite falls back to embedded Dolt with HOME=, which - # has a known cleanup race (see beads issue: TestCreateWithParentFlag - # TempDir RemoveAll "directory not empty" flake). Keep the tag in sync - # with internal/testutil/testdoltcommon.go:DoltDockerImage. - if: steps.detect.outputs.run_regression == 'true' - run: ./scripts/ci/pull-dolt-image.sh - - # Restore-only: actions/cache (bare) auto-saves on any key miss, which - # would let a same-repo PR that bumps BASELINE_VERSION write a baseline - # binary cache entry a later PR or main could read back unverified. The - # matching save below only runs off pull_request (B2, F7c implementation - # report). - - name: Restore baseline binary cache - if: steps.detect.outputs.run_regression == 'true' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v5 - with: - path: ~/.cache/beads-regression - key: regression-baseline-${{ hashFiles('tests/regression/BASELINE_VERSION') }} - - # Passing-side wall time already overlapped the go deadline below, so - # ordinary GitHub-runner speed variance -- not a real hang -- was - # tripping this step. Measured over the 100 most recent Regression - # Tests runs (2026-09-03/04, ~29.5h): p50 593s (~10m), max passing - # 1189s (~19.8m) against the prior 1200s (20m) cap, and 5 runs in that - # window hit the identical `panic: test timed out after 20m0s` with - # zero `--- FAIL` lines -- a budget defect, not a regression. Match - # main.yml's Test job fix for the same failure mode: raise the go - # deadline to cover the observed slowdown and keep it inside a larger - # finite job budget (see timeout-minutes above), so the go deadline - # fires first and prints goroutine stacks -- a REAL hang stays - # diagnosable instead of being cut off by a bare job kill. - - name: Run regression tests - if: steps.detect.outputs.run_regression == 'true' - run: go test -tags=regression,gms_pure_go -timeout=40m -v ./tests/regression/... - - - name: Save baseline binary cache - # Allow-list push/workflow_dispatch rather than deny-list - # pull_request: a deny-list also admits a hypothetical future - # merge_group event, which this job's runs-on expression already - # resolves to Blacksmith for. Pinned by - # TestBlacksmithReachableAdvisoryJobsNeverSaveACache (checks both the - # pull_request and merge_group trust contexts independently). - if: steps.detect.outputs.run_regression == 'true' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v5 - with: - path: ~/.cache/beads-regression - key: regression-baseline-${{ hashFiles('tests/regression/BASELINE_VERSION') }} diff --git a/.github/workflows/update-vendor-hash.yml b/.github/workflows/update-vendor-hash.yml index 672457fb1..8ad1b449f 100644 --- a/.github/workflows/update-vendor-hash.yml +++ b/.github/workflows/update-vendor-hash.yml @@ -3,8 +3,8 @@ name: Update vendorHash for dependabot Go bumps # Dependabot bumps to go.mod/go.sum invalidate the proxyVendor FOD hash in # default.nix, which fails the required PR Risk `test-nix` gate (F7c, # spec-f7.md §2.4: nix-build.yml itself no longer runs on pull_request, since -# test-nix's `nix run .#default` plus `nix flake check -L` is a superset of -# plain `nix build .#default`). This workflow detects the drift, computes the +# test-nix's `nix run .#default` plus `nix flake check -L`, which evaluates +# every flake output, is a superset of plain `nix build .#default`). This workflow detects the drift, computes the # new hash via scripts/update-nix-vendorhash.sh, and pushes the update back to # the dependabot branch so the gate goes green without a maintainer # round-trip. @@ -82,6 +82,14 @@ jobs: - name: Update vendorHash run: ./scripts/update-nix-vendorhash.sh + - name: Verify the build independently of the script's exit status + # update-nix-vendorhash.sh's own verification build (its step 5) is + # internal to the script; this step re-derives the same signal from + # a source the workflow doesn't have to trust: a plain `nix build` + # that this job step fails on if it fails, regardless of what the + # script itself reported. + run: nix build .#default + - name: Detect whether hash changed id: changed run: | diff --git a/.github/workflows/worker-env-autosync.yml b/.github/workflows/worker-env-autosync.yml new file mode 100644 index 000000000..2978a5617 --- /dev/null +++ b/.github/workflows/worker-env-autosync.yml @@ -0,0 +1,196 @@ +# Keep beads' rbe worker-env pin in step with gastownhall/gascity main +# without the ~100-minute wait #7419 fixed by hand. +# +# rbe-west's OSS pool is gascity's: its workers advertise the sha256 of the +# toolchain manifest gascity's tools/rbe/worker-env measures, and the +# schedulers match //platforms:rbe_worker's worker-env exec property +# exactly. beads' tools/rbe/worker-env.txt and the platforms/BUILD.bazel pin +# are a byte-for-byte copy of gascity main's; when gascity moves the pin (a +# Go, dolt, or OS/library bump -- #7387 was a Go security release), every +# beads remote-execution run stops in bazel.yml's rbe-job preflight +# (tools/rbe/worker-env-sync) until the copy catches up. nightly.yml's +# rbe-worker-env-sync job already opens a ci/infra issue for a human to fix; +# this instead opens the fix itself, every 15 minutes, so the gap is +# minutes, not until someone reads the issue. +# +# tools/rbe/worker-env-sync only detects the mismatch (exit 1) or that it +# could not compare with gascity (exit 2, e.g. GitHub is briefly +# unreachable; the next run retries). The write half, tools/rbe/worker-env- +# sync-copy, runs only after that exit-1 detection, on a checkout already in +# hand -- so a transient gascity outage can turn "in step" into "unknown", +# never into an unwanted write. +# +# TWO TOKENS, ONE JOB EACH: GitHub never runs checks on a PR a plain +# GITHUB_TOKEN opens (its loop-prevention rule), so this needs a GitHub App +# token to open the PR. The gastownhall-autofix App (contents:write only on +# this repo) mints push-token and does the git push of the fixed branch +# (bot/worker-env-sync); it cannot open, label or merge a PR. The separate +# gascity-autofix App (pull-requests:write only, no contents) mints pr-token +# and does everything PR-shaped: create/update, the status/needs-review-auto +# label, and arming auto-merge. Splitting them means a bug in the PR-shaped +# half can never push a commit, and a bug in the push half can never touch a +# PR; neither token can do the other's job even by accident. Both Apps' +# credentials are secrets of the same `autofix` environment. +# +# peter-evans/create-pull-request takes one token for the whole push+PR +# flow, so it cannot honor this split; this uses plain git for the push and +# gh for the PR instead. Every `${{ }}` is resolved into a step's `env:`, +# never written inside a `run:` script, so a value that happened to look +# like shell (a title or body containing `` ` `` or `$`) is data to the +# shell, not something GitHub's expression syntax or the shell re-parses. +# +# SECURITY: schedule and workflow_dispatch are never fork events (no +# pull_request trigger here at all), so neither App's private key -- secrets +# of the `autofix` environment, whose deployment-branch policy allows only +# main -- is ever readable by a fork. The guard on github.repository is +# defense in depth for a fork of this repo, where the secrets would not +# exist anyway. Both mint steps run only once worker-env-sync has already +# found a real mismatch, so a run that is in step or can't compare asks +# neither App for a token. gh pr merge --auto only arms GitHub's native +# auto-merge (it still waits for every required check and the branch +# protection rule); it does not merge anything itself. +name: rbe worker-env autosync + +on: + schedule: + - cron: "*/15 * * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + autosync: + name: Sync worker-env pin with gascity main + if: github.repository == 'gastownhall/beads' + runs-on: ubuntu-latest + timeout-minutes: 10 + # Grants the job read access to this environment's secrets (both Apps' + # id and private key); its deployment-branch policy restricts that to + # jobs running on main, which schedule and workflow_dispatch on this + # repo always are. + environment: autofix + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + with: + persist-credentials: false + + # Never fails the step itself: rc is the signal every later step + # gates on (1, a real mismatch; 2, gascity unreachable -- the next + # scheduled run retries; 0, in step). A run every 15 minutes failing + # red for however long a mismatch takes to review and merge would be + # noise, not signal. + - name: Compare the worker-env manifest and pin with gascity's main + id: sync + run: | + rc=0 + tools/rbe/worker-env-sync main || rc=$? + echo "rc=$rc" >> "$GITHUB_OUTPUT" + + - name: Copy gascity main's worker-env manifest and pin + if: steps.sync.outputs.rc == '1' + run: tools/rbe/worker-env-sync-copy main + + - name: Confirm only the worker-env files moved + if: steps.sync.outputs.rc == '1' + run: | + changed="$(git diff --name-only)" + untracked="$(git ls-files --others --exclude-standard)" + want=$'platforms/BUILD.bazel\ntools/rbe/worker-env.txt' + if [ -n "$untracked" ] || [ "$(printf '%s\n' "$changed" | sort)" != "$(printf '%s\n' "$want" | sort)" ]; then + echo "::error::worker-env-sync-copy touched more than platforms/BUILD.bazel and tools/rbe/worker-env.txt:" + printf '%s\n' "$changed" "$untracked" + exit 1 + fi + + # contents:write only, on this repo alone: all it can do is push + # bot/worker-env-sync. Minted only once a real mismatch needs a push. + - name: Mint push token (gastownhall-autofix) + id: push-token + if: steps.sync.outputs.rc == '1' + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3 + with: + app-id: ${{ secrets.AUTOFIX_APP_ID }} + private-key: ${{ secrets.AUTOFIX_APP_PRIVATE_KEY }} + owner: gastownhall + repositories: beads + permission-contents: write + + # pull-requests:write only, on this repo alone: all it can do is + # open, label and arm auto-merge on a PR -- never push a commit. + - name: Mint PR token (gascity-autofix) + id: pr-token + if: steps.sync.outputs.rc == '1' + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3 + with: + app-id: ${{ secrets.GASCITY_AUTOFIX_APP_ID }} + private-key: ${{ secrets.GASCITY_AUTOFIX_APP_PRIVATE_KEY }} + owner: gastownhall + repositories: beads + permission-pull-requests: write + + # push-token alone; it cannot see a PR exists, let alone touch one. + # Leased to the branch: a force-with-lease scoped to refs/heads/ + # bot/worker-env-sync only, so a push can never move any other ref. + - name: Commit and push the sync branch + if: steps.sync.outputs.rc == '1' + env: + PUSH_TOKEN: ${{ steps.push-token.outputs.token }} + REPO: ${{ github.repository }} + BRANCH: bot/worker-env-sync + COMMIT_SUBJECT: "build(rbe): sync worker-env pin with gascity main" + GIT_AUTHOR_NAME: gastownhall-autofix[bot] + GIT_AUTHOR_EMAIL: gastownhall-autofix[bot]@users.noreply.github.com + GIT_COMMITTER_NAME: gastownhall-autofix[bot] + GIT_COMMITTER_EMAIL: gastownhall-autofix[bot]@users.noreply.github.com + run: | + git checkout -B "$BRANCH" + git add platforms/BUILD.bazel tools/rbe/worker-env.txt + git commit -m "$COMMIT_SUBJECT" + git push "https://x-access-token:${PUSH_TOKEN}@github.com/${REPO}.git" \ + "HEAD:refs/heads/$BRANCH" "--force-with-lease=refs/heads/$BRANCH" + + # pr-token alone; it cannot push a commit, only act on the PR the + # step above already pushed. + - name: Open or update the sync PR + id: pr + if: steps.sync.outputs.rc == '1' + env: + GH_TOKEN: ${{ steps.pr-token.outputs.token }} + REPO: ${{ github.repository }} + BRANCH: bot/worker-env-sync + TITLE: "build(rbe): sync worker-env pin with gascity main" + LABEL: status/needs-review-auto + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + body="$(cat <> "$GITHUB_OUTPUT" + + - name: Enable auto-merge + if: steps.sync.outputs.rc == '1' && steps.pr.outputs.number + env: + GH_TOKEN: ${{ steps.pr-token.outputs.token }} + REPO: ${{ github.repository }} + PR_NUMBER: ${{ steps.pr.outputs.number }} + run: gh pr merge --auto --squash --repo "$REPO" "$PR_NUMBER" diff --git a/.golangci.yml b/.golangci.yml index 2298aebf6..1ed2975a4 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,3 +1,9 @@ +# Lint policy for nogo (//tools/nogo), which runs these linters beside every +# Bazel Go compile: tools/nogo/internal/golangci embeds this file and applies +# it as golangci-lint v2.10.1 would (enabled linters, settings, run.tests, +# generated files, exclusion rules). Decoding is strict, so a key the nogo +# wrappers do not implement fails the build. golangci-lint itself still reads +# it (editors, ad-hoc runs), but CI gates on nogo; see engdocs/LINTING.md. version: "2" run: @@ -461,12 +467,28 @@ linters: # tests: false` means forbidigo never analyzes a test file at all, so that # entry asserts nothing either way and scoping it would be the churn this # comment just refused to write. - - path: '^cmd/bd/(close|duplicates|find_duplicates|gate|gc|graph|info|label|orphans|purge|search|todo|wisp|human)(_proxied_server)?\.go$' + # + # `search` LEFT this list when all three of its routes moved onto + # issueops.Reader.List with issueops.SearchListRequest (cmd/bd/search.go); + # it builds no filter any more. + # + # `gate` LEFT it when `bd gate check` joined `bd gate list` on + # issueops.ListGates over the route's Querier: cmd/bd/gate.go and + # cmd/bd/gate_proxied_server.go name no filter type any more. + # `gate_discover` keeps its own hole below, since findPendingGates still + # asks SearchIssues for its gates. + - path: '^cmd/bd/(close|duplicates|find_duplicates|gc|graph|info|label|orphans|purge|todo|wisp|human)(_proxied_server)?\.go$' text: 'do not write a filter here' linters: - forbidigo # Molecule reporting: each selects the members of one molecule. - - path: '^cmd/bd/mol_(current|port|progress|ready_gated|stale)\.go$' + # + # `mol current` and `mol progress` LEFT this list when their in_progress + # and hooked listings moved onto issueops.Reader.List (cmd/bd/mol_roles.go) + # so a remote backend answers them. The proxied route's in-transaction + # port still searches through the unit of work, and that filter lives in + # mol_port.go beside the port. + - path: '^cmd/bd/mol_(port|ready_gated|stale)\.go$' text: 'do not write a filter here' linters: - forbidigo diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index fc8edcbea..fa008964c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,9 +1,15 @@ repos: - - repo: https://github.com/golangci/golangci-lint - rev: v2.10.1 + # Lint and vet: nogo (//tools/nogo) over the changed files' Bazel packages, + # the analyzers CI gates on (go test's vet checks plus the golangci-lint + # linters .golangci.yml enables). Needs bazel or bazelisk on PATH. + - repo: local hooks: - - id: golangci-lint - args: [--timeout=5m] + - id: nogo + name: nogo (bazel) + entry: make lint-changed LINT_CHANGED_SCOPE=staged + language: system + types: [go] + pass_filenames: false - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 diff --git a/AGENTS.md b/AGENTS.md index 18a5847d5..e908a5070 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,290 +1,227 @@ -# Agent Instructions +# Beads — Contributor Agent Instructions - +This file is for agents and humans **developing beads** (`bd`). If you are +using `bd` to track work in your own project, read the user docs instead: +[docs site](https://beads.gascity.com/) and +[IDE and agent setup](docs/getting-started/ide-setup.md). -See [AGENT_INSTRUCTIONS.md](AGENT_INSTRUCTIONS.md) for full instructions. + -This file exists for compatibility with tools that look for AGENTS.md. +Nested `AGENTS.md` files hold area-specific rules; the routing table at the +end lists them. `CLAUDE.md` files are symlinks to their sibling `AGENTS.md`. -The marker above tells `bd doctor` that the intentional divergence between -this file and `CLAUDE.md` (different audiences, different reading orders) is -expected and should not be flagged. +## How work flows here -## Key Sections +GitHub Issues is the public tracker. Use an issue when it adds context +reviewers need: a user-visible bug, a behavior or design change worth +discussing, or work that spans several PRs. The issue carries the +reproduction, impact, and evidence for a bug, or the motivation, impact, risk, +and verification plan for a change. Small, self-explanatory changes (typos, +flaky tests, refactors, CI or docs tweaks) can go straight to a PR whose body +explains the why. -- **Issue Tracking** - How to use bd for work management -- **Development Guidelines** - Code standards and testing -- **Project Scope** - Read [engdocs/PROJECT_CHARTER.md](engdocs/PROJECT_CHARTER.md) before adding new feature surface area -- **Visual Design System** - Status icons, colors, and semantic styling for CLI output -- **Contributor Protection** - Read [CONTRIBUTING.md](CONTRIBUTING.md) before handling external PRs -- **Maintainer PR Guidelines** - Read [PR_MAINTAINER_GUIDELINES.md](PR_MAINTAINER_GUIDELINES.md) before triaging, landing, or closing PRs +1. If the change warrants an issue, find or file one with the bug or feature + form. It does not need maintainer approval first; file it before or + alongside the PR. +2. Work on a branch, open a PR against `main` (its body says + `Closes #` when there is one), and let CI and review run. +3. Maintainers triage issues with `status/needs-triage`, `status/needs-info`, + `status/needs-repro`, `status/needs-design`, and `status/accepted` + (confirmed); see [CONTRIBUTING.md](CONTRIBUTING.md). -## Project Scope +Maintainers also keep an internal bd ledger. It is optional for contributors +and not a substitute for the GitHub issue. -Before adding new feature surface area, read -[engdocs/PROJECT_CHARTER.md](engdocs/PROJECT_CHARTER.md). Beads owns issue tracking -primitives and should not encode orchestration-layer policy, become a storage -engine, or casually expand the database schema when metadata would work. +## Agent contribution policy -## PR Safety for Agents +- File an issue when the change warrants one (see above). When you do, use + the bug or feature form fields, fill each from evidence, and answer + `NOT_ENOUGH_INFO` where the evidence runs out. +- A human reviews and stands behind every issue and PR an agent drafts. + Evidence that the change works end-to-end is required; "unit tests pass" + alone is not evidence. +- Before implementing work, opening a PR, or merging/closing a PR, run the PR + preflight: + ```bash + scripts/pr-preflight.sh --search "" --repo gastownhall/beads + scripts/pr-preflight.sh --repo gastownhall/beads + ``` + The preflight is the agent gate for PR handling; do not rely on + auto-discovery of CONTRIBUTING.md. +- Use `gh` for GitHub issues and PRs, not browser tools. Write PR, issue, + comment, and review bodies to a file, run `scripts/gh-body-lint `, + and pass the file with `gh ... --body-file`. Sign agent-written GitHub + comments and reviews per [engdocs/AGENT_SIGNING.md](engdocs/AGENT_SIGNING.md). -Before triaging, reviewing, landing, closing, or otherwise maintaining PRs, read +## Contributor protection + +External contributor PRs have priority. Read [CONTRIBUTING.md](CONTRIBUTING.md) +— it contains promises we've made to contributors — and, before triaging, +reviewing, landing, closing, or otherwise maintaining PRs, [PR_MAINTAINER_GUIDELINES.md](PR_MAINTAINER_GUIDELINES.md). The maintainer policy is to maximize community throughput: find useful contributor value, absorb or transform it locally when practical, preserve attribution, and use request-changes only as a last resort. -Before implementing work, opening a PR, or merging/closing a PR, run the PR -preflight: -```bash -scripts/pr-preflight.sh --search "" --repo gastownhall/beads -scripts/pr-preflight.sh --repo gastownhall/beads -``` +Before implementing any feature or fix, check for existing open PRs on the +same topic. If one exists: -External contributor PRs have priority. Review and build on their branch when -possible, preserve their tests and attribution, and never close or supersede -their PR silently. If a rewrite is unavoidable, explain why on the original PR -and credit their design/tests. +1. **Review it first** — read the diff, understand the approach. +2. **Build on their work, don't rewrite it** — check out their branch, + fix/adapt as needed. +3. **Preserve their tests** — keep them unless they're wrong. +4. **Attribute properly** — `Co-authored-by:` in commits, reference their PR. +5. **Never close or supersede their PR silently.** If a rewrite is + unavoidable, explain why on the original PR and credit their design/tests. -## Visual Design Anti-Patterns +## Scope: where a change belongs -**NEVER use emoji-style icons** (🔴🟠🟡🔵⚪) in CLI output. They cause cognitive overload. +Read [engdocs/PROJECT_CHARTER.md](engdocs/PROJECT_CHARTER.md) before adding +feature surface area. Beads owns issue tracking primitives and should not +encode orchestration-layer policy, become a storage engine, or casually expand +the database schema when metadata would work. Prefer, in order: issue +metadata over new fields, a flag on an existing command over a new command, +an integration or plugin over core, and leave orchestration policy to the +orchestration layer. -**ALWAYS use small Unicode symbols** with semantic colors (status uses symbols; priority uses labels): -- Status: `○ ◐ ● ✓ ❄` -- Priority: `P0`–`P4` label with color (no status glyph) +**Storage boundary.** Beads talks to storage through a driver interface +(`dolthub/driver` for Dolt). Do not add beads-side flocks, engine +introspection, storage-specific retry or crash-recovery logic, or public SDK +return types that leak driver internals. If the boundary is too narrow, widen +the interface or route the issue to the driver instead of patching around it +in beads. `bd doctor` support for embedded mode is enabled one subcommand at a +time, each human-vetted (GH#3794): do not lift the embedded-mode gate in +`cmd/bd/doctor.go` wholesale, and keep database-layer checks and fixes +server-gated until the driver interface covers them. -See [AGENT_INSTRUCTIONS.md](AGENT_INSTRUCTIONS.md) for full development guidelines. +**Layering.** Schema → `internal/storage/issueops` → `cmd/bd`. Add new +primitives at the lowest layer first, one layer per PR, stacked when a fix +spans layers. See +[CONTRIBUTING_PR_GUIDELINES.md](CONTRIBUTING_PR_GUIDELINES.md). -## Storage Boundary +## Build, test, lint -The canonical storage boundary is in -[engdocs/PROJECT_CHARTER.md](engdocs/PROJECT_CHARTER.md#storage-boundary). In short: -Beads talks to storage through a driver interface (`dolthub/driver` for Dolt). -Do not add beads-side flocks, engine introspection, storage-specific retry or -crash-recovery logic, or public SDK return types that leak driver internals. -If the boundary is too narrow, widen the interface or route the issue to the -driver instead of patching around it in beads. - -A live application of this rule: `bd doctor` support for embedded mode is -enabled one subcommand at a time, each human-vetted (GH#3794). Do not lift the -embedded-mode gate in `cmd/bd/doctor.go` wholesale, and keep database-layer -checks and fixes server-gated until the driver interface covers them. - -## Agent Warning: Interactive Commands - -**DO NOT use `bd edit`** - it opens an interactive editor ($EDITOR) which AI agents cannot use. - -Use `bd update` with flags instead: -```bash -bd update --description "new description" -bd update --title "new title" -bd update --design "design notes" -bd update --append-notes "additional notes" # --notes replaces existing notes and requires --force once notes are set -bd update --acceptance "acceptance criteria" - -# Use stdin for descriptions with special characters (backticks, !, nested quotes) -echo 'Description with `backticks` and "quotes"' | bd create "Title" --description=- -echo 'Updated text' | bd update --description=- -``` - -## Testing - -Use [engdocs/TESTING.md](engdocs/TESTING.md) for the canonical commands, -test-design guidance, and PR-readiness gates. - -## Non-Interactive Shell Commands - -**ALWAYS use non-interactive flags** with file operations to avoid hanging on confirmation prompts. - -Shell commands like `cp`, `mv`, and `rm` may be aliased to include `-i` (interactive) mode on some systems, causing the agent to hang indefinitely waiting for y/n input. - -**Use these forms instead:** -```bash -# Force overwrite without prompting -cp -f source dest # NOT: cp source dest -mv -f source dest # NOT: mv source dest -rm -f file # NOT: rm file - -# For recursive operations -rm -rf directory # NOT: rm -r directory -cp -rf source dest # NOT: cp -r source dest -``` - -**Other commands that may prompt:** -- `scp` - use `-o BatchMode=yes` for non-interactive -- `ssh` - use `-o BatchMode=yes` to fail instead of prompting -- `apt-get` - use `-y` flag -- `brew` - use `HOMEBREW_NO_AUTO_UPDATE=1` env var - -## Landing the Plane (Session Completion) - -**When ending a work session** (or when the user says "let's land the -plane"), you MUST complete ALL steps below. Work is NOT complete until -`git push` succeeds. - -**MANDATORY WORKFLOW:** - -1. **File issues for remaining work** - Create issues for anything that needs follow-up -2. **Run quality gates** (if code changed): - - `make ci-pr-lint` (required zero-finding formatting and lint wrapper) - - `make test` (and `make test-icu-path` only if you intentionally need the ICU regex path) - - File a P0 issue if quality gates are broken -3. **Update issue status** - Close finished work, update in-progress items -4. **PUSH TO REMOTE** - This is MANDATORY: - ```bash - git pull --rebase - git push - git status # MUST show "up to date with origin" - ``` -5. **Clean up**: - ```bash - git stash clear # Remove old stashes - git remote prune origin # Clean up deleted remote branches - ``` -6. **Verify** - All changes committed AND pushed, no untracked files remain -7. **Hand off** - Choose a follow-up issue and give the user a prompt for - the next session, e.g. "Continue work on bd-X: [issue title]. [Brief - context about what's been done and what's next]" - -**CRITICAL RULES:** -- Work is NOT complete until `git push` succeeds -- NEVER stop before pushing - that leaves work stranded locally -- NEVER say "ready to push when you are" - YOU must push -- If push fails, resolve and retry until it succeeds - -Close with a summary for the user: what was completed this session, issues -filed for follow-up, quality-gate status, confirmation everything is pushed, -and the recommended prompt for the next session. - - -## Issue Tracking with bd (beads) - -**IMPORTANT**: This project uses **bd (beads)** for ALL issue tracking. Do NOT use markdown TODOs, task lists, or other tracking methods. - -### Why bd? - -- Dependency-aware: Track blockers and relationships between issues -- Git-friendly: Dolt-powered version control with native sync -- Agent-optimized: JSON output, ready work detection, discovered-from links -- Prevents duplicate tracking systems and confusion - -### Quick Start - -**Check for ready work:** +Bazel is the build and test system: CI gates on the `bazel test` lanes in +`.github/workflows/bazel.yml`, and nogo (lint + vet), gofmt and the repository +guards exist only as Bazel targets. Install +[Bazelisk](https://github.com/bazelbuild/bazelisk) as `bazel`; the pre-commit +and pre-push hooks need it. ```bash -bd ready --json +make test # bazel test //... --config=ci: the CI test lane (nogo, gofmt, guards, unit tests) +make check # testing.Short policy + make ci-pr-lint + make test +make ci-pr-lint # nogo lint + vet gate, native plus windows/darwin +make check-docs # bazel docsync + doc freshness, then the CLI flag check +make bazel-sync # after adding/removing/renaming Go files or changing imports/go.mod +make install # build and install bd to ~/.local/bin (canonical) ``` -**Create new issues:** +- Each other tier has its own lane (`--config=integration`, `doltserver`, + `embedded`, ...); [engdocs/TESTING.md](engdocs/TESTING.md) lists the exact + command per lane and is the canonical source for test selection, design, + and PR-readiness gates. +- Where actions run: contributors add `--config=fork-cache` (rbe-west's + anonymous read-only cache; nothing is uploaded), maintainers with an rbe-west + certificate `--config=remote-exec`, agent hosts whose `~/.bazelrc` names the + executor neither. Make yours the default with a `build --config=...` line in + the gitignored `.bazelrc.local`, or pass `BAZEL_FLAGS=...` to make. +- Agents run tests only with `bazel test`, also while iterating on one + behavior: -```bash -bd create "Issue title" --description="Detailed context" -t bug|feature|task -p 0-4 --json -bd create "Issue title" --description="What this issue is about" -p 1 --deps discovered-from:bd-123 --json -``` + ```bash + bazel test //cmd/bd:bd_test --config=ci --test_filter='^TestName$' --test_output=all + ``` -**Claim and update:** + A target also passes when the test never ran (a filter that matches + nothing, a skip, a file the configuration does not compile), so count a run + only when its log shows `--- PASS: TestName` and no `--- SKIP` for the test + or a `TestName/...` subtest: Go prints `--- PASS` for a test whose every + subtest skipped. "Check That the Test Ran" in + [engdocs/TESTING.md](engdocs/TESTING.md) names the tests `--config=ci` does + not run (Dolt-backed, `-short`-gated, integration-tagged, `TestEmbedded*` + and embedded-Dolt, files `BUILD.bazel` does not list) and the way into + each. An unchanged target returns its cached result, which is the same + evidence. Finish with `make test`. +- Agents do not run `go test` (`./scripts/test.sh`, `make test-go`): CI does + not enforce it, it skips nogo, gofmt and the guards, and agent hosts may + refuse it. It stays a convenience for humans working offline. The exception + is regenerating golden files (`make corpus-regen`, `make githooks-regen`, + `BD_UPDATE_GOLDEN=1`), which Bazel cannot do: see "Regenerating Golden + Files" in [engdocs/TESTING.md](engdocs/TESTING.md). +- **Do NOT** use `go build -o bd ./cmd/bd`, `go install ./cmd/bd`, or raw + `go run ./cmd/bd ...`: they bypass the canonical build path, leave stale + binaries, and raw `go run` misses the `gms_pure_go` tag. Use `make install`, + `./bd`, or `go run -tags gms_pure_go ./cmd/bd ...`. +- All new features need tests. +- **Never pollute a production database with test issues.** Use `t.TempDir()` + in Go tests and a disposable working directory for manual `bd` experiments. +- `make ci-pr-lint` must pass with zero issues; see + [engdocs/LINTING.md](engdocs/LINTING.md). +- If BUILD files are out of sync and you cannot run `make bazel-sync`, CI + syncs them: on same-repo PRs the bazel-autofix workflow pushes the fix to + your branch (pull before pushing again); fork PRs get a comment with an + apply recipe. +- If you changed behavior, update the user docs (`docs/`, via the + `beads-docs` skill) or README in the same PR. -```bash -bd update --claim --json -bd update bd-42 --priority 1 --json -``` +## Commits and PRs -**Complete work:** +- Conventional Commits: `type(scope): summary` (`fix`, `feat`, `docs`, + `test`, `refactor`, `chore`, `ci`, `perf`). +- For agent-prepared commits, include the `Agent-Signature:` trailer described + in [engdocs/AGENT_SIGNING.md](engdocs/AGENT_SIGNING.md). Use + `unknown-model` or `unknown-reasoning` when reliable runtime metadata is + unavailable. +- Maintainers working from the internal ledger may also end the subject with + the bead ID, e.g. `(bd-abc)`, so `bd doctor` can detect orphaned issues. +- Work on a feature branch and open a PR against `main`; direct pushes to + `main` are reserved for releases and narrow operational fixes. +- When the user asks to bump the version, use `./scripts/bump-version.sh`; the + full release process is in [RELEASING.md](RELEASING.md). -```bash -bd close bd-42 --reason "Completed" --json -``` +## Ending a session -### Issue Types +Do not push to `main`. Before handing off: -- `bug` - Something broken -- `feature` - New functionality -- `task` - Work item (tests, docs, refactoring) -- `epic` - Large feature with subtasks -- `chore` - Maintenance (dependencies, tooling) +1. Run the quality gates your change needs (`make test`, `make ci-pr-lint`, + and the other Bazel lanes [engdocs/TESTING.md](engdocs/TESTING.md) + selects). If gates are broken on `main`, report it as a P0 issue. +2. Record follow-up work as GitHub issues (or ledger beads, for maintainers). +3. Commit, push, or open a PR only when the person you are working for asked + you to. Report changed files, validation run, and anything left open. -### Priorities +## CLI output -- `0` - Critical (security, data loss, broken builds) -- `1` - High (major features, important bugs) -- `2` - Medium (default, nice-to-have) -- `3` - Low (polish, optimization) -- `4` - Backlog (future ideas) +**NEVER use emoji-style icons** (🔴🟠🟡🔵⚪) in CLI output. **ALWAYS use small +Unicode symbols** with semantic colors: status `○ ◐ ● ✓ ❄`; priority as a +`P0`–`P4` label with color (no status glyph). The full visual design system +and CLI design principles are in +[engdocs/UI_PHILOSOPHY.md](engdocs/UI_PHILOSOPHY.md). -### Workflow for AI Agents +## Non-interactive shell commands -1. **Check ready work**: `bd ready` shows unblocked issues -2. **Claim your task atomically**: `bd update --claim` -3. **Work on it**: Implement, test, document -4. **Discover new work?** Create linked issue: - - `bd create "Found bug" --description="Details about what was found" -p 1 --deps discovered-from:` -5. **Complete**: `bd close --reason "Done"` +Agents cannot answer prompts. Use `cp -f`, `mv -f`, `rm -f`, `rm -rf`, +`cp -rf` (these may be aliased to `-i`); `scp`/`ssh -o BatchMode=yes`; +`apt-get -y`; `HOMEBREW_NO_AUTO_UPDATE=1 brew`. **DO NOT use `bd edit`** — it +opens `$EDITOR`; use `bd update --title/--description/--design/--acceptance/--append-notes` +(pipe text with special characters via `--description=-`). -### Quality -- Use `--acceptance` and `--design` fields when creating issues -- Use `--validate` to check description completeness +## Routing table -### Lifecycle -- `bd defer ` / `bd supersede ` for issue management -- `bd stale` / `bd orphans` / `bd lint` for hygiene -- `bd human ` to flag for human decisions -- `bd formula list` / `bd mol pour ` for structured workflows - -### Sync - -bd stores issue history in Dolt: - -- Each write auto-commits to Dolt history -- Use `bd dolt push`/`bd dolt pull` for remote sync -- Do not treat `.beads/issues.jsonl` as the sync protocol - -**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. - -### Important Rules - -- ✅ Use bd for ALL task tracking -- ✅ Always use `--json` flag for programmatic use -- ✅ Link discovered work with `discovered-from` dependencies -- ✅ Check `bd ready` before asking "what should I work on?" -- ❌ Do NOT create markdown TODO lists -- ❌ Do NOT use external issue trackers -- ❌ Do NOT duplicate tracking systems - -For more details, see README.md and https://github.com/gastownhall/beads/blob/main/docs/getting-started/quickstart.md. - -## Agent Context Profiles - -The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions. - -- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands. -- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise. -- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins. - -## Session Completion - -This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions. - -1. **File issues for remaining work** - Create beads for anything that needs follow-up -2. **Run quality gates** (if code changed) - Tests, linters, builds -3. **Update issue status** - Close finished work, update in-progress items -4. **Handle git/sync by active profile**: - ```bash - # Conservative/minimal/default: report status and proposed commands; wait for approval. - git status - - # Team-maintainer opt-in only, unless current instructions forbid it: - git pull --rebase - bd dolt push - git push - git status - ``` -5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step - -**Critical rules:** -- Explicit user or orchestrator instructions override this Beads block. -- Do not commit or push without clear authority from the active profile or the current user request. -- If a required sync or push is blocked, stop and report the exact command and error. - - +| When you are touching… | Read first | +|---|---| +| `cmd/bd/` (commands, output, proxied-server routes) | [cmd/bd/AGENTS.md](cmd/bd/AGENTS.md) | +| `engdocs/` (contributor and internals docs) | [engdocs/AGENTS.md](engdocs/AGENTS.md) | +| `docs/` (the published user docs) | `.claude/skills/beads-docs/SKILL.md` | +| Any Go test | [engdocs/TESTING.md](engdocs/TESTING.md) | +| Lint failures or `.golangci.yml` | [engdocs/LINTING.md](engdocs/LINTING.md) | +| A new storage operation or issueops role | [engdocs/ADDING_AN_ISSUEOPS_ROLE.md](engdocs/ADDING_AN_ISSUEOPS_ROLE.md) | +| Schema migrations | [internal/storage/schema/migrations/README.md](internal/storage/schema/migrations/README.md) | +| Dolt concurrency, server vs embedded mode | [engdocs/design/dolt-concurrency.md](engdocs/design/dolt-concurrency.md) | +| Errors returned to users | [engdocs/ERROR_HANDLING.md](engdocs/ERROR_HANDLING.md) | +| The `bd serve` HTTP surface | [engdocs/SERVE_RUNBOOK.md](engdocs/SERVE_RUNBOOK.md) | +| A new example under `examples/` | `examples/README.md` — give the example its own README and link it there | +| Releases and version bumps | [RELEASING.md](RELEASING.md) | +| Scope questions | [engdocs/PROJECT_CHARTER.md](engdocs/PROJECT_CHARTER.md) | +| Planned work and priorities | [ROADMAP.md](ROADMAP.md) | diff --git a/AGENT_INSTRUCTIONS.md b/AGENT_INSTRUCTIONS.md index 3afc356e7..b00961736 100644 --- a/AGENT_INSTRUCTIONS.md +++ b/AGENT_INSTRUCTIONS.md @@ -1,537 +1,9 @@ -# Detailed Agent Instructions for Beads Development +# Agent Instructions -**For project overview and quick start, see [AGENTS.md](AGENTS.md)** +Contributor instructions for agents developing beads live in +[AGENTS.md](AGENTS.md). Area-specific rules live in nested `AGENTS.md` files +listed in its routing table. -This document contains detailed operational instructions for AI agents working on beads development, testing, and releases. - -## Development Guidelines - -### Code Standards - -- **Go version**: see `go.mod` for the required version (currently 1.26+) -- **Linting**: `make ci-pr-lint` must pass with zero issues; see - [engdocs/LINTING.md](engdocs/LINTING.md) -- **Testing**: All new features need tests; use [engdocs/TESTING.md](engdocs/TESTING.md) for command selection, test design, and PR readiness. -- **Documentation**: Update relevant .md files - -### File Organization - -``` -beads/ -├── cmd/bd/ # CLI commands -├── internal/ -│ ├── types/ # Core data types -│ └── storage/ # Storage layer -│ └── dolt/ # Dolt implementation -├── examples/ # Integration examples -└── *.md # Documentation -``` - -### Testing Workflow - -**IMPORTANT:** Never pollute the production database with test issues! - -For test commands, tier selection, and test-design guidance, use the canonical -[engdocs/TESTING.md](engdocs/TESTING.md). - -**For manual testing**, keep initialization and all experiments in a disposable -working directory. This safety example supplements the canonical testing guide: - -```bash -beads_manual_dir="$(mktemp -d)" -( - set -e - cd "$beads_manual_dir" - bd init --quiet --prefix test --skip-hooks --skip-agents - bd create "Test issue" -p 1 -) -rm -rf -- "$beads_manual_dir" -``` - -`BEADS_DB` alone does not redirect `bd init` workspace setup. Do not run manual -initialization from a production workspace even when selecting another database. - -**For automated tests**, use `t.TempDir()` in Go tests: - -```go -func TestMyFeature(t *testing.T) { - tmpDir := t.TempDir() - testDB := filepath.Join(tmpDir, ".beads", "beads.db") - s := newTestStore(t, testDB) - // ... test code -} -``` - -**Git test isolation:** For tests that create temporary git repos, force repo-local hooks: - -```bash -git config core.hooksPath .git/hooks -``` - -Do not rely on the developer's global git config. Global `core.hooksPath` can leak -into temp repos and produce flaky test behavior. - -**Warning:** bd will warn you when creating issues with a "Test" prefix in the -production database. The disposable working directory is the isolation -boundary for manual initialization and experiments. - -**Tmpfs hosts:** the `cmd/bd` test suite creates an isolated `$HOME` and several -test binaries under `$TMPDIR`. They are normally cleaned by the test process, -but a SIGKILLed or OOMed run can leave orphans behind. On hosts where `/tmp` -is tmpfs (e.g. Fedora Atomic / Bluefin), run `make clean-test-tmp` between -test runs if `du -sh /tmp/beads-* /tmp/bd-*` shows accumulation. See bd-3q2u. - -### Before Committing - -1. **Run tests**: follow [engdocs/TESTING.md](engdocs/TESTING.md). -2. **Run the required lint contract when its code surface changed**: - `make ci-pr-lint` -3. **Update docs**: If you changed behavior, update README.md or other docs -4. **Sync Bazel BUILD files** if you added, removed or renamed Go files, or - changed imports or `go.mod`: `make bazel-sync` (needs Bazel), then commit - the BUILD.bazel / MODULE.bazel changes. Without Bazel, let CI do it: on - same-repo PRs the bazel-autofix workflow pushes the fix for the packages - your PR changed to your branch (pull before pushing again); fork PRs get - a comment with an apply recipe. -5. **Commit**: With git hooks installed (`bd hooks install`), Dolt changes are auto-committed - -### Commit Message Convention - -When committing work for an issue, include the issue ID in parentheses at the end: - -```bash -git commit -m "Fix auth validation bug (bd-abc)" -git commit -m "Add retry logic for database locks (bd-xyz)" -``` - -This enables `bd doctor` to detect **orphaned issues** - work that was committed but the issue wasn't closed. The doctor check cross-references open issues against git history to find these orphans. - -For agent-prepared commits, also include the -`Agent-Signature:` trailer described in -[engdocs/AGENT_SIGNING.md](engdocs/AGENT_SIGNING.md). Use `unknown-model` or -`unknown-reasoning` when reliable runtime metadata is unavailable. - -### Git Workflow - -bd uses **Dolt** as its primary database. Changes are committed to Dolt history automatically (one Dolt commit per write command). - -**Install git hooks** for commit integration and legacy fallback behavior: -```bash -bd hooks install -``` - -### Git Integration - -**Dolt sync**: Dolt handles sync natively via `bd dolt push` / `bd dolt pull`. No export/import round-trip needed for normal sync. - -**Protected branches**: Dolt stores data under `refs/dolt/data`, separate from standard Git refs. See [docs/reference/protected-branches.md](docs/reference/protected-branches.md). - -**Git worktrees**: Work directly with Dolt — no special flags needed. See [docs/reference/advanced.md](docs/reference/advanced.md). - -**Merge conflicts**: Rare with hash IDs. Dolt uses cell-level 3-way merge for conflict resolution. - -## Git Workflow: PR by Default - -Crew workers use a PR-based workflow. Beads is a dependency of a downstream consumer, so we -defer to the standard PR flow to keep changes reviewable. - -- Work on a feature branch, push the branch, open a PR against `main` -- `gh pr create` is the normal path to land work -- Direct push to main is reserved for releases (tag + release commit) and - narrow operational fixes; prefer a PR when unsure -- When handling external contributor PRs, use fix-merge: checkout the PR - branch locally, fix/rebase onto main, merge via PR, then close the PR - -### Maintainer PR Guidelines - -Before triaging, reviewing, landing, closing, or otherwise maintaining PRs, -read [PR_MAINTAINER_GUIDELINES.md](PR_MAINTAINER_GUIDELINES.md). The -maintainer policy is to maximize community throughput: find useful contributor -value, absorb or transform it locally when practical, preserve attribution, and -use request-changes only as a last resort. - -Sign agent-written GitHub comments and reviews using -[engdocs/AGENT_SIGNING.md](engdocs/AGENT_SIGNING.md). - -### External Contributor PRs: Check Before You Build - -**Read [CONTRIBUTING.md](CONTRIBUTING.md)** — it contains promises we've made to contributors. Violating them damages trust and community. - -Run the read-only preflight before implementing related work, opening a PR, or -merging/closing a PR: - -```bash -scripts/pr-preflight.sh --search "" --repo gastownhall/beads -scripts/pr-preflight.sh --repo gastownhall/beads -``` - -**Before implementing any feature or fix, check for existing open PRs on the same topic:** - -```bash -gh pr list --repo gastownhall/beads --state open --search "" --json number,title,author,headRefName -``` - -**Contributor work gets priority.** If an external PR already exists: -1. **Review it first** — read the diff, understand the approach -2. **Build on their work, don't rewrite it** — checkout their branch, fix/adapt as needed -3. **Preserve their tests** — contributor tests are signal; keep them unless they're wrong -4. **Attribute properly** — use `Co-authored-by:` in commits, reference their PR number -5. **Never auto-close a contributor PR** by merging a rewrite — that discards their contribution silently - -If you must rewrite (e.g., fundamentally different approach needed), explain why on the original PR and credit the contributor's design/tests in your commits. - -Do not rely on auto-discovery of CONTRIBUTING.md; the preflight is the agent -gate for PR handling. - -## Landing the Plane - -See [AGENTS.md](AGENTS.md#landing-the-plane-session-completion) for the -canonical session-completion protocol (quality gates, mandatory `git push`, -cleanup, and next-session hand-off). - -## Agent Session Workflow - -**WARNING: DO NOT use `bd edit`** - it opens an interactive editor ($EDITOR) which AI agents cannot use. Use `bd update` with flags instead: -```bash -bd update --description "new description" -bd update --title "new title" -bd update --design "design notes" -bd update --append-notes "additional notes" # --notes replaces existing notes and requires --force once notes are set -bd update --acceptance "acceptance criteria" -``` - -**Read execution metadata before prose.** When enacting a bd issue, inspect the -structured metadata before using description or notes to choose execution mode, -delegation, model, reasoning level, or parallel group: - -```bash -bd show --json | jq '.[0] | {id,title,metadata,description,notes}' -``` - -The execution metadata keys are: - -- `execution_agent_type` -- `execution_suggested_model` -- `execution_reasoning_effort` -- `execution_mode` -- `execution_parallel_group` - -When these keys are present, treat them as the authoritative execution hints. -Use `description` for the work scope and `notes` for rationale or fallback -context. Parent/orchestrator agents must read these fields before spawning -subagents because a running subagent cannot change its model or reasoning effort -after launch. - -**Use stdin for descriptions with special characters** (backticks, `!`, nested quotes): -```bash -# Pipe via stdin to avoid shell escaping issues -echo 'Description with `backticks` and "quotes"' | bd create "Title" --stdin -echo 'Updated description with $variables' | bd update --description=- - -# Or use --body-file for longer content -bd create "Title" --body-file=description.md -``` - -**GitHub body hygiene.** For GitHub PR, issue, comment, and review bodies, -write Markdown to a file and pass it with `gh ... --body-file`. Run -`scripts/gh-body-lint ` first to catch literal `\n` sequences and -non-linking `GH#123` references. - -**Example agent session:** - -```bash -# Make changes (each write auto-commits to Dolt) -bd create "Fix bug" -p 1 -bd create "Add tests" -p 1 -bd update bd-42 --claim -bd close bd-40 --reason "Completed" - -# Push Dolt data to remote if configured -bd dolt push - -# Now safe to end session -``` - -This installs: - -- **pre-commit** — Commits pending Dolt changes -- **post-merge** — Runs chained hooks and a legacy JSONL import fallback only when no Dolt remote is configured - -**Note:** Hooks are embedded in the bd binary and work for all bd users (not just source repo users). - -## Common Development Tasks - -### Visual Design System - -When adding CLI output features, follow these design principles for consistent, -cognitively friendly visuals. - -#### No Emoji-Style Icons - -Do not use large colored emoji icons like red/orange/yellow/blue/white circles -for priorities or status. They cause cognitive overload and break visual -consistency. - -Use small Unicode symbols with semantic colors applied via lipgloss: - -- Status: `○ ◐ ● ✓ ❄` -- Priority: `P0`–`P4` label with color (no status glyph) - -#### Status Icons - -Use these symbols consistently across all commands: - -```text -○ open - Available to work (white/default) -◐ in_progress - Currently being worked (yellow) -● blocked - Waiting on dependencies (red) -✓ closed - Completed (muted gray) -❄ deferred - Scheduled for later (blue/muted) -``` - -#### Priority Labels and Colors - -Format priority as the P-label with color only (no status glyph — `●` is blocked status): - -- `P0`: Red + bold (critical) -- `P1`: Orange (high) -- `P2`: Amber (elevated) -- `P3`–`P4`: Default text - -#### Issue Type Colors - -- `bug`: Red (problems need attention) -- `epic`: Purple (larger scope) -- Others: Default text - -#### Design Principles - -1. Small Unicode symbols only; avoid emoji blobs. -2. Semantic colors only for actionable items; do not color everything. -3. Closed items fade using muted gray. -4. Prefer icons over text labels for scanability. -5. Keep icons consistent across list, graph, show, and related commands. -6. Use tree connectors (`├──`, `└──`, `│`) for hierarchies. -7. Reduce cognitive noise; do not show `needs:1` when it is just the parent epic. - -#### Semantic Styles - -Use exported styles from `internal/ui/styles.go`: - -```go -// Status styles -ui.StatusInProgressStyle // Yellow - active work -ui.StatusBlockedStyle // Red - needs attention -ui.StatusClosedStyle // Muted gray - done - -// Priority styles -ui.PriorityP0Style // Red + bold -ui.PriorityP1Style // Orange - -// Type styles -ui.TypeBugStyle // Red -ui.TypeEpicStyle // Purple - -// General styles -ui.PassStyle, ui.WarnStyle, ui.FailStyle -ui.MutedStyle, ui.AccentStyle -ui.RenderMuted(text), ui.RenderAccent(text) -``` - -Example: - -```go -switch issue.Status { -case types.StatusOpen: - icon = "○" -case types.StatusInProgress: - icon = ui.StatusInProgressStyle.Render("◐") -case types.StatusBlocked: - icon = ui.StatusBlockedStyle.Render("●") -case types.StatusClosed: - icon = ui.StatusClosedStyle.Render("✓") -} -``` - -### CLI Design Principles - -**Minimize cognitive overload.** Every new command, flag, or option adds cognitive burden for users. Before adding anything: - -1. **Recovery/fix operations → `bd doctor --fix`**: Don't create separate commands like `bd recover` or `bd repair`. Doctor already detects problems - let `--fix` handle remediation. This keeps all health-related operations in one discoverable place. - For git hook marker migration specifically: use `bd migrate hooks --dry-run` to preview operations, and `bd doctor --fix` for the standard apply path. - -2. **Prefer flags on existing commands**: Before creating a new command, ask: "Can this be a flag on an existing command?" Example: `bd list --stale` instead of `bd stale`. - -3. **Consolidate related operations**: Related operations should live together. Version control uses `bd vc {log,diff,commit}`, not separate top-level commands. - -4. **Count the commands**: Run `bd --help` and count. If we're approaching 30+ commands, we have a discoverability problem. Consider subcommand grouping. - -5. **New commands need strong justification**: A new command should represent a fundamentally different operation, not just a convenience wrapper. - -### Adding a New Command - -1. Create file in `cmd/bd/` -2. Add to root command in `cmd/bd/main.go` -3. Implement with Cobra framework -4. Add `--json` flag for agent use -5. Add tests in `cmd/bd/*_test.go` -6. Document in README.md - -### Adding Storage Features - -1. Add Dolt SQL schema changes in `internal/storage/dolt/` -2. Add migration if needed -3. Update `internal/types/types.go` if new types -4. Implement in `internal/storage/dolt/` (queries, issues, etc.) -5. Add tests -6. Update export/import in `cmd/bd/export.go` and `cmd/bd/import.go` - -### Adding Examples - -1. Create directory in `examples/` -2. Add README.md explaining the example -3. Include working code -4. Link from `examples/README.md` -5. Mention in main README.md - -## Building - -```bash -# Build and install bd to ~/.local/bin (the canonical location) -make install - -# Verify installed binary -bd init --prefix test -bd create "Test issue" -p 1 -bd ready -``` - -For testing commands, test design, and PR-readiness gates, use -[engdocs/TESTING.md](engdocs/TESTING.md). - -> **WARNING**: Do NOT use `go build -o bd ./cmd/bd`, `go install ./cmd/bd`, -> or raw `go run ./cmd/bd ...`. -> These bypass the canonical build path, can create stale binaries in the -> working directory or `~/go/bin/`, and raw `go run` may miss the required -> `gms_pure_go` build tag. Always use `make install`, `./bd`, or -> `go run -tags gms_pure_go ./cmd/bd ...` when you explicitly need `go run`. - -## Version Management - -**IMPORTANT**: When the user asks to "bump the version" or mentions a new version number (e.g., "bump to 0.9.3"), use the version bump script: - -```bash -# Preview changes (shows diff, doesn't commit) -./scripts/bump-version.sh 0.9.3 - -# Auto-commit the version bump -./scripts/bump-version.sh 0.9.3 --commit -git push origin main -``` - -**What it does:** - -- Updates ALL version files (CLI, plugin, MCP server, docs) in one command -- Validates semantic versioning format -- Shows diff preview -- Verifies all versions match after update -- Creates standardized commit message - -**User will typically say:** - -- "Bump to 0.9.3" -- "Update version to 1.0.0" -- "Rev the project to 0.9.4" -- "Increment the version" - -**You should:** - -1. Run `./scripts/bump-version.sh --commit` -2. Push to GitHub -3. Confirm all versions updated correctly - -**Files updated automatically:** - -- `cmd/bd/version.go` - CLI version -- `plugins/beads/.claude-plugin/plugin.json` - Claude plugin version -- `plugins/beads/.codex-plugin/plugin.json` - Codex plugin version -- `.claude-plugin/marketplace.json` - Claude marketplace version -- `integrations/beads-mcp/pyproject.toml` - MCP server version -- `README.md` - Documentation version -- `PLUGIN.md` - Version requirements - -**Why this matters:** We had version mismatches (bd-66) when only `version.go` was updated. This script prevents that by updating all components atomically. - -See `scripts/README.md` for more details. - -## Release Process (Maintainers) - -See [RELEASING.md](RELEASING.md) for the complete release process, including -the automated `./scripts/release.sh ` script and the manual, -step-by-step channel-by-channel instructions. - -## Checking GitHub Issues and PRs - -**IMPORTANT**: When asked to check GitHub issues or PRs, use command-line tools like `gh` instead of browser/playwright tools. - -**Preferred approach:** - -```bash -# List open issues with details -gh issue list --limit 30 - -# List open PRs -gh pr list --limit 30 - -# View specific issue -gh issue view 201 -``` - -**Then provide an in-conversation summary** highlighting: - -- Urgent/critical issues (regressions, bugs, broken builds) -- Common themes or patterns -- Feature requests with high engagement -- Items that need immediate attention - -**Why this matters:** - -- Browser tools consume more tokens and are slower -- CLI summaries are easier to scan and discuss -- Keeps the conversation focused and efficient -- Better for quick triage and prioritization - -**Do NOT use:** `browser_navigate`, `browser_snapshot`, or other playwright tools for GitHub PR/issue reviews unless specifically requested by the user. - -## Telemetry - -`bd` collects anonymous command-usage metrics. Each event is a `cli_command` -record carrying only the command name; each batch also carries the bd version -and OS platform, keyed by a machine-derived, HMAC-protected distinct ID. No -email, repo path, remote URL, issue content, or user-supplied strings are -collected. Events are written under `~/.beads/eventsData` and POSTed to -`https://gastownhall-eventsapi.com/mp/collect`. - -Metrics are enabled by default (opt-out). The friendliest way to see or change -them is `bd metrics` (`bd metrics on` / `bd metrics off` / `bd metrics example`), -which takes effect on the next command with no restart. `BD_DISABLE_METRICS=1` -still works as a one-off, shell-scoped override. The cross-tool -[`DO_NOT_TRACK`](https://donottrack.sh/) standard is honored as a disable-only -opt-out: `DO_NOT_TRACK=1` opts out, while a falsey or empty value -(`DO_NOT_TRACK=0`, `false`, or unset-but-present) falls through to your saved -`bd metrics` preference instead of forcing metrics back on. `BD_DISABLE_METRICS` -is the bidirectional override and takes precedence when both are set. - -## Questions? - -- Check existing issues: `bd list` -- Look at recent commits: `git log --oneline -20` -- Read the docs: README.md, ADVANCED.md, docs/reference/configuration.md -- Create an issue if unsure: `bd create "Question: ..." -t task -p 2` - -## Important Files - -- **README.md** - Main documentation (keep this updated!) -- **ADVANCED.md** - Advanced features (rename, merge, compaction) -- **CONTRIBUTING.md** - Contribution guidelines -- **SECURITY.md** - Security policy +If you are using `bd` to track work in your own project, see the user docs: +[IDE and agent setup](docs/getting-started/ide-setup.md) and +[https://beads.gascity.com/](https://beads.gascity.com/). diff --git a/BUILD.bazel b/BUILD.bazel index 077a16413..0a1d10355 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -8,15 +8,23 @@ load("@rules_go//go:def.bzl", "go_library", "go_test") # out of every build except --config=integration (.bazelrc), which sets the tag. # gazelle:build_tags gms_pure_go,integration # integrations/ holds no Go; it stays visible to Bazel (not in .bazelignore) -# only so //test/docsync can declare the markdown its link checks resolve. +# so //:repo_files covers it for //test/docsync's link checks and the +# repository-policy tests in //scripts. # gazelle:exclude integrations +# The two example Go modules (own go.mod, built against a released beads) are +# not part of this build either, but they are tracked files the repository +# guards (gofmt, build-tag and install-guidance checks in +# //scripts/repochecks) must see, so they are not in .bazelignore. +# gazelle:exclude examples/library-usage +# gazelle:exclude examples/bd-example-extension-go gazelle(name = "gazelle") exports_files( [".buildflags"], visibility = [ - "//scripts/pr-lint:__pkg__", + "//scripts:__pkg__", "//scripts/prlintmake:__pkg__", + "//tests/upgrade_smoke:__pkg__", ], ) @@ -25,6 +33,17 @@ exports_files([ "go.sum", ]) +# The golangci-lint configuration nogo applies (//tools/nogo), and its test. +# //test/docsync checks the agent instructions' links to it. +exports_files( + [".golangci.yml"], + visibility = [ + "//test/docsync:__pkg__", + "//tools/nogo:__pkg__", + "//tools/nogo/internal/golangci:__pkg__", + ], +) + # Repository files read by source-scanning tests, declared as their `data` so # the tests run under `bazel test` and remote execution. exports_files( @@ -32,22 +51,67 @@ exports_files( visibility = ["//scripts/gitattributespolicy:__pkg__"], ) -# //scripts:scripts_test checks the pinned golangci-lint version/sha256 in -# engdocs/LINTING.md and the pre-commit hook's separate `go run` pin against -# scripts/ci/install-golangci-lint.sh, so both must be readable as data. +# //tests/hook_timeout_backends: the tracked git hooks whose managed section +# it runs against real timeout implementations. //scripts:shell_scripts_test +# runs pre-push's suite dispatch. exports_files( [ - "engdocs/LINTING.md", + ".githooks/post-checkout", + ".githooks/post-merge", ".githooks/pre-commit", + ".githooks/pre-push", + ".githooks/prepare-commit-msg", + ], + visibility = [ + "//scripts:__pkg__", + "//tests/hook_timeout_backends:__pkg__", + ], +) + +# //scripts:shell_scripts_test: scripts/test.sh's skip list. +exports_files( + [".test-skip"], + visibility = ["//scripts:__pkg__"], +) + +# //scripts:shell_scripts_test: Oracle A's runner, whose EXIT-trap removal of +# its reference worktree oracle_a_script_test.go checks in a fixture repository. +exports_files( + ["tests/oracle-a/run-oracle-a.sh"], + visibility = ["//scripts:__pkg__"], +) + +# The nested Go modules' go.mod files, which mark where the root module ends: +# //scripts:go_test_sources_test's scan of every _test.go file skips their +# trees, as `go test ./...` does. (go.mod is in no Go partition below: it is +# in //:repo_other_files.) +filegroup( + name = "nested_go_modules", + srcs = [ + "examples/bd-example-extension-go/go.mod", + "examples/library-usage/go.mod", + "//tools/nogo:go.mod", ], visibility = ["//scripts:__pkg__"], ) -# //scripts:scripts_test keeps pr.yml's release-target cross-compilation matrix -# in lockstep with the release targets .goreleaser.yml declares. +# //scripts/repochecks:winget_portable_alias_test: the winget manifests. +filegroup( + name = "winget_manifests", + srcs = glob(["winget/**"]), + visibility = ["//scripts/repochecks:__pkg__"], +) + +# //test/docsync: the repository files outside its Markdown and Go-test +# partitions that the docs and agent instructions link to by path. A new link +# to a file not listed here fails docsync_test under Bazel; add the file. exports_files( - [".goreleaser.yml"], - visibility = ["//scripts:__pkg__"], + [ + ".github/workflows/bazel.yml", + "beads.go", + "docs/docs.json", + ], + visibility = ["//test/docsync:__pkg__"], ) # //cmd/bd:bd_test: tracked git hooks (generator parity) and the formula @@ -66,42 +130,15 @@ exports_files( visibility = ["//cmd/bd/setup:__pkg__"], ) -# //test/docsync: the Mintlify site, engdocs, root markdown, and the files -# outside those trees that their local links point at. -# -# The out-of-tree link targets are hand-listed: a new docs/engdocs link to a -# file outside these globs passes `go test` but fails under Bazel until the -# target is added here. The globs stop at package boundaries, so no BUILD file -# may live under docs/ or engdocs/ (enforced by scripts/bazel_policy_test.go). -filegroup( - name = "docsync_files", - srcs = glob([ - "*.md", - "docs/**", - "engdocs/**", - ]) + [ - "integrations/beads-mcp/PYPI.md", - "//scripts:README.md", - ], - visibility = ["//test/docsync:__pkg__"], -) - -# //scripts:scripts_test workflow-policy and CI-script tests: the whole -# .github tree (workflows, composite actions, CI helper scripts) they parse -# and run. The one whole-tree input the plan allows (it is small). -filegroup( - name = "workflow_files", - srcs = glob([".github/**"]), - visibility = ["//scripts:__pkg__"], -) - # PR Risk's manifest-sharded tiers' shard scripts and their committed # manifests (embedded-Dolt cmd and storage, proxied-server cmd, server-Dolt -# storage). The variants (//cmd/bd:bd_embedded_test, //cmd/bd:bd_proxied_test, +# storage). The variants (//cmd/bd:bd_embedded_test and +# //cmd/bd:bd_embedded_part2_test, //cmd/bd:bd_proxied_test, # //internal/storage/embeddeddolt:embeddeddolt_embedded_test, # //internal/storage/dolt:dolt_server_full_test) run them through # tools/bazel/go_test_manifest_shard.sh, so each Bazel shard runs exactly the -# tests of the CI job with the same shard number. +# tests of the CI job with the same shard number. //scripts:go_test_sources_test +# checks the manifests and scripts against the tests they shard. exports_files( [ ".github/scripts/embedded-cmd-test-shards.txt", @@ -117,20 +154,10 @@ exports_files( "//cmd/bd:__pkg__", "//internal/storage/dolt:__pkg__", "//internal/storage/embeddeddolt:__pkg__", + "//scripts:__pkg__", ], ) -# //scripts:scripts_test runs scripts/test.sh, which sources the canonical -# build flags and reads the known-broken-test skip list. -filegroup( - name = "test_sh_files", - srcs = [ - ".buildflags", - ".test-skip", - ], - visibility = ["//scripts:__pkg__"], -) - # //internal/versioncheck and //scripts/check-versions release-gate tests: the # metadata surfaces versioncheck.releaseSources gates, plus the canonical # version it compares them against and the tracked git hooks whose version @@ -139,12 +166,6 @@ filegroup( # Hand-listed rather than globbed because releaseSources is itself a closed # list: a newly gated surface must be added here too, and until it is the test # fails under Bazel (it passes under `go test`, which sees the whole checkout). -# -# The exception is npm-package/package.json: npm-package/ is in .bazelignore, -# so no target can declare it. Listing it anyway passes under remote execution -# but fails in a local sandbox, which is how fork-PR CI runs. -# TestRepositoryReleaseVersionsMatch tolerates exactly its absence under -# Bazel; `go test` still checks it. filegroup( name = "release_metadata_files", srcs = [ @@ -152,6 +173,7 @@ filegroup( "integrations/beads-mcp/pyproject.toml", "integrations/beads-mcp/src/beads_mcp/__init__.py", "integrations/beads-mcp/uv.lock", + "npm-package/package.json", "//cmd/bd:version.go", "//cmd/bd:winres/manifest.xml", "//cmd/bd:winres/winres.json", @@ -165,35 +187,6 @@ filegroup( ], ) -# Inputs of the Bazel policy tests in //scripts (bazel_policy_test.go), so they -# run under `bazel test` as well as `go test`. -filegroup( - name = "bazel_policy_files", - srcs = [ - ".bazelrc", - ".bazelversion", - ".gitignore", - "BUILD.bazel", - "MODULE.bazel", - "go.mod", - ], - visibility = ["//scripts:__pkg__"], -) - -# F3: TestMCPPytestWorkerCountPinned (ci_workflow_test.go) reads the MCP -# package's pytest-xdist pin directly from its manifest and lock file, so it -# runs under `bazel test` as well as `go test`. integrations/beads-mcp has no -# BUILD.bazel of its own (unlike npm-package/, it is not .bazelignore'd), so -# these are ordinary sources under this package. -filegroup( - name = "mcp_package_policy_files", - srcs = [ - "integrations/beads-mcp/pyproject.toml", - "integrations/beads-mcp/uv.lock", - ], - visibility = ["//scripts:__pkg__"], -) - go_library( name = "beads", srcs = [ @@ -250,3 +243,945 @@ go_test( "//issueops", ], ) + +# //internal/httpclient/encode:encode_test regenerates and compares the shipped +# divergence ledger doc (TestDivergenceLedgerDocMatchesLedger), so the doc must +# be readable as data under `bazel test`. docsync_files above globs it too, but +# that filegroup's visibility is scoped to //test/docsync alone. +exports_files( + ["engdocs/design/http-divergence-ledger.md"], + visibility = ["//internal/httpclient/encode:__pkg__"], +) + +# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = ["bazel-*/**"], + ), + visibility = ["//:__subpackages__"], +) + +# --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = [ + "**/node_modules/**", + ".agents/**", + ".amp/**", + ".augment/**", + ".bazelrc.local", + ".claude/*.lock", + ".claude/*.log", + ".claude/settings.local.json", + ".codex/**", + ".cursor/**", + ".direnv/**", + ".envrc", + ".git/**", + ".idea/**", + ".logs/**", + ".vscode/**", + "bazel-*/**", + "bd", + "bd-fixed", + "bd-original", + "bd-test", + "bd_test", + "beads", + "go.work", + "go.work.sum", + "history/**", + "mcp_agent_mail/**", + "npm-package/bin/*.tar.gz", + "npm-package/bin/*.zip", + "npm-package/bin/CHANGELOG.md", + "npm-package/bin/LICENSE", + "npm-package/bin/README.md", + "npm-package/bin/bd", + "npm-package/package-lock.json", + "output", + "result", + "state.json", + "user.bazelrc", + ], + ) + [ + "//backend:repo_doc_files", + "//backend/conformance:repo_doc_files", + "//backend/http:repo_doc_files", + "//backend/http/corpus:repo_doc_files", + "//beadserrors:repo_doc_files", + "//cmd/bd:repo_doc_files", + "//cmd/bd/doctor:repo_doc_files", + "//cmd/bd/doctor/fix:repo_doc_files", + "//cmd/bd/protocol:repo_doc_files", + "//cmd/bd/setup:repo_doc_files", + "//format:repo_doc_files", + "//internal/ado:repo_doc_files", + "//internal/atomicfile:repo_doc_files", + "//internal/audit:repo_doc_files", + "//internal/beads:repo_doc_files", + "//internal/ceiling:repo_doc_files", + "//internal/compact:repo_doc_files", + "//internal/config:repo_doc_files", + "//internal/configfile:repo_doc_files", + "//internal/creds:repo_doc_files", + "//internal/debug:repo_doc_files", + "//internal/doltremote:repo_doc_files", + "//internal/doltserver:repo_doc_files", + "//internal/doltversion:repo_doc_files", + "//internal/eventsjournal:repo_doc_files", + "//internal/execenv:repo_doc_files", + "//internal/fdhygiene:repo_doc_files", + "//internal/formula:repo_doc_files", + "//internal/formula/cmd/schemagen:repo_doc_files", + "//internal/formula/schemagen:repo_doc_files", + "//internal/git:repo_doc_files", + "//internal/gitenv:repo_doc_files", + "//internal/githooksenv:repo_doc_files", + "//internal/github:repo_doc_files", + "//internal/gitignore:repo_doc_files", + "//internal/gitlab:repo_doc_files", + "//internal/gittraceenv:repo_doc_files", + "//internal/hooks:repo_doc_files", + "//internal/httpapi:repo_doc_files", + "//internal/httpapi/apigen:repo_doc_files", + "//internal/httpapi/spec:repo_doc_files", + "//internal/httpapi/wireshape:repo_doc_files", + "//internal/httpapi/wireshape/cmd/gendigest:repo_doc_files", + "//internal/httpclient:repo_doc_files", + "//internal/httpclient/encode:repo_doc_files", + "//internal/httpclient/wire:repo_doc_files", + "//internal/idgen:repo_doc_files", + "//internal/initprocs:repo_doc_files", + "//internal/jira:repo_doc_files", + "//internal/linear:repo_doc_files", + "//internal/lockfile:repo_doc_files", + "//internal/memoryapi:repo_doc_files", + "//internal/metrics:repo_doc_files", + "//internal/migration:repo_doc_files", + "//internal/migration/legacysqlite:repo_doc_files", + "//internal/molecules:repo_doc_files", + "//internal/notion:repo_doc_files", + "//internal/procid:repo_doc_files", + "//internal/query:repo_doc_files", + "//internal/recipes:repo_doc_files", + "//internal/remotecache:repo_doc_files", + "//internal/routing:repo_doc_files", + "//internal/storage:repo_doc_files", + "//internal/storage/backendnames:repo_doc_files", + "//internal/storage/backends:repo_doc_files", + "//internal/storage/batchbench:repo_doc_files", + "//internal/storage/batchfixtures:repo_doc_files", + "//internal/storage/contextinfo:repo_doc_files", + "//internal/storage/createbatchequiv:repo_doc_files", + "//internal/storage/dberrors:repo_doc_files", + "//internal/storage/dbproxy/identity:repo_doc_files", + "//internal/storage/dbproxy/pidfile:repo_doc_files", + "//internal/storage/dbproxy/proxy:repo_doc_files", + "//internal/storage/dbproxy/server:repo_doc_files", + "//internal/storage/dbproxy/util:repo_doc_files", + "//internal/storage/depid:repo_doc_files", + "//internal/storage/dolt:repo_doc_files", + "//internal/storage/doltutil:repo_doc_files", + "//internal/storage/domain:repo_doc_files", + "//internal/storage/domain/db:repo_doc_files", + "//internal/storage/domain/fs:repo_doc_files", + "//internal/storage/domain/git:repo_doc_files", + "//internal/storage/embeddeddolt:repo_doc_files", + "//internal/storage/embeddeddolt/cmd:repo_doc_files", + "//internal/storage/externaldeps:repo_doc_files", + "//internal/storage/fs:repo_doc_files", + "//internal/storage/git:repo_doc_files", + "//internal/storage/historyoffequiv:repo_doc_files", + "//internal/storage/issueops:repo_doc_files", + "//internal/storage/journalscan:repo_doc_files", + "//internal/storage/kvkeys:repo_doc_files", + "//internal/storage/memoryops:repo_doc_files", + "//internal/storage/rowid:repo_doc_files", + "//internal/storage/schema:repo_doc_files", + "//internal/storage/sqlbuild:repo_doc_files", + "//internal/storage/sqlclass:repo_doc_files", + "//internal/storage/sqlcount:repo_doc_files", + "//internal/storage/storagecontract:repo_doc_files", + "//internal/storage/unsupportedgen:repo_doc_files", + "//internal/storage/uow:repo_doc_files", + "//internal/storage/versioncontrolops:repo_doc_files", + "//internal/telemetry:repo_doc_files", + "//internal/templates:repo_doc_files", + "//internal/templates/agents:repo_doc_files", + "//internal/testutil:repo_doc_files", + "//internal/testutil/bazeltest:repo_doc_files", + "//internal/testutil/credentialcmd:repo_doc_files", + "//internal/testutil/fixtures:repo_doc_files", + "//internal/testutil/integration:repo_doc_files", + "//internal/timeparsing:repo_doc_files", + "//internal/tracker:repo_doc_files", + "//internal/tracker/conformance:repo_doc_files", + "//internal/types:repo_doc_files", + "//internal/ui:repo_doc_files", + "//internal/uimd:repo_doc_files", + "//internal/utils:repo_doc_files", + "//internal/validation:repo_doc_files", + "//internal/versioncheck:repo_doc_files", + "//internal/versionedhistory:repo_doc_files", + "//internal/workapi:repo_doc_files", + "//internal/workapi/storecounter:repo_doc_files", + "//internal/workapi/storequerier:repo_doc_files", + "//internal/workapi/storereader:repo_doc_files", + "//internal/workapi/storereadycounter:repo_doc_files", + "//internal/workapi/storestats:repo_doc_files", + "//internal/workapi/storeversionreconciler:repo_doc_files", + "//internal/workapi/storeworkspaceconfig:repo_doc_files", + "//internal/workspacegate:repo_doc_files", + "//internal/worktreeremove:repo_doc_files", + "//issueops:repo_doc_files", + "//journalops:repo_doc_files", + "//memoryops:repo_doc_files", + "//platforms:repo_doc_files", + "//plugins/beads:repo_doc_files", + "//schema:repo_doc_files", + "//scripts:repo_doc_files", + "//scripts/bench-ready-indexes:repo_doc_files", + "//scripts/check-versions:repo_doc_files", + "//scripts/checkworkflowtags:repo_doc_files", + "//scripts/gitattributespolicy:repo_doc_files", + "//scripts/internal/testbash:repo_doc_files", + "//scripts/migration-test/catalog:repo_doc_files", + "//scripts/pr-lint:repo_doc_files", + "//scripts/prlintmake:repo_doc_files", + "//scripts/repochecks:repo_doc_files", + "//scripts/repro-dolt-hang:repo_doc_files", + "//scripts/repro-dolt-prod-timeouts:repo_doc_files", + "//scripts/workflowtags:repo_doc_files", + "//test/conformance:repo_doc_files", + "//test/docsync:repo_doc_files", + "//test/embedder:repo_doc_files", + "//test/testmainconvention:repo_doc_files", + "//tests/hook_timeout_backends:repo_doc_files", + "//tests/migration:repo_doc_files", + "//tests/regression:repo_doc_files", + "//tests/upgrade_smoke:repo_doc_files", + "//third_party/cc_toolchain:repo_doc_files", + "//third_party/patches:repo_doc_files", + "//tools/bazel:repo_doc_files", + "//tools/docsmint:repo_doc_files", + "//tools/nogo:repo_doc_files", + "//tools/nogo/analyzers/depguard:repo_doc_files", + "//tools/nogo/analyzers/errcheck:repo_doc_files", + "//tools/nogo/analyzers/forbidigo:repo_doc_files", + "//tools/nogo/analyzers/gosec:repo_doc_files", + "//tools/nogo/analyzers/misspell:repo_doc_files", + "//tools/nogo/analyzers/sloglint:repo_doc_files", + "//tools/nogo/analyzers/unconvert:repo_doc_files", + "//tools/nogo/analyzers/unparam:repo_doc_files", + "//tools/nogo/internal/analyzertest:repo_doc_files", + "//tools/nogo/internal/golangci:repo_doc_files", + "//tools/nogo/internal/position:repo_doc_files", + ], + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_files", + srcs = [ + ":repo_doc_files", + ":repo_go_srcs", + ":repo_go_test_srcs", + ":repo_other_files", + ], + visibility = [ + "//scripts:__pkg__", + "//scripts/repochecks:__pkg__", + ], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ".agents/**", + ".amp/**", + ".augment/**", + ".bazelrc.local", + ".claude/*.lock", + ".claude/*.log", + ".claude/settings.local.json", + ".codex/**", + ".cursor/**", + ".direnv/**", + ".envrc", + ".git/**", + ".idea/**", + ".logs/**", + ".vscode/**", + "bazel-*/**", + "bd", + "bd-fixed", + "bd-original", + "bd-test", + "bd_test", + "beads", + "go.work", + "go.work.sum", + "history/**", + "mcp_agent_mail/**", + "npm-package/bin/*.tar.gz", + "npm-package/bin/*.zip", + "npm-package/bin/CHANGELOG.md", + "npm-package/bin/LICENSE", + "npm-package/bin/README.md", + "npm-package/bin/bd", + "npm-package/package-lock.json", + "output", + "result", + "state.json", + "user.bazelrc", + ], + ) + [ + "//backend:repo_go_srcs", + "//backend/conformance:repo_go_srcs", + "//backend/http:repo_go_srcs", + "//backend/http/corpus:repo_go_srcs", + "//beadserrors:repo_go_srcs", + "//cmd/bd:repo_go_srcs", + "//cmd/bd/doctor:repo_go_srcs", + "//cmd/bd/doctor/fix:repo_go_srcs", + "//cmd/bd/protocol:repo_go_srcs", + "//cmd/bd/setup:repo_go_srcs", + "//format:repo_go_srcs", + "//internal/ado:repo_go_srcs", + "//internal/atomicfile:repo_go_srcs", + "//internal/audit:repo_go_srcs", + "//internal/beads:repo_go_srcs", + "//internal/ceiling:repo_go_srcs", + "//internal/compact:repo_go_srcs", + "//internal/config:repo_go_srcs", + "//internal/configfile:repo_go_srcs", + "//internal/creds:repo_go_srcs", + "//internal/debug:repo_go_srcs", + "//internal/doltremote:repo_go_srcs", + "//internal/doltserver:repo_go_srcs", + "//internal/doltversion:repo_go_srcs", + "//internal/eventsjournal:repo_go_srcs", + "//internal/execenv:repo_go_srcs", + "//internal/fdhygiene:repo_go_srcs", + "//internal/formula:repo_go_srcs", + "//internal/formula/cmd/schemagen:repo_go_srcs", + "//internal/formula/schemagen:repo_go_srcs", + "//internal/git:repo_go_srcs", + "//internal/gitenv:repo_go_srcs", + "//internal/githooksenv:repo_go_srcs", + "//internal/github:repo_go_srcs", + "//internal/gitignore:repo_go_srcs", + "//internal/gitlab:repo_go_srcs", + "//internal/gittraceenv:repo_go_srcs", + "//internal/hooks:repo_go_srcs", + "//internal/httpapi:repo_go_srcs", + "//internal/httpapi/apigen:repo_go_srcs", + "//internal/httpapi/spec:repo_go_srcs", + "//internal/httpapi/wireshape:repo_go_srcs", + "//internal/httpapi/wireshape/cmd/gendigest:repo_go_srcs", + "//internal/httpclient:repo_go_srcs", + "//internal/httpclient/encode:repo_go_srcs", + "//internal/httpclient/wire:repo_go_srcs", + "//internal/idgen:repo_go_srcs", + "//internal/initprocs:repo_go_srcs", + "//internal/jira:repo_go_srcs", + "//internal/linear:repo_go_srcs", + "//internal/lockfile:repo_go_srcs", + "//internal/memoryapi:repo_go_srcs", + "//internal/metrics:repo_go_srcs", + "//internal/migration:repo_go_srcs", + "//internal/migration/legacysqlite:repo_go_srcs", + "//internal/molecules:repo_go_srcs", + "//internal/notion:repo_go_srcs", + "//internal/procid:repo_go_srcs", + "//internal/query:repo_go_srcs", + "//internal/recipes:repo_go_srcs", + "//internal/remotecache:repo_go_srcs", + "//internal/routing:repo_go_srcs", + "//internal/storage:repo_go_srcs", + "//internal/storage/backendnames:repo_go_srcs", + "//internal/storage/backends:repo_go_srcs", + "//internal/storage/batchbench:repo_go_srcs", + "//internal/storage/batchfixtures:repo_go_srcs", + "//internal/storage/contextinfo:repo_go_srcs", + "//internal/storage/createbatchequiv:repo_go_srcs", + "//internal/storage/dberrors:repo_go_srcs", + "//internal/storage/dbproxy/identity:repo_go_srcs", + "//internal/storage/dbproxy/pidfile:repo_go_srcs", + "//internal/storage/dbproxy/proxy:repo_go_srcs", + "//internal/storage/dbproxy/server:repo_go_srcs", + "//internal/storage/dbproxy/util:repo_go_srcs", + "//internal/storage/depid:repo_go_srcs", + "//internal/storage/dolt:repo_go_srcs", + "//internal/storage/doltutil:repo_go_srcs", + "//internal/storage/domain:repo_go_srcs", + "//internal/storage/domain/db:repo_go_srcs", + "//internal/storage/domain/fs:repo_go_srcs", + "//internal/storage/domain/git:repo_go_srcs", + "//internal/storage/embeddeddolt:repo_go_srcs", + "//internal/storage/embeddeddolt/cmd:repo_go_srcs", + "//internal/storage/externaldeps:repo_go_srcs", + "//internal/storage/fs:repo_go_srcs", + "//internal/storage/git:repo_go_srcs", + "//internal/storage/historyoffequiv:repo_go_srcs", + "//internal/storage/issueops:repo_go_srcs", + "//internal/storage/journalscan:repo_go_srcs", + "//internal/storage/kvkeys:repo_go_srcs", + "//internal/storage/memoryops:repo_go_srcs", + "//internal/storage/rowid:repo_go_srcs", + "//internal/storage/schema:repo_go_srcs", + "//internal/storage/sqlbuild:repo_go_srcs", + "//internal/storage/sqlclass:repo_go_srcs", + "//internal/storage/sqlcount:repo_go_srcs", + "//internal/storage/storagecontract:repo_go_srcs", + "//internal/storage/unsupportedgen:repo_go_srcs", + "//internal/storage/uow:repo_go_srcs", + "//internal/storage/versioncontrolops:repo_go_srcs", + "//internal/telemetry:repo_go_srcs", + "//internal/templates:repo_go_srcs", + "//internal/templates/agents:repo_go_srcs", + "//internal/testutil:repo_go_srcs", + "//internal/testutil/bazeltest:repo_go_srcs", + "//internal/testutil/credentialcmd:repo_go_srcs", + "//internal/testutil/fixtures:repo_go_srcs", + "//internal/testutil/integration:repo_go_srcs", + "//internal/timeparsing:repo_go_srcs", + "//internal/tracker:repo_go_srcs", + "//internal/tracker/conformance:repo_go_srcs", + "//internal/types:repo_go_srcs", + "//internal/ui:repo_go_srcs", + "//internal/uimd:repo_go_srcs", + "//internal/utils:repo_go_srcs", + "//internal/validation:repo_go_srcs", + "//internal/versioncheck:repo_go_srcs", + "//internal/versionedhistory:repo_go_srcs", + "//internal/workapi:repo_go_srcs", + "//internal/workapi/storecounter:repo_go_srcs", + "//internal/workapi/storequerier:repo_go_srcs", + "//internal/workapi/storereader:repo_go_srcs", + "//internal/workapi/storereadycounter:repo_go_srcs", + "//internal/workapi/storestats:repo_go_srcs", + "//internal/workapi/storeversionreconciler:repo_go_srcs", + "//internal/workapi/storeworkspaceconfig:repo_go_srcs", + "//internal/workspacegate:repo_go_srcs", + "//internal/worktreeremove:repo_go_srcs", + "//issueops:repo_go_srcs", + "//journalops:repo_go_srcs", + "//memoryops:repo_go_srcs", + "//platforms:repo_go_srcs", + "//plugins/beads:repo_go_srcs", + "//schema:repo_go_srcs", + "//scripts:repo_go_srcs", + "//scripts/bench-ready-indexes:repo_go_srcs", + "//scripts/check-versions:repo_go_srcs", + "//scripts/checkworkflowtags:repo_go_srcs", + "//scripts/gitattributespolicy:repo_go_srcs", + "//scripts/internal/testbash:repo_go_srcs", + "//scripts/migration-test/catalog:repo_go_srcs", + "//scripts/pr-lint:repo_go_srcs", + "//scripts/prlintmake:repo_go_srcs", + "//scripts/repochecks:repo_go_srcs", + "//scripts/repro-dolt-hang:repo_go_srcs", + "//scripts/repro-dolt-prod-timeouts:repo_go_srcs", + "//scripts/workflowtags:repo_go_srcs", + "//test/conformance:repo_go_srcs", + "//test/docsync:repo_go_srcs", + "//test/embedder:repo_go_srcs", + "//test/testmainconvention:repo_go_srcs", + "//tests/hook_timeout_backends:repo_go_srcs", + "//tests/migration:repo_go_srcs", + "//tests/regression:repo_go_srcs", + "//tests/upgrade_smoke:repo_go_srcs", + "//third_party/cc_toolchain:repo_go_srcs", + "//third_party/patches:repo_go_srcs", + "//tools/bazel:repo_go_srcs", + "//tools/docsmint:repo_go_srcs", + "//tools/nogo:repo_go_srcs", + "//tools/nogo/analyzers/depguard:repo_go_srcs", + "//tools/nogo/analyzers/errcheck:repo_go_srcs", + "//tools/nogo/analyzers/forbidigo:repo_go_srcs", + "//tools/nogo/analyzers/gosec:repo_go_srcs", + "//tools/nogo/analyzers/misspell:repo_go_srcs", + "//tools/nogo/analyzers/sloglint:repo_go_srcs", + "//tools/nogo/analyzers/unconvert:repo_go_srcs", + "//tools/nogo/analyzers/unparam:repo_go_srcs", + "//tools/nogo/internal/analyzertest:repo_go_srcs", + "//tools/nogo/internal/golangci:repo_go_srcs", + "//tools/nogo/internal/position:repo_go_srcs", + ], + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = [ + "**/node_modules/**", + ".agents/**", + ".amp/**", + ".augment/**", + ".bazelrc.local", + ".claude/*.lock", + ".claude/*.log", + ".claude/settings.local.json", + ".codex/**", + ".cursor/**", + ".direnv/**", + ".envrc", + ".git/**", + ".idea/**", + ".logs/**", + ".vscode/**", + "bazel-*/**", + "bd", + "bd-fixed", + "bd-original", + "bd-test", + "bd_test", + "beads", + "go.work", + "go.work.sum", + "history/**", + "mcp_agent_mail/**", + "npm-package/bin/*.tar.gz", + "npm-package/bin/*.zip", + "npm-package/bin/CHANGELOG.md", + "npm-package/bin/LICENSE", + "npm-package/bin/README.md", + "npm-package/bin/bd", + "npm-package/package-lock.json", + "output", + "result", + "state.json", + "user.bazelrc", + ], + ) + [ + "//backend:repo_go_test_srcs", + "//backend/conformance:repo_go_test_srcs", + "//backend/http:repo_go_test_srcs", + "//backend/http/corpus:repo_go_test_srcs", + "//beadserrors:repo_go_test_srcs", + "//cmd/bd:repo_go_test_srcs", + "//cmd/bd/doctor:repo_go_test_srcs", + "//cmd/bd/doctor/fix:repo_go_test_srcs", + "//cmd/bd/protocol:repo_go_test_srcs", + "//cmd/bd/setup:repo_go_test_srcs", + "//format:repo_go_test_srcs", + "//internal/ado:repo_go_test_srcs", + "//internal/atomicfile:repo_go_test_srcs", + "//internal/audit:repo_go_test_srcs", + "//internal/beads:repo_go_test_srcs", + "//internal/ceiling:repo_go_test_srcs", + "//internal/compact:repo_go_test_srcs", + "//internal/config:repo_go_test_srcs", + "//internal/configfile:repo_go_test_srcs", + "//internal/creds:repo_go_test_srcs", + "//internal/debug:repo_go_test_srcs", + "//internal/doltremote:repo_go_test_srcs", + "//internal/doltserver:repo_go_test_srcs", + "//internal/doltversion:repo_go_test_srcs", + "//internal/eventsjournal:repo_go_test_srcs", + "//internal/execenv:repo_go_test_srcs", + "//internal/fdhygiene:repo_go_test_srcs", + "//internal/formula:repo_go_test_srcs", + "//internal/formula/cmd/schemagen:repo_go_test_srcs", + "//internal/formula/schemagen:repo_go_test_srcs", + "//internal/git:repo_go_test_srcs", + "//internal/gitenv:repo_go_test_srcs", + "//internal/githooksenv:repo_go_test_srcs", + "//internal/github:repo_go_test_srcs", + "//internal/gitignore:repo_go_test_srcs", + "//internal/gitlab:repo_go_test_srcs", + "//internal/gittraceenv:repo_go_test_srcs", + "//internal/hooks:repo_go_test_srcs", + "//internal/httpapi:repo_go_test_srcs", + "//internal/httpapi/apigen:repo_go_test_srcs", + "//internal/httpapi/spec:repo_go_test_srcs", + "//internal/httpapi/wireshape:repo_go_test_srcs", + "//internal/httpapi/wireshape/cmd/gendigest:repo_go_test_srcs", + "//internal/httpclient:repo_go_test_srcs", + "//internal/httpclient/encode:repo_go_test_srcs", + "//internal/httpclient/wire:repo_go_test_srcs", + "//internal/idgen:repo_go_test_srcs", + "//internal/initprocs:repo_go_test_srcs", + "//internal/jira:repo_go_test_srcs", + "//internal/linear:repo_go_test_srcs", + "//internal/lockfile:repo_go_test_srcs", + "//internal/memoryapi:repo_go_test_srcs", + "//internal/metrics:repo_go_test_srcs", + "//internal/migration:repo_go_test_srcs", + "//internal/migration/legacysqlite:repo_go_test_srcs", + "//internal/molecules:repo_go_test_srcs", + "//internal/notion:repo_go_test_srcs", + "//internal/procid:repo_go_test_srcs", + "//internal/query:repo_go_test_srcs", + "//internal/recipes:repo_go_test_srcs", + "//internal/remotecache:repo_go_test_srcs", + "//internal/routing:repo_go_test_srcs", + "//internal/storage:repo_go_test_srcs", + "//internal/storage/backendnames:repo_go_test_srcs", + "//internal/storage/backends:repo_go_test_srcs", + "//internal/storage/batchbench:repo_go_test_srcs", + "//internal/storage/batchfixtures:repo_go_test_srcs", + "//internal/storage/contextinfo:repo_go_test_srcs", + "//internal/storage/createbatchequiv:repo_go_test_srcs", + "//internal/storage/dberrors:repo_go_test_srcs", + "//internal/storage/dbproxy/identity:repo_go_test_srcs", + "//internal/storage/dbproxy/pidfile:repo_go_test_srcs", + "//internal/storage/dbproxy/proxy:repo_go_test_srcs", + "//internal/storage/dbproxy/server:repo_go_test_srcs", + "//internal/storage/dbproxy/util:repo_go_test_srcs", + "//internal/storage/depid:repo_go_test_srcs", + "//internal/storage/dolt:repo_go_test_srcs", + "//internal/storage/doltutil:repo_go_test_srcs", + "//internal/storage/domain:repo_go_test_srcs", + "//internal/storage/domain/db:repo_go_test_srcs", + "//internal/storage/domain/fs:repo_go_test_srcs", + "//internal/storage/domain/git:repo_go_test_srcs", + "//internal/storage/embeddeddolt:repo_go_test_srcs", + "//internal/storage/embeddeddolt/cmd:repo_go_test_srcs", + "//internal/storage/externaldeps:repo_go_test_srcs", + "//internal/storage/fs:repo_go_test_srcs", + "//internal/storage/git:repo_go_test_srcs", + "//internal/storage/historyoffequiv:repo_go_test_srcs", + "//internal/storage/issueops:repo_go_test_srcs", + "//internal/storage/journalscan:repo_go_test_srcs", + "//internal/storage/kvkeys:repo_go_test_srcs", + "//internal/storage/memoryops:repo_go_test_srcs", + "//internal/storage/rowid:repo_go_test_srcs", + "//internal/storage/schema:repo_go_test_srcs", + "//internal/storage/sqlbuild:repo_go_test_srcs", + "//internal/storage/sqlclass:repo_go_test_srcs", + "//internal/storage/sqlcount:repo_go_test_srcs", + "//internal/storage/storagecontract:repo_go_test_srcs", + "//internal/storage/unsupportedgen:repo_go_test_srcs", + "//internal/storage/uow:repo_go_test_srcs", + "//internal/storage/versioncontrolops:repo_go_test_srcs", + "//internal/telemetry:repo_go_test_srcs", + "//internal/templates:repo_go_test_srcs", + "//internal/templates/agents:repo_go_test_srcs", + "//internal/testutil:repo_go_test_srcs", + "//internal/testutil/bazeltest:repo_go_test_srcs", + "//internal/testutil/credentialcmd:repo_go_test_srcs", + "//internal/testutil/fixtures:repo_go_test_srcs", + "//internal/testutil/integration:repo_go_test_srcs", + "//internal/timeparsing:repo_go_test_srcs", + "//internal/tracker:repo_go_test_srcs", + "//internal/tracker/conformance:repo_go_test_srcs", + "//internal/types:repo_go_test_srcs", + "//internal/ui:repo_go_test_srcs", + "//internal/uimd:repo_go_test_srcs", + "//internal/utils:repo_go_test_srcs", + "//internal/validation:repo_go_test_srcs", + "//internal/versioncheck:repo_go_test_srcs", + "//internal/versionedhistory:repo_go_test_srcs", + "//internal/workapi:repo_go_test_srcs", + "//internal/workapi/storecounter:repo_go_test_srcs", + "//internal/workapi/storequerier:repo_go_test_srcs", + "//internal/workapi/storereader:repo_go_test_srcs", + "//internal/workapi/storereadycounter:repo_go_test_srcs", + "//internal/workapi/storestats:repo_go_test_srcs", + "//internal/workapi/storeversionreconciler:repo_go_test_srcs", + "//internal/workapi/storeworkspaceconfig:repo_go_test_srcs", + "//internal/workspacegate:repo_go_test_srcs", + "//internal/worktreeremove:repo_go_test_srcs", + "//issueops:repo_go_test_srcs", + "//journalops:repo_go_test_srcs", + "//memoryops:repo_go_test_srcs", + "//platforms:repo_go_test_srcs", + "//plugins/beads:repo_go_test_srcs", + "//schema:repo_go_test_srcs", + "//scripts:repo_go_test_srcs", + "//scripts/bench-ready-indexes:repo_go_test_srcs", + "//scripts/check-versions:repo_go_test_srcs", + "//scripts/checkworkflowtags:repo_go_test_srcs", + "//scripts/gitattributespolicy:repo_go_test_srcs", + "//scripts/internal/testbash:repo_go_test_srcs", + "//scripts/migration-test/catalog:repo_go_test_srcs", + "//scripts/pr-lint:repo_go_test_srcs", + "//scripts/prlintmake:repo_go_test_srcs", + "//scripts/repochecks:repo_go_test_srcs", + "//scripts/repro-dolt-hang:repo_go_test_srcs", + "//scripts/repro-dolt-prod-timeouts:repo_go_test_srcs", + "//scripts/workflowtags:repo_go_test_srcs", + "//test/conformance:repo_go_test_srcs", + "//test/docsync:repo_go_test_srcs", + "//test/embedder:repo_go_test_srcs", + "//test/testmainconvention:repo_go_test_srcs", + "//tests/hook_timeout_backends:repo_go_test_srcs", + "//tests/migration:repo_go_test_srcs", + "//tests/regression:repo_go_test_srcs", + "//tests/upgrade_smoke:repo_go_test_srcs", + "//third_party/cc_toolchain:repo_go_test_srcs", + "//third_party/patches:repo_go_test_srcs", + "//tools/bazel:repo_go_test_srcs", + "//tools/docsmint:repo_go_test_srcs", + "//tools/nogo:repo_go_test_srcs", + "//tools/nogo/analyzers/depguard:repo_go_test_srcs", + "//tools/nogo/analyzers/errcheck:repo_go_test_srcs", + "//tools/nogo/analyzers/forbidigo:repo_go_test_srcs", + "//tools/nogo/analyzers/gosec:repo_go_test_srcs", + "//tools/nogo/analyzers/misspell:repo_go_test_srcs", + "//tools/nogo/analyzers/sloglint:repo_go_test_srcs", + "//tools/nogo/analyzers/unconvert:repo_go_test_srcs", + "//tools/nogo/analyzers/unparam:repo_go_test_srcs", + "//tools/nogo/internal/analyzertest:repo_go_test_srcs", + "//tools/nogo/internal/golangci:repo_go_test_srcs", + "//tools/nogo/internal/position:repo_go_test_srcs", + ], + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ".agents/**", + ".amp/**", + ".augment/**", + ".bazelrc.local", + ".claude/*.lock", + ".claude/*.log", + ".claude/settings.local.json", + ".codex/**", + ".cursor/**", + ".direnv/**", + ".envrc", + ".git/**", + ".idea/**", + ".logs/**", + ".vscode/**", + "bazel-*/**", + "bd", + "bd-fixed", + "bd-original", + "bd-test", + "bd_test", + "beads", + "go.work", + "go.work.sum", + "history/**", + "mcp_agent_mail/**", + "npm-package/bin/*.tar.gz", + "npm-package/bin/*.zip", + "npm-package/bin/CHANGELOG.md", + "npm-package/bin/LICENSE", + "npm-package/bin/README.md", + "npm-package/bin/bd", + "npm-package/package-lock.json", + "output", + "result", + "state.json", + "user.bazelrc", + ], + ) + [ + "//backend:repo_other_files", + "//backend/conformance:repo_other_files", + "//backend/http:repo_other_files", + "//backend/http/corpus:repo_other_files", + "//beadserrors:repo_other_files", + "//cmd/bd:repo_other_files", + "//cmd/bd/doctor:repo_other_files", + "//cmd/bd/doctor/fix:repo_other_files", + "//cmd/bd/protocol:repo_other_files", + "//cmd/bd/setup:repo_other_files", + "//format:repo_other_files", + "//internal/ado:repo_other_files", + "//internal/atomicfile:repo_other_files", + "//internal/audit:repo_other_files", + "//internal/beads:repo_other_files", + "//internal/ceiling:repo_other_files", + "//internal/compact:repo_other_files", + "//internal/config:repo_other_files", + "//internal/configfile:repo_other_files", + "//internal/creds:repo_other_files", + "//internal/debug:repo_other_files", + "//internal/doltremote:repo_other_files", + "//internal/doltserver:repo_other_files", + "//internal/doltversion:repo_other_files", + "//internal/eventsjournal:repo_other_files", + "//internal/execenv:repo_other_files", + "//internal/fdhygiene:repo_other_files", + "//internal/formula:repo_other_files", + "//internal/formula/cmd/schemagen:repo_other_files", + "//internal/formula/schemagen:repo_other_files", + "//internal/git:repo_other_files", + "//internal/gitenv:repo_other_files", + "//internal/githooksenv:repo_other_files", + "//internal/github:repo_other_files", + "//internal/gitignore:repo_other_files", + "//internal/gitlab:repo_other_files", + "//internal/gittraceenv:repo_other_files", + "//internal/hooks:repo_other_files", + "//internal/httpapi:repo_other_files", + "//internal/httpapi/apigen:repo_other_files", + "//internal/httpapi/spec:repo_other_files", + "//internal/httpapi/wireshape:repo_other_files", + "//internal/httpapi/wireshape/cmd/gendigest:repo_other_files", + "//internal/httpclient:repo_other_files", + "//internal/httpclient/encode:repo_other_files", + "//internal/httpclient/wire:repo_other_files", + "//internal/idgen:repo_other_files", + "//internal/initprocs:repo_other_files", + "//internal/jira:repo_other_files", + "//internal/linear:repo_other_files", + "//internal/lockfile:repo_other_files", + "//internal/memoryapi:repo_other_files", + "//internal/metrics:repo_other_files", + "//internal/migration:repo_other_files", + "//internal/migration/legacysqlite:repo_other_files", + "//internal/molecules:repo_other_files", + "//internal/notion:repo_other_files", + "//internal/procid:repo_other_files", + "//internal/query:repo_other_files", + "//internal/recipes:repo_other_files", + "//internal/remotecache:repo_other_files", + "//internal/routing:repo_other_files", + "//internal/storage:repo_other_files", + "//internal/storage/backendnames:repo_other_files", + "//internal/storage/backends:repo_other_files", + "//internal/storage/batchbench:repo_other_files", + "//internal/storage/batchfixtures:repo_other_files", + "//internal/storage/contextinfo:repo_other_files", + "//internal/storage/createbatchequiv:repo_other_files", + "//internal/storage/dberrors:repo_other_files", + "//internal/storage/dbproxy/identity:repo_other_files", + "//internal/storage/dbproxy/pidfile:repo_other_files", + "//internal/storage/dbproxy/proxy:repo_other_files", + "//internal/storage/dbproxy/server:repo_other_files", + "//internal/storage/dbproxy/util:repo_other_files", + "//internal/storage/depid:repo_other_files", + "//internal/storage/dolt:repo_other_files", + "//internal/storage/doltutil:repo_other_files", + "//internal/storage/domain:repo_other_files", + "//internal/storage/domain/db:repo_other_files", + "//internal/storage/domain/fs:repo_other_files", + "//internal/storage/domain/git:repo_other_files", + "//internal/storage/embeddeddolt:repo_other_files", + "//internal/storage/embeddeddolt/cmd:repo_other_files", + "//internal/storage/externaldeps:repo_other_files", + "//internal/storage/fs:repo_other_files", + "//internal/storage/git:repo_other_files", + "//internal/storage/historyoffequiv:repo_other_files", + "//internal/storage/issueops:repo_other_files", + "//internal/storage/journalscan:repo_other_files", + "//internal/storage/kvkeys:repo_other_files", + "//internal/storage/memoryops:repo_other_files", + "//internal/storage/rowid:repo_other_files", + "//internal/storage/schema:repo_other_files", + "//internal/storage/sqlbuild:repo_other_files", + "//internal/storage/sqlclass:repo_other_files", + "//internal/storage/sqlcount:repo_other_files", + "//internal/storage/storagecontract:repo_other_files", + "//internal/storage/unsupportedgen:repo_other_files", + "//internal/storage/uow:repo_other_files", + "//internal/storage/versioncontrolops:repo_other_files", + "//internal/telemetry:repo_other_files", + "//internal/templates:repo_other_files", + "//internal/templates/agents:repo_other_files", + "//internal/testutil:repo_other_files", + "//internal/testutil/bazeltest:repo_other_files", + "//internal/testutil/credentialcmd:repo_other_files", + "//internal/testutil/fixtures:repo_other_files", + "//internal/testutil/integration:repo_other_files", + "//internal/timeparsing:repo_other_files", + "//internal/tracker:repo_other_files", + "//internal/tracker/conformance:repo_other_files", + "//internal/types:repo_other_files", + "//internal/ui:repo_other_files", + "//internal/uimd:repo_other_files", + "//internal/utils:repo_other_files", + "//internal/validation:repo_other_files", + "//internal/versioncheck:repo_other_files", + "//internal/versionedhistory:repo_other_files", + "//internal/workapi:repo_other_files", + "//internal/workapi/storecounter:repo_other_files", + "//internal/workapi/storequerier:repo_other_files", + "//internal/workapi/storereader:repo_other_files", + "//internal/workapi/storereadycounter:repo_other_files", + "//internal/workapi/storestats:repo_other_files", + "//internal/workapi/storeversionreconciler:repo_other_files", + "//internal/workapi/storeworkspaceconfig:repo_other_files", + "//internal/workspacegate:repo_other_files", + "//internal/worktreeremove:repo_other_files", + "//issueops:repo_other_files", + "//journalops:repo_other_files", + "//memoryops:repo_other_files", + "//platforms:repo_other_files", + "//plugins/beads:repo_other_files", + "//schema:repo_other_files", + "//scripts:repo_other_files", + "//scripts/bench-ready-indexes:repo_other_files", + "//scripts/check-versions:repo_other_files", + "//scripts/checkworkflowtags:repo_other_files", + "//scripts/gitattributespolicy:repo_other_files", + "//scripts/internal/testbash:repo_other_files", + "//scripts/migration-test/catalog:repo_other_files", + "//scripts/pr-lint:repo_other_files", + "//scripts/prlintmake:repo_other_files", + "//scripts/repochecks:repo_other_files", + "//scripts/repro-dolt-hang:repo_other_files", + "//scripts/repro-dolt-prod-timeouts:repo_other_files", + "//scripts/workflowtags:repo_other_files", + "//test/conformance:repo_other_files", + "//test/docsync:repo_other_files", + "//test/embedder:repo_other_files", + "//test/testmainconvention:repo_other_files", + "//tests/hook_timeout_backends:repo_other_files", + "//tests/migration:repo_other_files", + "//tests/regression:repo_other_files", + "//tests/upgrade_smoke:repo_other_files", + "//third_party/cc_toolchain:repo_other_files", + "//third_party/patches:repo_other_files", + "//tools/bazel:repo_other_files", + "//tools/docsmint:repo_other_files", + "//tools/nogo:repo_other_files", + "//tools/nogo/analyzers/depguard:repo_other_files", + "//tools/nogo/analyzers/errcheck:repo_other_files", + "//tools/nogo/analyzers/forbidigo:repo_other_files", + "//tools/nogo/analyzers/gosec:repo_other_files", + "//tools/nogo/analyzers/misspell:repo_other_files", + "//tools/nogo/analyzers/sloglint:repo_other_files", + "//tools/nogo/analyzers/unconvert:repo_other_files", + "//tools/nogo/analyzers/unparam:repo_other_files", + "//tools/nogo/internal/analyzertest:repo_other_files", + "//tools/nogo/internal/golangci:repo_other_files", + "//tools/nogo/internal/position:repo_other_files", + ], + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/CHANGELOG.md b/CHANGELOG.md index fce76c527..884a0d7f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,683 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `bd versions ` lists the versions recorded for a bead, and + `versioned-history.enabled` turns recording on. While it is on, every + accepted change to a bead created while it is on, or that enters the issues + plane while it is on (a wisp promoted or made persistent), stores a + snapshot of it as a row of `issue_versions` in the same transaction. It is + off by default and nothing is backfilled: a bead already on the issues + plane when it is turned on is legacy, and editing it records nothing. A + recorded write leaves `updated_at` where an unrecorded one would, so + `bd import`'s stale check sees the same timestamps either way. + `bd versions --json` answers `{"versions": [...], "recording": bool}`; the + command still lists what was recorded after recording is turned off, and + proxied-server and HTTP workspaces refuse it. The setting is a row of each + store's `config` table (`bd config set versioned-history.enabled true`), + and every store reads its own when it is opened: a write routed into + another workspace (a prefix-routed `bd update` or `bd close`, + `bd create --repo`) follows the target store's row, a proxied-server + provider reads it when it is constructed, and a long-lived `bd serve` + keeps the value it read until it restarts. + `BD_VERSIONED_HISTORY_ENABLED=1` (or a `config.yaml` value) turns + recording on for every store the process opens, and never turns it off. + The row replicates on `bd dolt push`/`pull`, and recording is single-writer + only: two clones recording at once can mint the same revision and fail the + pull, and a write from a writer that is not recording is folded into the + next recorded version under that version's actor, so keep recording on for + every writer of a store or off for all of them. Turning it on with + `bd config set` first checks every issue the store would version and + refuses, writing nothing, while any holds a number outside the I-JSON + exact-integer range (magnitude above 2^53-1, however it is spelled) in its + metadata or in a gate's timeout (held as nanoseconds, so about 104.25 + days), and prints the count, the ids, the field and the fix. There is no + override, and the check runs once; after that, a recorded write that would + hold such a number fails atomically. Migration 0071 adds a nullable + `removed_restriction` column to `issue_versions`. `bd version` now refuses + an argument and suggests `bd versions `, instead of printing bd's + build for a mistyped `bd version bd-123`. +- `bd blocked --flags` prints the blocked flag for each id read from stdin + (one per line; blank lines and repeats ignored), with `--json` as + `[{"id","is_blocked"}]` in the order the ids were given, omitting an id that + names no row on either plane. A closed id is answered too, with its stored + flag (a `status <> 'closed'` SQL read of the column leaves it out). It is the flag `bd ready` filters on, not the + listing: a row whose stored flag is set with no nameable blocker reads true + here and is absent from `bd blocked`. It runs `issueops.BlockedFlags` on + every route; over HTTP that is `listBlockingAnnotations` with `is_blocked`, + behind `dependencies.blocking.isBlocked`, refused before the dial against a + server that does not advertise it. The listing's filter flags are refused + with `--flags`. +- `bd blocked --flags --raw` answers the stored `is_blocked` column itself, + without the external-dependency policy: a row blocked only by an + unsatisfied `external:` ref reads `false` (the policy-aware `--flags` + reads `true`); a stale flag reads `true` either way. `--raw` is for the + local and proxied routes, where it reads the column directly and the two + answer the same. Over HTTP it is answered only by a server that does not + advertise `policy.external_dependencies` (whose flag is the column); a + server advertising it answers only the policy-aware flag, so `--raw` + against it is refused before the dial rather than answered with the + decorated flag. `--raw` without `--flags` is refused. +- `bd blocked` works over a connected HTTP workspace. The blocked listing is + a role, `issueops.BlockedLister` (`ListBlocked(BlockedRequest{ParentID, + Labels, LabelsAny, ExcludeLabels}) -> BlockedResult{Items}`), on every + backend leg over the same body `GetBlockedIssues` runs, and `bd serve` + publishes it as `GET /v0/beads/blocked` (`parent`, and the repeatable + `label`, `label_any` and `exclude_label`), answering `{items, has_more}` + with `BlockedIssue` rows (the element `bd blocked --json` prints), behind + the new `blocked.list` capability token (additive; no wire_revision bump). + The listing names unsatisfied `external:` blockers wherever the + external-dependency policy applies: on the server when it advertises + `policy.external_dependencies`, else on the client, as every other policy + read does. The HTTP backend's `BlockedLister()` and legacy + `GetBlockedIssues` dial it; against a server that does not advertise the + token they refuse before dialing with a typed capability error naming + `blocked.list`, and never compose the listing from other reads. The + listing is unpaged: a server answer that reports `has_more` is refused + with the new `httpclient.TruncatedListingError` rather than returned + short, and an answer over the client's 32 MiB response limit is refused + as any oversized response is. The external-dependency decorator's legacy + `GetBlockedIssues` over an HTTP store now reads the extra sources through + the served roles (it failed on a raw multi-id read before), so callers of + that door no longer fail on it; commands that also make other raw reads + the HTTP backend does not serve (`bd ready --explain`) still refuse on + those. `bd + blocked` runs the role on every route (the proxied-server route through + the provider's accessor) with unchanged output: `--json` prints the same + rows in the same order (priority, then newest first, then id, which now + also breaks a tie the order used to leave to chance), and `[]`, never + `null`, when nothing is blocked. +- `bd list`'s remaining filters work over a connected HTTP workspace. + `GET /v0/beads/issues` accepts `updated_after`/`updated_before`, + `closed_after`/`closed_before`, `defer_after`/`defer_before`, + `due_after`/`due_before`, `priority`, `priority_min`, `priority_max`, + `title_contains`, `desc_contains`, `notes_contains`, `external_contains`, + `external_ref`, `spec`, `label_pattern`, `label_regex`, + `empty_description`, `no_labels`, `no_parent`, a repeatable + `exclude_type`, `pinned`, `no_pinned`, `deferred`, `overdue`, `mol_type` + and `wisp_type`, behind one new capability token, `issues.list.filters` + (additive; no wire_revision bump; the names are `issues:count`'s where it + already spells the filter), and applies them through the same Reader role a + local `bd list` reads through. Bounds are strict and compared at + whole-second precision on both routes; relative and date-only values are + resolved on the client's clock and timezone as locally, while `--overdue` + compares against the server's clock. Against a server that does not + advertise the token the client refuses before dialing, naming + `issues.list.filters`, rather than sending a filter an older server rejects + or dropping one and answering a wider listing. The 29 corresponding + divergence-ledger refusal rows are removed. The default `bd list --parent` + tree view does not carry these filters yet: its descendant walk still + refuses one over HTTP rather than drop it, and `--flat` or `--json` skips + the walk and applies them to the parent's direct children (not its whole + subtree). +- `issueops.ListRequest.ExcludeStatus`: statuses to leave out of a listing, + appended to the default exclusions (never re-admitting what they hide), + comma-separated or repeated, each validated against the workspace's + statuses like `CountRequest.ExcludeStatus` (an unknown name is + `ErrValidation`). `GET /v0/beads/issues` accepts it as a repeatable + `exclude_status` under the same `issues.list.filters` token (an unknown + name is a `400` on `exclude_status`), so an HTTP-backed caller can leave + closed history out of an `all` listing (`all` plus + `exclude_status=closed` keeps every status not named, the `pinned` and + `hooked` statuses and custom done/frozen statuses included) instead of + reading the whole history. It is refused together with `ReadyFlag`, like the other + members the ready query cannot carry. There is no `bd list` flag for it + yet. + +- `bd serve` publishes the gate members: `await_type`, + `await_id`, `timeout` (nanoseconds) and `waiters` on `POST + /v0/beads/issues` and on `issues:batchApply` create items, behind the new + `issues.create.gates` capability token, and `await_id` and `waiters` (a + whole-value replacement; `[]` clears) on the `patch` of `PATCH + /v0/beads/issues/{id}` and of `issues:batchApply` update items, behind + `issues.update.gates`. Additive; no wire_revision bump. The bounds are the + library role's, the same ones a local create or update now enforces (see + Changed), answered as `400 invalid_argument` with `param` naming the + member. +- `issueops.IssuePatch.Waiters`: a whole-value replacement of a gate's waiter + list (nil or empty clears it, stored as `[]`), on `Lifecycle.Update` and on + `BatchApplier` update items, on every backend. `issueops.GateFieldError` + (`Field`, `Detail`; wraps `ErrValidation`) names the gate member a create or + update refused, as one of the new `issueops.GateFieldAwaitType`, + `GateFieldAwaitID`, `GateFieldTimeout` and `GateFieldWaiters` constants. +- The HTTP client sends the gate members on create, update and + `issues:batchApply` (create and update items) to a server that advertises + `issues.create.gates` / `issues.update.gates`. Against an older server a + request naming any gate member is refused before the dial with a typed + capability error naming the missing token (never sent without the + member); a batchApply plan is checked whole, so no partial plan is sent. + A request naming no gate member is unaffected by either token. +- `bd heartbeat` works over a connected HTTP workspace. + The lease refresh is a role, `issueops.Heartbeater` + (`Heartbeat(HeartbeatRequest{Actor, IssueID}) -> HeartbeatResult{IssueID, + Holder, HeartbeatAt, LeaseExpiresAt, Rearmed}`), on every backend leg, and + `bd serve` publishes it as `POST /v0/beads/issues/{id}:heartbeat` behind the + new `issues.heartbeat` capability token (additive; no wire_revision bump), + with the new `lease_not_held` (409) problem code (`reason: ephemeral` for a + wisp). A refresh writes ONLY the lease row: the issue's `revision` is not + reminted (a guarded write against the pre-heartbeat token still lands), no + version, event, journal entry or Dolt commit is recorded, and no hook + fires. `Rearmed` is true only when the heartbeat created the caller's lease + row (a hand-doled claim's first heartbeat). A re-arm is recorded as a + mutation; a refresh is not: the re-arm remints `revision`, stamps + `updated_at`, records a `lease_rearmed` event, a journal entry and a + version, makes a Dolt commit and fires `on_update` (see Fixed); the + reported times are whole seconds, exactly what the lease row stores. The + HTTP backend's `Heartbeater()` and legacy `HeartbeatIssue` dial it; + against a server that does not advertise the token they refuse before + dialing with a typed capability error naming `issues.heartbeat`, and never + fall back to a re-claim or a metadata stamp. A + busy (503) answer is replayed, because a repeat only moves the expiry later. + `bd heartbeat` now runs the role on every route (the proxied-server route + through the provider's accessor), with the same + `{"id","status":"heartbeat","owner"}` success output and the same exit + codes. Refusal TEXT on stderr changes per route: the direct routes (Dolt + server, embedded) gain a `lease not held: ` prefix + (`heartbeat X: lease not held: issue not claimable: X status closed`); the + proxied-server route loses its + `Heartbeat: db: IssueSQLRepository.HeartbeatIssue: ` prefix and reads as the + direct routes do; over HTTP the refusal is the problem's detail, which names + the state found (`it is closed`, `an ephemeral wisp`, `open and not + claimed`) or, for a foreign holder, the native `issue already claimed by + `. An id that names no row answers not-found from the role rather + than "not claimable" (the CLI resolves the id first, so its output is + unchanged), and every refusal for a caller that holds no live claim + (closed, released, reclaimed, moved off in_progress, or a wisp) is + `issueops.ErrLeaseNotHeld`, which still matches `ErrNotClaimable`. + +- `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 + (`*issueops.NotAWispError`, the sentence `bd promote` always printed), moves + it with ONE `Lifecycle.Update` whose patch is `Persistence = persistent` + (labels, dependencies, events, comments and the child counter move with it + in the role's transaction), then records the promotion comment. The direct + and proxied-server routes run it over their own roles, so a local promote + now makes the same plane move `bd update --persistent` makes, honoring + `dolt.auto-commit`. That changes five things a script can see on those + routes: the workspace's `on_update` hook fires twice, once for the move and + once for the comment (the direct route never fired it, the proxied-server + route fired it once); the promotion comment is a row `bd comments` lists + (the direct route recorded only a `commented` event); a promoted parent + keeps its child counter, so its next `bd create --parent` mints the number + after its wisp children's instead of failing with + `issue already exists: .1`; a promotion records two Dolt + commits, `bd: promote ` for the move and `bd: comment ` for the + comment (an embedded workspace recorded one, `bd: promote (auto-commit)`, + and the proxied-server route one, `bd: promote `); and a promote that + loses a race to a concurrent one fails with the not-a-wisp sentence instead + of `promoting : wisp not found`. A comment that cannot + be written leaves the promotion standing behind a warning on every route; + the proxied-server route used to roll the promotion back. `bd serve` + publishes the move as `patch.persistence` on `PATCH /v0/beads/issues/{id}` + behind the new `issues.update.persistence` capability (additive; + `wire_revision` is unchanged), which also carries `bd update --persistent`, + `--ephemeral` and `--no-history` over HTTP. Against a server without the + token the client refuses before the dial, naming it; nothing is written. A + move the workspace refuses (an `unversioned`-class row asked for + `--ephemeral` or `--no-history`, or a demotion of a row with retained + snapshots) matches `ErrValidation` on every route: `bd serve` answers it + `400 invalid_argument`, and the local refusal gains a `validation failed: ` + prefix. +- `bd serve` advertises the new `issues.update.claim` behavior token for what + `PATCH /v0/beads/issues/{id}` already served untokened: `claim` (upstream + #6890), resolved on both planes, so a wisp is claimable there (additive; no + wire_revision bump). The HTTP client now picks the claim route from the + handshake before dialing: with the token every claim is one updateIssue call; + without it a claim alone goes to `{id}:claim` (no doomed 400 first; a wisp + still refuses by name, W-ClaimRequest.Wisp, now naming the token), and a + claim beside a patch, a guard, a force override or `allow_template` is + refused before the dial with an unsupported error naming + `issues.update.claim`. Skew note: a server that serves `claim` untokened + (wire_revision 2 builds before this release) now gets those two refusals + from a new client where it used to serve them; upgrade bd serve. A template + claimed alone without the token is still refused, on the client's own + pre-read: `{id}:claim` has no template guard (bd-jkp9v3). +- `issueops.LeaseReclaimer`, the stale-lease sweep behind `bd reclaim`, is a + role on every leg (dolt, embedded dolt, the unit-of-work provider and the + HTTP client), and `bd serve` publishes it as `POST /v0/beads/issues:reclaim` + behind the new `issues.reclaim` capability (additive; `wire_revision` is + unchanged). Every reverted row mints a new revision, reported per entry as + `revision`, so a holder that writes with its pre-reclaim token gets a version + mismatch. An id that is not a stale lease is left out of the answer, not + refused. `bd reclaim` now runs the role on both routes, which changes four + things a script can see: its `--json` entries gain `revision`; the + workspace's `on_update` hook fires once per reverted row (the raw path fired + none); `--id` now accepts at most 1000 ids per run (more is refused, never + truncated); and the role records its own version commit, honoring + `dolt.auto-commit` the way `bd prune` does, as + `bd: reclaim N expired lease(s)` on both routes. Over a connected HTTP + workspace `bd reclaim` now works instead of refusing. +- **`bd show --comments-tail N`** renders only the last N comments in text + output (including under `--watch`) + ([#6618](https://github.com/gastownhall/beads/pull/6618)), preceded by one + elision line naming how many older ones were hidden. A render-only cap for + fat, append-only beads whose full comment history is hundreds of KB — + description and metadata are unchanged, and omitting the flag (or passing + `0`) is byte-identical to today's output. JSON output is untouched; + `--include-comments` still streams every comment there. +- `GET /v0/beads/issues` accepts `no_assignee`, `title` and a repeatable `id` + (one id per value, at most 200), each behind its own new capability token + (`issues.list.noAssignee`, `issues.list.title`, `issues.list.ids`; additive, + no wire_revision bump; `id` and its token are bd-enterprise's contract, + adopted unchanged), and applies them through + the same Reader role a local `bd list` reads through. Over a connected HTTP + workspace `bd list --no-assignee`, `--title` and `--id` now work instead of + refusing. Against a server that does not advertise a flag's token the + client refuses before dialing, and the refusal names the token (every + capability refusal over HTTP now names its token). +- `GET /v0/beads/issues` accepts `q`, `bd search`'s free text, behind the + new `issues.list.search` capability token (additive; no wire_revision + bump). `issueops.ListRequest` gains `Query`, with `SearchIssues`' meaning + (title or id contains the text, case-insensitively), on every Reader + implementation, and `issueops.SearchListRequest` is search's scope as a + request. Every `bd search` route (direct, `--proxied-server` and the HTTP + backend) now asks `Reader.List` with it through one flag mapping; against + a server that does not advertise the token the HTTP client refuses before + dialing with a typed capability error. Two things a script can see follow + from that mapping: `bd search --type` expands aliases (`feat`, `mol`, + `dec`, ...) and validates the type as `bd list` does, so an unknown type + now exits 1 where it used to answer an empty result, and `bd search + --json` rows carry `comments_omitted` (additive) as `bd list --json` rows + do. +- `bd create --graph` now plans its batch through `issueops.BatchApplier` + instead of the old `buildDomainGraphPlan` path, so a graph create gets the + same atomic multi-row semantics as `bd batch apply`. A `waits-for` edge's + `metadata.spawner_id` is stamped only when that edge names a spawner + (never defaulted onto an edge that names none), and `thread_id` now survives + translation into the batch request alongside every other + `GraphApplyEdge`/`GraphApplyNodeDep` field — pinned by a reflection-based + field-coverage test (`TestBuildGraphApplyBatchRequestFieldsSurvive`) that + fails closed if a future field is added to either struct without an + explicit decision about where it goes. The hierarchy/cycle rejection + scenarios this path's local gates cover (blocking through existing or + planned hierarchy, transitive external-parent paths, reverse parent-to-child + edges, cycles hidden in an inline dep, combined scheduling cycles, the end + gate alone with the per-edge cycle probe skipped) are exercised against a + real Dolt store, not just skipped placeholders. A graph plan whose translated + BatchApplier items (nodes, edges and deferred assignments combined) exceed + `issueops.MaxApplyBatchItems` (1000) is now refused outright with + `GraphApplyTooLargeError` rather than silently chunked across several + transactions — `bd create --graph` promises one atomic request, so a plan + over the cap must be split by the caller into multiple `bd create --graph` + calls instead. +- `--if-revision` (gastownhall/beads#4682) is extended to `bd reopen`, the + one lifecycle verb #7203 did not add it to, reusing the same + `issueops.ReopenRequest.ExpectedVersion` field the library already + exposed and the same `parseIfRevisionFlag` / `requireSingleIfRevisionID` + / `reportIfRevisionFailure` helpers #7203 introduced for the other four + verbs — no new CLI surface, no new JSON body shape. A guarded reopen of an + issue that is already open is still judged against the guard on both + routes: a stale revision exits 13, and a matching one is the usual + "already open" no-op. A faithful port of + gc's (gascity) `bdstore_conditional.go` decode logic is now run against a + real built `bd` for all five guarded verbs + (`TestEmbeddedGCConditionalMatcherDecode`), confirming gc's matcher decodes + #7203's numeric-only `expected_revision`/`current_revision` body exactly + — no decimal-string twin fields are needed, since `encoding/json` decodes + a JSON number straight into an `int64` struct field with no lossy + `float64` intermediate. The proxied-server route (`*_proxied_server.go`'s + uow-backed preflight/apply path), previously untested for `--if-revision` + on any verb, now has coverage for all five. +- `backends.Backend` gains an optional `OpenWith(ctx, beadsDir, OpenOptions)` + and a `Remote bool` field for a registered extension backend (for example + an HTTP client registrant). `OpenOptions{Credential, HTTPClient, + UserAgent}` carries per-open injections — the motivating case is a single + embedder process serving many workspaces with distinct credentials against + a backend whose dialer would otherwise be process-global. `Open` keeps + working unmodified: a backend with no `OpenWith` falls back to it and + ignores `HTTPClient`/`UserAgent`, but refuses rather than silently drops a + non-nil `Credential`. The public SDK gains `beads.OpenBestAvailableWith` + (and the `backend` package's matching aliases); `beads.OpenBestAvailable` + is now that function called with a zero `OpenOptions`, with identical + behavior for every existing backend. `doltserver.ResolvePhysicalRoots` now + recognizes a registered remote backend (`backends.IsRemote`) before any + Dolt-mode check, so a remote-backend workspace is never misclassified as + having a local Dolt root to gate. +- `bd serve`'s `GET /v0/beads/context` now reports `wire_revision` (the + non-additive wire-shape counter for this build) and + `min_client_wire_revision` (the oldest revision this build still answers + correctly). A client may declare the revision it was built for on any + request via the optional `Bd-Wire-Revision` header (a plain non-negative + decimal — no leading `+` or leading zero); a declared revision below + `min_client_wire_revision` is refused with `400 invalid_argument`/`reason: + "wire_revision_unsupported"` and `min_wire_revision`, `wire_revision`, and + `bd_version` fields naming this server's floor, current revision, and + release string. The header is absent by default and an absent header is + served exactly as before — this is additive, not a new precondition on + existing clients. A client with no `wire_revision` signal to read yet may + infer one from `bd_version` only as an ADVISORY hint (string-or-number, + never a refusal on an inferred `0`) — see the `wire_revision` property's + inference notes in `internal/httpapi/spec/openapi.v0.yaml` for the cutoff + and known-exception builds. See `internal/httpapi/wire_revision.go` and + that same property for the full revision history. +- `GET /v0/beads/issues`'s `sort` parameter now advertises the + `issues.list.sort` capability token, the same way an operation itself + does, and a CI rule + (`TestNewParameterOnExistingOperationHasABehaviorToken`) requires every + new parameter on an existing operation, or new request body member on an + existing operation, to carry a token that `Capabilities()` actually + advertises (not just backticked `a.b` text shaped like one). Three frozen + baselines (`internal/httpapi/testdata/pretoken_*.json`) grandfather what + predates the rule and are pinned never to grow + (`TestPretokenBaselinesNeverGrow`); a brand-new operation is permanently + exempt — its own review decides its capability story. +- A CI golden digest (`internal/httpapi/wireshape`) pins the JSON name, + type, format, enum, required-ness, and nullability of every EXISTING + response AND request-body member across the whole HTTP spec — including + array item shape and `additionalProperties` value shape — recursing + through `$ref` and through a schema's own `allOf` or `oneOf`, and fails if + any changes without `wire_revision` bumping to match; + `go run ./internal/httpapi/wireshape/cmd/gendigest` refuses to write a + changed or removed entry unless `wire_revision` has moved past what the + existing golden recorded, and refuses any write at a lower + `wire_revision` (purely additive entries otherwise always write). The + same digest also pins every operation PARAMETER (query, path and header), + keyed by operationId + location + name, and records its type, item shape, + enum, required-ness, effective style and explode (OpenAPI's defaults + filled in where unset), and default — a parameter retyped, re-enumerated, + narrowed, re-serialized, switched required, or removed is non-additive + exactly like a response or request-body member. A new member or + parameter always counts as additive, even a REQUIRED one an old client + will not send, and value constraints (`maxLength`, `pattern` and the + like) are outside the digest: such changes need their own review against + `wire_revision`. +- `cmd/bd` registers the http client backend built on top of the v0 `bd + serve` wire (`internal/httpclient`), so a workspace whose + `.beads/metadata.json` selects `"backend": "http"` opens over HTTP through + the ordinary `OpenBestAvailable` path, exactly like a registered extension + backend does. A new `bd connect ` command performs the handshake + (`api_version`, wire revision, and — with `--expect-project-id` — workspace + identity) and writes nothing until it succeeds; it then records the + per-user activation sidecar (`.beads/http_target.json`, never + git-tracked — `cmd/bd/doctor/gitignore.go` now requires it and its local + metadata sidecar `http_local_metadata.json` be ignored) and sets + `metadata.json`'s backend to `"http"`. `bd connect` refuses a plain `http://` + URL to a non-loopback host (a bearer credential would cross the network in + the clear) unless `--allow-plaintext` is given, and refuses to switch a + workspace that already selects a different backend unless `--force`. A + credential is never accepted on the command line or written to disk; it + comes from the same ladder every http request already uses + (`BEADS_HTTP_TOKEN=host[:port]=`, then + `BEADS_HTTP_TOKEN_COMMAND=host[:port]=`, then the credentials + file, then none); both variables take only that host-scoped form, and a + bare value is refused, since it would be sent to whatever server the + workspace's `http_target.json` names. + `bd create` sends no `created_by` on any backend: the + create role defaults it to the request's actor (see *Changed*). The + external-dependency policy decorator (`internal/storage/externaldeps`) + still wraps an http store, and passes every ready, claim, claim-next, + close, blocking and tree request through untouched when the server's + handshake advertises `policy.external_dependencies`, which every `bd + serve` composed through the policy now does (see below). Only against a + server that does not advertise it (an older `bd serve`, or one handed raw + roles) does the client apply the policy itself, in role terms: ready reads + and the ready claim exclude the workspace-wide externally blocked set over + a widened window, and per-issue checks (claim, close, batch close, list + annotations, tree leaves) read only the named issues' edges. + `bd close --claim-next` refuses over http before anything closes, since + the wire's batch close cannot carry the claim; its error says to close + without it and then run `bd ready --claim`. +- `bd serve` advertises the conditional behavior token + `policy.external_dependencies` exactly when the roles or provider it + serves were composed through the external-dependency policy + (`httpapi.Config.ExternalDependencyPolicy`, which `bd serve` derives with + `externaldeps.Applied` / `externaldeps.AppliedToProvider`); a server handed + raw roles withholds it. A client that sees it hands claim-next to the + server as one atomic call and takes the ready count from the server, + instead of judging external dependencies a second time against the CLIENT + machine's project config. +- `bd ping` works on an http workspace (a new `storage.Pinger`, which the + http store answers with its authenticated context read). +- The public `backend/http` package (`bdhttp`) is the out-of-tree door onto + this backend for an embedder that links beads as a library rather than + running `cmd/bd`: `Register(Options)` adds `"http"` to the registry and + installs its transport, `Open`/`Handshake` dial a server directly with no + workspace on disk, and the existing public `beads.OpenBestAvailableWith` + takes a per-call `OpenOptions.Credential` through it — the case a + multi-tenant embedder serving many workspaces needs, where a + process-global credential cannot stand in for one tenant's own. + EXPERIMENTAL, pin an exact beads version. +- Unlimited ready and query reads over the HTTP backend (`bd ready --limit + 0`, `bd query --limit 0`, and every library read asking for no limit) + return every row against any server, bounded on the client by the new + `BEADS_HTTP_UNLIMITED_READ_CAP` (a positive integer up to 1000000; default + 10000). The client never puts `limit=0` on the wire, which a `bd serve + --allow-non-loopback` refuses and which an older server answered with its + default page, silently capping the result: an unlimited ready or query + read is one request bounded at the cap plus one (one consistent snapshot). + Past the cap, or when a server reports more rows below the requested + bound, the read is refused with a typed error + (`httpclient.ErrUnlimitedReadCap`) naming the cap, never truncated. An + unlimited `bd list` is unchanged: it walks its keyset cursor a page at a + time and is bounded only by `--max-rows` / `BEADS_MAX_ROWS`. Unlike a + malformed `BEADS_MAX_ROWS`, which is ignored with a warning, a malformed + cap value fails every unlimited ready or query read rather than falling + back to the default. +- Two molecule capability tokens on `bd serve`. `issues.close.autoCloseMolecule` + announces that `POST /v0/beads/issues/{id}:close` and `POST + /v0/beads/issues:batchClose` accept `auto_close_molecule` and answer + `auto_closed_molecule` and `molecule_auto_close_refusal`; + `issues.advanceMolecule` is the new `POST + /v0/beads/issues/{id}:advanceMolecule`, `bd close --continue`'s advance. + Both run the one library entry (`issueops.CloseRequest.AutoCloseMolecule`, + `issueops.MoleculeStepper`) on the server. The public `issueops` package + gains the molecule rules as one implementation over the BatchGetter, + Relations and EdgeReader roles (`MoleculeRoots`, `LoadMolecule`, + `AnalyzeMolecule`, `ViewMolecule`, `ReadMoleculeProgress`, + `ActiveMoleculeIDs`, `CompletedMolecule`, `MoleculeRootClose`); a + molecule's membership is the parent-child edge. Against a server that + does not advertise a token the HTTP client refuses a library close that + sets `AutoCloseMolecule`, or an advance, before dialing, with a typed + capability error; it never runs a client-side copy of either rule. +- `bd close --json` reports the molecule auto-close. The entry of a close + that completed a molecule carries the root it closed as + `auto_closed_molecule`, or why the root stayed open as + `molecule_auto_close_refusal`, on every route; before, that refusal + reached only stderr. Both members are absent from every other entry, so + each entry still decodes as the closed issue, and the output stays an + array (under `closed` with `--suggest-next`, `--continue` or + `--claim-next`). + ### Changed +- Over an HTTP workspace, `bd ready --json` without `BD_JSON_ENVELOPE` no + longer sends `GET /v0/beads/ready:count` after a page the limit cut short: + the total only went into the stderr hint. It lists one row past the limit + instead, and the hint says more issues matched without saying how many + (the wording the proxied-server route already uses). A local store, and the + envelope's `pagination.total`, keep the total. +- `bd` initializes its packages with `GOMAXPROCS` capped at 4 and hands it + back before `main` runs anything, so the garbage collections package + initialization triggers do not stop the world across every CPU of a large + host. On a 192-CPU machine this takes about 17 ms off every bd process. An + explicit `GOMAXPROCS` is restored as set. +- Over an HTTP workspace, `bd ready` no longer fetches `GET /v0/beads/context` + before its listing in every process only to learn whether the server + enforces the external-dependency policy. The answer is kept for 5 minutes + per server URL and pinned project under the user cache directory + (`BEADS_HTTP_POLICY_CACHE_TTL`, a duration, a number of seconds, or `off`), + and a handshake the process already holds still wins. Claims and closes + always ask the server. +- `bd serve` normalizes every RFC 3339 time bound on the issue listing and + count (`created_*`, `updated_*`, `closed_*`, and the new `defer_*` and + `due_*`) to UTC before it reaches storage. A bound carrying an offset + (`...+02:00`) now selects exactly what its `Z` twin does; previously a + backend whose timestamp column has no zone could read the offset bound's + wall clock and compare it hours off. `bd`'s own client always sent `Z`, so + its answers are unchanged. +- `bd serve` answers a `label_regex` the database cannot compile with + `400 invalid_argument` (`invalid_value` on `label_regex`) on + `GET /v0/beads/issues`, `GET /v0/beads/ready`, `GET /v0/beads/ready:count` + and `POST /v0/beads/issues:claimNext`, instead of `500 internal`. The pattern is + still compiled by the database in its own dialect; only the attribution + of its refusal changed. +- `issueops.Reader.List` refuses `PinnedFlag` together with `NoPinnedFlag` + with `ErrValidation` (`--pinned and --no-pinned are mutually exclusive`) on + every backend; it used to let `PinnedFlag` win silently. `bd list` already + refused the pair at flag parse, so its behavior is unchanged; over HTTP the + pair is a `400 invalid_argument` on `no_pinned`. +- `issueops.Reader.List` refuses `ParentID` together with `NoParent` with + `ErrValidation` (`--parent and --no-parent are mutually exclusive`) on + every backend, as `CountRequest` already did; it used to answer with only + the edge-less rows under the parent's dotted id, which both clauses match. + `bd list` already refused the pair at flag parse, so its behavior is + unchanged; over HTTP the pair is a `400 invalid_argument` on `no_parent`. + +- **`bd gate discover` skips template gates, as `bd gate check` does.** A + template gh:run gate is a proto that work is poured from; on the direct, + proxied and embedded routes `bd gate discover` used to record a discovered + run ID on it, which every later pour copied. It is now left alone on every + route. `bd gate add-waiter` on a template gate is refused by the update + role's template guard, where the direct, proxied and embedded routes all + used to write the waiter. +- **`bd gate create` refuses a negative `--timeout` on every route** + (`timeout cannot be negative`); the direct, proxied and embedded routes + used to store it. A `--type` longer than 32 characters fails with the same + typed validation error instead of a raw Dolt column error. +- **`bd gate create` and `bd gate add-waiter` follow `dolt.auto-commit` + like every other role write.** Under `dolt.auto-commit=off` `bd gate + create` no longer makes its own Dolt commit on the direct and embedded + routes (the proxied route already did not). The Dolt commit messages are + the role's: `bd: create gate X blocking Y` becomes the create's default + message, and `bd gate add-waiter`'s becomes the update's (`bd: update X` + on the direct and embedded routes, `update issue` on the proxied route). + On the proxied route `bd gate create` no longer journals a + `dependency_added` event on the blocked issue, matching the direct route + and `bd create --deps`. +- **Gate members are bounds-checked in the library, on every local backend.** + `issueops.Lifecycle.Create`, `Lifecycle.Update` and `BatchApplier` (create + and update items) now refuse, with a typed `*issueops.GateFieldError` + wrapping `ErrValidation`: a negative `Timeout` (previously accepted and + stored), an `await_type` over 32 characters, an `await_id` over 255 + characters, and a waiter list whose JSON encoding exceeds its TEXT column + (65535 bytes). Creates check all four; an update can change only + `await_id` and `waiters`, so it checks those two. The over-width values + previously failed with a raw Dolt driver error. There is no `await_type` vocabulary, no gate-type-only rule + and no waiter deduplication. +- **Over an http workspace, a bd command answers its repeated reads of a row + or setting from one response.** `bd show --json` makes one request + instead of three, text `bd show` three instead of six, and `bd update`, + `bd close`, `bd label add`, `bd comments` and `bd dep add` one to seven + fewer (port of bd-enterprise e626072b8). A one-shot command's transport + answers an identical `getIssue`, `getSetting` or `listSettings` GET from the + answer it already received, for at most 5 s from that answer. Any write the + command makes clears it, and only a 2xx that decoded is kept. `bd serve`, + `--watch` and `--follow` never memoize, and neither do library embedders. + Within one command a re-read no longer sees another writer's change made in + the meantime (ledger row `L-read-memo`); `BD_HTTP_READ_MEMO=0` turns the + memo off. The identity-gate preview and the real open now share one + transport, so a write makes one handshake. `bd list` reads its vocabulary + with one `listSettings`, and the hook decorator skips its post-write re-reads + when no hook for the event is installed. +- **`created_by` defaults to the actor in the library, for every create + shape and every backend.** `PreparePublicCreateRequest`, which + `Lifecycle.Create`, `BatchCreator` items and batch-apply create items all + prepare through, now sets an empty `Issue.CreatedBy` to the request's + `Actor`; an explicit value is kept. The CLI (`bd create`, the state event + create) and the three `bd serve` create handlers no longer stamp it + themselves. A library caller that left `CreatedBy` empty used to store + `""` locally and the actor over http; both now store the actor. The raw + `CreateIssue` seam is unchanged: import keeps the creator its rows carry, + and `bd swarm`, `bd todo`, `bd gate` and the create form still stamp + `currentActor()` there. +- **On an http workspace, `bd update -s closed` does not record + `closed_by_session`.** The update wire cannot carry it, so the CLI drops + it rather than refusing the close; the status change, its close-policy + guards and every other field in the same update still apply. A one-line + notice on stderr names the drop, both for an explicit `--session` and for + the ambient `CLAUDE_SESSION_ID` every agent under Claude Code exports, so + it is never silent. `bd close` (and `bd close --session`) still records + the session over http: its wire operation carries it. Local backends are + unchanged. +- **On an http workspace, `bd reopen` sends no Provenance label.** The + CLI's label is the fixed `bd: reopen `, which the wire cannot carry; + the server records its own reopen entry for the same issue and actor, so + the reopen no longer refuses. Local backends still record the label. +- **Routing settings are local-only on a remote backend.** For an http + workspace, `routing.mode`, `routing.contributor`, `routing.default`, + `routing.maintainer`, `contributor.auto_route` and + `contributor.planning_repo` come from local config (`config.yaml` or the + environment) only; the server's shared settings document is not read for + them, because routing targets are local filesystem paths that one shared + document cannot name for every client. `bd create`'s routing decision, `bd + migrate-personal` and the missing-id lookup fallback all read the same + local-only answer, and none pays a settings round trip for it. Local + backends still fall back to the database values. +- **The molecule auto-close runs inside the step's close, and an error in + it fails the close.** `bd close` of a molecule's last step closes the + root in the same transaction (opt-in `AutoCloseMolecule`, so an + orchestrator that runs its own molecule lifecycle is not doubled), and it + replays on an idempotent re-close. The root close is unforced, so a root + a direct close would refuse stays open and is reported while the step's + close stands: one its close policy refuses (such as a live blocker), and + now also one a close guard refuses (a template, a pinned root, a root + another actor holds). Any other failure of the root close (such as a + storage error) now fails the step's close with it, where the CLI used to + close the root afterwards and only warn. + Two closes that finish a molecule's last steps at the same time no + longer leave its root open: one of them retries and closes it. The cost + is that concurrent closes of steps under one open auto-closing root now + serialize, whether or not either finishes the molecule: each conflict is + retried, and a close still conflicting when its retry budget runs out + fails with the serialization error. A batch close reports each root once, + on the first item under it that closed. +- **`bd close --continue` claims the next step for real.** The advance is + the `MoleculeStepper` role on every route: the assignee is set and a step + another agent holds is skipped, never taken (the direct and http routes + used to flip the status only). +- **`bd mol current`, `bd mol progress`, `bd ready --mol` and `bd mol show` + read through the library's molecule entries on every route**, so + membership is the parent-child edge everywhere (`bd mol show` no longer + adds children found only by an id pattern). +- **Against a server without the molecule tokens, `bd close` says what it + did not do.** If the server does not advertise + `issues.close.autoCloseMolecule` (an older `bd serve`, or one whose + orchestrator owns the molecule lifecycle), the close goes out without the + auto-close request. When that leaves a molecule with every step closed and + its root open, a notice on stderr names the root, once per root in a batch + and again on a re-close; a step under an ordinary epic or an unfinished + molecule prints nothing. If it does not advertise + `issues.advanceMolecule`, or the handshake that would say so fails, `bd + close --continue` refuses before closing anything, so the step is never + left closed with the next step unclaimed. +- Every `bd` invocation used to start two git subprocesses before doing any + work: `git rev-parse` to locate the repository and `git config user.name` + to resolve the actor. On Linux the repository is now located in-process + (ordinary repositories, linked worktrees, submodules, no repository), + producing exactly what `git rev-parse` printed and still running git for + anything it does not model (`GIT_DIR` and related overrides, + `core.worktree`/`core.bare`, repository extensions, includes, foreign + ownership subject to `safe.directory`). The `git config user.name` actor + fallback is resolved only when a command actually needs an actor, so + read-only commands such as `bd list` and `bd show` start no git process + for it. The actor's value and priority order are unchanged. In an embedded + workspace with `backup.enabled` unset, the per-command auto-backup check + ("is there a git remote?") is likewise answered from the git config files + when they are plain (no includes, no command-line config), instead of + running `git -C .beads rev-parse --git-common-dir` and `git remote`. + +- `bd create --graph` now stores a plan whose path from a node's parent to + the node runs through a `waits-for` edge; the graph-only preflight that + walked every ready-work edge used to refuse it. The plan now goes through + the same end gate as `bd dep add` and `bd batch apply`, which walks only + the scheduling edges (`blocks`, `conditional-blocks`, `parent-child`) and + stores this shape too. Avoid it in plans: once the `waits-for` spawner has + an open child, every issue in the shape, that child included, stays + blocked and none is ever ready. The same path through scheduling edges + alone is still refused. - `bd preflight --fix --json` no longer returns a `Version sync` fix result: version updates must keep all release surfaces aligned via `scripts/update-versions.sh`. - Release-tag pushes require Go and reject batches containing different release versions. @@ -17,9 +692,748 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `scripts/check-versions.sh` and `bd preflight` list the three that work: with `cmd/bd/version.go` already at the release version, that re-run rewrites only the `.githooks` markers and `uv.lock` and leaves any other drifted file as it was. +- **BREAKING (fail-closed): bd no longer migrates an existing database without + explicit consent** (Beads 1.2 release remediation). The 1.2.0/1.2.1 releases + applied migrations 54–65 at store open on ANY command — including pure reads + like `bd list` — with no prompt, and older binaries then refuse the migrated + database (schema-skew guard). A command that would apply pending + main-sequence migrations to an existing database at store open (in embedded + mode that includes reads) now refuses with guidance instead, and the refused + open performs ZERO writes (dolt_ignore seeding and clone-local migrations + included). Server-mode read commands open without running migrations, so + they keep reading at the current schema. `bd dolt commit` and `bd vc commit` + warn and commit at the current schema without migrating, so the dirty-table + recovery (commit, then `bd migrate schema`) still works on a database that + is both behind and dirty. Consent is any of: `bd migrate schema`, the verb + that names the migration (a preview flag withholds it); `--force` on + `bd migrate` or `bd migrate schema`; or `BD_ALLOW_MIGRATE=1` for scripts/CI + (`BD_ALLOW_REMOTE_MIGRATE=1` is honored as an alias). Bare `bd migrate`, + including `--update-repo-id`, `--inspect` and `--dry-run`, does not consent. + Fresh databases (`bd init`) still migrate to latest — creating a database is + consent for its schema, kept across the retry of an interrupted server + bootstrap — and the same creation principle covers a workspace the + invocation just cloned into existence (`bd init --remote`, `bd bootstrap` + sync), so the #4259 behind-remote flows keep their exact behavior. A + database already at this binary's latest version never consults the gate; + one left at v65 by 1.2.x or at v66 by 1.3.x still has migrations pending + under this release, so it asks once. The remote-backed case keeps all of the + #4259 remote-migrate gate's additional protections (smart gate, adopt + fast-forward, fork-skew analysis) unchanged. JSON consumers: the refusal + renders as a structured error whose `error` states the refusal and whose + `hint` is a non-runnable operator directive (neither names a migration + command or a consent variable), plus a `migrate_consent` object + (`current_version`, `required_version`, `pending`, `severity: "blocking"`, + `human_decision_required: true`, and `options`: `migrate` runs + `bd migrate schema`, or `bd migrate schema --global` under `--global`; + `keep` has no command). +- **Shipped migrations are frozen by CI** (same remediation): the content hash + of every released up-migration (main 0001–0066, ignored 0001–0026, through + the 1.3.x releases) is pinned by `TestShippedMigrationsAreFrozen`. Any + amendment to a released migration must land as a new migration (0070+, or + ignored 0028+, as of this change) so installed schemas and freshly-migrated + ones cannot fork. +- **BREAKING: the close guards now hold for every close operation, not only + `bd close`.** The template read-only guard, the pin guard and the assignee + authority fence (be-035) used to be a pre-read in `cmd/bd`, so a close + through `bd serve` (`POST /v0/beads/issues/{id}:close`), `issues:batchClose`, + a `close` item of `issues:batchApply`, or a library caller of + `issueops.Lifecycle.Close`, `BatchCloser` or `BatchApplier` closed a + template, a pinned issue, or a bead another actor holds that `bd close` + refused. They now live in the role, inside the close's own transaction, on + every backend: a template refuses with `*issueops.TemplateReadOnlyError` (no + bypass), and unless `Force` is set a pinned issue refuses with + `*issueops.PinnedError` and another actor's bead with + `*issueops.CloseNotAssigneeError` (matching `ErrNotOwner`). Over HTTP they + are `409` `template_read_only`, `issue_pinned` and `not_assignee` (the + holder in `assignee`, also on a batch-close outcome), and the client + rebuilds the same typed errors. `bd close` prints the same lines and exits + as before, and `bd close --if-revision`, which skipped the guards, now + applies them too. Two paths stay outside the guards. The raw storage + `CloseIssue`, which a `close` line of `bd batch` and the other closes + `cmd/bd` makes outside `bd close` use, runs neither the guards nor close + policy on dolt, embedded or proxied; over HTTP it now sends + `force`, so there it also stops applying close policy, and only a template + refuses. A status update into the done category (`bd update -s closed`, a + `PATCH` whose `status` is done, an `update` item of `issues:batchApply`) + answers to close policy only, as before, so it still closes a pinned issue + or another actor's bead. Migration: HTTP and library callers that close + pinned issues or beads another actor holds must send `force` (`Force` on the + request), or reclaim the bead first; the close operations never close a + template, forced or not (pour it instead). +- **BREAKING (out-of-tree storage backends): a create without a priority now + arrives as priority 0 with `DefaultPriority` set.** `bd create` without + `--priority`, a `bd create --graph` node without `priority` and a + `bd create --file` template without a valid `### Priority` used to reach a + backend's `IssueLifecycle().Create`, `BatchCreator().CreateBatch` and + `BatchApplier().ApplyBatch` as priority 2. They now arrive as priority 0 + with `issueops.CreateRequest.DefaultPriority` (or `BatchCreateItem` / + `CreateItem.DefaultPriority`) set, as does an HTTP create without + `priority` when `bd serve` fronts the backend. The fields are additive, so + such a backend compiles unchanged, but the shared preparation that applies + the default lives under `internal/`, so a backend that ignores the flag now + stores P0 (critical) for those `bd create` paths, and still stores P0 for + that HTTP create. Migration: store `issueops.DefaultCreatePriority` when + `DefaultPriority` is set, and refuse `DefaultPriority` with a non-zero + priority as `ErrValidation`; `conformance.RunRoleContracts` checks both + through `RunLifecycleCreateAppliesTheDefaultPriority`, + `RunBatchCreatorAppliesTheDefaultPriority` and + `RunBatchApplyAppliesTheDefaultPriority`. ### Fixed +- An HTTP workspace whose server cannot be reached now says which step + failed. A connect that is refused names the address and says nothing is + listening; one that times out (a filtered port, a down host) names the + address that never answered and how long it waited; a host name that does + not resolve is named as such. The error was the transport's + `Get "https://…/v0/beads/context": dial tcp …: i/o timeout`, which named the + request rather than the address. +- **`bd link` works over a connected HTTP workspace.** It wrote through the + store's raw `AddDependencyWithOptions`, which the HTTP client refuses, so + every `bd link` failed there with `operation "AddDependencyWithOptions" not + supported by the http backend`, whatever the type. It now writes through + the `DependencyEditor` role, the route `bd dep add` takes, on the direct + and HTTP routes alike (the proxied-server route is unchanged). Over HTTP + that is one `dependencies:add` request, so `bd link` keeps accepting any + non-empty type of at most 32 characters (`owned-by`, `ships-in`, ...). + An empty or over-long type is still refused before anything is written, + and an edge that already exists with another type still reports the typed + conflict. On a Dolt store the history commit is now the role's, like + `bd dep add`'s: `bd: dep add ` in place of + `dependency: add -> `. + +- **`bd query` reports an uppercase duration unit as an unparseable time, not + a negated internal error.** `created>30M` failed with + `not a compact duration: "-30M"`, naming a value nobody typed; it now fails + with `cannot parse time expression: "30M"`. A signed spelling + (`created>+30M`) stops at the parser, as `created>+30x` already did, so + quote one to match it as a literal (`label="+30M"`). Units remain lowercase + (`30min`, `6h`, `7d`, `2w`, `3m`, `1y`); help and docs already say so. +- **Strict `--readonly` no longer creates workspace gate files.** A + `bd --readonly` command took its shared workspace gates with + create-if-missing, so on a workspace no bd command had gated yet it left + `/.beads.gate.lock` and the physical-root gate file + (`.beads/embeddeddolt.gate.lock` or `.beads/dolt.gate.lock`) behind, although + strict readonly promises not to mutate the workspace. It now opens an + existing gate file read-only and holds it shared as before, so a maintenance + operation still sees it and a running one still makes it wait; when no gate + file exists it holds nothing. Every other command still creates the files. +- **Strict `--readonly` refuses `bd backup init`, `backup sync`, + `backup remove`, `backup restore` and `bd import`.** None of them checked + readonly mode. On a server-mode store they ran to completion under + `--readonly`: `backup init` and `backup remove` rewrote or emptied the + server's backup registry, `backup sync` wrote the backup destination, + `backup restore --force` replaced the store, and `import` wrote issues. On + an embedded store they failed with the storage layer's `store is read-only` + error instead, after `backup sync` had left `.beads/backup.lock` behind and + `backup restore` had left workspace-gate holder files. They now exit 1 with + the standard `Error: operation '' is not allowed in read-only mode`, + and a restore is refused before it takes the exclusive workspace gate. + `bd import --dry-run` is refused too, as `bd create --dry-run` already is + and as a migration freeze already refuses it. `bd backup status` still runs + under `--readonly`. +- **`bd init --server --external` no longer starts a Dolt server of its own.** + Init builds its store config by hand and turned auto-start on for every + server init, so an `--external` init that named no port launched a + repo-local `dolt sql-server`, although `--external` says the server is + managed outside bd. `--external` now turns auto-start off. When the + external server cannot be reached, init gives one message on every route + (host and port, socket, shared server, auto-start pinned off): it names the + endpoint it dialed, says that bd did not start a server, and no longer + advises `bd dolt start`. With no port named at all, it asks for one + (`--server-port` or `BEADS_DOLT_SERVER_PORT`) instead of offering a default. +- **A failed `bd init --server` can be retried.** A first attempt that could + not reach its server left an empty `.beads/dolt` and nothing on disk that + records the server choice, so the legacy-upgrade guard refused every retry + as a "legacy Dolt workspace" and no bd command could repair it. When init + itself selects server mode, the guard now admits exactly that root: empty, + with no `.local_version` witness. A pre-1.0 witness, or a `.beads/dolt` that + holds anything, is still refused, and commands other than `bd init` are + decided as before. +- **A graph-mode workspace is refused instead of opened as an Issue store.** + Graph-preview builds mark their workspaces with `"graph_mode": "link"` and + `graph_*` binding fields in `metadata.json`, beside an ordinary Dolt + backend. bd opened such a workspace as an Issue store and ran Issue schema + initialization against the graph database, and every `metadata.json` rewrite + (including the `config.json` to `metadata.json` migration) dropped the + marker and the binding. Now any `graph_mode` other than `dependency`, + including a value bd does not recognize, makes every command that runs in + the workspace or names it with `--db` or `BEADS_DB` (`bd init`, `bd doctor` + and `bd bootstrap` included), and `bd create --repo` aimed at it, refuse it + before touching anything. The refusal names the format and exits with code + 16, so installed beads git hooks refuse commits and pushes there too. + Commands that reach such a workspace only through a route from another + one, such as a routed `bd show`, fail without touching it, but not with + code 16. Store-less commands such as `bd version` and `bd help` still run. + A `metadata.json` rewrite keeps `graph_mode` and the `graph_*` fields + graph-preview builds write, and like those builds it omits a zero + `graph_schema_version` and a false `graph_ready`. +- **A graph workspace without `graph_mode` in its metadata is refused too.** + Graph-preview builds write a `.beads/graph-preview-format` marker before + `metadata.json`. bd ignored it. When an older bd had rewritten + `metadata.json` without `graph_mode`, bd opened the graph database by its + recorded name and ran Issue schema initialization against it; when + `metadata.json` was never written or was lost, bd fell back to the default + database name and created an Issue database inside the graph workspace, and + `bd init` initialized an Issue workspace there. A `.beads` holding that + marker, whatever it contains and whatever its metadata says (absent, + stripped, unparseable or an explicit `dependency`), is now refused wherever + a `graph_mode` workspace is: commands run in it or naming it with `--db` or + `BEADS_DB`, `bd create --repo` aimed at it, and `bd bootstrap` in a + workspace below it that would take its metadata exit with code 16 and a + hint to restore `metadata.json`, and routed and cross-repository opens fail + without opening its database. +- **The Go library's opens refuse a graph workspace too.** + `beads.OpenBestAvailable`, `OpenBestAvailableWith`, `OpenFromConfig` and + `OpenGated` opened a workspace whose `metadata.json` declares a + `graph_mode` other than `dependency`, or whose `.beads` holds the + `graph-preview-format` marker, as an Issue store and ran Issue schema + migrations into the graph database. They now + return `*beads.UnsupportedWorkspaceFormatError` (match it with `errors.As`) + before opening, creating or changing anything, the same refusal the CLI + exits 16 with. +- **`bd setup claude --remove` no longer leaves a blank-line hole.** Removing + the beads section from `CLAUDE.md` (or, with the other setup recipes, from + `AGENTS.md` or `GEMINI.md`) left the blank lines around it behind, three in + the `CLAUDE.md` `bd init` writes, and setup then re-added the section after + two more, so every remove and re-add grew the file. `--remove` now takes + those blank lines with the section, and setup appends a section after one + blank line, so removing and re-adding it toggles between the same two files. + A re-added section goes at the end of the file. +- **`bd config set` no longer truncates a `config.yaml` that has a line of + 64 KiB or more.** Setting an undotted key (such as `actor` or `no-db`) + rewrites the file line by line, and a line of 65,536 bytes or more ended + that read early without an error, so the command reported success and wrote + back only the lines before the long one, plus the key it set. Dotted keys + and `bd config unset` were not affected. Setting an undotted key in such a + file now fails with `bufio.Scanner: token too long`. `bd config set` leaves + the file as it was. `set-many` stops at that key, but it has already written + any `config.yaml` keys listed before it, such as a dotted `sync.remote`. +- **`bd show --as-of` exits 1 when it reads no issue.** A ref the Dolt AS OF + read does not take (an instant, a versioned-history address), a ref that + does not exist, or an issue that did not exist at the ref was reported on + stderr while the command exited 0 with nothing on stdout, even under + `--json`. It now ends the way plain `bd show` does: exit 1, with the JSON + error envelope on stdout under `--json`. A batch that reads at least one of + its ids still exits 0. Both the direct and the proxied-server routes + changed. +- **`bd list --format dot` prints the same graph the same way every time.** + Nodes are declared in id order and edges in source, target and type order. + They used to follow the listing order, which breaks a priority tie by + creation time to the second, so two equal-priority issues swapped places + depending on whether they were created in the same second, and the + proxied-server route did not pin the order of one issue's edges. `--sort` + and `--limit` still choose which issues are listed. +- **`bd init --quiet` no longer prints "Removed SessionStart hook" or "Removed + PreCompact hook"** when the project's `.claude/settings.json` (or the legacy + `.claude/settings.local.json`) still carries the bare `bd prime` hooks an + older bd registered. The hooks are still migrated to the SessionStart + `bd prime --hook-json` hook; the removal lines now go to the installer's own + output, which `--quiet` discards, instead of straight to stdout. +- **A new `AGENTS.md` from `bd init` lists `bd dolt push` in its Quick + Reference only when the workspace has a Dolt remote.** The managed Beads + section already left out its push lines when no Dolt remote is configured or + the workspace is `no-push`, but the Quick Reference above it still showed + `bd dolt push # Push beads data to remote`. It now follows the same rule. + `bd init` still leaves an existing `AGENTS.md` alone outside the managed + section, and writes an `--agents-template` as given. +- **`bd setup claude` no longer rewrites a CLAUDE.md whose beads section is + already current.** A rerun (and `bd init`, which runs it) wrote the same + bytes back as a new file, resetting its mode to 0644 and its mtime, and + reported "Updated existing beads section"; it now leaves the file alone and + reports the section current (the report `bd init` already gives a current + AGENTS.md). `bd setup factory`, `opencode`, `mux` and `gemini` share the + fix. A section whose END marker is missing or comes before BEGIN, which was + also reported as updated while nothing changed, is now reported as an error: + `bd setup factory`, `opencode` and `mux` exit 1 (`mux` before installing its + `.mux` hooks), while `claude` and `gemini` warn and carry on. When CLAUDE.md + is an `@AGENTS.md` stub and it is AGENTS.md that cannot be updated, `claude` + now names AGENTS.md in the warning and keeps the beads block left in the + stub, which it used to delete although AGENTS.md was never updated. +- **Time-bound filters and the keyset cursor compare the same instant on every + engine, whatever zone they are given in.** The storage filter builder binds + every time bound (`created_*`, `updated_*`, `closed_*`, `started_*`, + `defer_*`, `due_*`) as the UTC spelling of its instant. An engine whose + timestamp column carries no zone drops a literal's offset, so a `+02:00` + bound would have compared as that wall clock; Dolt already honored the + offset and `bd` resolves bounds to UTC, so no answer changes here. The + keyset cursor (`AfterCreatedAt`) is now bound in UTC too: embedded Dolt's + driver sends a `time.Time` as its wall clock with no zone, so a library + caller paging with a cursor in another zone was answered from the wrong + position there (server Dolt was unaffected). +- **`bd setup claude --global` keeps its beads section in `~/.claude/CLAUDE.md`.** + It wrote the section into the current directory's `CLAUDE.md`: run from your + home directory it created `~/CLAUDE.md`, which by default stops Claude Code + reading `AGENTS.md` in the projects below it, and `--remove --global` + stripped the section a project's own install had put in its `CLAUDE.md` + while leaving that project's hooks in place. A global install and removal now + use only the user-level files beside `~/.claude/settings.json`. A new + `~/.claude/CLAUDE.md` holds just the section, rendered the same whichever + project you run from. Claude Code loads that file in every project, so its + section, task-tracking rules included, applies only in repositories that use + beads. With global or plugin hooks `--check` accepts it when the project's + instructions have none, or names `--global` when it is missing and the + project has no `CLAUDE.md` of its own. Run from `~/.claude`, + or from your home directory unless `~/CLAUDE.md` still holds a section an + earlier run left there, `--check` judges the user-level files, and from your + home directory it names `--global` when no hooks are installed. From your + home directory, whose `.claude/settings.json` is the global one, `--remove` + removes the user-level section with the hooks. If you ran `--global` before, + re-run `bd setup claude --global` to add the section to `~/.claude/CLAUDE.md`. + A section an earlier `--global` run left in a directory's `CLAUDE.md` stays + there; delete it by hand if you don't want it. +- **`bd blocked --label`, `--label-any` and `--exclude-label` apply to a row + blocked only by an unsatisfied `external:` dependency.** The + external-dependency policy lists such a row itself, after the label query + has run, and it was listed whatever its labels; it is now narrowed by the + label filters like every other row, on every route. On the proxied-server + route such a row also printed with no labels; it now prints them. +- **`bd gate add-waiter` survives contention the store gave up replaying.** + It retried only a version miss, so a convoy adder failed when its guarded + write ended in a serialization failure or deadlock the backend stopped + replaying (Dolt/MySQL 1213/1205, Postgres 40001/40P01), or, over HTTP, in a + 503 busy. Those are now retried, but at most twice: each arrives only after + the store or `bd serve` has spent a whole replay budget on the write (up to + 15s), so the 20-write bound a version miss gets could hold an adder for + minutes. Each retry waits the jittered backoff plus a busy answer's + Retry-After, as `bd serve` sent it. The retry is safe because every round + re-reads the gate, deduplicates and writes the whole list guarded by the + version it read: a 503 is not proof that nothing was written (a gateway can + answer one after the commit), and a write that did land is found on the + re-read, so the waiter is never added twice; when the last write allowed is + answered busy, one more read checks for it before the command fails. A + server fault (500) and an unreachable database are still returned at once, + and once the retries run out the error says no write was confirmed and + names the write contention, instead of saying the gate kept changing. +- `bd list --title-contains X` works against an HTTP workspace. The client + folds it onto the listing's existing `title` parameter (the store compiles + both flags to the same case-insensitive substring predicate), so it needs + the `issues.list.title` capability, like `--title`. A `--title` and a + `--title-contains` that differ other than in letter case are two + predicates, so they ride `title` and `title_contains` together and also + need `issues.list.filters` (see Added), as does the `--closed-after` in + gascity's polecat pre-flight lookup of recently closed beads. Either flag + with `--parent` in the default tree view still refuses over HTTP. +- **`bd gate create`, `bd gate add-waiter` and `bd gate discover` work over a + connected HTTP workspace.** They wrote through the legacy `CreateIssue`, + `AddDependency` and map-based `UpdateIssue`, which the HTTP store does not + implement, so each failed before any gate member reached the wire. They now + run through the library roles on every route: + - `bd gate create` is ONE `Lifecycle.Create` carrying the gate members and + a reverse `blocks` edge from the blocked issue to the new gate, so the + gate and its edge land atomically (one `createIssue` over HTTP, behind + `issues.create.gates`). The direct route used to make two writes and an + explicit commit; the proxied-server route now uses the same role. + - `bd gate add-waiter` reads the gate through `Reader.Get`, deduplicates, + and writes the whole waiter list through `Lifecycle.Update` guarded by + the row version it read. On a version mismatch it re-reads and retries + after a jittered, doubling backoff (10 ms up to 400 ms per wait, at most + 20 writes), so a convoy of workers registering on one gate at once all + succeed. On the direct route concurrent adders used to lose + each other's waiters while every one exited 0; no waiter is lost now. + Over HTTP it needs `issues.update.gates`. + - `bd gate discover` lists through `issueops.ListGates` (as `bd gate check` + does) and records each discovered run ID through `Lifecycle.Update`, the + same `await_id` write `bd gate check` and `bd close` make. Over HTTP it + needs `issues.update.gates`. Its summary now counts only the gates whose + run ID was recorded, and it exits non-zero when any matched gate's write + failed (it used to report such a gate as updated and exit 0). + + Against a server that does not advertise the token it needs, `bd gate + create` and `bd gate add-waiter` are refused before any write, naming the + token; `bd gate discover` writes nothing and reports the token as that + gate's error. The served corpus gains `mc-gate-create-timer`, + `mc-gate-check-timer-resolves`, `mc-gate-add-waiter` and + `mc-update-await-id` (pending until the reference server advertises the + gate tokens), pinned passing by `TestE2E_GatesOverHTTP`. +- **`bd import` no longer reports a failed dependency check as a skipped + dependency.** Import skips an edge the dependency checks refuse (a + self-dependency, a cycle, or a blocker that is the issue's own ancestor or + descendant) and reports it on a `Skipped dependency:` line, or in + `skipped_dependencies` with `--json`. It did the same when the check's own + query failed, for example on a timeout, a dropped connection or a statement + the backend could not run: the SQL error became the skip reason, and on + Dolt, where the transaction survives a failed statement, the import + committed without the edge and exited 0. Such an error now fails the + import. Refused edges are still skipped as before. + +- **`bd mol bond ` ignored prefix routing** — operand resolution now uses + the same routing fallback as `bd show`/`bd update`/`bd close`, so a bead that + lives in a routed store (a prefix-routed rig via `routes.jsonl`, or the + contributor planning store) resolves instead of failing with `'' not found + as issue or formula`. Previously `bd mol bond` resolved operands + against the local store only, so `gt sling ` — which cooks the + default formula and bonds it to a rig-routed bead — died at `bd mol bond` even + though `bd show ` resolved the same ID. Resolution is write-intent: the + routed target opens writable and the bond commits where the bead lives. Two + operands that live in the same routed rig share one store handle and bond + normally; only a bond whose operands resolve to genuinely different databases + is rejected rather than written to the wrong one. As part of this change, an + auto-route — contributor, maintainer or default — now opens writable for the + commands that change an existing issue (`bd update`, `bd close`, + `bd comment`, `bd unclaim`, `bd dep` and the other routed mutation commands, + as well as `bd mol bond`), so the write commits where the issue lives: for a + contributor, in the planning repository, as the contributor workflow + documents. Every auto-route used to open read-only, so on an embedded + workspace these writes were refused. `bd unclaim` now opens a routed issue + writable, as `bd update --claim` does, and commits the release there; on an + embedded workspace `bd human respond` and `bd human dismiss` now record a + routed change as a Dolt commit in the routed repository instead of leaving it + uncommitted in that repository's working set. A routed + write, prefix or auto, never creates the target's database: an embedded + repository that has not been bootstrapped yet fails the write instead of + gaining an empty database that `bd bootstrap` would then take for the real + one. An auto-routed store, read or write, now opens the target's own + configured `dolt_database`, as a prefix route already did, even when + `BEADS_DOLT_SERVER_DATABASE` names the current workspace's database. An + auto-routed write refuses a target whose `metadata.json` is unreadable or + names no `dolt_database`, while a target with no `metadata.json` at all (a + planning repository nothing has been created in yet) opens the one embedded + database it holds, or its default database when it holds none or several; a + prefix route still requires the target's `dolt_database`. A + routing failure, such as an unreadable `routes.jsonl` or a + routed store that fails to open, is now reported as itself instead of as + `no issue found matching`. Same routing-parity fix as + [#3608](https://github.com/gastownhall/beads/issues/3608) for `bd close`. + Fixes [#4714](https://github.com/gastownhall/beads/issues/4714). + +- **`bd gate check` works over a connected HTTP workspace.** Its open-gate + listing built the same raw `SearchIssues` filter `bd gate list` did before + S20, so the HTTP backend refused the command before reading a gate and gc's + core `gate-sweep` order (`bd gate check --type=timer --escalate`) failed on + every remote scope. It now lists through `issueops.ListGates` over the + route's Querier (direct, proxied and remote alike). Closing a resolved gate + was already served. A bead gate's first sighting of its awaited bead + (`await_seen`, recorded when the check finds that bead, not yet closed, in + the gate's own store) was written through the legacy map-based + `UpdateIssue`, which the HTTP store does not implement, so every open bead + gate with an open target was an error on every sweep; it now goes through + the Lifecycle role's `Update` (a single-key metadata set, `issues.update` on + the wire), as does the gh:run discovery's `await_id` persist, which the + HTTP client sends to a server that advertises `issues.update.gates` (see + Added). Against an older server it refuses that patch before the dial, so a + gh:run gate with a workflow-name hint stays that gate's error, naming the + missing token and the server rather than a Go method. + The sweep also skips the gates of a persisted proto + (`bd cook --persist`): they are templates that every pour copies, so a + write to one was refused on every sweep and, in a local workspace, a + resolved one (an expired timer, say) was closed in the proto itself. The + listing's query leaves them out (`template=false`), so they take no row of + `--limit` and cannot crowd a live gate out of the sweep; `bd gate list` + still lists them. A negative `--limit` is now an error; the direct and + proxied routes used to read it as no limit. The served corpus gains + `mc-gate-check-timer`, `mc-gate-check-gh`, `gate-check-all` and a served + test over await-typed and template gates. + +- **`bd list`'s text renderings read only the listed issues' dependency + edges.** The tree (the default), `--deps`, `--parent`, `--format` and + `--watch` loaded every dependency record in the workspace + (`GetAllDependencyRecords`) to draw one page. Over a connected HTTP + workspace that is a walk of the whole workspace: every issue id, 200 per + request, then every id's edges, 100 per request. `bd list --limit 20` + against a ~3,800-issue workspace made 62 sequential requests (~5.7 s at + ~50 ms a round trip). Every rendering reads only edges a listed issue owns, + so the listing now reads exactly those through the `EdgeReader` role: one + request per 100 listed ids over HTTP. The same listing makes 6 requests + (~0.5 s), one more than `bd list --json`, and prints the same bytes. On a + local store a default page is as fast or faster. A listing that covers most + of a large store now pays batched reads (four queries per 200 listed ids) + instead of one scan of both edge tables, which costs more past roughly + 1,000 listed rows: +0.07 s at 1,000 rows and +0.46 s at 4,000 on embedded + Dolt. A store with many wisps, whose edges the old read also scanned, is + faster at every page size. +- A heartbeat can no longer resurrect a lease after a release or close. A + heartbeat re-arming a hand-doled claim (in_progress with no lease row) could + race a release or close on Dolt and leave an orphaned lease row on an open + or closed issue; every later heartbeat by the former holder then refreshed + it and answered success for a claim it no longer held. This affected every + Dolt route, including releases before this one. The re-arm is now recorded + as a mutation and remints the issue's row_lock, which every claim-ending + path rewrites, so it collides with a racing release or close and one side + is replayed against the other's result (the cost: a hand-doled claim's + first heartbeat changes its `revision` once). The refresh also requires, in + the same transaction, that the issue is still in_progress under the holder, + and a refusal deletes the caller's orphaned lease row, so a lease row + orphaned any other way never answers a heartbeat. A refresh and a refusal + still make no Dolt commit on any route; a re-arm commits only its own + tables (never `DOLT_COMMIT('-Am')`), so another writer's uncommitted + batch-mode edits to other tables stay uncommitted (a re-arm stages its + tables whole, as every other direct-route write does). On embedded Dolt, a heartbeat landing in + the same second as the previous one no longer re-grants the lease + (rewriting its `granted_at` / `granted_node`), and on every route a + heartbeat whose actor is a different spelling of the lease's holder + (`gastown.mayor` for `gastown__mayor`) refreshes the lease in place, + keeping its `granted_at` and granting replica, instead of re-granting it + under this node. For a Postgres port: the + refresh now reads the issue row, so under SERIALIZABLE expect more retried + serialization failures between a holder's own edits and its heartbeat. +- **`bd gate list` works over a connected HTTP workspace** (S20). The + workspace-wide listing built a raw `SearchIssues` filter, which the HTTP + backend refuses, so gc's `renudge-stale-human-gates` order failed on every + remote scope. Every route now calls one library entry, + `issueops.ListGates`, which asks the Querier role (`queryIssues`, served by + every deployed server) for `type=gate` with closed rows hidden unless + `--all`: the same rows the raw filter selected, on both planes. `--limit 0` + is unlimited, as before. The bead-scoped form (`bd gate list `) is + unchanged. +- **`bd export` works over a connected HTTP workspace** (S21). It read + through the raw `SearchIssues` method and the bulk label, dependency and + comment reads, which the HTTP backend refuses, so gc's 15-minute JSONL + export order (`gc bd export --all`) failed on every remote scope. On a remote + backend the read set now comes from one library entry, `issueops.ReadExport`, + composed over role reads every deployed server publishes: an unlimited + `Reader.List` for the rows, their labels and counts, `EdgeReader.ReadEdges` + for the dependency records, and `Reader.Get` with comments for each row + that has any. The JSONL is written by the same code as on every other + route. Memories (`--all`, `--include-memories`) come from the served memory + plane (`listMemories`), not the settings listing, which withholds every + `kv.*` row and so exported none. A failed read fails the export, never + shortens it. A remote export does not yet stamp the `wisp_plane` marker, + because the server publishes no plane membership. So a current `bd import` + of a remote export puts genuine no-history wisps on the durable issues + plane instead of the wisps plane, and gc's JSONL archive keeps them. + Nothing is dropped. +- **A silent HTTP connection no longer costs a read the full 60s.** The HTTP + backend client gives a read's first attempt 15s from when it is sent to get + its response headers (`BEADS_HTTP_RESPONSE_HEADER_TIMEOUT`: a duration, a + number of seconds, or `off`), then retries it once on another connection + with no header timer, on what is left of the same 60s request timeout. A + slow but healthy read still finishes if its retry's headers and body + together fit in that remainder (about 45s); one that needs longer now fails + at 60s. A read whose connection is reset is retried the same way (on Windows + only when the reset surfaces as an early EOF), and each retry is logged to + stderr with its count. The events:watch stream's connect gets neither the + timer nor the retry. A write is never retried; one that was sent and timed + out before its headers fails with a typed `wire.ResponseHeaderTimeoutError` + naming the server's host, because it may or may not have been applied, + while a dial or TLS timeout stays a plain connection error. The batch get, + a read on POST, is now also retried on a 503 the way a GET is. +- **A large batch apply over HTTP no longer fails at 60s while the server + commits it.** `bd serve` runs an `issues:batchApply` of more than 100 items + (a large `bd create --graph` plan, say) under its `--large-apply-ceiling` + (5 minutes by default), on a context detached from the client, but the HTTP + backend client gave every request 60s. A large apply that took longer + failed client-side with a timeout while the server went on to commit it. + Such a request is now dialed with 6 minutes, which covers the server's + default ceiling plus what it may spend before (reading the request, waiting + for the one-wide large-apply slot) and after (writing the answer back). + Every other request keeps 60s. An `*http.Client` passed in through + `backend/http`'s `Options.HTTPClient` is raised the same way for that one + request when its `Timeout` is shorter than 6 minutes; one with no `Timeout` + stays unbounded. A server whose `--large-apply-ceiling` is raised past about + 5m15s can still outlast the client: it does not advertise its ceiling, so + the client cannot learn it. +- **An update of a template is now refused for every caller, not only + `bd update`.** The template guard used to be a pre-read in `cmd/bd`, so an + update through `bd serve` (`PATCH /v0/beads/issues/{id}`), an `update` item + of `issues:batchApply`, or a library caller of `issueops.Lifecycle.Update` or + `BatchApplier` edited a template that `bd update` refused. It now lives in + the role, in the update's own transaction, on every backend: any update + naming a template refuses with `*issueops.TemplateReadOnlyError` (matching + `ErrTemplateReadOnly`), whatever its patch and force flags, after the + compare-and-set guards. Over HTTP it is `409` `template_read_only`, and the + client rebuilds the same typed error. HTTP and library callers that edited + templates are now refused (pour the template instead) unless they set the + new `UpdateRequest.AllowTemplate` (`allow_template` on the PATCH body), which + stands the guard down for that one request. `bd update`, `bd assign` and the + proxied `bd tag` print the same line as before; `bd label` and + `bd set-state` set `AllowTemplate` and keep editing templates as they always + have. A batch create that makes a template and splices its metadata still + lands: the splice finishes the create. Version skew: a new `bd` against an + older `bd serve` (no `issues.update.allowTemplate` token in the handshake) + refuses a single template update itself before dialing, and never sends + `allow_template` to it. A batch `update` item gets no such check (its target + resolves on the server), so through an older `bd serve` it still edits a + template. An older `bd label` or `bd set-state` against a new `bd serve` + cannot send `allow_template`, so it now gets `409` `template_read_only` on a + template; upgrade the client. Not yet moved: `bd comment`, `bd note`, + `bd priority` and `bd tag` still refuse templates with their own pre-read in + `cmd/bd` (their direct-route writes do not go through `Lifecycle.Update`), so + for those four the guard lives only in the CLI. Claim, reopen, `:casMetadata` + and the served `addComment` have no template check at all yet (bd-jkp9v3): + `POST /v0/beads/issues/{id}:claim` (`issueops.Claimer`) still claims a + template that a `PATCH` with `claim: true` refuses. Close's guards move to + the role in their own change (#7425). +- The dotted-id hierarchy refusal (a child such as `bd-abc.1` may not carry an + explicit edge to its own ancestor, other than the parent-child edge to its + immediate parent) moved from `cmd/bd` into the library as + `issueops.CheckDottedChildDependency` / `*issueops.DottedChildDependencyError` + (unwraps to `ErrValidation`). Every `DependencyEditor` (dolt, embedded, + unit of work, HTTP) and every `BatchApplier` dep_add item now enforces it, so + an HTTP `dependencies:add`, a `batch:apply` edge and `bd create --graph`'s own + edges are refused like `bd dep add` (HTTP: 400 `invalid_argument`). `bd dep + add`, `bd dep --blocks`, `bd link` and `bd dep add --file` print the same + messages as before, and a `bd batch` script's `dep add` line, which neither + backend checked, is now refused with that message and rolls the whole batch + back. The refusal is decided from the two ids, ahead of every check that + reads the stored graph, so for a child whose parent-child edge is already + stored (a `bd create --parent` child) an HTTP caller now gets that 400 where + it used to get 409 `dependency_cycle` (a blocking type) or + `dependency_exists` (any other type). +- An HTTP create (`issues:create`, `issues:batchCreate`, a `batch:apply` + create item) that omits `priority` now stores the create default, P2, as the + spec documents, instead of P0 (critical). The default lives in one place: + `issueops.CreateRequest.DefaultPriority` (and `BatchCreateItem` / + `CreateItem.DefaultPriority`) asks the shared create preparation to store + `issueops.DefaultCreatePriority`; the handlers set it for an absent member, + the HTTP client omits `priority` for it only when the server advertises the + new additive `issues.create.defaultPriority` handshake token (an older + `bd serve` reads an absent `priority` as P0, so a new client sends `2` + explicitly to it), and `bd create` (no `--priority`), + `bd create --graph` (a node without `priority`) and `bd create --file` (a + template without `### Priority`) rely on it rather than spelling 2. An + explicit `0` is still P0, and `DefaultPriority` with a non-zero priority is + `ErrValidation`. CLI output is unchanged on the in-tree backends, except + that `bd create --file` now warns on stderr about a `### Priority` it cannot + parse, as it already did for `### Type`, rather than dropping it silently. + The client decides from the handshake its store cached (once per command + in `bd`), so a create that lands on an older build behind the same URL (a + `bd serve` rolled back under a live store, or mixed builds during a + rollout) still stores P0, with no error on either side. + Out-of-tree storage backends must now honor `DefaultPriority`; see the + BREAKING (out-of-tree storage backends) entry under `### Changed`. +- Blocked-state repair no longer lets a stale `is_blocked` bit on a parent + with no reason row of its own hold itself up through a parent that blocks + on its own child, in a malformed parent-child cycle (gastownhall/beads#7386). + The explained-parent walk, on both the full repair and the per-write + recompute, now climbs through such a parent, whose bit is inherited, + instead of treating it as a final unexplained ancestor; `bd doctor`'s + Blocked State check counts the stale bit and `--fix` clears it. + +- `bd show --current` over the HTTP backend no longer prints the wrong issue. + Its in-progress/hooked lookup used the raw `SearchIssues` method, which + the HTTP backend refuses; the refusal was swallowed and the command fell + back to the last-touched issue, exit 0. The lookup now reads through the + `issueops.Querier` role, and a failed read is an error on every route + (including `--proxied-server`), never a fallback. A miss (nothing in + progress or hooked, or no actor) is another matter: `--proxied-server` now + falls back to the last-touched issue as the direct route always has, where + it used to fail with `no current issue found`. +- `bd list --type --include-ephemeral` (and `GET + /v0/beads/issues` with the same parameters) now include that type's durable + rows — a promoted wisp, an issue retyped after it was created — beside its + wisps, as `--include-ephemeral` promises; the type used to narrow the read + to its wisps alone. `bd count --include-infra --include-ephemeral` and the + count endpoint count the same rows. An infra `--type` without + `--include-ephemeral` still reads only the wisps, and `bd search --type + `, now served by the same listing, still finds that type's + wisps and durable rows alike. +- `bd recompute-blocked` on a workspace connected to `bd serve` is a no-op + that exits 0 instead of refusing: the server maintains `is_blocked` on + every write and the column lives in its database. `--json` reports + `{"rows_corrected": 0, "maintained_by": "server"}`. +- **The http store's `GetIssue` answers a miss with `storage.ErrNotFound`, + like the local stores.** It used to answer a missing (or empty) id with + `(nil, nil)`, which every caller written against the backend contract + read as a hit: `bd create --graph` refused every plan naming an explicit + id over http. The miss is now `not found: issue `, wrapping + `storage.ErrNotFound` exactly as `issueops.GetIssueInTx` does; the empty + id never dials. +- **`bd list`, `bd children`, `bd show --json` counts, the default `bd dep + tree`, `bd ready --claim` and `bd close` work on an http workspace.** The + external-dependency decorator rebuilt its views from storage seams the + http store only partly serves, so `bd list`/`bd children` refused, `bd + show --json` printed zero dependency and comment counts without an error, + and the default dep tree refused; each view now passes the server's own + role through (see *Added*). A missing id is a plain not-found after one + `getIssue`, instead of a partial-id search refusal, and `bd update + --claim` answers a not-found gc classifies. +- **`bd mol wisp gc --age 0s` can miss a just-created wisp.** Dolt's + `DATETIME(0)` column rounds fractional seconds half-up on write rather + than truncating, so a wisp created in the second half of a wall-clock + second can read back with `updated_at` up to 0.5s in the future. The GC's + age check (`now.Sub(updatedAt) > ageThreshold`) then compares against a + negative duration and fails, even though `--age 0s`'s own contract is + that every wisp qualifies. `ageThreshold <= 0` now bypasses the clock + comparison entirely (#7236). +- **`bd mol wisp gc` no longer deletes a fresh step because a wisp it + depends on is abandoned.** The GC applied `--age` only to the wisps it + selected directly, then deleted their dependents at any age as long as + they were not live work, so a step created seconds earlier went with an + old wisp it depended on, and raising `--age` did not help. A dependent + now has to meet `--age` itself, by the same rule as the wisp it depends + on (including the #7236 rounding fix). One that is too young is spared + and loses its edge to the deleted wisp: an open one is collected once it + ages out, a closed one is left for `--all`, `--closed` or `bd purge`, + since without `--all` the GC reaches a closed wisp only as the dependent + of an abandoned one (#5219). +- `bd create --parent` works on the HTTP backend: the create role mints the + `.` child id (and inherits the parent's labels) inside the + create on every route, instead of the CLI reserving it through a raw + `GetNextChildID` the HTTP backend does not serve. `bd mol current` (with + or without an id) and `bd mol progress` no longer answer empty or refuse + over http, and `bd ready --mol` step rows carry their assignee and + timestamps. +- **Server-mode config writes are committed again.** On the direct SQL-server + route, `bd remember`, `bd forget` and `bd config set|unset|set-many` wrote + the `config` table but never created a Dolt commit: `maybeAutoCommit` + returns early off the embedded route, and plain `Commit()` excludes config + (GH#2455). The rows sat in the working set, where `bd dolt push` does not + carry them, and a dirty internal key such as `status.custom` made the next + `bd dolt pull` refuse until an explicit `bd dolt commit`. With + `dolt.auto-commit` on (the default) these writes now commit right away + through the scoped `CommitConfigOnly`, which stages only `config` and the + lookup tables projected from it, so a concurrent operation's other dirty + tables are never swept; `batch` and `off` defer them to `bd dolt commit` + like every other write. `bd remember` and `bd forget` commit only user + `kv.*` rows. When an internal config key is dirty (such as the + `issue_prefix` that `bd rename-prefix` writes), the memory is still + stored but not committed: the command warns on stderr with the keys named + and exits 0, `--json` adds `committed: false`, `commit_error` and + `dirty_config_keys`, and `bd dolt commit` publishes the memory with those + keys. v1.0.1 ([#3052](https://github.com/gastownhall/beads/pull/3052)), + whose commits this restores, also warned on a failed memory commit + instead of failing the write. `bd config unset` of a yaml-only secret key + also commits its delete of a credential row an older bd stored in the + database, so HEAD, which `bd dolt push` publishes, no longer keeps it + ([#4078](https://github.com/gastownhall/beads/issues/4078)). + +- **PRs based on `hotfix/**` branches now run full CI, not just + cross-version historical smokes and triage labeling.** `pr.yml`, + `pr-risk.yml`, `conformance.yml`, `cross-version-smoke.yml` and + `regression.yml` all trigger `pull_request` on `main` and `release/**`, + but not on `hotfix/**` — a backport PR based on a hotfix line (the same + position `release/**` was added for) got no unit shards, no lint, no + risk gate, and no required CI Gate at all: 15 passing cross-version + smokes and triage jobs, nothing else. Added `hotfix/**` alongside + `release/**` in all five (#7148). + + +- **Ordinary bd commands now wait out a maintenance operation instead of + failing at once.** While `bd init`, `bd backup restore`, `bd migrate` or + `bd bootstrap` holds the workspace gate exclusively, every other bd command + on that workspace — and, in shared-server mode, on every project sharing + the server (another project's ~8s `bd init`) — failed immediately with "a + maintenance operation is running". They now wait up to 30s (one "waiting + for another bd process" notice after 2s; Ctrl-C aborts), then fail with the + same error naming the bound (and, in shared-server mode, saying the holder + may be another project). Override with `BEADS_GATE_WAIT_TIMEOUT` (`1m`, + `90`); scripts that relied on the old fail-fast behavior should set + `BEADS_GATE_WAIT_TIMEOUT=0`. Git hooks stay fail-fast so a commit or + checkout is never stalled. Waiting is writer-fair: once a maintenance + operation is waiting for the gate, newly started commands queue behind it, + so a steady stream of short commands can no longer starve `bd init`. The + queue only ever delays a command, never fails it, and a maintenance + operation that cannot get in (for example behind a `bd list --watch`) + stops queueing others after 10s. Queued maintenance operations run one + after another, and a waiting command waits for all of them. The queue + marker is an OS lock beside the gate (`*.gate.lock.intent`, covered by the + existing `*.gate.lock*` gitignore pattern), so a crashed waiter never + leaves a stale queue behind. `bd init`'s own wait (`BEADS_INIT_GATE_TIMEOUT`) + rises from 30s to 60s, since back-to-back inits under load take 10-15s + each. + +- **Concurrent `bd init --shared-server` runs in different projects no + longer refuse each other.** Every shared-server project gates the one shared + dolt data dir, and `bd init` holds that gate exclusively for its ~8s run but + waited only 5s for it, so a second init (or an init during another + project's long command) failed with "bd init refuses to run over live bd + activity". `bd init` now waits (60s by default, see the gate-wait entry + above), printing one "waiting for another bd process on the shared server" + notice after 2s, then fails with the same refusal naming the bound. + Override it with `BEADS_INIT_GATE_TIMEOUT` (`2m`, `90`). Other exclusive + operations keep their 5s wait. + - **A proxied-server command against an unreachable external Dolt upstream now fails within about a second with a clear error instead of stalling ~20-30s.** The local db proxy stayed up, so the client only saw a bare @@ -33,6 +1447,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 is still ridden out within one command. A backend that drops a connection after the greeting, a dial timeout, and every refusal from a managed (local sidecar) backend keep the full transient retry. +- **`bd ready --explain` no longer reports a pinned dependency as a resolved + blocker.** The ready query skips a pinned target exactly as it skips a closed + one, so a `blocks` edge onto a pinned bead never fences its dependent — but + the explanation listed every blocking edge of a ready issue under + `Resolved blockers`, status unread, and a bead wired behind a long-lived + pinned bring-up reported itself satisfied while its precondition was unmet. + Each blocking edge is now sorted by the target's status: closed under + `Resolved blockers` (and `resolved_blockers`), pinned under + `Pinned dependencies (never block)` (`pinned_dependencies`), and any other + status under `Open dependencies (not blocking)` (`open_dependencies`) — the + shape #6066 reports for a foreign-prefix blocker, now visible instead of + passing as resolved. `Reason` keeps its `N blocker(s) resolved` lead and + appends the pinned and open counts as clauses. Both routes fetch the ready + issues' dependency targets alongside the blockers they already fetched. + Pinned-never-blocks itself is unchanged. + - **`bd list` no longer silently drops all but the last repeated filter flag.** `--status`, `--state`, and `--id` were plain string flags, so `bd list --status open --status closed --status pinned` kept only `pinned` — @@ -241,6 +1671,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `bd context` also prints `cwd repo: git: unavailable` rather than silently omitting the one degraded state it exists to report. +- **Server-mode `bd federation sync` and `bd federation status` work with Dolt + remotes that have no stored peer credentials** + ([#5128](https://github.com/gastownhall/beads/pull/5128), fixes + [#4837](https://github.com/gastownhall/beads/issues/4837)). A remote added + by `bd federation add-peer` without `--user` or by `bd dolt remote add` has + no `federation_peers` row, and every server-mode `bd federation` push, pull + and fetch to it failed at the credential lookup with `failed to get peer + credentials: not found: federation peer `. A missing row now means no + stored credentials, as it already did in embedded mode, so the operation + runs with Dolt's own credential discovery: `bd federation sync` without + `--peer` syncs those remotes too, and `status` fetches them. Errors reading + or decrypting a stored row still fail. A mistyped `--peer` now fails with + Dolt's own unknown-remote error instead. + - **`bd comment`/`bd comments add` refuse an abbreviated id and a reserved word instead of silently resolving one to the wrong issue** ([#5393](https://github.com/gastownhall/beads/pull/5393)). `bd comment list @@ -267,6 +1711,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 resolution never performed abbreviation matching in the first place) — a regression test now locks that in rather than leaving it undocumented. +- **`bd delete` no longer resolves an id it cannot find to a different issue + whose id begins with it.** + ([#7375](https://github.com/gastownhall/beads/pull/7375)). The direct + (embedded and server) route resolved + each id with the abbreviation-tolerant resolver, so an id that was already + gone (a retried delete, a re-run `--from-file` list, a parent whose child + survives) resolved by leading-prefix match to whichever surviving issue's id + it begins: after `fx-t00003` was deleted, `bd delete fx-t00003` previewed + `fx-t000031` and printed `bd delete fx-t000031 --force` as the next step, + and with `--force` deleted it. `--quiet` silenced the partial-id notice, so + a `--force --quiet` re-run deleted issues it never named without a word. + `bd delete` now requires an exact id on the preview and with `--force`, as + `bd comment` does and as the team-server route already did; full ids, bare + full hashes, child ids and routed ids resolve as before. An abbreviation is + refused with `issue "t000" not found: bd delete needs the full issue id, and + "t000" is only the start of fx-t000031`, naming every id it matches; under + `--if-revision` it is the guard's lost race instead (`precondition_failed`, + exit 13), as for any other gone id. This is a user-visible change: a script + or habit that deletes by abbreviation now gets that error and must pass the + full id. Reads and other writes keep accepting abbreviations; see [Working + with IDs](docs/core-concepts/hash-ids.md#working-with-ids). + - **A git hook beads never wrote is no longer reported as installed** ([#6084](https://github.com/gastownhall/beads/issues/6084)). `getHookVersion` returns no error for a readable hook file that carries no beads markers, so a @@ -287,6 +1753,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 installed/missing check still only tests for file existence and is tracked separately. +- **`bd close` verifies a bead gate in proxied-server mode.** The close + pre-check built its bead-gate lookup on the local store, which the + proxied-server route never opens, so closing a bead gate there refused with + `no local store available` even after the awaited bead had closed, while + `bd gate check` resolved the same gate. The close pre-check now reads the + awaited bead through the same fresh-read path `bd gate check` uses on that + route; the direct and embedded routes are unchanged + ([#5861](https://github.com/gastownhall/beads/issues/5861) item 1). + +- **`bd recall`, `bd forget`, `bd remember `, + `GET /v0/beads/memories/{key}` and `DELETE /v0/beads/memories/{key}` now + treat an empty-valued memory as present** + ([#5964](https://github.com/gastownhall/beads/pull/5964), fixes + [#5963](https://github.com/gastownhall/beads/issues/5963)). Presence used to + be derived from the stored value's truthiness, so a memory written out of + band with an empty string was invisible even though its row existed. `bd + recall` printed "No memory with key" and exited 1, `bd forget` refused to + delete it, `bd remember ` refused to recall it, and both HTTP + doors answered 404 (the DELETE leaving the row in place), while + `GET /v0/beads/memories` already enumerated the same row. Presence now comes from row existence on direct Dolt, embedded Dolt and + the proxied backend. An empty-valued memory is found, recalls as an empty + string, and is deleted on the first forget. Only a key with no row is a + miss. + - **`bd doctor` no longer flags a `.local_version` that starts with `v`.** The canonical spelling of a Go module version — and the string a build stamped from a Go pseudo-version reports and writes into `.local_version` itself — @@ -643,6 +2133,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 section — plus the upgrade and init-safety ordering rules — now records the `bd dolt pull` exception instead of stating the pull is always refused. + **Proxied-server mode reaches the stop too, and is told where to run the + remedy.** The store-open gate on that path supplied no branch-position + callback, so a proxied clone that was level on schema and behind in data + could never be classified data-behind: it got the blunt shared-store refusal, + whose body is the designated-migrator recipe — `bd migrate --force` then + `bd dolt push` — which in this state is the wedge the stop exists to prevent. + It now routes to the same data-behind stop as every other topology. Because + `bd dolt pull` is refused at the proxied front door + (`proxy.dolt_pull.unsupported`), along with `bd dolt push`, the bare + `bd migrate` and `bd conflicts`, the guidance there names the machine the pull + has to run on rather than printing a command this binary rejects; the `--json` + option is `pull-first-on-server-host`, and `expected` carries the same + qualifier so a single-field reader is not handed a locally-refused command. + The shared-store consent step is the other way round: `bd migrate schema + --force` is *not* refused here — the capability registry permits the + two-word `migrate schema` path — so the guidance says it can be run from this + workspace but only after the pull lands on the server host, and the warning + against forcing past the stop names it alongside `BD_ALLOW_REMOTE_MIGRATE=1` + as the two consent surfaces this topology can still reach. Read-only proxied + opens print the same pull-first block instead of the shared-consent template. + The *Clone behind the remote* docs section the payload links to, and the + upgrade and init-safety ordering rules that point at it, now give the same + proxied-server answer. + Both existing escape hatches are unchanged: `bd migrate --force` / `BD_ALLOW_REMOTE_MIGRATE=1` are still consulted before the smart gate, and `BD_SMART_GATE=0` still yields the blunt gate unconditionally (including for @@ -983,6 +2497,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **`bd init` refuses to initialize directly in your home directory** + ([#4635](https://github.com/gastownhall/beads/issues/4635)). `bd init` sets + up the directory it runs in as a project: it runs `git init` there unless it + finds a repository, and installs agent files — `CLAUDE.md`, `AGENTS.md`, + `.gitignore`, `.claude/`, `.codex/`, `.cursor/`, `.agents/`. In your home + directory most of those are your agents' user-wide settings, so bd's hooks + ended up running in every project, and init did this silently under + `--non-interactive`, which engages automatically whenever stdin is not a TTY + (so: whenever an agent runs it). A project is virtually never the home + directory itself, so this now refuses with exit code `15` + (`ExitHomeDirRefused`; `13` and `14` already mean a lost conditional-write + race and a migration freeze), documented at + `docs/recovery/init-safety.md#init-home-refused`. + + Deliberately narrow: it fires only when the working directory is *exactly* + your home directory, your home is not itself a git repository (tracked + dotfiles are unaffected, but a home that only sits inside an enclosing + repository, or a `GIT_DIR` inherited from the environment, does not count), + and you did not name a `BEADS_DIR` yourself. A subdirectory of home is an + ordinary project and is never refused. If you do name a `BEADS_DIR` from + an untracked home, init sets up only that workspace: no `git init`, no + agent files or `.gitignore` in your home directory, and nothing in a + repository your home sits inside (no hooks, `beads.role`, Dolt remote taken + from its origin, or bootstrap commit) unless a flag such as `--stealth` or + `--setup-exclude` asks for it. `--force` and + `--reinit-local` do not override the refusal — they bypass the local + data-safety guard, which is a different question from "is this the right + directory". The guard runs first in init's `RunE`, ahead of every path with + an effect, including the proxied dispatch and the store-opening + `--reinit-local` pre-checks. + - **The managed shared Dolt server now opens its configured remotesapi listener** ([#6020](https://github.com/gastownhall/beads/pull/6020)). `dolt.remotesapi-port` (machine-global user config) and @@ -1247,6 +2792,71 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **`bd gate check` no longer reports an unreadable store as "pending".** The + bead arm of the check dropped the lookup error on the floor, so with dolt + down (or any backend or transport failure on the awaited bead's read) every + bead gate printed as still waiting and the command exited 0 — the same + output as a healthy, genuinely pending gate. A read of the workspace's own + store that fails for any reason other than not-found is now an error row + (`✗ : error checking - ...`), counted in the summary, and `bd close` + on such a gate keeps refusing (`could not check bead gate`, `--force` to + override) rather than letting a dead store read as satisfied. On the + classic and proxied routes alike, `bd gate check` now exits non-zero + whenever any gate it checks (gh, timer, or bead) could not be checked or + closed. A bead in a prefix-routed rig whose store cannot be read stays + pending, with the routing failure in its reason (`cannot confirm the + awaited bead is gone`); for a missing bead, see + [#6395](https://github.com/gastownhall/beads/pull/6395). + +- **`bd gate check` resolves a bead gate whose awaited bead was deleted** + ([#6395](https://github.com/gastownhall/beads/pull/6395)). A bead gate + waited for its target to close, so deleting the target left the gate + pending forever and its step blocked. The first `bd gate check` that finds + the target in this rig's own store now records the sighting in the gate's + metadata (`await_seen`), and a later check that no longer finds it there + resolves the gate (`awaited bead no longer exists`). An await ID that + no check has seen, such as a typo or a bead deleted before the first check, + stays pending with a diagnostic instead of unblocking the step: correct the + await ID or close the gate with `bd gate resolve`. A miss outside this + rig's store (a target whose prefix routes to another rig, or a contributor + auto-routed store) does not prove the bead gone, so the gate stays pending + and the reason names the cause. `bd close` on a bead gate follows the same + rule: it no longer needs `--force` once an earlier check saw the awaited + bead and the bead is gone from the gate's rig, with no route pointing + elsewhere. `bd rename` and `bd rename-prefix` point a bead gate at its + bead's new ID, sighting included, so a renamed bead does not read as + deleted, even to a check or `bd close` that read the gate before the + rename; a rename that fails partway leaves the gate pending without a + sighting, never resolved. A rename by an older bd does not move the + gate: if a check had already seen the bead, a later check or `bd close` + treats that rename as a deletion and closes the gate while the bead is + still open, so upgrade every client that renames beads together with the + ones that check gates. + +- **An epic that blocks on its own children no longer hides them from `bd + ready`** ([#6506](https://github.com/gastownhall/beads/issues/6506)). A + parent-child edge now propagates only a parent's *exogenous* blockedness — + blockedness whose cause lies outside the parent's own subtree — so the + close-gate idiom, a parent carrying `blocks` edges onto its own children (or + grandchildren) so it cannot close before them, stops darkening the very work + it is waiting for. The parent itself stays blocked, and a close gate does not + unlock the work under an epic that is itself blocked from outside: a sub-epic + blocked BOTH by its own children AND by an exogenously blocked ancestor still + darkens its children + ([#6601](https://github.com/gastownhall/beads/issues/6601)). + "Inside my own subtree" is decided to a fixed depth of **four** + parent-child levels — epic → sub-epic → leg → task — so a parent that + blocks on something deeper than that still darkens its whole subtree, exactly + as it did before this fix; that depth is a measured trade (the + bounded walk is a fixed chain of index probes, where a recursive one cost + 7.5x per evaluation) and raising it is a one-constant change. Existing stores + repair on the next write that touches the hierarchy, or with + `bd doctor --fix`. +- `bd dep add` no longer explains its refusal of a blocking edge onto your own + descendant by claiming the block would cascade down and never clear — it + does not, as of the fix above. The refusal stands, and now names the + sanctioned way to say it: a waits-for gate over the children. + - **`routes.jsonl` prefixes containing a hyphen now route** ([#5048](https://github.com/gastownhall/beads/issues/5048)). Prefix routing cut the bead ID at its first `-` and required an exact match, so a route diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 9f08e2027..000000000 --- a/CLAUDE.md +++ /dev/null @@ -1,23 +0,0 @@ -# Claude Code Entry Point for Beads - -This file is intentionally short. Do not copy workflow, build, storage, or UI -rules here; those details drift quickly when repeated across agent entrypoints. - -## Read First - -- **Workflow and safety**: [AGENTS.md](AGENTS.md) -- **Detailed agent operations**: [AGENT_INSTRUCTIONS.md](AGENT_INSTRUCTIONS.md) -- **Architecture orientation**: [engdocs/CLAUDE.md](engdocs/CLAUDE.md) -- **PR maintenance policy**: [PR_MAINTAINER_GUIDELINES.md](PR_MAINTAINER_GUIDELINES.md) - -## Current Ground Rules - -- Run `bd prime` before doing tracked work. -- Follow `go.mod` and [AGENT_INSTRUCTIONS.md](AGENT_INSTRUCTIONS.md) for build - and test commands; do not hard-code toolchain versions here. -- Beads uses Dolt as the issue database. Use `bd dolt push` / `bd dolt pull` - for issue data sync; do not use export/import as a routine git workflow. -- The CLI Visual Design System lives in - [AGENT_INSTRUCTIONS.md](AGENT_INSTRUCTIONS.md#visual-design-system). -- If this file conflicts with a linked source, trust the linked source and fix - this file by removing the duplicate. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 000000000..47dc3e3d8 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bfd65e364..daca0d8ab 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,14 +2,65 @@ Thank you for your interest in contributing to bd! This document provides guidelines and instructions for contributing. +## Issues and pull requests + +GitHub Issues is the public tracker. Use an issue when it adds context +reviewers need: a user-visible bug, a behavior or design change worth +discussing first, or work that spans several pull requests. The issue holds +why the change is needed, what it affects, and how we will know it works; file +it with the bug or feature form before or alongside your pull request, and it +does not need maintainer approval first. Small, self-explanatory changes +(typos, flaky tests, refactors, CI or docs tweaks) can go straight to a pull +request whose description explains the why. + +### Triage labels + +| Label | Meaning | Applied by | +|---|---|---| +| `status/needs-triage` | Awaiting initial triage. | Automation, on every new issue | +| `status/needs-info` | Waiting on essential information from the reporter. | Maintainers | +| `status/needs-repro` | Needs a reproducible bug report. | Maintainers | +| `status/needs-design` | The direction needs a design decision before work starts. | Maintainers | +| `status/accepted` | Confirmed and on our radar. | Maintainers | + +Issues left in `status/needs-info` or `status/needs-repro` are closed after 14 +days without a reply to the request; reply with the details and a +maintainer will reopen them. +Priority (`priority/p0`–`priority/p3`) and kind (`kind/bug`, `kind/feature`, +`kind/docs`, `kind/chore`) labels are set during triage. + +### Pull request pipeline labels + +These labels drive the maintainers' automated review and merge workflow. They +are applied by maintainers and automation; contributors don't need to set +them. + +| Label | Meaning | +|---|---| +| `status/needs-review` | Request the PR review workflow. | +| `status/needs-review-auto` | Request the automated PR review workflow. | +| `status/reviewing` | The PR review workflow is running. | +| `status/review-failed` | The PR review workflow failed before merge-ready. | +| `status/merge-ready` | The PR is ready for the merge workflow. | +| `status/merge-queued` | Queued for deterministic PR-review merge. | +| `status/merge-failed` | The merge queue needs operator attention. | +| `status/needs-bugflow` | Request the bugflow investigation workflow. | + +The current priorities are on the [roadmap](ROADMAP.md); work in a priority +area is reviewed first. + ## Development Setup ### Prerequisites -- Go (see `go.mod` for the required version; currently 1.26+) +- [Bazelisk](https://github.com/bazelbuild/bazelisk), installed as `bazel` + (it reads `.bazelversion`). **Required:** Bazel is the build and test system + CI gates on, and the pre-commit (nogo lint) and pre-push (test suite) hooks + run it. +- Go (see `go.mod` for the required version; currently 1.26+), for `make + install` and the `go test` inner loop - Git - A C compiler (CGO is required for the embedded Dolt database) -- golangci-lint v2.10.1 for the required local lint gate - ICU headers are **not required** for building -- see [engdocs/ICU-POLICY.md](engdocs/ICU-POLICY.md) ### Getting Started @@ -19,16 +70,44 @@ Thank you for your interest in contributing to bd! This document provides guidel git clone https://github.com/gastownhall/beads cd beads -# Build the project (uses gms_pure_go tag via Makefile) -make build +# Read rbe-west's anonymous, read-only cache: everything CI already built and +# tested is a cache hit, and nothing you build is uploaded. +echo 'build --config=fork-cache' >> .bazelrc.local -# Run tests (uses correct build tags automatically) +# Run the test suite CI gates on (bazel test //... --config=ci) make test -# Build and install locally to ~/.local/bin +# Build and install bd to ~/.local/bin (also enables the git hooks) make install ``` +### Building and Testing + +Bazel is the gate: `.github/workflows/bazel.yml` runs every pull request's +tests as `bazel test` lanes, and nogo (lint + vet), gofmt and the repository +guards exist only as Bazel targets. The make targets run the same commands: + +| Command | Runs | +|---|---| +| `make test` | `bazel test //... --config=ci`: the test lane (unit tests, nogo, gofmt, repository guards) | +| `make check` | the testing.Short policy, `make ci-pr-lint` and `make test` | +| `make ci-pr-lint` | nogo natively plus the windows/amd64 and darwin/arm64 passes | +| `make check-docs` | the Bazel docsync and doc-freshness tests, then the CLI flag check | +| `bazel test //... --config=integration` | the integration lane; [engdocs/TESTING.md](engdocs/TESTING.md) lists every other lane's command | + +Where actions run is your choice, set in the gitignored `.bazelrc.local` (or +per command with `make test BAZEL_FLAGS=--config=...`): + +- `--config=fork-cache` (contributors): reads the anonymous cache, runs misses + on your machine, uploads nothing. +- `--config=remote-exec` (maintainers with an rbe-west client certificate): + executes remotely; the executor and TLS lines stay in your `user.bazelrc` or + `.bazelrc.local`. + +`go test` (`./scripts/test.sh`, or `make test-go` / `make check-go` / +`make check-docs-go`) still works as an inner-loop convenience, but CI does not +enforce it and it skips nogo, gofmt and the guards. Finish with `make test`. + ## Project Structure ``` @@ -38,7 +117,7 @@ beads/ │ ├── types/ # Core data types (Issue, Dependency, etc.) │ └── storage/ # Storage interface and implementations │ └── dolt/ # Dolt database backend -├── .golangci.yml # Linter configuration +├── .golangci.yml # Linter configuration (applied by nogo, tools/nogo) └── .github/workflows/ # CI/CD pipelines ``` @@ -61,23 +140,24 @@ We follow standard Go conventions: ### Linting -Use the same pinned golangci-lint version and repository-owned wrapper as CI: +Lint and vet run as nogo under Bazel: go test's vet checks plus the +golangci-lint linters `.golangci.yml` enables, the same analyzers CI gates on. ```bash -# Install the version pinned by CI -go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.10.1 - -# Run the required formatting and lint contract +# Run the required lint and vet gate (native, windows and darwin) make ci-pr-lint + +# Faster: only the Bazel packages of your changed Go files +make lint-changed ``` -`make ci-pr-lint` must pass with zero issues. It checks formatting, lints the -repository's normal `gms_pure_go` build, and cross-lints Windows-only non-CGO -code. Accepted intentional patterns are encoded narrowly in `.golangci.yml`; -do not ignore a failing baseline. See [engdocs/LINTING.md](engdocs/LINTING.md) -for the full policy. +`make ci-pr-lint` must pass with zero issues. It analyzes the repository's +normal `gms_pure_go` build and cross-checks the Windows- and macOS-only +non-cgo code. Accepted intentional patterns are encoded narrowly in +`.golangci.yml`; do not ignore a failing baseline. See +[engdocs/LINTING.md](engdocs/LINTING.md) for the full policy. -CI runs the same required wrapper on all pull requests. +CI runs the same analyzers on all pull requests, in the Bazel test lane. ## Making Changes @@ -90,21 +170,23 @@ engine, or expand the database schema when issue metadata is sufficient. ### Workflow -1. Fork the repository -2. Create a feature branch (`git checkout -b feature/my-feature`) +1. If the change warrants one, find or file an issue (see [Issues and pull requests](#issues-and-pull-requests)) +2. Fork the repository and create a feature branch (`git checkout -b feature/my-feature`) 3. Make your changes 4. Add tests for new functionality 5. Run tests and linter locally 6. Commit your changes with clear messages 7. Push to your fork -8. Open a pull request +8. Open a pull request that explains the change and says `Closes #` when there is one ### Commit Messages -Write clear, concise commit messages: +Use [Conventional Commits](https://www.conventionalcommits.org/): +`type(scope): summary`, where type is one of `fix`, `feat`, `docs`, `test`, +`refactor`, `chore`, `ci`, or `perf`. ``` -Add cycle detection for dependency graphs +feat(dep): add cycle detection for dependency graphs - Implement recursive CTE-based cycle detection - Add tests for simple and complex cycles @@ -115,6 +197,10 @@ Add cycle detection for dependency graphs **One issue per PR, and one PR per issue.** No piggybacking or riders — each PR should address exactly one thing. +Read [CONTRIBUTING_PR_GUIDELINES.md](CONTRIBUTING_PR_GUIDELINES.md) for the +layering rules (schema → storage/issueops → cmd/bd, one layer per PR) and the +repro and benchmark evidence reviewers expect. + - Keep PRs focused on a single feature or fix - Do not include unrelated changes, cleanup, or "while I'm here" improvements - Do not include `.beads/` data (database, JSONL) in your PR @@ -138,7 +224,8 @@ For test commands, test design, and PR-readiness gates, see the canonical - Follow the proportional validation budget in [engdocs/TESTING.md](engdocs/TESTING.md): docs-only changes use docs checks; - Go changes use focused and affected-package tests plus one final `make test`. + Go changes use focused and affected-package tests plus one final `make test` + (the Bazel test lane). - If you hit a test failure unrelated to your change, don't silently skip it -- check `.test-skip` and file an issue if it's not already tracked (see [engdocs/TESTING.md](engdocs/TESTING.md#failures-skips-and-review)). @@ -178,22 +265,12 @@ round-trip paths should pattern-match on those tests. ## Feature Requests and Bug Reports -### Reporting Bugs - -Include in your bug report: -- Steps to reproduce -- Expected behavior -- Actual behavior -- Version of bd (`bd version` if implemented) -- Operating system and Go version - -### Feature Requests - -When proposing new features: -- Explain the use case -- Describe the proposed solution -- Consider backwards compatibility -- Discuss alternatives you've considered +Use the issue forms: [bug report](https://github.com/gastownhall/beads/issues/new?template=bug_report.yml) +or [feature request](https://github.com/gastownhall/beads/issues/new?template=feature_request.yml). +The feature form asks for the motivation, impact, risk and compatibility, +and verification plan up front, so a maintainer can accept the issue without +a round trip. Questions go to +[Discussions](https://github.com/gastownhall/beads/discussions). ## Your PR Will Not Be Overwritten @@ -291,7 +368,7 @@ docker run --rm -v $(pwd):/workspace -w /workspace nixos/nix \ If the build fails with a `vendorHash` mismatch, run `./scripts/update-nix-vendorhash.sh` to recompute and update `default.nix`, or update it manually with the `got:` hash from the error message and rebuild. -On a PR, this is covered by PR Risk's required `test-nix` job (`.github/workflows/pr-risk.yml`), which runs `nix run .#default -- --help` plus `nix flake check -L` on every PR touching `go.mod`, `go.sum`, `default.nix`, `flake.nix`, or `flake.lock` -- a superset of plain `nix build .#default`. `.github/workflows/nix-build.yml` dropped its own `pull_request` trigger as redundant (F7c, spec-f7.md §2.4) and now only runs `nix build .#default` on push to `main` and on `workflow_dispatch`, so dependabot bumps that invalidate `vendorHash` still fail loudly post-merge instead of silently breaking Nix users on main. For dependabot Go-module bumps specifically, `.github/workflows/update-vendor-hash.yml` runs the same `update-nix-vendorhash.sh` script and pushes the hash bump back to the dependabot branch automatically (note: GitHub does not retrigger `pull_request` workflows for `GITHUB_TOKEN`-authored commits, so a maintainer may need to re-run PR Risk's `test-nix` once after the auto-fix push to mark the gate green). +On a PR, this is covered by PR Risk's required `test-nix` job (`.github/workflows/pr-risk.yml`), which runs `nix run .#default -- --help` plus `nix flake check -L` (an evaluation of every flake output; the flake has no test checks) on every PR touching `go.mod`, `go.sum`, `default.nix`, `flake.nix`, or `flake.lock` -- a superset of plain `nix build .#default`. `.github/workflows/nix-build.yml` dropped its own `pull_request` trigger as redundant (F7c, spec-f7.md §2.4) and now only runs `nix build .#default` on push to `main` and on `workflow_dispatch`, so dependabot bumps that invalidate `vendorHash` still fail loudly post-merge instead of silently breaking Nix users on main. For dependabot Go-module bumps specifically, `.github/workflows/update-vendor-hash.yml` runs the same `update-nix-vendorhash.sh` script and pushes the hash bump back to the dependabot branch automatically (note: GitHub does not retrigger `pull_request` workflows for `GITHUB_TOKEN`-authored commits, so a maintainer may need to re-run PR Risk's `test-nix` once after the auto-fix push to mark the gate green). ### Debugging @@ -309,11 +386,7 @@ dlv debug ./cmd/bd -- create "Test issue" (For maintainers) -1. Update version in code -2. Update CHANGELOG.md -3. Tag release: `git tag v0.x.0` -4. Push tag: `git push origin v0.x.0` -5. GitHub Actions will build and publish +Follow [RELEASING.md](RELEASING.md); it is the canonical release process. The pre-push version gate requires Go and validates each `v*` release tag against the checkout's canonical version. A batch containing different release diff --git a/MODULE.bazel b/MODULE.bazel index ff3e3cafb..e157d6d59 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -5,8 +5,194 @@ module( bazel_dep(name = "platforms", version = "1.1.0") bazel_dep(name = "rules_go", version = "0.63.0") + +# nogo honors //nolint directives through ast.CommentMap ranges, which differ +# from golangci-lint's (a comment trailing `func f(...) {` attaches to the +# body's first statement). This tree's directives were written against +# golangci-lint, so the patch adds golangci-lint's ranges as well. +single_version_override( + module_name = "rules_go", + patch_strip = 1, + patches = ["//third_party/patches:rules_go_nogo_golangci_nolint.patch"], + version = "0.63.0", +) + bazel_dep(name = "gazelle", version = "0.53.0") bazel_dep(name = "rules_shell", version = "0.6.1") +bazel_dep(name = "toolchains_llvm", version = "1.11.0") + +# Loaded by @llvm_dist_linux_x86_64's BUILD file (toolchains_llvm's template). +bazel_dep(name = "rules_cc", version = "0.2.17") + +# Hermetic C/C++ toolchain, ported from gastownhall/gascity. rules_go builds +# the Go stdlib under -race and every cgo package (mattn/go-sqlite3, gozstd, +# ...) with the registered C toolchain, and every Go compile depends on the +# stdlib, so a host-detected toolchain (local_config_cc: CC=/usr/bin/gcc, +# -fuse-ld=lld only where the CLIENT has lld, gcc-version-specific generated +# inputs) keys those actions to the machine that ran the analysis and fails +# remotely on workers without lld. Instead: LLVM pinned by sha256, plus a +# sysroot of pinned Ubuntu 24.04 packages (the RBE workers' release, so +# binaries load the same glibc and libstdc++ there), byte-identical on every +# Linux x86_64 host. No ICU: beads builds go-mysql-server with its pure-Go +# regex backend (engdocs/ICU-POLICY.md), so nothing may link libicu. .bazelrc +# turns host detection off so nothing falls back to the host compiler; +# scripts/bazel_hermetic_cc_test.go guards both. +deb_sysroot = use_repo_rule("//third_party/cc_toolchain:deb_sysroot.bzl", "deb_sysroot") + +# Where every pinned Ubuntu 24.04 package below comes from, tried in order +# (the sha256 pins, not the source, decide what is accepted): +# - gascity's content-addressed mirror, a release holding each pinned +# .deb as .deb (gascity's tools/cc_toolchain/mirror_debs.sh +# publishes it; gascity pins the same packages), so a cold fetch does not +# depend on Canonical's servers; +# - the snapshot these packages were pinned from (immutable, but a single +# host that returns 503 for minutes at a time); +# - Launchpad's librarian, which keeps every file ever published to the +# primary archive, superseded versions included; +# - archive.ubuntu.com, which drops superseded versions. +NOBLE_DEB_URLS = [ + "https://github.com/gastownhall/gascity/releases/download/toolchain-noble-debs-20261001/{sha256}.deb", + "https://snapshot.ubuntu.com/ubuntu/20261001T000000Z/{path}", + "https://launchpad.net/ubuntu/+archive/primary/+files/{file}", + "https://archive.ubuntu.com/ubuntu/{path}", +] + +deb_sysroot( + name = "cc_sysroot_noble_amd64", + packages = { + "pool/main/g/gcc-13/libgcc-13-dev_13.3.0-6ubuntu2~24.04.1_amd64.deb": "cd689db2691edaa10f37329307292796bb599e722e0505c79e14caaa1fe9a93a", + "pool/main/g/gcc-13/libstdc++-13-dev_13.3.0-6ubuntu2~24.04.1_amd64.deb": "ee5633e863e19c3381ed97842ce35ed32ede96a3d1ae4e94c051d3036fe21347", + "pool/main/g/gcc-14/libgcc-s1_14.2.0-4ubuntu2~24.04.1_amd64.deb": "aa7fadbe33b78bcf99885318040601c550c208929565b179891d9a3cc2aa68cd", + "pool/main/g/gcc-14/libstdc++6_14.2.0-4ubuntu2~24.04.1_amd64.deb": "a51f8de7829211db961a31f02158058ad1a95f92ac6d0a5dff6350e2821c54c0", + "pool/main/g/glibc/libc6-dev_2.39-0ubuntu8.9_amd64.deb": "e13d5fcc1b2a86f75bca8e0026a8e39f24fe97ca86e92be79991f8697eb1306f", + "pool/main/g/glibc/libc6_2.39-0ubuntu8.9_amd64.deb": "ff5557d99b51f761c4b7c92368b9cc45565eda17df9bf9eb4b134d09825008be", + "pool/main/l/linux/linux-libc-dev_6.8.0-146.146_amd64.deb": "1a7bb04132d01cd14bea3d615e5861096ca1f70c4659902eb14b36c21993cadc", + }, + remove = [ + "etc", + "usr/bin", + "usr/sbin", + "usr/share", + "usr/lib/x86_64-linux-gnu/gconv", + "usr/lib/gcc/x86_64-linux-gnu/13/crtoffload*", + "usr/lib/gcc/x86_64-linux-gnu/13/lib*san*", + "usr/lib/gcc/x86_64-linux-gnu/13/libatomic*", + "usr/lib/gcc/x86_64-linux-gnu/13/libbacktrace*", + "usr/lib/gcc/x86_64-linux-gnu/13/libgcov*", + "usr/lib/gcc/x86_64-linux-gnu/13/libgomp*", + "usr/lib/gcc/x86_64-linux-gnu/13/libitm*", + "usr/lib/gcc/x86_64-linux-gnu/13/libquadmath*", + "usr/lib/gcc/x86_64-linux-gnu/13/libstdc++*.a", + ], + urls = NOBLE_DEB_URLS, +) + +LLVM_VERSION = "22.1.8" + +llvm_dist = use_repo_rule("//third_party/cc_toolchain:llvm_dist.bzl", "llvm_dist") + +llvm_dist( + name = "llvm_dist_linux_x86_64", + llvm_version = LLVM_VERSION, + members = [ + "bin/clang", + "bin/clang++", + "bin/clang-22", + "bin/clang-cpp", + "bin/ld.lld", + "bin/ld64.lld", + "bin/lld", + "bin/llvm-ar", + "bin/llvm-as", + "bin/llvm-cov", + "bin/llvm-install-name-tool", + "bin/llvm-nm", + "bin/llvm-objcopy", + "bin/llvm-objdump", + "bin/llvm-profdata", + "bin/llvm-ranlib", + "bin/llvm-readelf", + "bin/llvm-readobj", + "bin/llvm-strip", + "bin/llvm-symbolizer", + "bin/wasm-ld", + "include/c++", + "include/x86_64-unknown-linux-gnu", + "lib/clang/22/include", + "lib/clang/22/lib/x86_64-unknown-linux-gnu/clang_rt.crtbegin.o", + "lib/clang/22/lib/x86_64-unknown-linux-gnu/clang_rt.crtend.o", + "lib/clang/22/lib/x86_64-unknown-linux-gnu/libclang_rt.builtins.a", + # `bazel coverage` links cgo binaries with -fprofile-instr-generate, + # which pulls in compiler-rt's profile runtime (~170KB). + "lib/clang/22/lib/x86_64-unknown-linux-gnu/libclang_rt.profile.a", + ], + # LLVM-22.1.8-Linux-X64.tar.xz (sha256 df0e1ecf...0006384), sliced to the + # members above by tools/cc_toolchain/repack_llvm.sh: 149 MB instead of + # 1.94 GB, and no single-threaded xz pass on every cold runner. The files + # are byte-identical to the release's, so no action key changes. + # tools/cc_toolchain/llvm_members.txt must list the same members. + sha256 = "de6147773999137b70ef3d7bd8ecb1e5b91f2a161d02fd09aec591b84516bec5", + sliced = True, + stub_tools = [ + "clang-format", + "clang-tidy", + "clangd", + "llvm-dwp", + ], + # The sha256 pin, not the host, guarantees the bytes. gascity's release + # asset for now; a beads mirror of the same bytes can be listed first. + urls = [ + "https://github.com/gastownhall/gascity/releases/download/toolchain-llvm-22.1.8-slice-1/LLVM-22.1.8-Linux-X64-slice.tar.zst", + ], +) + +# Every other host (macOS arm64, Linux arm64) runs toolchains_llvm's stock +# LLVM_VERSION release for its platform, pinned by sha256 in toolchains_llvm's +# distribution table and fetched only there. Once any toolchain_root is set, +# toolchains_llvm creates no stock distribution of its own and fails every +# build on a host no root covers. Not hermetic there: no sysroot, so cgo +# uses the host's headers and libraries, as before. +llvm_host_dist = use_repo_rule("@toolchains_llvm//toolchain:rules.bzl", "llvm") + +llvm_host_dist( + name = "llvm_dist_host", + llvm_version = LLVM_VERSION, + # The bare rule reads the per-host dict; llvm_toolchain's macro would + # fill it in from llvm_version. + llvm_versions = {"": LLVM_VERSION}, +) + +llvm = use_extension("@toolchains_llvm//toolchain/extensions:llvm.bzl", "llvm") +llvm.toolchain( + name = "llvm_toolchain", + # Pair Darwin's host SDK with its native linker. LLVM 22.1.8's ld64.lld + # cannot parse the arm64e.x1 TAPI targets in the macOS 27 SDK. Keep the + # pinned Clang compiler; Linux keeps the bundled LLD and pinned sysroot. + linker = { + "darwin-aarch64": "auto", + "darwin-x86_64": "auto", + }, + llvm_version = LLVM_VERSION, + # The sysroot's libstdc++, linked dynamically as host-gcc builds did. + stdlib = {"linux-x86_64": "dynamic-stdc++"}, +) +llvm.toolchain_root( + name = "llvm_toolchain", + label = "@llvm_dist_linux_x86_64//:BUILD.bazel", + targets = ["linux-x86_64"], +) +llvm.toolchain_root( + name = "llvm_toolchain", + label = "@llvm_dist_host//:BUILD.bazel", +) +llvm.sysroot( + name = "llvm_toolchain", + label = "@cc_sysroot_noble_amd64//:sysroot", + targets = ["linux-x86_64"], +) +use_repo(llvm, "llvm_toolchain") + +register_toolchains("@llvm_toolchain//:all") go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk") go_sdk.download( @@ -15,8 +201,36 @@ go_sdk.download( ) use_repo(go_sdk, "go_sdk") +# nogo: //tools/nogo's analyzers (go test's vet checks plus the golangci-lint +# linters .golangci.yml enables) run beside every first-party Go compile, so +# a finding fails `bazel build`/`bazel test` wherever it executes (RBE +# included). External repos only feed analyzer facts; they are not validated. +go_sdk.nogo( + includes = ["//:__subpackages__"], + nogo = "//tools/nogo", +) + +# gazelle compiles fetch_repo and gazelle, which every go_deps repository +# runs, with `go build` in a repository rule before any go_deps fetch can +# start (18-24 s of every CI lane's loading). This substitute serves those +# reproducible binaries from the repository cache by pinned sha256 and builds +# them from source on a miss (tools/bazel/go_repository_tools.bzl). +gazelle_non_module_deps = use_extension("@gazelle//internal/bzlmod:non_module_deps.bzl", "non_module_deps") + +go_repository_tools = use_repo_rule("//tools/bazel:go_repository_tools.bzl", "go_repository_tools") + +go_repository_tools(name = "gazelle_go_repository_tools") + +override_repo( + gazelle_non_module_deps, + bazel_gazelle_go_repository_tools = "gazelle_go_repository_tools", +) + +# gazelle.go.work joins the beads module and the nogo analyzers' module +# (tools/nogo/go.mod) into one dependency graph for Bazel only; `go build` in +# the repository root never reads it (it is not named go.work). go_deps = use_extension("@gazelle//:extensions.bzl", "go_deps") -go_deps.from_file(go_mod = "//:go.mod") +go_deps.from_file(go_work = "//:gazelle.go.work") # beads builds go-mysql-server with its stdlib-regex backend (ICU policy): # gazelle must see gms_pure_go as satisfied so it selects regex_pure.go and @@ -28,6 +242,23 @@ go_deps.gazelle_override( ], path = "github.com/dolthub/go-mysql-server", ) + +# protoc-gen-validate ships validate/validate.pb.go, so its Go library can +# compile from the checked-in code. Its own validate/BUILD instead makes the +# Go library a go_proto_library, so every lane built protoc from source just +# to regenerate that file: about 4.5k C++ compile, link and archive actions, +# each carrying the LLVM toolchain as inputs. The module reaches the graph +# only through grpc xds and the cloud SDKs. Gazelle regenerates its BUILD +# files with proto rules off; build_file_name makes it write BUILD.bazel (which +# Bazel prefers) rather than merge into the upstream BUILD files. +go_deps.gazelle_override( + build_file_generation = "on", + directives = [ + "gazelle:build_file_name BUILD.bazel", + "gazelle:proto disable", + ], + path = "github.com/envoyproxy/protoc-gen-validate", +) go_deps.module_override( patch_strip = 1, patches = ["//third_party/patches:eventsapi_schema_build.patch"], @@ -50,7 +281,17 @@ go_deps.module_override( patches = ["//third_party/patches:gozstd_nocgo.patch"], path = "github.com/dolthub/gozstd", ) -use_repo(go_deps, "com_github_anthropics_anthropic_sdk_go", "com_github_burntsushi_toml", "com_github_cenkalti_backoff_v4", "com_github_charmbracelet_x_ansi", "com_github_data_dog_go_sqlmock", "com_github_dolthub_dolt_go", "com_github_dolthub_driver_v2", "com_github_dolthub_eventkit", "com_github_dolthub_go_mysql_server", "com_github_dolthub_vitess", "com_github_go_sql_driver_mysql", "com_github_google_uuid", "com_github_gowebpki_jcs", "com_github_invopop_jsonschema", "com_github_johanneskaufmann_html_to_markdown_v2", "com_github_mattn_go_sqlite3", "com_github_microcosm_cc_bluemonday", "com_github_oapi_codegen_oapi_codegen_v2", "com_github_olebedev_when", "com_github_spf13_cobra", "com_github_spf13_pflag", "com_github_spf13_viper", "com_github_stretchr_testify", "com_github_subosito_gotenv", "com_github_testcontainers_testcontainers_go", "com_github_testcontainers_testcontainers_go_modules_dolt", "com_github_yuin_goldmark", "in_gopkg_yaml_v3", "io_opentelemetry_go_otel", "io_opentelemetry_go_otel_exporters_otlp_otlpmetric_otlpmetrichttp", "io_opentelemetry_go_otel_exporters_stdout_stdoutmetric", "io_opentelemetry_go_otel_exporters_stdout_stdouttrace", "io_opentelemetry_go_otel_metric", "io_opentelemetry_go_otel_sdk", "io_opentelemetry_go_otel_sdk_metric", "io_opentelemetry_go_otel_trace", "io_rsc_script", "land_charm_glamour_v2", "land_charm_huh_v2", "land_charm_lipgloss_v2", "org_golang_x_mod", "org_golang_x_net", "org_golang_x_sync", "org_golang_x_sys", "org_golang_x_term") + +# nogo does not analyze the standard library, so ctrlflow has no noReturn +# facts for t.Fatal, log.Fatal, os.Exit, ...; buildssa (unparam) and the vet +# passes then treat them as returning, unlike golangci-lint and go vet. The +# patch makes ctrlflow know those standard-library functions intrinsically. +go_deps.module_override( + patch_strip = 1, + patches = ["//third_party/patches:x_tools_ctrlflow_stdlib_noreturn.patch"], + path = "golang.org/x/tools", +) +use_repo(go_deps, "cc_mvdan_unparam", "com_github_anthropics_anthropic_sdk_go", "com_github_ashanbrown_forbidigo_v2", "com_github_burntsushi_toml", "com_github_cenkalti_backoff_v4", "com_github_charmbracelet_x_ansi", "com_github_creack_pty", "com_github_data_dog_go_sqlmock", "com_github_dolthub_dolt_go", "com_github_dolthub_driver_v2", "com_github_dolthub_eventkit", "com_github_dolthub_go_mysql_server", "com_github_dolthub_vitess", "com_github_go_sql_driver_mysql", "com_github_golangci_misspell", "com_github_golangci_unconvert", "com_github_google_uuid", "com_github_gowebpki_jcs", "com_github_invopop_jsonschema", "com_github_johanneskaufmann_html_to_markdown_v2", "com_github_kisielk_errcheck", "com_github_mattn_go_sqlite3", "com_github_microcosm_cc_bluemonday", "com_github_oapi_codegen_oapi_codegen_v2", "com_github_olebedev_when", "com_github_openpeedeep_depguard_v2", "com_github_securego_gosec_v2", "com_github_spf13_cobra", "com_github_spf13_pflag", "com_github_spf13_viper", "com_github_stretchr_testify", "com_github_subosito_gotenv", "com_github_testcontainers_testcontainers_go", "com_github_testcontainers_testcontainers_go_modules_dolt", "com_github_yuin_goldmark", "in_gopkg_yaml_v3", "io_opentelemetry_go_otel", "io_opentelemetry_go_otel_exporters_otlp_otlpmetric_otlpmetrichttp", "io_opentelemetry_go_otel_exporters_stdout_stdoutmetric", "io_opentelemetry_go_otel_exporters_stdout_stdouttrace", "io_opentelemetry_go_otel_metric", "io_opentelemetry_go_otel_sdk", "io_opentelemetry_go_otel_sdk_metric", "io_opentelemetry_go_otel_trace", "io_rsc_script", "land_charm_glamour_v2", "land_charm_huh_v2", "land_charm_lipgloss_v2", "org_go_simpler_sloglint", "org_golang_x_mod", "org_golang_x_net", "org_golang_x_sync", "org_golang_x_sys", "org_golang_x_term", "org_golang_x_tools") # Hermetic Dolt CLI for tests (tools/bazel/dolt.bzl pins the release to # scripts/ci/install-dolt.sh). //tools/bazel:dolt selects the repository for @@ -76,3 +317,101 @@ dolt_release( name = "dolt_darwin_arm64", platform = "darwin-arm64", ) + +# The migration corpus's external Dolt runtime (scripts/migration-test/lib/ +# versions.sh DOLT_TEST_RUNTIME_VERSION): an older release than DOLT_VERSION, +# deliberately, as the historical server-Dolt fixtures' host. +dolt_release( + name = "dolt_test_runtime_linux_amd64", + platform = "linux-amd64", + version = "2.1.8", +) + +# The tracked release formula, for //scripts:shell_scripts_test and the +# whole-checkout guard //scripts/repochecks:go_install_guidance_test. .beads/ +# also holds live bd data and is in .bazelignore, so no main-repo target can +# declare the formula; this local repository exposes only .beads/formulas. +new_local_repository = use_repo_rule("@bazel_tools//tools/build_defs/repo:local.bzl", "new_local_repository") + +new_local_repository( + name = "beads_formulas", + build_file_content = """exports_files( + glob(["*.formula.toml"]), + visibility = [ + "@@//scripts:__pkg__", + "@@//scripts/repochecks:__pkg__", + ], +) +""", + path = ".beads/formulas", +) + +# Historical bd releases for the regression, migration and cross-version +# suites (tools/bazel/bd_releases.bzl): one repository per release in the +# release catalog that records a linux_amd64 asset digest, behind the +# @bd_releases hub. Adding a release is a catalog change only. +bd_releases = use_extension("//tools/bazel:bd_releases.bzl", "bd_releases") +bd_releases.catalog(path = "//scripts:migration-test/release-catalog.json") +use_repo(bd_releases, "bd_releases") + +# The source-tag SQLite release (v0.9.1) has no release asset: the migration +# corpus builds it from its module source with the Go release it was +# qualified on, offline (//tests/migration:bd_source_tag). The proxy files +# are pinned in tests/migration/source_tag_modules.json, the toolchain here. +go_module_proxy = use_repo_rule("//tools/bazel:go_module_proxy.bzl", "go_module_proxy") + +go_module_proxy( + name = "bd_source_tag_goproxy", + lock = "//tests/migration:source_tag_modules.json", +) + +http_archive = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "go_1_25_0_linux_amd64", + build_file_content = """exports_files( + ["go/bin/go"], + visibility = ["//visibility:public"], +) + +filegroup( + name = "sdk", + srcs = glob(["go/**"]), + visibility = ["//visibility:public"], +) +""", + sha256 = "2852af0cb20a13139b3448992e69b868e50ed0f8a1e5940ee1de9e19a123b613", + urls = ["https://go.dev/dl/go1.25.0.linux-amd64.tar.gz"], +) + +# The timeout implementations //tests/hook_timeout_backends runs the tracked +# git hook shims against (formerly checks.nix's hook-timeout-backends, which +# took them from nixpkgs): static x86_64 builds, so the test needs nothing +# from the executor beyond a shell, perl and GNU coreutils. +http_file = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") + +http_file( + name = "busybox_static", + executable = True, + sha256 = "6e123e7f3202a8c1e9b1f94d8941580a25135382b99e8d3e34fb858bba311348", + urls = ["https://busybox.net/downloads/binaries/1.35.0-x86_64-linux-musl/busybox"], +) + +http_file( + name = "toybox_static", + executable = True, + sha256 = "38e03ffd8aead8ca26833e1e5c90a9ea7250f3719c29d779ebff7aa55c9d2dac", + urls = ["https://landley.net/toybox/downloads/binaries/0.8.15/toybox-x86_64"], +) + +http_archive( + name = "uutils_coreutils", + build_file_content = """exports_files( + ["coreutils"], + visibility = ["//visibility:public"], +) +""", + sha256 = "9b555b01457279bcc3e46753f0ef324fd3d02a0535111200a4632d1297263b54", + strip_prefix = "coreutils-0.12.0-x86_64-unknown-linux-musl", + urls = ["https://github.com/uutils/coreutils/releases/download/0.12.0/coreutils-0.12.0-x86_64-unknown-linux-musl.tar.gz"], +) diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index d4d434b48..82bd1b0bc 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -18,9 +18,12 @@ "https://bcr.bazel.build/modules/apple_support/1.15.1/MODULE.bazel": "a0556fefca0b1bb2de8567b8827518f94db6a6e7e7d632b4c48dc5f865bc7c85", "https://bcr.bazel.build/modules/apple_support/1.21.0/MODULE.bazel": "ac1824ed5edf17dee2fdd4927ada30c9f8c3b520be1b5fd02a5da15bc10bff3e", "https://bcr.bazel.build/modules/apple_support/1.21.1/MODULE.bazel": "5809fa3efab15d1f3c3c635af6974044bac8a4919c62238cce06acee8a8c11f1", - "https://bcr.bazel.build/modules/apple_support/1.24.2/MODULE.bazel": "0e62471818affb9f0b26f128831d5c40b074d32e6dda5a0d3852847215a41ca4", - "https://bcr.bazel.build/modules/apple_support/1.24.2/source.json": "2c22c9827093250406c5568da6c54e6fdf0ef06238def3d99c71b12feb057a8d", - "https://bcr.bazel.build/modules/bazel_features/1.1.0/MODULE.bazel": "cfd42ff3b815a5f39554d97182657f8c4b9719568eb7fded2b9135f084bf760b", + "https://bcr.bazel.build/modules/apple_support/2.5.2/MODULE.bazel": "bb1b7081e390a8d3885f642cb0073dfcf8e7a36525e079fa8f5835af7079c0fe", + "https://bcr.bazel.build/modules/apple_support/2.5.2/source.json": "dd51ee925a550e92b55eb41c4c809a967da311a2d2520241252a238a48b39c4c", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.14.0/MODULE.bazel": "2b31ffcc9bdc8295b2167e07a757dbbc9ac8906e7028e5170a3708cecaac119f", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.19.3/MODULE.bazel": "253d739ba126f62a5767d832765b12b59e9f8d2bc88cc1572f4a73e46eb298ca", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.19.3/source.json": "ffab9254c65ba945f8369297ad97ca0dec213d3adc6e07877e23a48624a8b456", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.8.1/MODULE.bazel": "812d2dd42f65dca362152101fbec418029cc8fd34cbad1a2fde905383d705838", "https://bcr.bazel.build/modules/bazel_features/1.1.1/MODULE.bazel": "27b8c79ef57efe08efccbd9dd6ef70d61b4798320b8d3c134fd571f78963dbcd", "https://bcr.bazel.build/modules/bazel_features/1.10.0/MODULE.bazel": "f75e8807570484a99be90abcd52b5e1f390362c258bcb73106f4544957a48101", "https://bcr.bazel.build/modules/bazel_features/1.11.0/MODULE.bazel": "f9382337dd5a474c3b7d334c2f83e50b6eaedc284253334cf823044a26de03e8", @@ -35,10 +38,13 @@ "https://bcr.bazel.build/modules/bazel_features/1.3.0/MODULE.bazel": "cdcafe83ec318cda34e02948e81d790aab8df7a929cec6f6969f13a489ccecd9", "https://bcr.bazel.build/modules/bazel_features/1.30.0/MODULE.bazel": "a14b62d05969a293b80257e72e597c2da7f717e1e69fa8b339703ed6731bec87", "https://bcr.bazel.build/modules/bazel_features/1.33.0/MODULE.bazel": "8b8dc9d2a4c88609409c3191165bccec0e4cb044cd7a72ccbe826583303459f6", + "https://bcr.bazel.build/modules/bazel_features/1.34.0/MODULE.bazel": "e8475ad7c8965542e0c7aac8af68eb48c4af904be3d614b6aa6274c092c2ea1e", "https://bcr.bazel.build/modules/bazel_features/1.36.0/MODULE.bazel": "596cb62090b039caf1cad1d52a8bc35cf188ca9a4e279a828005e7ee49a1bec3", + "https://bcr.bazel.build/modules/bazel_features/1.38.0/MODULE.bazel": "f9b8a9c890ebd216b4049fd12a31d3c2602e3403c7af636b04fbbd7453edc9c9", "https://bcr.bazel.build/modules/bazel_features/1.4.1/MODULE.bazel": "e45b6bb2350aff3e442ae1111c555e27eac1d915e77775f6fdc4b351b758b5d7", "https://bcr.bazel.build/modules/bazel_features/1.42.1/MODULE.bazel": "275a59b5406ff18c01739860aa70ad7ccb3cfb474579411decca11c93b951080", "https://bcr.bazel.build/modules/bazel_features/1.42.1/source.json": "fcd4396b2df85f64f2b3bb436ad870793ecf39180f1d796f913cc9276d355309", + "https://bcr.bazel.build/modules/bazel_features/1.9.0/MODULE.bazel": "885151d58d90d8d9c811eb75e3288c11f850e1d6b481a8c9f766adee4712358b", "https://bcr.bazel.build/modules/bazel_features/1.9.1/MODULE.bazel": "8f679097876a9b609ad1f60249c49d68bfab783dd9be012faf9d82547b14815a", "https://bcr.bazel.build/modules/bazel_skylib/1.0.3/MODULE.bazel": "bcb0fd896384802d1ad283b4e4eb4d718eebd8cb820b0a2c3a347fb971afd9d8", "https://bcr.bazel.build/modules/bazel_skylib/1.1.1/MODULE.bazel": "1add3e7d93ff2e6998f9e118022c84d163917d912f5afafb3058e3d2f1545b5e", @@ -56,10 +62,8 @@ "https://bcr.bazel.build/modules/bazel_skylib/1.8.2/source.json": "34a3c8bcf233b835eb74be9d628899bb32999d3e0eadef1947a0a562a2b16ffb", "https://bcr.bazel.build/modules/buildozer/8.5.1/MODULE.bazel": "a35d9561b3fc5b18797c330793e99e3b834a473d5fbd3d7d7634aafc9bdb6f8f", "https://bcr.bazel.build/modules/buildozer/8.5.1/source.json": "e3386e6ff4529f2442800dee47ad28d3e6487f36a1f75ae39ae56c70f0cd2fbd", - "https://bcr.bazel.build/modules/gazelle/0.32.0/MODULE.bazel": "b499f58a5d0d3537f3cf5b76d8ada18242f64ec474d8391247438bf04f58c7b8", - "https://bcr.bazel.build/modules/gazelle/0.33.0/MODULE.bazel": "a13a0f279b462b784fb8dd52a4074526c4a2afe70e114c7d09066097a46b3350", - "https://bcr.bazel.build/modules/gazelle/0.34.0/MODULE.bazel": "abdd8ce4d70978933209db92e436deb3a8b737859e9354fb5fd11fb5c2004c8a", - "https://bcr.bazel.build/modules/gazelle/0.36.0/MODULE.bazel": "e375d5d6e9a6ca59b0cb38b0540bc9a05b6aa926d322f2de268ad267a2ee74c0", + "https://bcr.bazel.build/modules/gawk/5.3.2.bcr.1/MODULE.bazel": "cdf8cbe5ee750db04b78878c9633cc76e80dcf4416cbe982ac3a9222f80713c8", + "https://bcr.bazel.build/modules/gawk/5.3.2.bcr.1/source.json": "fa7b512dfcb5eafd90ce3959cf42a2a6fe96144ebbb4b3b3928054895f2afac2", "https://bcr.bazel.build/modules/gazelle/0.51.3/MODULE.bazel": "618a729142f66de1e2cb776d026413763be5b80d5e3d29ffb9d3d90c5defde90", "https://bcr.bazel.build/modules/gazelle/0.53.0/MODULE.bazel": "76158efbaf12e35ae17af02f4a715bc6e7b3b410c693d34f422922ff4a56a925", "https://bcr.bazel.build/modules/gazelle/0.53.0/source.json": "1f5a4dd0399e5a20e0daeaa3ba1f42391a1b909bc3d337f7a62d3216ddbdfad0", @@ -70,12 +74,17 @@ "https://bcr.bazel.build/modules/googletest/1.15.2/MODULE.bazel": "6de1edc1d26cafb0ea1a6ab3f4d4192d91a312fd2d360b63adaa213cd00b2108", "https://bcr.bazel.build/modules/googletest/1.17.0/MODULE.bazel": "dbec758171594a705933a29fcf69293d2468c49ec1f2ebca65c36f504d72df46", "https://bcr.bazel.build/modules/googletest/1.17.0/source.json": "38e4454b25fc30f15439c0378e57909ab1fd0a443158aa35aec685da727cd713", + "https://bcr.bazel.build/modules/jq.bzl/0.1.0/MODULE.bazel": "2ce69b1af49952cd4121a9c3055faa679e748ce774c7f1fda9657f936cae902f", + "https://bcr.bazel.build/modules/jq.bzl/0.1.0/source.json": "746bf13cac0860f091df5e4911d0c593971cd8796b5ad4e809b2f8e133eee3d5", "https://bcr.bazel.build/modules/jsoncpp/1.9.5/MODULE.bazel": "31271aedc59e815656f5736f282bb7509a97c7ecb43e927ac1a37966e0578075", "https://bcr.bazel.build/modules/jsoncpp/1.9.6/MODULE.bazel": "2f8d20d3b7d54143213c4dfc3d98225c42de7d666011528dc8fe91591e2e17b0", "https://bcr.bazel.build/modules/jsoncpp/1.9.6/source.json": "a04756d367a2126c3541682864ecec52f92cdee80a35735a3cb249ce015ca000", "https://bcr.bazel.build/modules/libpfm/4.11.0/MODULE.bazel": "45061ff025b301940f1e30d2c16bea596c25b176c8b6b3087e92615adbd52902", + "https://bcr.bazel.build/modules/mboworks_bzl/0.5.1/MODULE.bazel": "20c921aded4f4e00a6128dad47a843371c196ba8987474c11c8ba7b9da8c16f1", + "https://bcr.bazel.build/modules/mboworks_bzl/0.5.1/source.json": "3d9086bb203475113a16afb0ca0c9b97fdb37fc6e5a62b604b60ffc2450dc8c5", "https://bcr.bazel.build/modules/nlohmann_json/3.6.1/MODULE.bazel": "6f7b417dcc794d9add9e556673ad25cb3ba835224290f4f848f8e2db1e1fca74", "https://bcr.bazel.build/modules/nlohmann_json/3.6.1/source.json": "f448c6e8963fdfa7eb831457df83ad63d3d6355018f6574fb017e8169deb43a9", + "https://bcr.bazel.build/modules/package_metadata/0.0.2/MODULE.bazel": "fb8d25550742674d63d7b250063d4580ca530499f045d70748b1b142081ebb92", "https://bcr.bazel.build/modules/package_metadata/0.0.3/MODULE.bazel": "77890552ecea9e284b5424c9de827a58099348763a4359e975c359a83d4faa83", "https://bcr.bazel.build/modules/package_metadata/0.0.5/MODULE.bazel": "ef4f9439e3270fdd6b9fd4dbc3d2f29d13888e44c529a1b243f7a31dfbc2e8e4", "https://bcr.bazel.build/modules/package_metadata/0.0.5/source.json": "2326db2f6592578177751c3e1f74786b79382cd6008834c9d01ec865b9126a85", @@ -93,13 +102,11 @@ "https://bcr.bazel.build/modules/protobuf/21.7/MODULE.bazel": "a5a29bb89544f9b97edce05642fac225a808b5b7be74038ea3640fae2f8e66a7", "https://bcr.bazel.build/modules/protobuf/27.0/MODULE.bazel": "7873b60be88844a0a1d8f80b9d5d20cfbd8495a689b8763e76c6372998d3f64c", "https://bcr.bazel.build/modules/protobuf/27.1/MODULE.bazel": "703a7b614728bb06647f965264967a8ef1c39e09e8f167b3ca0bb1fd80449c0d", - "https://bcr.bazel.build/modules/protobuf/29.0-rc2.bcr.1/MODULE.bazel": "52f4126f63a2f0bbf36b99c2a87648f08467a4eaf92ba726bc7d6a500bbf770c", "https://bcr.bazel.build/modules/protobuf/29.0-rc2/MODULE.bazel": "6241d35983510143049943fc0d57937937122baf1b287862f9dc8590fc4c37df", "https://bcr.bazel.build/modules/protobuf/29.0-rc3/MODULE.bazel": "33c2dfa286578573afc55a7acaea3cada4122b9631007c594bf0729f41c8de92", "https://bcr.bazel.build/modules/protobuf/29.0/MODULE.bazel": "319dc8bf4c679ff87e71b1ccfb5a6e90a6dbc4693501d471f48662ac46d04e4e", "https://bcr.bazel.build/modules/protobuf/29.1/MODULE.bazel": "557c3457560ff49e122ed76c0bc3397a64af9574691cb8201b4e46d4ab2ecb95", "https://bcr.bazel.build/modules/protobuf/3.19.0/MODULE.bazel": "6b5fbb433f760a99a22b18b6850ed5784ef0e9928a72668b66e4d7ccd47db9b0", - "https://bcr.bazel.build/modules/protobuf/3.19.2/MODULE.bazel": "532ffe5f2186b69fdde039efe6df13ba726ff338c6bc82275ad433013fa10573", "https://bcr.bazel.build/modules/protobuf/3.19.6/MODULE.bazel": "9233edc5e1f2ee276a60de3eaa47ac4132302ef9643238f23128fea53ea12858", "https://bcr.bazel.build/modules/protobuf/32.1/MODULE.bazel": "89cd2866a9cb07fee9ff74c41ceace11554f32e0d849de4e23ac55515cfada4d", "https://bcr.bazel.build/modules/protobuf/33.4/MODULE.bazel": "114775b816b38b6d0ca620450d6b02550c60ceedfdc8d9a229833b34a223dc42", @@ -131,19 +138,16 @@ "https://bcr.bazel.build/modules/rules_cc/0.1.5/MODULE.bazel": "88dfc9361e8b5ae1008ac38f7cdfd45ad738e4fa676a3ad67d19204f045a1fd8", "https://bcr.bazel.build/modules/rules_cc/0.2.0/MODULE.bazel": "b5c17f90458caae90d2ccd114c81970062946f49f355610ed89bebf954f5783c", "https://bcr.bazel.build/modules/rules_cc/0.2.13/MODULE.bazel": "eecdd666eda6be16a8d9dc15e44b5c75133405e820f620a234acc4b1fdc5aa37", + "https://bcr.bazel.build/modules/rules_cc/0.2.15/MODULE.bazel": "6a0a4a75a57aa6dc888300d848053a58c6b12a29f89d4304e1c41448514ec6e8", "https://bcr.bazel.build/modules/rules_cc/0.2.17/MODULE.bazel": "1849602c86cb60da8613d2de887f9566a6d354a6df6d7009f9d04a14402f9a84", "https://bcr.bazel.build/modules/rules_cc/0.2.17/source.json": "3832f45d145354049137c0090df04629d9c2b5493dc5c2bf46f1834040133a07", - "https://bcr.bazel.build/modules/rules_cc/0.2.8/MODULE.bazel": "f1df20f0bf22c28192a794f29b501ee2018fa37a3862a1a2132ae2940a23a642", "https://bcr.bazel.build/modules/rules_foreign_cc/0.9.0/MODULE.bazel": "c9e8c682bf75b0e7c704166d79b599f93b72cfca5ad7477df596947891feeef6", "https://bcr.bazel.build/modules/rules_fuzzing/0.5.2/MODULE.bazel": "40c97d1144356f52905566c55811f13b299453a14ac7769dfba2ac38192337a8", - "https://bcr.bazel.build/modules/rules_go/0.41.0/MODULE.bazel": "55861d8e8bb0e62cbd2896f60ff303f62ffcb0eddb74ecb0e5c0cbe36fc292c8", - "https://bcr.bazel.build/modules/rules_go/0.42.0/MODULE.bazel": "8cfa875b9aa8c6fce2b2e5925e73c1388173ea3c32a0db4d2b4804b453c14270", - "https://bcr.bazel.build/modules/rules_go/0.46.0/MODULE.bazel": "3477df8bdcc49e698b9d25f734c4f3a9f5931ff34ee48a2c662be168f5f2d3fd", - "https://bcr.bazel.build/modules/rules_go/0.59.0/MODULE.bazel": "b7e43e7414a3139a7547d1b4909b29085fbe5182b6c58cbe1ed4c6272815aeae", "https://bcr.bazel.build/modules/rules_go/0.63.0/MODULE.bazel": "a2079e783a5d2715a90e6e2970ec8ffd717a487ff2aecb5f553e3975c5294a21", "https://bcr.bazel.build/modules/rules_go/0.63.0/source.json": "5bf37b45c440ac03abad0cbfa8b8b8dd89cc4e82bc8305f468b8436fa58bae78", "https://bcr.bazel.build/modules/rules_java/4.0.0/MODULE.bazel": "5a78a7ae82cd1a33cef56dc578c7d2a46ed0dca12643ee45edbb8417899e6f74", "https://bcr.bazel.build/modules/rules_java/5.3.5/MODULE.bazel": "a4ec4f2db570171e3e5eb753276ee4b389bae16b96207e9d3230895c99644b86", + "https://bcr.bazel.build/modules/rules_java/6.3.0/MODULE.bazel": "a97c7678c19f236a956ad260d59c86e10a463badb7eb2eda787490f4c969b963", "https://bcr.bazel.build/modules/rules_java/6.5.2/MODULE.bazel": "1d440d262d0e08453fa0c4d8f699ba81609ed0e9a9a0f02cd10b3e7942e61e31", "https://bcr.bazel.build/modules/rules_java/7.10.0/MODULE.bazel": "530c3beb3067e870561739f1144329a21c851ff771cd752a49e06e3dc9c2e71a", "https://bcr.bazel.build/modules/rules_java/7.12.2/MODULE.bazel": "579c505165ee757a4280ef83cda0150eea193eed3bef50b1004ba88b99da6de6", @@ -190,6 +194,7 @@ "https://bcr.bazel.build/modules/rules_python/1.7.0/source.json": "028a084b65dcf8f4dc4f82f8778dbe65df133f234b316828a82e060d81bdce32", "https://bcr.bazel.build/modules/rules_shell/0.2.0/MODULE.bazel": "fda8a652ab3c7d8fee214de05e7a9916d8b28082234e8d2c0094505c5268ed3c", "https://bcr.bazel.build/modules/rules_shell/0.3.0/MODULE.bazel": "de4402cd12f4cc8fda2354fce179fdb068c0b9ca1ec2d2b17b3e21b24c1a937b", + "https://bcr.bazel.build/modules/rules_shell/0.4.1/MODULE.bazel": "00e501db01bbf4e3e1dd1595959092c2fadf2087b2852d3f553b5370f5633592", "https://bcr.bazel.build/modules/rules_shell/0.6.1/MODULE.bazel": "72e76b0eea4e81611ef5452aa82b3da34caca0c8b7b5c0c9584338aa93bae26b", "https://bcr.bazel.build/modules/rules_shell/0.6.1/source.json": "20ec05cd5e592055e214b2da8ccb283c7f2a421ea0dc2acbf1aa792e11c03d0c", "https://bcr.bazel.build/modules/rules_swift/1.16.0/MODULE.bazel": "4a09f199545a60d09895e8281362b1ff3bb08bbde69c6fc87aff5b92fcc916ca", @@ -199,13 +204,21 @@ "https://bcr.bazel.build/modules/rules_swift/3.1.2/source.json": "e85761f3098a6faf40b8187695e3de6d97944e98abd0d8ce579cb2daf6319a66", "https://bcr.bazel.build/modules/stardoc/0.5.1/MODULE.bazel": "1a05d92974d0c122f5ccf09291442580317cdd859f07a8655f1db9a60374f9f8", "https://bcr.bazel.build/modules/stardoc/0.5.3/MODULE.bazel": "c7f6948dae6999bf0db32c1858ae345f112cacf98f174c7a8bb707e41b974f1c", + "https://bcr.bazel.build/modules/stardoc/0.6.2/MODULE.bazel": "7060193196395f5dd668eda046ccbeacebfd98efc77fed418dbe2b82ffaa39fd", "https://bcr.bazel.build/modules/stardoc/0.7.0/MODULE.bazel": "05e3d6d30c099b6770e97da986c53bd31844d7f13d41412480ea265ac9e8079c", "https://bcr.bazel.build/modules/stardoc/0.7.2/MODULE.bazel": "fc152419aa2ea0f51c29583fab1e8c99ddefd5b3778421845606ee628629e0e5", "https://bcr.bazel.build/modules/stardoc/0.7.2/source.json": "58b029e5e901d6802967754adf0a9056747e8176f017cfe3607c0851f4d42216", "https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.1/MODULE.bazel": "5e463fbfba7b1701d957555ed45097d7f984211330106ccd1352c6e0af0dcf91", "https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.2/MODULE.bazel": "75aab2373a4bbe2a1260b9bf2a1ebbdbf872d3bd36f80bff058dccd82e89422f", "https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.2/source.json": "5fba48bbe0ba48761f9e9f75f92876cafb5d07c0ce059cc7a8027416de94a05b", + "https://bcr.bazel.build/modules/tar.bzl/0.2.1/MODULE.bazel": "52d1c00a80a8cc67acbd01649e83d8dd6a9dc426a6c0b754a04fe8c219c76468", + "https://bcr.bazel.build/modules/tar.bzl/0.6.0/MODULE.bazel": "a3584b4edcfafcabd9b0ef9819808f05b372957bbdff41601429d5fd0aac2e7c", + "https://bcr.bazel.build/modules/tar.bzl/0.6.0/source.json": "4a620381df075a16cb3a7ed57bd1d05f7480222394c64a20fa51bdb636fda658", + "https://bcr.bazel.build/modules/toolchains_llvm/1.11.0/MODULE.bazel": "c0b9c103deeaf0fc103934ff0a189273b4f9b82cc1622c59b67e1c3a83d6b5e6", + "https://bcr.bazel.build/modules/toolchains_llvm/1.11.0/source.json": "d06e53520101c3890a094e5849b0ff16dde3a6f6531f25c997f340ebff34d569", "https://bcr.bazel.build/modules/upb/0.0.0-20220923-a547704/MODULE.bazel": "7298990c00040a0e2f121f6c32544bab27d4452f80d9ce51349b1a28f3005c43", + "https://bcr.bazel.build/modules/yq.bzl/0.1.1/MODULE.bazel": "9039681f9bcb8958ee2c87ffc74bdafba9f4369096a2b5634b88abc0eaefa072", + "https://bcr.bazel.build/modules/yq.bzl/0.1.1/source.json": "2d2bad780a9f2b9195a4a370314d2c17ae95eaa745cefc2e12fbc49759b15aa3", "https://bcr.bazel.build/modules/zlib/1.2.11/MODULE.bazel": "07b389abc85fdbca459b69e2ec656ae5622873af3f845e1c9d80fe179f3effa0", "https://bcr.bazel.build/modules/zlib/1.2.12/MODULE.bazel": "3b1a8834ada2a883674be8cbd36ede1b6ec481477ada359cd2d3ddc562340b27", "https://bcr.bazel.build/modules/zlib/1.3.1.bcr.5/MODULE.bazel": "eec517b5bbe5492629466e11dae908d043364302283de25581e3eb944326c4ca", @@ -216,7 +229,7 @@ "moduleExtensions": { "@@pybind11_bazel+//:internal_configure.bzl%internal_configure_extension": { "general": { - "bzlTransitiveDigest": "NRXra7941UfmNUyIxnLt82V5hULluVGL2nBsijTl4j4=", + "bzlTransitiveDigest": "BsgERqYptkJeeC8wFaLj251IoTZTSy/58WA6kVp0q8I=", "usagesDigest": "D1r3lfzMuUBFxgG8V6o0bQTLMk3GkaGOaPzw53wrwyw=", "recordedInputs": [ "REPO_MAPPING:pybind11_bazel+,bazel_tools bazel_tools", @@ -238,7 +251,7 @@ }, "@@rules_kotlin+//src/main/starlark/core/repositories:bzlmod_setup.bzl%rules_kotlin_extensions": { "general": { - "bzlTransitiveDigest": "+Kp6j204mBZ3mxlIDDR0gBoP45BZ4jYRhRAcB8sU0qc=", + "bzlTransitiveDigest": "WDuVCwqV73DvcHB5Of+02lhUZgPxr9MqtpvMRyUi0eQ=", "usagesDigest": "QI2z8ZUR+mqtbwsf2fLqYdJAkPOHdOV+tF2yVAUgRzw=", "recordedInputs": [ "REPO_MAPPING:rules_kotlin+,bazel_tools bazel_tools" @@ -295,7 +308,7 @@ }, "@@rules_python+//python/extensions:config.bzl%config": { "general": { - "bzlTransitiveDigest": "dzD8Q2YmrP3fz8saWLHPmlwPLO91ImtTmP/c9JKTStM=", + "bzlTransitiveDigest": "L+2ZCpb7GIJqvWaXpzkfk/80d916sIFVmSPzrSm6of8=", "usagesDigest": "ZVSXMAGpD+xzVNPuvF1IoLBkty7TROO0+akMapt1pAg=", "recordedInputs": [ "REPO_MAPPING:rules_python+,bazel_tools bazel_tools", @@ -463,7 +476,7 @@ }, "@@rules_python+//python/uv:uv.bzl%uv": { "general": { - "bzlTransitiveDigest": "ijW9KS7qsIY+yBVvJ+Nr1mzwQox09j13DnE3iIwaeTM=", + "bzlTransitiveDigest": "IgkgxNrtlAec7OnaFrWoCC5NQhHcY/aIz4jsqcNMm8Y=", "usagesDigest": "H8dQoNZcoqP+Mu0tHZTi4KHATzvNkM5ePuEqoQdklIU=", "recordedInputs": [ "REPO_MAPPING:rules_python+,bazel_tools bazel_tools", @@ -490,6 +503,26 @@ } } } + }, + "@@toolchains_llvm+//toolchain/extensions:distributions.bzl%llvm_distributions": { + "general": { + "bzlTransitiveDigest": "RfYsFLwRh0rVY8ReiYgbOEyr84zuBs7mbcHq3dPY3jI=", + "usagesDigest": "vl2VXD2E16aV3RG06i5tx7yyYASHiQFjvsiNZSDzQIg=", + "recordedInputs": [], + "generatedRepoSpecs": { + "llvm_distributions_data": { + "repoRuleId": "@@toolchains_llvm+//toolchain/internal:distributions_repo.bzl%llvm_distributions_repo", + "attributes": { + "srcs": [ + "@@toolchains_llvm+//toolchain/distributions:pre_github.jsonc", + "@@toolchains_llvm+//toolchain/distributions:github_legacy.jsonc", + "@@toolchains_llvm+//toolchain/distributions:github.jsonc", + "@@toolchains_llvm+//toolchain/distributions:extra.jsonc" + ] + } + } + } + } } }, "facts": { diff --git a/Makefile b/Makefile index 24b375ea2..d0bfbbdc6 100644 --- a/Makefile +++ b/Makefile @@ -44,13 +44,32 @@ endif endif .PHONY: all build doctor-build test test-icu-path test-full-cgo test-regression test-upgrade test-cross-version test-migration corpus-regen githooks-regen bench bench-quick clean clean-test-tmp install install-force help check-up-to-date fmt fmt-check check-testing-short -.PHONY: ci-pr-core ci-pr-policy ci-pr-lint ci-complexity ci-complexity-diff ci-complexity-check ci-package-mcp ci-package-npm +.PHONY: lint lint-changed vet +.PHONY: check check-go test-go check-docs-go +.PHONY: ci-pr-core ci-pr-lint ci-complexity ci-complexity-diff ci-complexity-check ci-package-mcp ci-package-npm nogo-ownership .PHONY: api-gen api-check .PHONY: bazel-sync bazel-sync-check # Default target all: build +# Build and test engine. Bazel is what CI gates on: .github/workflows/bazel.yml +# runs `bazel test` lanes on rbe-west, and nogo (lint + vet), formatting and +# the repository guards are Bazel targets there. The primary targets (test, +# check, check-docs) run the same `bazel test` commands as those lanes, so a +# local run shares CI's action keys and its remote cache (engdocs/TESTING.md +# "Building and testing"). Each keeps a plain go twin under an explicit -go +# name (test-go, check-go, check-docs-go) for offline work and hosts Bazel does +# not serve; that twin is an inner-loop convenience, not what CI enforces. +# GitHub Actions jobs that still run Go-native suites call the -go names. +BAZEL ?= bazel +# Extra flags for every `bazel test` below: --config=fork-cache (contributors: +# the anonymous read-only cache) or --config=remote-exec (maintainers with an +# rbe-west client certificate). Hosts whose ~/.bazelrc names the executor need +# neither. Better: put `build --config=...` in the gitignored .bazelrc.local. +BAZEL_FLAGS ?= +BAZEL_TEST = $(BAZEL) test $(BAZEL_FLAGS) + BUILD_DIR := . BD_BUILD_OUTPUT := $(BUILD_DIR)/bd$(if $(filter Windows_NT,$(OS)),.exe) GIT_BUILD := $(shell git rev-parse --short HEAD) @@ -173,11 +192,27 @@ doctor-build: echo " CGO_ENABLED=1 go build -tags gms_pure_go ./cmd/bd" ;; \ esac -# Run all tests (skips known broken tests listed in .test-skip) +# bazel.yml's test lane (`bazel test //... --config=ci`): every untagged +# go_test with PR Core's selection (race, -short, skips), plus nogo lint/vet, +# formatting and the repository guards. The other lanes' commands are in +# engdocs/TESTING.md "Building and testing". test: + $(BAZEL_TEST) //... --config=ci + +# Plain go test (skips known broken tests listed in .test-skip): an inner-loop +# convenience without Bazel; CI does not run it. +test-go: @echo "Running tests..." @TEST_COVER=1 ./scripts/test.sh +# Fast quality gates: the testing.Short policy, the full nogo lint gate +# (native plus the windows/darwin passes) and `make test`. +check: check-testing-short ci-pr-lint test + +# The same gates without Bazel where they have a Go form: gofmt and go test. +# nogo has no go twin, so this is a convenience CI does not enforce. +check-go: fmt-check check-testing-short test-go + # Run the opt-in ICU regex path test suite (no skip list). # This is a local developer workflow for intentionally exercising the leftover # ICU path; it is not part of normal validation. @@ -194,12 +229,59 @@ test-full-cgo: ci-pr-core: @./scripts/ci/pr-core.sh -ci-pr-policy: - @./scripts/ci/pr-policy.sh - +# Lint and vet are nogo (//tools/nogo): go test's vet checks plus the +# golangci-lint linters .golangci.yml enables, validated beside every Go +# compile, so any `bazel build`/`bazel test` (local or on rbe-west) fails on a +# finding. These targets ask Bazel for the analysis alone (.bazelrc's +# --config=nogo; nothing is linked). ci-pr-lint: @./scripts/ci/pr-lint.sh +# nogo-ownership is a dynamic, advisory cross-check (not part of the required +# //scripts static suite, which cannot shell out to Bazel): it asks real +# `bazel aquery` whether the nogo owner lane for each configuration group +# (today: race, bazel-test/--config=ci) really does validate every file a +# non-owner lane (embedded, doltserver, doltserver-proxied, dolt-race, which +# pass --norun_validations) compiles. See tools/bazel/nogo_ownership.py and +# scripts/nogo_lint_policy_test.go's nogoConfigurations table. +nogo-ownership: + @python3 tools/bazel/nogo_ownership.py + +# The CI lint gate: native, plus //tools/bazel:release_cross for windows/amd64 +# and darwin/arm64 (BD_LINT_TARGETS selects; scripts/pr-lint). +lint: ci-pr-lint + +# go test's vet checks run inside nogo; same as lint. +vet: lint + +# nogo over the Bazel packages of changed Go files, natively (the pre-commit +# hook's lint). LINT_CHANGED_SCOPE: staged, or worktree (changed against +# LINT_CHANGED_REF, staged, and untracked). +LINT_CHANGED_SCOPE ?= worktree +LINT_CHANGED_REF ?= HEAD +lint-changed: + @case "$(LINT_CHANGED_SCOPE)" in \ + staged) files="$$(git diff --cached --name-only --diff-filter=ACMRT -- '*.go')" ;; \ + worktree) files="$$( \ + git diff --name-only --diff-filter=ACMRT "$(LINT_CHANGED_REF)" -- '*.go'; \ + git diff --cached --name-only --diff-filter=ACMRT -- '*.go'; \ + git ls-files --others --exclude-standard -- '*.go')" ;; \ + *) echo "unknown LINT_CHANGED_SCOPE=$(LINT_CHANGED_SCOPE); expected staged or worktree" >&2; exit 2 ;; \ + esac; \ + packages=""; missing=""; \ + for file in $$files; do \ + dir="$$(dirname "$$file")"; \ + case "/$$dir/" in */testdata/*) continue ;; esac; \ + if [ -f "$$dir/BUILD.bazel" ]; then packages="$$packages //$${dir#.}:all"; else missing="$$missing $$dir"; fi; \ + done; \ + if [ -n "$$missing" ]; then \ + echo "lint-changed: no BUILD.bazel in$$missing; run 'make bazel-sync'" >&2; exit 1; \ + fi; \ + packages="$$(printf '%s\n' $$packages | sort -u | sed 's#^///#//#; s#^//\.:#//:#')"; \ + if [ -z "$$packages" ]; then echo "lint-changed: no changed Go packages"; exit 0; fi; \ + echo "lint-changed:" $$packages; \ + $(BAZEL) build --config=nogo -- $$packages + # Opt-in architecture experiment. Install gocyclo v0.6.0 first; # report is advisory while check exercises the local baseline guard. ci-complexity: @@ -220,9 +302,8 @@ api-gen: go generate -tags "$(BUILD_TAGS)" ./internal/httpapi/apigen # Two-part spec drift gate: regenerate and fail if regeneration CHANGED -# anything, then run the spec tests. Runs in the PR workflow's policy job -# (scripts/ci/pr-policy.sh), on every pull request, never only on -# push-to-main. +# anything, then run the spec tests. CI runs the drift half as +# //scripts/repochecks:types_gen_drift_test. # # The drift question is "do the checked-out types already match the checked-out # spec", so the comparison is before-vs-after regeneration rather than @@ -380,8 +461,15 @@ fmt: fmt-check: @./scripts/ci/fmt-check.sh -# Validate documentation references against actual CLI flags +# Docs checks: docsync and doc freshness as bazel.yml's test lane runs them, +# then the CLI flag check, which validates against bd built from the release in +# docs/cli-docs.pin (so it stays a script, like pr.yml's check-doc-flags job). check-docs: + $(BAZEL_TEST) //test/docsync:docsync_test //scripts/repochecks:doc_freshness_test --config=ci + @./scripts/check-doc-flags.sh + +# The same docs checks with plain go test and a go-built bd. +check-docs-go: @echo "Building bd for docs checks..." @CGO_ENABLED=0 go build -tags "$(BUILD_TAGS)" -ldflags="-X main.Build=$(GIT_BUILD)" -o "$(BUILD_DIR)/bd" ./cmd/bd @./scripts/check-doc-flags.sh "$(BUILD_DIR)/bd" @@ -416,12 +504,10 @@ diagrams-excalidraw: docs-dev: ./mint.sh dev -# Bazel (side-by-side with the Go toolchain; `go build`/`go test` do not need -# it). Regenerate BUILD.bazel files with gazelle and refresh the MODULE.bazel +# Regenerate BUILD.bazel files with gazelle and refresh the MODULE.bazel # use_repo list + MODULE.bazel.lock, then refresh the go_srcs filegroups that # source-scanning tests declare as data (tools/bazel/go_srcs.py). Run after # changing Go imports, go.mod, or packages. -BAZEL ?= bazel bazel-sync: $(BAZEL) run //:gazelle python3 tools/bazel/go_srcs.py @@ -457,12 +543,16 @@ help: @echo "Beads Makefile targets:" @echo " make build - Build the bd binary" @echo " make doctor-build - Diagnose build env (GOFLAGS/CGO/CC) for the ICU build trap" - @echo " make test - Run all tests" + @echo " make test - bazel test //... --config=ci (bazel.yml's test lane; BAZEL_FLAGS adds flags)" + @echo " make test-go - Plain go test via scripts/test.sh (inner loop; not what CI enforces)" + @echo " make check - testing.Short policy + nogo lint gate + make test" + @echo " make check-go - gofmt + testing.Short policy + make test-go (no Bazel)" @echo " make test-icu-path - Run opt-in ICU regex path tests (maintainer-only)" @echo " make test-full-cgo - Deprecated alias for make test-icu-path" @echo " make ci-pr-core - Run required PR core Go test wrapper" - @echo " make ci-pr-policy - Run required PR policy wrapper" - @echo " make ci-pr-lint - Run required PR formatting and lint wrapper" + @echo " make ci-pr-lint - Run the required lint gate: nogo (vet + golangci-lint's linters) under Bazel, native + windows/darwin" + @echo " make lint - Same as ci-pr-lint (make vet too)" + @echo " make lint-changed - nogo over the Bazel packages of changed Go files (LINT_CHANGED_SCOPE=staged|worktree)" @echo " make ci-complexity - Report production cyclomatic complexity (advisory)" @echo " make ci-complexity-diff - Compare complexity with COMPLEXITY_BASE_REF" @echo " make ci-complexity-check - Check complexity against the local baseline" @@ -478,7 +568,8 @@ help: @echo " make install-force - Install bd, skipping the origin/main update check" @echo " make fmt - Format all Go files with gofmt" @echo " make fmt-check - Check Go formatting (for CI)" - @echo " make check-docs - Validate docs against CLI flags" + @echo " make check-docs - Bazel docsync + doc freshness tests, then the CLI flag check" + @echo " make check-docs-go - The same docs checks with plain go test" @echo " make api-gen - Regenerate HTTP API types from the OpenAPI spec" @echo " make api-check - OpenAPI drift gate (regenerate, diff-or-fail, spec tests)" @echo " make bazel-sync - Regenerate Bazel BUILD files and tidy MODULE.bazel (gazelle + mod tidy)" diff --git a/README.md b/README.md index 6bc34354f..f7909900f 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ bd setup factory # Factory.ai Droid - creates/updates AGENTS.md **Note:** Beads is a CLI tool you install once and use everywhere. You don't need to clone this repository into your project. -`bd init` creates or updates `AGENTS.md` by default so agents can discover the beads workflow, and also installs project Claude/Codex integrations unless you pass `--skip-agents` or `--stealth`. Use `bd setup --list` to see supported integrations, including `bd setup codex`, `bd setup factory`, `bd setup claude`, `bd setup mux`, `bd setup cursor`, and more. See [Agent and IDE setup](docs/getting-started/ide-setup.md). +`bd init` creates or updates `AGENTS.md` by default so agents can discover the beads workflow, and also installs the project Claude Code, Codex, and Cursor integrations unless you pass `--skip-agents` or `--stealth`. Use `bd setup --list` to see supported integrations, including `bd setup codex`, `bd setup factory`, `bd setup claude`, `bd setup mux`, `bd setup cursor`, and more. See [Agent and IDE setup](docs/getting-started/ide-setup.md). Manual copy-paste is only for unsupported agents, existing projects where you cannot rerun `bd init`/`bd setup`, or custom instruction files. In those cases, run `bd onboard` and paste the printed snippet into the file your agent reads. @@ -109,8 +109,8 @@ version: sync remote-backed databases with your current `bd`, back up with `bd export --all`, upgrade the binary, then run `bd info --whats-new`, `bd hooks install`, and `bd version`. If the upgrade crosses a schema migration on a remote-backed database, exactly one designated clone runs -`bd migrate` and `bd dolt push`; other clones install the new binary -and run `bd bootstrap`. See the full +`bd migrate schema` and `bd dolt push`; other clones install the new +binary and run `bd bootstrap`. See the full [upgrade guide](https://beads.gascity.com/getting-started/upgrading) or [docs/getting-started/installation.md](docs/getting-started/installation.md#updating-bd). @@ -175,6 +175,153 @@ are unaffected. the guard with a warning on stderr. Use this only if you know the forward migrations are additive and safe for your specific workload. +## 🔌 HTTP Backend (experimental) + +A workspace can also talk to a remote `bd serve` over HTTP instead of opening +a local Dolt database — useful for a thin client against a shared server, or +for embedding beads in another program as a library. + +```bash +# Point this workspace at a server (verifies the server first; writes nothing on failure) +bd connect https://bd.example.com --expect-project-id my-project + +# The everyday commands work the same way: create, show, list, update, close, +# dependencies (including `bd dep tree`), comments, ready/count queries, and +# batch apply all round-trip over the wire with the same semantics as a local +# database. So does `bd ready --claim`, except against an older server or while +# any issue holds an unsatisfied external ref: then it lists and claims in two +# steps rather than one transaction (ledger row L14, linked below). +bd create "Fix auth bug" -p 1 -t bug +bd ready --json +bd close bd-a1b2 "Fixed" + +# Loopback needs no TLS +bd connect http://127.0.0.1:8080 + +# Forget the server and restore this workspace's previous backend selection +bd connect --clear +``` + +HTTP mode is not a byte-for-byte mirror of local mode, though: some +operations are knowingly refused (the wire has no way to express them) or +degrade to a different-but-not-misreadable behavior (for example, a few +unbounded listing shapes lose single-query snapshot isolation and instead +walk the server page by page). Every one of these is a deliberate, tested +row, never a silent gap — see +[`engdocs/design/http-divergence-ledger.md`](engdocs/design/http-divergence-ledger.md) +for the full, generated list of what differs and why before depending on an +HTTP-backed workspace for a workflow you haven't checked against it. One +refusal to know up front: `bd close --claim-next` closes nothing over HTTP, +because the wire's batch close cannot carry the claim. Close without it, then +run `bd ready --claim`. + +[Cross-repo dependencies](docs/core-concepts/dependencies.md#cross-repo-dependencies) +keep their policy over HTTP. The client resolves each `external:` reference +against its own `external_projects` configuration. `bd dep tree` shows the +reference as a leaf, and while it is unsatisfied the issue stays out of +`bd ready` and `bd ready --claim`, and `bd close` refuses it without +`--force`. A server that advertises enforcing that policy itself is trusted +to do so instead. + +Three CLI-level differences are worth knowing up front: + +- IDs resolve exactly: an abbreviated id is not expanded (the wire has no + substring search), and a missing id is reported as not found after one + lookup. +- `bd update -s closed` does not record `closed_by_session` (from `--session` + or `CLAUDE_SESSION_ID`), because the wire's update cannot carry it; the + close itself happens as usual. `bd close` does record the session. `bd + reopen`'s history entry carries the server's own label. +- Contributor auto-routing (`routing.*` settings) is read from local + `config.yaml` / environment only, never from the server's settings: its + targets are local paths. + +`bd connect` writes two things on success: `.beads/metadata.json` gets +`"backend": "http"`, and a per-user, never-git-tracked sidecar +(`.beads/http_target.json`) records the server URL and pinned project id. It +never writes a credential to disk. A bearer credential, if the server +requires one, comes from `BEADS_HTTP_TOKEN=host[:port]=`, then +`BEADS_HTTP_TOKEN_COMMAND=host[:port]=` (a helper that prints a +token), then the credentials file, then no credential at all. Both variables +must name the server they are for (a pattern without a port matches that +host on any port); a bare value is refused, because it would be sent to +whatever server the workspace's `http_target.json` names. Connecting to a +non-loopback server over plain `http://` is refused by default (a bearer +credential would cross the network unencrypted) — pass `--allow-plaintext` to +override, or use `https://`. Switching a workspace that already selects a +different backend needs `--force`. + +Each read (a GET, or the POST batch get) gives its first attempt 15s, from +when the request is sent, to get the server's response headers +(`BEADS_HTTP_RESPONSE_HEADER_TIMEOUT`: a duration such as `30s`, a number of +seconds, or `off`). A read whose headers do not arrive in time, or whose +connection is reset, is retried once on another connection, and each retry +is logged to stderr with its count. The retry has no header timer, but it +runs on what is left of the 60s bound on the whole request, counted from +when the first attempt was sent: a slow but healthy read still finishes if +the retry's headers and body together fit in that remainder (about 45s after +a header timeout), and one that needs longer now fails at 60s. The header +timer never cuts off a body that is still streaming; the 60s bound still +does. The events:watch stream's connect gets neither the header timer nor +the retry. On Windows a reset connection is retried only when it surfaces as +an early EOF, because the check matches the Unix reset error (`ECONNRESET`), +which a Windows reset (`WSAECONNRESET`) is not. A write gets no +header timer (the server answers a write only after it commits, so a large +one can be slow and healthy) and is never retried; if the 60s bound expires +after it was sent but before its headers, it fails with an error naming the +server's host, because it may or may not have been applied. A batch apply of +more than 100 items (a large `bd create --graph` plan, say) gets 6 minutes +instead of 60s, because `bd serve` gives such a request its +`--large-apply-ceiling` (5 minutes by default) and finishes it even after the +client has given up. A server whose ceiling is raised past about 5m15s can +still outlast the client. A dial or TLS timeout stays a plain connection +error, since the server never saw the request, and a connect that fails says +so: it names the address that refused the connection (nothing listening) or +never answered (a filtered port or a down host, after the dialer's 30s), or +the host name that did not resolve. `off` turns off only the +header timer: a reset read is still retried, and a write's timeout is still +reported as above. + +Whether the server applies bd's external-dependency policy itself (the +`policy.external_dependencies` capability) is remembered for 5 minutes per +server URL and pinned project, in `beads/http-policy/` under the user cache +directory, so `bd ready` does not fetch the server's context before every +listing just to learn it. `BEADS_HTTP_POLICY_CACHE_TTL` sets that window (a +duration such as `1m`, a number of seconds, or `off`); a server restarted +with a different composition is seen once it passes. Claims and closes never +use the cached answer: they ask the server, since a stale one could skip the +client-side refusal of externally blocked work. A workspace connected without +a project pin is not cached. + +`bd search`, `bd show --current` and `bd recompute-blocked` work over HTTP +too, each in its own way. `bd search` asks the server's listing with its text (`q`, behind the `issues.list.search` capability) and +refuses before dialing against a server that does not advertise it. `bd list +--no-assignee`, `--title` and `--id` likewise ride the listing's +`no_assignee`, `title` and repeatable `id`, each behind its own capability +(`issues.list.noAssignee`, `issues.list.title`, `issues.list.ids`), and the +rest of `bd list`'s filters (`--updated-*`, `--closed-*`, `--defer-*`, +`--due-*`, `--priority*`, the text and external-ref matches, `--spec`, +`--label-pattern`/`--label-regex`, `--exclude-type`, `--no-parent`, +`--no-labels`, `--empty-description`, `--pinned`/`--no-pinned`, +`--deferred`, `--overdue`, `--mol-type`, `--wisp-type`) ride it behind one +capability, `issues.list.filters`. Time bounds are resolved on the client as +they are locally; `--overdue` compares against the server's clock. The +default `--parent` tree view does not carry those filters yet and refuses one +rather than drop it; `--flat` or `--json` applies them to the parent's direct +children (not its whole subtree). +`bd show --current` finds the actor's in-progress or hooked issue through the +server's boolean query. `bd recompute-blocked` is a no-op that exits 0: the +server maintains `is_blocked` on every write, and repairing a stale flag is +done in the server's own workspace (`--json` reports +`{"rows_corrected": 0, "maintained_by": "server"}`). + +An embedding program that links beads as a library rather than running +`cmd/bd` registers this backend itself through the public +[`backend/http`](backend/http) package (`bdhttp.Register`), and can open a +workspace with a credential scoped to one caller via +`beads.OpenBestAvailableWith` — see that package's doc comment for the +multi-tenant case. This surface is EXPERIMENTAL: pin an exact beads version. + ## 🌐 Community Tools See [docs/community-tools.md](docs/community-tools.md) for a curated list of community-built UIs, extensions, and integrations—including terminal interfaces, web UIs, editor extensions, and native apps. @@ -211,5 +358,6 @@ This is useful for: ## 📝 Documentation -* [Documentation site](https://beads.gascity.com/) | [Installing](docs/getting-started/installation.md) | [Sync Concepts](docs/core-concepts/sync-concepts.md) | [Agent Workflow](AGENT_INSTRUCTIONS.md) | [Copilot CLI Setup](docs/integrations/copilot-cli.md) | [Copilot VS Code MCP](docs/integrations/github-copilot.md) | [Articles](ARTICLES.md) | [Sync Branch Mode](docs/reference/protected-branches.md) | [Troubleshooting](docs/reference/troubleshooting.md) | [FAQ](docs/reference/faq.md) +* [Documentation site](https://beads.gascity.com/) | [Installing](docs/getting-started/installation.md) | [Sync Concepts](docs/core-concepts/sync-concepts.md) | [Agent Setup](docs/getting-started/ide-setup.md) | [Copilot CLI Setup](docs/integrations/copilot-cli.md) | [Copilot VS Code MCP](docs/integrations/github-copilot.md) | [Articles](ARTICLES.md) | [Sync Branch Mode](docs/reference/protected-branches.md) | [Troubleshooting](docs/reference/troubleshooting.md) | [FAQ](docs/reference/faq.md) +* Contributing: [CONTRIBUTING.md](CONTRIBUTING.md) (Bazel builds and tests beads: install [Bazelisk](https://github.com/bazelbuild/bazelisk), then `make test`) | [Roadmap](ROADMAP.md) | [Contributor agent instructions](AGENTS.md) * [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/gastownhall/beads) diff --git a/RELEASING.md b/RELEASING.md index 894abbb20..50acb6497 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -94,15 +94,19 @@ release-critical gates do not all run on every PR, so "tag the tip of main" means tagging a SHA nobody has fully tested. A burned tag is never reused (the v1.1.1 and v1.2.0 precedents), so that gamble is expensive. -**Cut the branch from a SHA that is green on both `Main` and -`Nightly Full Tests`.** The `Main` workflow runs on push to `main` and the -`Nightly Full Tests` workflow runs on a 2am UTC schedule, so the newest SHA -with both is usually a few hours behind the tip: +**Cut the branch from a SHA that is green on `Bazel`, `Main` and +`Nightly`.** The `Bazel` workflow (every Linux test lane, on rbe-west) and +the `Main` workflow (the macOS and Windows jobs) run on push to `main`, and +the `Nightly` workflow (the full Bazel suite with no cached test results) +runs on a 2am UTC schedule, so the newest SHA with all three is usually a +few hours behind the tip: ```bash +gh run list --workflow Bazel --branch main --event push --status success --limit 5 \ + --json headSha,conclusion,createdAt gh run list --workflow Main --branch main --status success --limit 5 \ --json headSha,conclusion,createdAt -gh run list --workflow "Nightly Full Tests" --status success --limit 3 \ +gh run list --workflow Nightly --status success --limit 3 \ --json headSha,conclusion,createdAt git fetch origin @@ -136,16 +140,17 @@ git log --oneline main..release/1.3.0 Before starting a release: -- [ ] `release/x.y.z` branch cut from a SHA green on `Main` **and** - `Nightly Full Tests` (see [Release Branches](#release-branches)) -- [ ] All tests passing (`go test ./...`) +- [ ] `release/x.y.z` branch cut from a SHA green on `Bazel`, `Main` **and** + `Nightly` (see [Release Branches](#release-branches)) +- [ ] All tests passing (`make test`, the Bazel test lane) - [ ] npm package tests passing (`cd npm-package && npm run test:all`) - [ ] **Upgrade smoke tests pass** (`make test-upgrade`) — see [Release Stability Gate](engdocs/RELEASE-STABILITY-GATE.md) -- [ ] **Regression tests pass** (`make test-regression`) +- [ ] **Regression tests pass** + (`bazel test //tests/regression:regression_test --config=doltserver-cmd`) - [ ] **Every release target cross-compiles** — see - [Cross-compile before tagging](#cross-compile-before-tagging). PR CI does - not build them ([#5662](https://github.com/gastownhall/beads/issues/5662)), - and a target that fails at tag time burns the tag. + [Cross-compile before tagging](#cross-compile-before-tagging). PR CI + builds them only with cgo off, and a target that fails at tag time + burns the tag. - [ ] **CHANGELOG.md updated with release notes** (see format below) - [ ] **CHANGELOG rollup checked** — nothing left under `[Unreleased]` that belongs in this release, and nothing filed under a *previous* release's @@ -163,12 +168,15 @@ Before starting a release: ### Cross-compile before tagging -`.goreleaser.yml` builds darwin, linux, windows **and freebsd**, but PR CI -builds none of the cross targets — the v1.2.0 tag burned on a freebsd -compilation failure that no pre-tag gate could have caught -([#5661](https://github.com/gastownhall/beads/pull/5661) fixed the break, -[#5662](https://github.com/gastownhall/beads/issues/5662) tracks the CI gap). -Until that gap is closed, build them by hand before tagging: +`.goreleaser.yml` builds darwin, linux, windows **and freebsd**; the v1.2.0 +tag burned on a freebsd compilation failure no pre-tag gate caught +([#5661](https://github.com/gastownhall/beads/pull/5661), +[#5662](https://github.com/gastownhall/beads/issues/5662)). PR CI now builds +the whole tree for every target in `scripts/ci/release-targets.txt` with Bazel +(`scripts/ci/bazel-release-cross-compile.sh`, in bazel.yml's pure-Go lane), +but with cgo off, while linux/amd64, linux/arm64, windows/amd64 and the darwin +pair ship with `CGO_ENABLED=1`. Build the real release configuration by hand +before tagging: ```bash goreleaser build --snapshot --clean diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 000000000..006b5602e --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,71 @@ +# Beads Roadmap + +Last updated: 2026-10-05 · Owner: [@julianknutsen](https://github.com/julianknutsen) + +This page lists the areas the maintainers are prioritizing. It reflects +current thinking, not commitments or dates: priorities change as we learn, +and the live state of each item is its tracking issue on GitHub. + +## How this roadmap is used + +- **Priority areas get expedited review.** Issues and PRs that advance a + priority area below are triaged and reviewed first. +- **Propose work with an issue when it warrants discussion.** For work + inside or outside a priority area that needs context or a design decision, + open an issue with the feature form, before or alongside your PR; small, + self-explanatory changes can go straight to a PR. See + [CONTRIBUTING.md](CONTRIBUTING.md#issues-and-pull-requests). +- **Scope.** Proposals must fit the product boundary in + [engdocs/PROJECT_CHARTER.md](engdocs/PROJECT_CHARTER.md). +- **Updates.** The owner rewrites this page at each minor release; the date + above says when it was last reviewed. + +## Priority areas for 1.4 + +### Versioned beads and history + +- **Goal:** every change to a bead is recorded as a version. Users can read + a bead's history and past versions, and writers can use `expectedRevision` + compare-and-swap to avoid lost updates. Everything ships behind a flag, off + by default, until the conformance suite and a production-corpus soak say + otherwise. +- **This period:** all six phases, enabled from the CLI by the end of the + period: conformance suite + ([#6133](https://github.com/gastownhall/beads/issues/6133)), additive + schema ([#6134](https://github.com/gastownhall/beads/issues/6134)), + dual-write history behind a flag + ([#6135](https://github.com/gastownhall/beads/issues/6135)), versioned + reads and CAS ([#6136](https://github.com/gastownhall/beads/issues/6136)), + production-corpus validation + ([#6137](https://github.com/gastownhall/beads/issues/6137)), and CLI + surfacing and enablement + ([#6138](https://github.com/gastownhall/beads/issues/6138)). +- **Tracking issue:** [#6132](https://github.com/gastownhall/beads/issues/6132); + design discussion stays on + [#5898](https://github.com/gastownhall/beads/issues/5898). + +### Beads Graph Preview 2 + +- **Goal:** ship Beads Graph Preview 2, the next public checkpoint for the + generic Bead-and-Link graph model: a coherent daily-use CLI journey in + graph mode that behaves like ordinary `bd`, backed by a complete, + reviewable CLI specification. +- **This period:** the reviewed graph CLI specification, a complete + daily-use Issue journey proven through the installed CLI on embedded and + shared-server Dolt, and editing around that Issue (labels, notes, Memory + and Link edits). +- **Tracking issue:** [#7170](https://github.com/gastownhall/beads/issues/7170) + +### Contributor onboarding + +- **Goal:** a new contributor, human or agent, finds the rules for the code + they are changing next to that code, understands its intent and + invariants, and lands a well-explained PR, backed by an issue when the + change warrants one. +- **This period:** contributor-only agent instructions and documented-issue + intake ([#7223](https://github.com/gastownhall/beads/pull/7223)); + per-package `AGENTS.md` files for the storage packages, naming their + guard tests and lint rules; a package-doc linter and package docs for the + packages that have none; and a curated set of `help wanted` starter + issues. +- **Tracking issue:** [#7228](https://github.com/gastownhall/beads/issues/7228) diff --git a/VERSIONED-BEADS-WRITE-PATHS.md b/VERSIONED-BEADS-WRITE-PATHS.md index 887816aad..bed384ade 100644 --- a/VERSIONED-BEADS-WRITE-PATHS.md +++ b/VERSIONED-BEADS-WRITE-PATHS.md @@ -19,7 +19,7 @@ Row numbers are the historical table's. Line numbers in this table are against t | # | Path | Version seam at this head | Disposition | Mechanism | |---|---|---|---|---| -| 13 | any of rows 1-8 whose target row is a wisp **or a promoted no-history bead** | no | NO-OP | `RecordVersionInTx` returns on `IsWisp`, which is `Ephemeral \|\| NoHistory` (helpers.go:36-41): wisps per FR-8, and a promoted no-history bead — a durable issues-plane row with `NoHistory=true` — because no-history means no history. Wording only; the code did not change. | +| 13 | any of rows 1-8 whose target row is a wisp **or a promoted no-history bead** | no | NO-OP (a flagged issues-table create is stamped, not versioned) | The table that holds the row decides its plane, not its flags. A row in the wisps table mints and stamps nothing, whatever its flags say (FR-8). An update-shaped call on a flagged wisp returns on `IsWisp`, which is `Ephemeral \|\| NoHistory` (helpers.go:36-41). Every other wisps-table row is excluded by the seam's read of `participation_generation` from the issues table, which finds no row and returns: a flagged wisp's create-shaped call, and an unflagged row (bd mol squash's in-place flag clear, import's `wisp_plane` marker), which passes `IsWisp`. An issues-table row carrying `NoHistory` (a promoted no-history bead, bd-r9uce) is never versioned while it says so, because no-history means no history: an update-shaped call returns on `IsWisp`. A create-shaped call on such a row, with the flag on, still stamps `participation_generation` and mints nothing, so the row is not legacy once `bd update --persistent` repairs the flag in place. | | 14 | dependencies.go:`addDependencyInTx` via `AddDependencyInTx` from the store verbs, `ApplyParentPatch`, `applyBatchRun.applyDepAdd` | yes | VERSIONED | mint moved into `addDependencyInTx` (`mintDependencyVersion`, dependencies.go:393), gated on the row insert rather than on `eventWritten`; the publicops editor's own mint call was removed so no leg double-mints | | 15 | domain/db/dependency.go:`dependencySQLRepositoryImpl.Insert` (uow `AddDependencies`, create-time edges) | yes | VERSIONED | seam at dependency.go:228 and :240 after the insert | | 16 | dependencies.go:`removeDependencyInTx` via `RemoveDependencyInTx` and domain/db/dependency.go:`Delete` | yes | VERSIONED | gated on the row delete; dependency.go:409 on the uow leg | diff --git a/backend/BUILD.bazel b/backend/BUILD.bazel index 0f7dac0be..912285a3e 100644 --- a/backend/BUILD.bazel +++ b/backend/BUILD.bazel @@ -43,3 +43,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/backend/backend.go b/backend/backend.go index de2f184dd..2981739aa 100644 --- a/backend/backend.go +++ b/backend/backend.go @@ -140,6 +140,37 @@ type VCStatus = storage.Status // store. See the field docs on the aliased struct. type Backend = backends.Backend +// OpenOptions carries per-open injections (Credential, HTTPClient, +// UserAgent) that Backend.OpenWith may use. See the field docs on the +// aliased struct. +type OpenOptions = backends.OpenOptions + +// Credential is the opaque per-open credential marker OpenOptions.Credential +// carries. A backend that needs one declares its own narrower interface and +// type-asserts the value its OpenWith receives. See the aliased type's docs. +type Credential = backends.Credential + +// ErrCredentialWithoutOpenWith is returned by Backend.OpenWithOptions when +// OpenOptions.Credential is set but the backend has no OpenWith to honor it. +var ErrCredentialWithoutOpenWith = backends.ErrCredentialWithoutOpenWith + +// ErrHTTPClientWithoutOpenWith is returned by Backend.OpenWithOptions when +// OpenOptions.HTTPClient is set but the backend has no OpenWith to honor it. +// Same fail-closed family as ErrCredentialWithoutOpenWith. +var ErrHTTPClientWithoutOpenWith = backends.ErrHTTPClientWithoutOpenWith + +// ErrUserAgentWithoutOpenWith is returned by Backend.OpenWithOptions when +// OpenOptions.UserAgent is set but the backend has no OpenWith to honor it. +// Same fail-closed family as ErrCredentialWithoutOpenWith. +var ErrUserAgentWithoutOpenWith = backends.ErrUserAgentWithoutOpenWith + +// ErrUnsupportedCredential is the typed refusal an OpenWith implementation +// MUST return (directly or wrapped, so errors.Is still matches) when it +// receives a non-nil Credential that does not type-assert to the narrower +// credential interface that backend's OpenWith expects. See the aliased +// error's docs in internal/storage/backends for the full contract. +var ErrUnsupportedCredential = backends.ErrUnsupportedCredential + // Register adds a backend under name. It is process-start wiring: call it // once during initialization (typically from a registrant package's init that // the embedding binary blank-imports), before any concurrent store access. @@ -171,6 +202,12 @@ func WorkspaceIsBeadsDir(name string) bool { return backends.WorkspaceIsBeadsDir(name) } +// IsRemote reports whether name is a registered backend that is a pure +// network client of a bd serve with no local database (see Backend.Remote). +func IsRemote(name string) bool { + return backends.IsRemote(name) +} + // Iter is the streaming-read cursor returned by the Iter* methods. type Iter[T any] = storage.Iter[T] diff --git a/backend/conformance/BUILD.bazel b/backend/conformance/BUILD.bazel index 89773dfbd..2ba90b30b 100644 --- a/backend/conformance/BUILD.bazel +++ b/backend/conformance/BUILD.bazel @@ -11,8 +11,11 @@ go_library( "audit_molecule_wisp_batch_iter.go", "audit_search-counts-stats.go", "batch_apply_contract.go", + "batch_apply_gate_contract.go", "batch_closer_contract.go", "batch_creator_contract.go", + "batch_getter_contract.go", + "blocked_lister_contract.go", "blocked_state.go", "blocking_annotator_contract.go", "bootstrapper_contract.go", @@ -26,19 +29,25 @@ go_library( "deleter_contract.go", "dependency_editor_contract.go", "dualwrite_history_contract.go", + "dualwrite_participation_generation_contract.go", "edge_reader_contract.go", "expected_revision_contract.go", "graph_counter_contract.go", + "heartbeater_contract.go", "history_matching.go", "importer_contract.go", "issue_operations_contract.go", "issue_operations_staging.go", "journal_contract.go", + "lease_reclaimer_contract.go", "lifecycle_close_reopen_contract.go", "lifecycle_create_contract.go", + "lifecycle_create_gate_contract.go", "lifecycle_update_contract.go", + "lifecycle_update_gate_contract.go", "memories_contract.go", "metadata_cas_contract.go", + "molecule_contract.go", "portable.go", "querier_contract.go", "reader_contract.go", @@ -56,11 +65,13 @@ go_library( "transaction_parity.go", "tree_walker_contract.go", "version_reconciler_contract.go", + "versioned_read_contract.go", "workspaceconfig_contract.go", ], importpath = "github.com/steveyegge/beads/backend/conformance", visibility = ["//visibility:public"], deps = [ + "//internal/hooks", "//internal/storage", "//internal/storage/issueops", "//internal/storage/kvkeys", @@ -110,3 +121,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/backend/conformance/batch_apply_contract.go b/backend/conformance/batch_apply_contract.go index 354f0cde3..333745ada 100644 --- a/backend/conformance/batch_apply_contract.go +++ b/backend/conformance/batch_apply_contract.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "reflect" + "strings" "testing" "github.com/steveyegge/beads/internal/types" @@ -170,6 +171,12 @@ func RunBatchApplyAppliesEveryItemInDeclarationOrder(t *testing.T, ctx context.C if got := batchApplyColumn(t, ctx, fixture, "status", blocked); got == string(types.StatusClosed) { t.Errorf("%s was closed by a request that only asked to close %s", blocked, blocker) } + // Neither create item names a creator, so each defaults to the request's actor. + for _, id := range []string{blocked, blocker} { + if got := batchApplyColumn(t, ctx, fixture, "created_by", id); got != "apply-writer" { + t.Errorf("%s created_by = %q, want the request's actor %q", id, got, "apply-writer") + } + } } // RunBatchApplyBindsEachNamedKeyToItsMintedID pins ApplyBatchResult.Keys: it is @@ -881,9 +888,12 @@ func RunBatchApplyEvaluatesExpectedAssigneeAsModified(t *testing.T, ctx context. // close it. The refusal is the assertion; the rollback of the parent it created // is what says the refusal took the request with it. // -// POSITIVE HALF: the identical request with Force lands, which is the whole of -// what Force does ("bypasses blocker and open-child close policy, and nothing -// else") and the proof that the refusal was the policy rather than the shape. +// POSITIVE HALF: the identical request with Force lands, and that is the proof +// the refusal was the policy rather than the shape. Force "bypasses blocker and +// open-child close policy, the pin and the assignee fence, and never the +// template guard" (batchapplier.go), and the parent trips no guard — the +// unforced half reached the policy, which the guards run before — so the +// policy is the only refusal Force had to waive. func RunBatchApplyClosePolicyEvaluatesAtTheCloseItem(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { t.Helper() parent := fixture.IssuePrefix + "-closepolicy-parent" @@ -923,7 +933,7 @@ func RunBatchApplyClosePolicyEvaluatesAtTheCloseItem(t *testing.T, ctx context.C t.Errorf("%s status = %q under Force, want %q", parent, got, types.StatusClosed) } if got := batchApplyColumn(t, ctx, fixture, "status", child); got != string(types.StatusOpen) { - t.Errorf("%s status = %q, want %q: Force bypasses the close policy and nothing else", child, got, types.StatusOpen) + t.Errorf("%s status = %q, want %q: Force waives the parent's close policy, it does not close the child", child, got, types.StatusOpen) } assertBatchApplyTypedEdgeCount(t, ctx, fixture, child, parent, string(publicops.DepParentChild), 1) } @@ -1521,6 +1531,215 @@ func RunBatchApplyNormalizesTheWaitsForGate(t *testing.T, ctx context.Context, f }) } +// RunBatchApplyStampsSpawnerIDOnlyWhenNamed is the S11 review fix-up +// regression for HIGH-2: a waits-for DepAddItem must only acquire +// metadata.spawner_id when the caller explicitly named a spawner +// (HasSpawner=true, which bd create --graph sets when the plan declares +// edges[].spawner_key/spawner_id, as does an embedder lowering such a plan +// onto this role). An edge with no named spawner must keep its gate-only +// metadata untouched — stamping it unconditionally from the resolved target +// caused unnecessary rewrite/version churn when gc re-applies the same edge +// (see CHANGELOG.md). +func RunBatchApplyStampsSpawnerIDOnlyWhenNamed(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + spawner := fixture.IssuePrefix + "-spawner-named" + waiter := fixture.IssuePrefix + "-waiter-named" + batchApplySeedIssue(t, ctx, fixture, spawner, types.StatusOpen) + batchApplySeedIssue(t, ctx, fixture, waiter, types.StatusOpen) + + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + {Kind: publicops.ItemDepAdd, DepAdd: &publicops.DepAddItem{ + Source: publicops.Ref{ID: waiter}, + Target: publicops.Ref{ID: spawner}, + Type: publicops.DepWaitsFor, + Metadata: `{"gate":"any-children"}`, + HasSpawner: true, + }}, + }, + }) + stored := batchApplyEdgeMetadata(t, ctx, fixture, waiter, spawner) + var meta types.WaitsForMeta + if err := json.Unmarshal([]byte(stored), &meta); err != nil { + t.Fatalf("stored named-spawner metadata %q: %v", stored, err) + } + if meta.SpawnerID != spawner { + t.Errorf("named-spawner edge spawner_id = %q, want %q (metadata %q)", meta.SpawnerID, spawner, stored) + } + + spawner2 := fixture.IssuePrefix + "-spawner-unnamed" + waiter2 := fixture.IssuePrefix + "-waiter-unnamed" + batchApplySeedIssue(t, ctx, fixture, spawner2, types.StatusOpen) + batchApplySeedIssue(t, ctx, fixture, waiter2, types.StatusOpen) + + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + batchApplyDepAdd(publicops.Ref{ID: waiter2}, publicops.Ref{ID: spawner2}, publicops.DepWaitsFor, `{"gate":"any-children"}`), + }, + }) + stored2 := batchApplyEdgeMetadata(t, ctx, fixture, waiter2, spawner2) + var meta2 types.WaitsForMeta + if err := json.Unmarshal([]byte(stored2), &meta2); err != nil { + t.Fatalf("stored unnamed-spawner metadata %q: %v", stored2, err) + } + if meta2.SpawnerID != "" { + t.Errorf("unnamed-spawner edge must not stamp spawner_id, got %q (metadata %q)", meta2.SpawnerID, stored2) + } +} + +// RunBatchApplyCarriesThreadIDOntoTheStoredEdge pins DepAddItem.ThreadID +// (the 2026-10 Opus-review HIGH-2 finding): a conversation-threading id named +// on a dep_add item must land on the stored dependency row's own thread_id +// column, and an item that names none must store none. ThreadID is a plain +// column read independently of HasSpawner/Metadata, so this is its own case +// rather than a clause folded onto the spawner one above. +// +// Wired onto the http leg this exercises BOTH halves of the wire at once: the +// client's applyDepAddItemBody encode (batchapplier.go) and the server's +// applyDepAddItemMembers decode (internal/httpapi/batch_apply.go) must each +// carry the field, because either one silently dropping it leaves the stored +// column blank and fails the assertion below. +func RunBatchApplyCarriesThreadIDOntoTheStoredEdge(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + source := fixture.IssuePrefix + "-thread-source" + target := fixture.IssuePrefix + "-thread-target" + batchApplySeedIssue(t, ctx, fixture, source, types.StatusOpen) + batchApplySeedIssue(t, ctx, fixture, target, types.StatusOpen) + + const thread = "thread-conv-1" + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + {Kind: publicops.ItemDepAdd, DepAdd: &publicops.DepAddItem{ + Source: publicops.Ref{ID: source}, Target: publicops.Ref{ID: target}, + Type: publicops.DepBlocks, ThreadID: thread, + }}, + }, + }) + if got := batchApplyEdgeThreadID(t, ctx, fixture, source, target); got != thread { + t.Errorf("stored edge thread_id = %q, want %q", got, thread) + } + + source2 := fixture.IssuePrefix + "-thread-none-source" + target2 := fixture.IssuePrefix + "-thread-none-target" + batchApplySeedIssue(t, ctx, fixture, source2, types.StatusOpen) + batchApplySeedIssue(t, ctx, fixture, target2, types.StatusOpen) + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + batchApplyDepAdd(publicops.Ref{ID: source2}, publicops.Ref{ID: target2}, publicops.DepBlocks, ""), + }, + }) + if got := batchApplyEdgeThreadID(t, ctx, fixture, source2, target2); got != "" { + t.Errorf("an edge naming no thread must not stamp thread_id, got %q", got) + } +} + +// RunBatchApplyCarriesThreadIDOntoAnExistingEdge pins DepAddItem.ThreadID on +// the re-add arm: a dep_add naming an edge that already exists with the same +// type is the idempotent re-add, and a thread it names still has to reach the +// stored row. That arm once compared and rewrote metadata alone, so a +// thread-only re-add was a silent no-op and a re-add moving both landed the +// metadata and dropped the thread — on the very path gc re-applies its plans +// through. +// +// The steps run on ONE edge, each from the state the step before it left: a +// thread-only re-add puts a thread on an edge that had none, a re-add moving +// the gate and the thread lands both, and a re-add naming no thread keeps the +// stored one, because an empty ThreadID names no thread rather than asking for +// none. +func RunBatchApplyCarriesThreadIDOntoAnExistingEdge(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + source := fixture.IssuePrefix + "-rethread-source" + spawner := fixture.IssuePrefix + "-rethread-spawner" + batchApplySeedIssue(t, ctx, fixture, source, types.StatusOpen) + batchApplySeedIssue(t, ctx, fixture, spawner, types.StatusOpen) + + add := func(gate, thread string) { + t.Helper() + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + {Kind: publicops.ItemDepAdd, DepAdd: &publicops.DepAddItem{ + Source: publicops.Ref{ID: source}, Target: publicops.Ref{ID: spawner}, + Type: publicops.DepWaitsFor, Metadata: `{"gate":"` + gate + `"}`, ThreadID: thread, + }}, + }, + }) + } + assertEdge := func(step, wantGate, wantThread string) { + t.Helper() + assertBatchApplyEdgeCount(t, ctx, fixture, source, spawner, 1) + stored := batchApplyEdgeMetadata(t, ctx, fixture, source, spawner) + var meta types.WaitsForMeta + if err := json.Unmarshal([]byte(stored), &meta); err != nil { + t.Fatalf("%s: stored waits-for metadata %q is not a gate object: %v", step, stored, err) + } + if meta.Gate != wantGate { + t.Errorf("%s: stored gate = %q (metadata %q), want %q", step, meta.Gate, stored, wantGate) + } + if got := batchApplyEdgeThreadID(t, ctx, fixture, source, spawner); got != wantThread { + t.Errorf("%s: stored edge thread_id = %q, want %q", step, got, wantThread) + } + } + + add(types.WaitsForAllChildren, "") + assertEdge("the first add, naming no thread", types.WaitsForAllChildren, "") + + add(types.WaitsForAllChildren, "thread-conv-1") + assertEdge("a re-add moving the thread alone", types.WaitsForAllChildren, "thread-conv-1") + + add(types.WaitsForAnyChildren, "thread-conv-2") + assertEdge("a re-add moving the gate and the thread", types.WaitsForAnyChildren, "thread-conv-2") + + add(types.WaitsForAnyChildren, "") + assertEdge("a re-add naming no thread", types.WaitsForAnyChildren, "thread-conv-2") +} + +// RunBatchApplyRefusesAThreadIDLongerThanItsColumn pins the bound on +// DepAddItem.ThreadID: one longer than the thread_id column holds is +// ErrValidation and writes no edge, on every leg alike. The http leg's decode +// refused it as a typed 400 while the local legs carried it to the write, where +// it failed as whatever storage error the column raised, mid-transaction — two +// error classes for one request. The shared plan bounds it now, before any +// database work. +// +// The positive half is the same edge with a thread exactly at the bound, which +// lands whole; without it, a role refusing every thread id satisfies the +// refusal. +func RunBatchApplyRefusesAThreadIDLongerThanItsColumn(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + source := fixture.IssuePrefix + "-longthread-source" + target := fixture.IssuePrefix + "-longthread-target" + batchApplySeedIssue(t, ctx, fixture, source, types.StatusOpen) + batchApplySeedIssue(t, ctx, fixture, target, types.StatusOpen) + + request := func(thread string) publicops.ApplyBatchRequest { + return publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + {Kind: publicops.ItemDepAdd, DepAdd: &publicops.DepAddItem{ + Source: publicops.Ref{ID: source}, Target: publicops.Ref{ID: target}, + Type: publicops.DepBlocks, ThreadID: thread, + }}, + }, + } + } + tooLong := strings.Repeat("t", types.MaxFieldLen+1) + if _, err := fixture.BatchApplier.ApplyBatch(ctx, request(tooLong)); !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("a %d-character thread_id: error = %v, want ErrValidation", len(tooLong), err) + } + assertBatchApplyEdgeCount(t, ctx, fixture, source, target, 0) + + atBound := strings.Repeat("t", types.MaxFieldLen) + batchApplyMust(t, ctx, fixture, request(atBound)) + if got := batchApplyEdgeThreadID(t, ctx, fixture, source, target); got != atBound { + t.Errorf("a %d-character thread_id stored as %d characters, want it whole", len(atBound), len(got)) + } +} + // RunBatchApplySplicesAForwardMetadataRef pins the one exception to the // backward-only rule (CreateItem.MetadataRefs): "IT IS THE ONE PLACE A KEY MAY // REACH FORWARD … Every id is minted before any splice is applied, so the @@ -2184,6 +2403,20 @@ func batchApplyEdgeMetadata(t *testing.T, ctx context.Context, fixture BatchAppl return blob } +// batchApplyEdgeThreadID reads the stored thread_id column of one edge, which +// is where DepAddItem.ThreadID has to be visible — a plain column, independent +// of the type-specific Metadata blob batchApplyEdgeMetadata reads. +func batchApplyEdgeThreadID(t *testing.T, ctx context.Context, fixture BatchApplyFixture, source, target string) string { + t.Helper() + var value string + const query = "SELECT COALESCE(thread_id, '') FROM dependencies WHERE issue_id = ?" + + " AND COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?" + if err := fixture.QueryScalar(ctx, query, []any{source, target}, &value); err != nil { + t.Fatalf("reading edge thread_id for %s -> %s: %v", source, target, err) + } + return value +} + // batchApplyMetadataKey reads the WHOLE metadata blob off a row and reports one // key's raw bytes. The whole blob is read rather than a JSON path extract, // because that is what lets a case see an absent key and a null one as the @@ -2268,3 +2501,287 @@ func batchApplyHistoryMatching(t *testing.T, ctx context.Context, fixture BatchA } return count } + +// RunBatchApplyUpdateItemsRefuseATemplate pins that an update item answers to +// Lifecycle.Update's template guard: an item targeting a template refuses with +// an *ItemError carrying *TemplateReadOnlyError, whatever force flags it +// carries, and the request is all or nothing, so the create ahead of it does +// not land and the template is untouched. +func RunBatchApplyUpdateItemsRefuseATemplate(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + template := fixture.IssuePrefix + "-tmplupd-template" + bystander := fixture.IssuePrefix + "-tmplupd-bystander" + seeded := batchApplyIssue(template, "a template") + seeded.IsTemplate = true + if err := fixture.CreateIssue(ctx, seeded, "seed"); err != nil { + t.Fatalf("seed %s: %v", template, err) + } + + update := batchApplyUpdate(publicops.Ref{ID: template}, publicops.IssuePatch{ + Title: publicops.Field[string]{Set: true, Value: "edited"}, + Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusClosed}, + }) + update.Update.ForceClosePolicy = true + _, err := fixture.BatchApplier.ApplyBatch(ctx, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + ForceIDPrefix: true, + Items: []publicops.ApplyItem{ + batchApplyCreate("bystander", batchApplyIssue(bystander, "must not land beside a refusal")), + update, + }, + }) + var itemErr *publicops.ItemError + if !errors.As(err, &itemErr) { + t.Fatalf("an update item on template %s: error = %v, want an *ItemError", template, err) + } + if itemErr.Kind != publicops.ItemUpdate || itemErr.Index != 1 { + t.Errorf("ItemError = %#v, want the update item at index 1", itemErr) + } + var refusal *publicops.TemplateReadOnlyError + if !errors.As(err, &refusal) || refusal.IssueID != template { + t.Errorf("update item on template = %v, want *TemplateReadOnlyError naming %s", err, template) + } + assertBatchApplyRowCount(t, ctx, fixture, "issues", bystander, 0) + if got := batchApplyColumn(t, ctx, fixture, "title", template); got != "a template" { + t.Errorf("%s title after the refusal = %q, want it untouched", template, got) + } + if got := batchApplyColumn(t, ctx, fixture, "status", template); got != string(types.StatusOpen) { + t.Errorf("%s status after the refusal = %q, want it untouched", template, got) + } +} + +// RunBatchApplySplicesTheMetadataOfATemplateItCreates is the template guard's +// boundary: the one write a template legitimately takes inside a batch is a +// CREATE item that makes it and asks for a metadata splice. The splice runs as +// an update of the row the request itself is creating, after every id exists, +// and it must land — the template is being written, not modified — so a guard +// placed where the splice reaches it would refuse a template's own creation. +func RunBatchApplySplicesTheMetadataOfATemplateItCreates(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + created := fixture.IssuePrefix + "-tmplsplice-created" + fresh := batchApplyIssue(created, "a template this request creates") + fresh.IsTemplate = true + item := batchApplyCreate("created", fresh) + item.Create.MetadataRefs = map[string]publicops.Ref{"gc.self": {Key: "created"}} + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", ForceIDPrefix: true, Items: []publicops.ApplyItem{item}, + }) + if _, ok := batchApplyMetadataKey(t, ctx, fixture, created, "gc.self"); !ok { + t.Errorf("%s carries no gc.self key: the splice that finishes a template's own create must land", created) + } +} + +// RunBatchApplyCloseItemsAnswerToTheCloseGuards pins that a close item answers +// to the close guards Lifecycle.Close states, under CloseRequest's rules: a +// template refuses forced or not, a pin and another actor's bead refuse unless +// the item's Force is set. A refusal is the item's *ItemError carrying the +// guard's typed error, and the request is all or nothing, so the create item +// ahead of it does not land. +// +// The assignee case is AS-MODIFIED: the holder is set by an update item of the +// same request, so a guard that read the row before the request began — or not +// at all — closes it. +func RunBatchApplyCloseItemsAnswerToTheCloseGuards(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + template := fixture.IssuePrefix + "-closeguard-template" + pinned := fixture.IssuePrefix + "-closeguard-pinned" + held := fixture.IssuePrefix + "-closeguard-held" + bystander := fixture.IssuePrefix + "-closeguard-bystander" + for _, issue := range []*types.Issue{ + {ID: template, IsTemplate: true}, + {ID: pinned, Pinned: true}, + {ID: held}, + } { + issue.Title, issue.Status, issue.Priority, issue.IssueType = issue.ID, types.StatusOpen, 2, types.TypeTask + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", issue.ID, err) + } + } + + plan := func(target string, force bool, extra ...publicops.ApplyItem) publicops.ApplyBatchRequest { + closeItem := batchApplyClose(publicops.Ref{ID: target}) + closeItem.Close.Force = force + items := []publicops.ApplyItem{batchApplyCreate("bystander", batchApplyIssue(bystander, "must not land beside a refusal"))} + items = append(items, extra...) + return publicops.ApplyBatchRequest{Actor: "apply-closer", ForceIDPrefix: true, Items: append(items, closeItem)} + } + refused := func(label string, request publicops.ApplyBatchRequest, check func(error)) { + t.Helper() + _, err := fixture.BatchApplier.ApplyBatch(ctx, request) + var itemErr *publicops.ItemError + if !errors.As(err, &itemErr) { + t.Fatalf("%s: error = %v, want an *ItemError", label, err) + } + if itemErr.Kind != publicops.ItemClose || itemErr.Index != len(request.Items)-1 { + t.Errorf("%s: ItemError = %#v, want the close item at index %d", label, itemErr, len(request.Items)-1) + } + check(err) + assertBatchApplyRowCount(t, ctx, fixture, "issues", bystander, 0) + } + + for _, force := range []bool{false, true} { + refused("template close item", plan(template, force), func(err error) { + var refusal *publicops.TemplateReadOnlyError + if !errors.As(err, &refusal) || refusal.IssueID != template { + t.Errorf("template close item (force=%v) = %v, want *TemplateReadOnlyError naming %s", force, err, template) + } + }) + } + refused("pinned close item", plan(pinned, false), func(err error) { + var refusal *publicops.PinnedError + if !errors.As(err, &refusal) || refusal.IssueID != pinned { + t.Errorf("pinned close item = %v, want *PinnedError naming %s", err, pinned) + } + }) + assign := batchApplyUpdate(publicops.Ref{ID: held}, publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "holder"}}) + refused("held close item", plan(held, false, assign), func(err error) { + var refusal *publicops.CloseNotAssigneeError + if !errors.As(err, &refusal) { + t.Errorf("close item on a bead an earlier item assigned away = %v, want *CloseNotAssigneeError", err) + return + } + if refusal.IssueID != held || refusal.Assignee != "holder" || refusal.Actor != "apply-closer" { + t.Errorf("assignee refusal = %#v, want IssueID %q, Assignee holder, Actor apply-closer", refusal, held) + } + }) + for _, id := range []string{template, pinned, held} { + if got := batchApplyColumn(t, ctx, fixture, "status", id); got != string(types.StatusOpen) { + t.Errorf("%s status after the refusals = %q, want it still open", id, got) + } + } + + // The item's Force waives the pin and the assignee fence. + forcedPin := plan(pinned, true) + forcedPin.Items = forcedPin.Items[1:] + batchApplyMust(t, ctx, fixture, forcedPin) + forcedHeld := plan(held, true, assign) + forcedHeld.Items = forcedHeld.Items[1:] + batchApplyMust(t, ctx, fixture, forcedHeld) + for _, id := range []string{pinned, held} { + if got := batchApplyColumn(t, ctx, fixture, "status", id); got != string(types.StatusClosed) { + t.Errorf("%s status under the item's Force = %q, want %q", id, got, types.StatusClosed) + } + } +} + +// RunBatchApplyRefusesADottedChildGatedOnItsOwnParent pins the dotted-id +// hierarchy rule (publicops.CheckDottedChildDependency) on a dep_add item: an +// edge from a dotted-id child to its own ancestor is refused with an +// *ItemError naming the edge, and the whole request rolls back. The rule is +// applied to the RESOLVED ids, so a key bound to a dotted child this request +// creates — the `bd create --graph` shape — is refused like a stored id. +// +// POSITIVE HALF: the parent-child edge to the immediate dotted parent lands. +// +// WITH THE HIERARCHY STORED: once that edge exists (the shape `bd create +// --parent` leaves), a blocking edge on the same pair is still this validation +// refusal, not the hierarchy conflict the stored edge would raise (which does +// not match ErrValidation) — the rule reads only the resolved ids, so it +// answers first — and the stored edge survives. +func RunBatchApplyRefusesADottedChildGatedOnItsOwnParent(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + parent := fixture.IssuePrefix + "-dotted" + child := parent + ".1" + minted := parent + ".2" + batchApplySeedIssue(t, ctx, fixture, parent, types.StatusOpen) + batchApplySeedIssue(t, ctx, fixture, child, types.StatusOpen) + + for _, refused := range []struct { + name string + items []publicops.ApplyItem + index int + }{ + {"a stored child blocking on its parent", []publicops.ApplyItem{ + batchApplyDepAdd(publicops.Ref{ID: child}, publicops.Ref{ID: parent}, publicops.DepBlocks, ""), + }, 0}, + {"a child this request creates blocking on its parent", []publicops.ApplyItem{ + batchApplyCreate("child", batchApplyIssue(minted, "the new child")), + batchApplyDepAdd(publicops.Ref{Key: "child"}, publicops.Ref{ID: parent}, publicops.DepBlocks, ""), + }, 1}, + } { + _, err := fixture.BatchApplier.ApplyBatch(ctx, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + ForceIDPrefix: true, + Items: refused.items, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("%s: error = %v, want ErrValidation", refused.name, err) + continue + } + var itemErr *publicops.ItemError + if !errors.As(err, &itemErr) { + t.Errorf("%s: error = %v, want an *ItemError naming the edge item", refused.name, err) + continue + } + if itemErr.Index != refused.index || itemErr.Kind != publicops.ItemDepAdd { + t.Errorf("%s: ItemError = %#v, want Index %d and Kind %q", refused.name, itemErr, refused.index, publicops.ItemDepAdd) + } + } + assertBatchApplyEdgeCount(t, ctx, fixture, child, parent, 0) + assertBatchApplyRowCount(t, ctx, fixture, "issues", minted, 0) + + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + batchApplyDepAdd(publicops.Ref{ID: child}, publicops.Ref{ID: parent}, publicops.DepParentChild, ""), + }, + }) + assertBatchApplyEdgeCount(t, ctx, fixture, child, parent, 1) + + _, err := fixture.BatchApplier.ApplyBatch(ctx, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + batchApplyDepAdd(publicops.Ref{ID: child}, publicops.Ref{ID: parent}, publicops.DepBlocks, ""), + }, + }) + var itemErr *publicops.ItemError + if !errors.Is(err, publicops.ErrValidation) || !errors.As(err, &itemErr) { + t.Errorf("blocks on a parent whose parent-child edge is stored: error = %v, want an *ItemError matching ErrValidation", err) + } + assertBatchApplyEdgeCount(t, ctx, fixture, child, parent, 1) +} + +// RunBatchApplyAppliesTheDefaultPriority pins CreateItem.DefaultPriority: a +// create item that asks for the default stores publicops.DefaultCreatePriority, +// and one naming priority 0 stores P0. `bd create --graph` sends a node without +// a priority this way, and so does an HTTP batch apply create item without one. +// A create item asking for the default while naming a priority is +// ErrValidation and writes nothing, as it is for Lifecycle.Create. +func RunBatchApplyAppliesTheDefaultPriority(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + unset := batchApplyMintedIssue("defaulted") + unset.Priority = 0 + zero := batchApplyMintedIssue("critical") + zero.Priority = 0 + result := batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + {Kind: publicops.ItemCreate, Create: &publicops.CreateItem{Key: "d", Issue: unset, DefaultPriority: true}}, + {Kind: publicops.ItemCreate, Create: &publicops.CreateItem{Key: "z", Issue: zero}}, + }, + }) + for key, want := range map[string]int{"d": publicops.DefaultCreatePriority, "z": 0} { + id := result.Keys[key] + if id == "" { + t.Fatalf("key %q bound no id: %v", key, result.Keys) + } + if got := batchApplyCount(t, ctx, fixture, "SELECT priority FROM issues WHERE id = ?", []any{id}); got != want { + t.Errorf("stored priority of %s (%s) = %d, want %d", key, id, got, want) + } + } + + conflict := fixture.IssuePrefix + "-prio-conflict" + clash := batchApplyIssue(conflict, conflict) + clash.Priority = 3 + _, err := fixture.BatchApplier.ApplyBatch(ctx, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + ForceIDPrefix: true, + Items: []publicops.ApplyItem{ + {Kind: publicops.ItemCreate, Create: &publicops.CreateItem{Key: "c", Issue: clash, DefaultPriority: true}}, + }, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("DefaultPriority with priority 3: err = %v, want ErrValidation", err) + } + assertBatchApplyRowCount(t, ctx, fixture, "issues", conflict, 0) +} diff --git a/backend/conformance/batch_apply_gate_contract.go b/backend/conformance/batch_apply_gate_contract.go new file mode 100644 index 000000000..c38689461 --- /dev/null +++ b/backend/conformance/batch_apply_gate_contract.go @@ -0,0 +1,145 @@ +package conformance + +import ( + "context" + "encoding/json" + "errors" + "slices" + "testing" + "time" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// The BatchApplier half of the gate-member clauses; see +// lifecycle_create_gate_contract.go. + +// RunBatchApplyCarriesTheGateMembers pins the gate members through +// BatchApplier: a create item stores all four, an update item replaces the +// waiter list of an existing row whole, a clear through an update item stores +// the empty list `[]`, and a create or update item past a bound refuses the +// WHOLE request as ErrValidation naming its member (on its *ItemError for the +// update item), so the earlier item rolls back with it. +func RunBatchApplyCarriesTheGateMembers(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + + gate := fixture.IssuePrefix + "-bag-gate" + existing := fixture.IssuePrefix + "-bag-existing" + batchApplySeedIssue(t, ctx, fixture, existing, types.StatusOpen) + + issue := batchApplyIssue(gate, "a gate made by a plan") + issue.IssueType = types.TypeGate + issue.AwaitType = "timer" + issue.AwaitID = "await-plan" + issue.Timeout = 2 * time.Hour + issue.Waiters = []string{"a", "a", "b"} + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + ForceIDPrefix: true, + Items: []publicops.ApplyItem{ + batchApplyCreate("gate", issue), + batchApplyUpdate(publicops.Ref{ID: existing}, publicops.IssuePatch{ + AwaitID: publicops.Field[string]{Set: true, Value: "bead:" + gate}, + Waiters: publicops.Field[[]string]{Set: true, Value: []string{"x", "y"}}, + }), + }, + }) + assertBatchApplyGateColumns(t, ctx, fixture, gate, "timer", "await-plan", 2*time.Hour, []string{"a", "a", "b"}) + assertBatchApplyGateColumns(t, ctx, fixture, existing, "", "bead:"+gate, 0, []string{"x", "y"}) + + // A clear through an update item stores the empty JSON list, not NULL and + // not the JSON null: the column is read raw here because every reader + // above treats the three alike. + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + batchApplyUpdate(publicops.Ref{ID: existing}, publicops.IssuePatch{ + AwaitID: publicops.Field[string]{Set: true}, + Waiters: publicops.Field[[]string]{Set: true}, + }), + }, + }) + assertBatchApplyGateColumns(t, ctx, fixture, existing, "", "", 0, nil) + var clearedWaiters string + if err := fixture.QueryScalar(ctx, "SELECT COALESCE(waiters, '') FROM issues WHERE id = ?", []any{existing}, &clearedWaiters); err != nil { + t.Fatalf("read the waiters column of %s: %v", existing, err) + } + if clearedWaiters != "[]" { + t.Errorf("%s waiters column after a clear = %q, want the stored empty list %q", existing, clearedWaiters, "[]") + } + + first := fixture.IssuePrefix + "-bag-rolledback" + refused := batchApplyIssue(fixture.IssuePrefix+"-bag-refused", "past the bound") + refused.AwaitType = gateFieldAtBoundAwaitType + "x" + _, err := fixture.BatchApplier.ApplyBatch(ctx, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + ForceIDPrefix: true, + Items: []publicops.ApplyItem{ + batchApplyCreate("first", batchApplyIssue(first, "rolls back with the refusal")), + batchApplyCreate("refused", refused), + }, + }) + assertGateFieldError(t, err, "a create item with await_type past its bound", publicops.GateFieldAwaitType) + assertBatchApplyRowCount(t, ctx, fixture, "issues", first, 0) + + // An update item past a bound refuses the same way, named on its own + // item: the earlier create rolls back, and the target keeps its columns. + firstOfUpdate := fixture.IssuePrefix + "-bag-rolledback-upd" + _, err = fixture.BatchApplier.ApplyBatch(ctx, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + ForceIDPrefix: true, + Items: []publicops.ApplyItem{ + batchApplyCreate("first", batchApplyIssue(firstOfUpdate, "rolls back with the refusal")), + batchApplyUpdate(publicops.Ref{ID: gate}, publicops.IssuePatch{ + Title: publicops.Field[string]{Set: true, Value: "must not land"}, + AwaitID: publicops.Field[string]{Set: true, Value: gateFieldAtBoundAwaitID + "x"}, + }), + }, + }) + assertGateFieldError(t, err, "an update item with await_id past its bound", publicops.GateFieldAwaitID) + var itemErr *publicops.ItemError + if !errors.As(err, &itemErr) { + t.Fatalf("an update item with await_id past its bound: error = %v, want an *ItemError naming the item", err) + } + if itemErr.Index != 1 || itemErr.Kind != publicops.ItemUpdate { + t.Errorf("ItemError = %#v, want Index 1 and Kind %q", itemErr, publicops.ItemUpdate) + } + assertBatchApplyRowCount(t, ctx, fixture, "issues", firstOfUpdate, 0) + assertBatchApplyGateColumns(t, ctx, fixture, gate, "timer", "await-plan", 2*time.Hour, []string{"a", "a", "b"}) + if got := batchApplyColumn(t, ctx, fixture, "title", gate); got != "a gate made by a plan" { + t.Errorf("%s title = %q, want the created title: a refused item writes nothing", gate, got) + } +} + +// assertBatchApplyGateColumns reads the four gate columns of one durable row +// raw, so neither side of the comparison comes from the role. +func assertBatchApplyGateColumns(t *testing.T, ctx context.Context, fixture BatchApplyFixture, id, awaitType, awaitID string, timeout time.Duration, waiters []string) { + t.Helper() + var gotType, gotID, gotWaiters string + var gotTimeout int64 + if err := fixture.QueryScalar(ctx, + "SELECT COALESCE(await_type, ''), COALESCE(await_id, ''), COALESCE(timeout_ns, 0), COALESCE(waiters, '') FROM issues WHERE id = ?", + []any{id}, &gotType, &gotID, &gotTimeout, &gotWaiters); err != nil { + t.Fatalf("read the gate columns of %s: %v", id, err) + } + if gotType != awaitType || gotID != awaitID || time.Duration(gotTimeout) != timeout { + t.Errorf("%s gate columns = (%q, %q, %s), want (%q, %q, %s)", id, gotType, gotID, time.Duration(gotTimeout), awaitType, awaitID, timeout) + } + if stored := parseGateWaiters(gotWaiters); !slices.Equal(stored, waiters) { + t.Errorf("%s waiters column = %q (%q), want %q", id, gotWaiters, stored, waiters) + } +} + +// parseGateWaiters reads the waiters TEXT column's JSON array, treating the +// empty string, `null` and `[]` as the one empty list they all mean. +func parseGateWaiters(raw string) []string { + if raw == "" || raw == "null" || raw == "[]" { + return nil + } + var out []string + if err := json.Unmarshal([]byte(raw), &out); err != nil { + return []string{""} + } + return out +} diff --git a/backend/conformance/batch_closer_contract.go b/backend/conformance/batch_closer_contract.go index fde364126..a62b7a667 100644 --- a/backend/conformance/batch_closer_contract.go +++ b/backend/conformance/batch_closer_contract.go @@ -39,9 +39,10 @@ import ( // still reports OpenChildren (batchcloser.go:81-86); a duplicated id is one // of those at its own index, and the first occurrence's reason is what the // row keeps (batchcloser.go:28-33). -// - Force is request-wide and bypasses only blocker and open-child policy; -// the per-item precondition its clause also names is a category the request -// type keeps EMPTY (batchcloser.go:43-53). +// - Force is request-wide and bypasses blocker and open-child policy, the +// pin and the assignee fence, never the template guard; the per-item +// precondition its clause also names is a category the request type keeps +// EMPTY (batchcloser.go:43-55). // - ClaimNext runs after the closes, inside the same transaction, and only // when at least one item closed (batchcloser.go:55-70, 100-103, 143-146). // - LANDED means CHANGED: an all-idempotent batch earns no claim and records @@ -1397,3 +1398,96 @@ func requireBatchCloserWisps(t *testing.T, fixture BatchCloserFixture) { t.Skipf("fixture has no CreateWisp: this backend cannot seed the ephemeral plane, so the ephemeral rules are UNPINNED here") } } + +// RunBatchCloserItemsAnswerToTheCloseGuards pins that every item of a batch +// answers to the close guards Lifecycle.Close states — template, pin, assignee +// — as a PER-ITEM refusal carrying the same typed error, while the survivors +// still commit; and that the request-wide Force waives the pin and the +// assignee fence and never the template. +// +// The guarded items sit between two plain ones, so an implementation that +// aborted the batch on a guard, or skipped the guard for items after the +// first, fails here rather than in `bd close a b c`. +func RunBatchCloserItemsAnswerToTheCloseGuards(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + first := fixture.IssuePrefix + "-guard-first" + template := fixture.IssuePrefix + "-guard-template" + pinned := fixture.IssuePrefix + "-guard-pinned" + held := fixture.IssuePrefix + "-guard-held" + last := fixture.IssuePrefix + "-guard-last" + seedBatchCloserIssue(t, ctx, fixture, first) + seedBatchCloserIssue(t, ctx, fixture, last) + for _, issue := range []*types.Issue{ + {ID: template, IsTemplate: true}, + {ID: pinned, Status: types.StatusPinned}, + {ID: held, Assignee: "holder"}, + } { + issue.Title, issue.Priority, issue.IssueType = issue.ID, 2, types.TypeTask + if issue.Status == "" { + issue.Status = types.StatusOpen + } + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", issue.ID, err) + } + } + + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: first}, {IssueID: template}, {IssueID: pinned}, {IssueID: held}, {IssueID: last}}, + }) + if err != nil { + t.Fatalf("CloseBatch over guarded items: %v, want per-item refusals", err) + } + if len(result.Outcomes) != 5 { + t.Fatalf("outcomes = %d, want 5", len(result.Outcomes)) + } + for _, i := range []int{0, 4} { + if result.Outcomes[i].Err != nil || !result.Outcomes[i].Changed { + t.Errorf("outcome %d (%s) = %+v, want the plain item to land", i, result.Outcomes[i].IssueID, result.Outcomes[i]) + } + } + var templateRefusal *publicops.TemplateReadOnlyError + if !errors.As(result.Outcomes[1].Err, &templateRefusal) || templateRefusal.IssueID != template { + t.Errorf("template item = %v, want *TemplateReadOnlyError naming %s", result.Outcomes[1].Err, template) + } + var pinRefusal *publicops.PinnedError + if !errors.As(result.Outcomes[2].Err, &pinRefusal) || pinRefusal.IssueID != pinned { + t.Errorf("pinned item = %v, want *PinnedError naming %s", result.Outcomes[2].Err, pinned) + } + var assigneeRefusal *publicops.CloseNotAssigneeError + if !errors.As(result.Outcomes[3].Err, &assigneeRefusal) { + t.Errorf("held item = %v, want *CloseNotAssigneeError", result.Outcomes[3].Err) + } else if assigneeRefusal.IssueID != held || assigneeRefusal.Assignee != "holder" || assigneeRefusal.Actor != "closer" { + t.Errorf("held item refusal = %#v, want IssueID %q, Assignee holder, Actor closer", assigneeRefusal, held) + } + for _, i := range []int{1, 2, 3} { + if result.Outcomes[i].Issue != nil { + t.Errorf("refused outcome %d carries an Issue snapshot, want nil beside Err", i) + } + } + assertBatchCloserStatus(t, ctx, fixture, first, types.StatusClosed) + assertBatchCloserStatus(t, ctx, fixture, last, types.StatusClosed) + assertBatchCloserStatus(t, ctx, fixture, template, types.StatusOpen) + assertBatchCloserStatus(t, ctx, fixture, pinned, types.StatusPinned) + assertBatchCloserStatus(t, ctx, fixture, held, types.StatusOpen) + + forced, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: template}, {IssueID: pinned}, {IssueID: held}}, + Force: true, + }) + if err != nil { + t.Fatalf("forced CloseBatch over guarded items: %v", err) + } + if !errors.Is(forced.Outcomes[0].Err, publicops.ErrTemplateReadOnly) { + t.Errorf("forced template item = %v, want ErrTemplateReadOnly: force never waives read-only", forced.Outcomes[0].Err) + } + for _, i := range []int{1, 2} { + if forced.Outcomes[i].Err != nil || !forced.Outcomes[i].Changed { + t.Errorf("forced outcome %d (%s) = %+v, want force to bypass the guard", i, forced.Outcomes[i].IssueID, forced.Outcomes[i]) + } + } + assertBatchCloserStatus(t, ctx, fixture, template, types.StatusOpen) + assertBatchCloserStatus(t, ctx, fixture, pinned, types.StatusClosed) + assertBatchCloserStatus(t, ctx, fixture, held, types.StatusClosed) +} diff --git a/backend/conformance/batch_creator_contract.go b/backend/conformance/batch_creator_contract.go index 0b48334f0..1ff4852f4 100644 --- a/backend/conformance/batch_creator_contract.go +++ b/backend/conformance/batch_creator_contract.go @@ -97,6 +97,14 @@ func RunBatchCreatorCreatesEveryItemAsOneAct(t *testing.T, ctx context.Context, } seen[issue.ID] = true assertBatchCreatorRowCount(t, ctx, fixture, "issues", issue.ID, 1) + // No item names a creator, so each defaults to the batch's actor. + var createdBy string + if err := fixture.QueryScalar(ctx, "SELECT COALESCE(created_by, '') FROM issues WHERE id = ?", []any{issue.ID}, &createdBy); err != nil { + t.Fatalf("read created_by for %s: %v", issue.ID, err) + } + if createdBy != request.Actor || issue.CreatedBy != request.Actor { + t.Errorf("item %d created_by = %q (result %q), want the request's actor %q", i, createdBy, issue.CreatedBy, request.Actor) + } } if labels := result.Issues[0].Labels; len(labels) != 1 || labels[0] != "alpha" { t.Errorf("result issue 0 labels = %v, want [alpha]: the snapshot is promised hydrated with labels", labels) @@ -689,3 +697,63 @@ func batchCreatorHistoryCount(t *testing.T, ctx context.Context, fixture BatchCr } return entries } + +// RunBatchCreatorAppliesTheDefaultPriority pins BatchCreateItem.DefaultPriority: +// an item that asks for the default stores publicops.DefaultCreatePriority, and +// an item naming priority 0 stores P0 in the same batch. The default is +// Lifecycle.Create's, applied in the shared preparation, so an HTTP +// batchCreate without `priority` and a `bd create --file` template without one +// land the same row. An item asking for the default while naming a priority is +// ErrValidation and writes nothing, as it is for Lifecycle.Create. +func RunBatchCreatorAppliesTheDefaultPriority(t *testing.T, ctx context.Context, fixture BatchCreatorFixture) { + t.Helper() + // Minted ids and an unset status, so the case asks nothing of the items + // but their priority — the http wire's batch item has no id or status slot. + unset := &types.Issue{Title: fixture.IssuePrefix + " defaulted", IssueType: types.TypeTask} + zero := &types.Issue{Title: fixture.IssuePrefix + " critical", IssueType: types.TypeTask} + + result, err := fixture.BatchCreator.CreateBatch(ctx, publicops.CreateBatchRequest{ + Actor: "batch-writer", + Items: []publicops.BatchCreateItem{ + {Issue: unset, DefaultPriority: true}, + {Issue: zero}, + }, + }) + if err != nil { + t.Fatalf("CreateBatch: %v", err) + } + if len(result.Issues) != 2 || result.Issues[0] == nil || result.Issues[1] == nil { + t.Fatalf("result = %v, want two created issues", result.Issues) + } + for i, want := range []int{publicops.DefaultCreatePriority, 0} { + created := result.Issues[i] + if created.Priority != want { + t.Errorf("item %d result priority = %d, want %d", i, created.Priority, want) + } + var got int + if err := fixture.QueryScalar(ctx, "SELECT priority FROM issues WHERE id = ?", []any{created.ID}, &got); err != nil { + t.Fatalf("read priority of %s: %v", created.ID, err) + } + if got != want { + t.Errorf("item %d stored priority = %d, want %d", i, got, want) + } + } + + conflict := fixture.IssuePrefix + " conflicting" + _, err = fixture.BatchCreator.CreateBatch(ctx, publicops.CreateBatchRequest{ + Actor: "batch-writer", + Items: []publicops.BatchCreateItem{ + {Issue: &types.Issue{Title: conflict, Priority: 3, IssueType: types.TypeTask}, DefaultPriority: true}, + }, + }) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("DefaultPriority with priority 3: err = %v, want ErrValidation", err) + } + var stored int + if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM issues WHERE title = ?", []any{conflict}, &stored); err != nil { + t.Fatalf("count issues titled %q: %v", conflict, err) + } + if stored != 0 { + t.Errorf("issues titled %q after the conflicting priority batch = %d, want 0", conflict, stored) + } +} diff --git a/backend/conformance/batch_getter_contract.go b/backend/conformance/batch_getter_contract.go new file mode 100644 index 000000000..f64dabde6 --- /dev/null +++ b/backend/conformance/batch_getter_contract.go @@ -0,0 +1,443 @@ +package conformance + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the contract every implementation of publicops.BatchGetter +// must satisfy. Each case asserts what issueops/batchgetter.go PROMISES, cited +// by symbol; a backend that disagrees is parked at its own wiring site with +// skipKnownDivergence so the case still runs on the ones that agree. +// +// THREE LEGS, ONE BODY, GraphCounterFixture's reason: all three reach the same +// storage/issueops.ExecuteGetMany, which itself reaches GetIssuesByIDsInTx for +// the actual read. The two stores wrap it in their own read transaction, and +// the unit-of-work provider reaches it through the domain repository, whose +// runner publishes exactly the DBTX method set that function takes. So a +// three-leg run here is ONE READING plus two engine checks and three wrapper +// checks, and the cases are written for that: they assert the result's shape +// and order rather than message text, so a wrapper that loses the request, +// drops ordering or breaks errors.Is is what a per-leg failure would actually +// be. +// +// EVERY CASE NAMES THE EXACT IDS IT SEEDED, GraphCounterFixture's reason: the +// three fixtures share one database per suite and the two store fixtures share +// it with every other role's cases. +type BatchGetterFixture struct { + // IssuePrefix namespaces the ids each assertion seeds, so several of them + // can share one database. + IssuePrefix string + BatchGetter publicops.BatchGetter + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateIssues seeds many durable issues in one call. Optional: only + // RunBatchGetterAcceptsExactlyTheCap uses it, to seed its MaxGetManyIDs + // issues in one write instead of MaxGetManyIDs single-row commits (about + // 200s of the embedded suites' race runs); nil falls back to CreateIssue + // per row. The seeded rows are the same either way, and the case asserts + // only on the GetMany read. + CreateIssues func(context.Context, []*types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate + // field rather than an Ephemeral flag on CreateIssue because the three + // adapters reach the two planes through different verbs. + CreateWisp func(context.Context, *types.Issue, string) error + // CountHistory reports how many history entries the fixture's branch has. + // A nil hook means "this backend cannot observe history", and the case that + // needs it SKIPS rather than passing quietly. + CountHistory func(context.Context) (int, error) +} + +// RunBatchGetterFindsRequestedIssues pins the found half of GetManyResult: an +// id a GetManyRequest names and the store holds comes back hydrated, with the +// id that resolved it. +func RunBatchGetterFindsRequestedIssues(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + first := fixture.IssuePrefix + "-found-a" + second := fixture.IssuePrefix + "-found-b" + seedBatchGetterIssues(t, ctx, fixture, first, second) + + result := getMany(t, ctx, fixture, publicops.GetManyRequest{IDs: []string{first, second}}) + assertBatchGetterIssueIDs(t, result, first, second) + assertBatchGetterMissingIDs(t, result) +} + +// RunBatchGetterReportsMissingIDs pins GetManyResult.Missing: an id naming no +// stored row is reported there, beside whatever else resolved, rather than +// refusing the whole call. The ghost sits BETWEEN two real ids, the same +// placement RunGraphCounterDistinguishesNoEdgesFromNoAnchor uses, so a body +// that short-circuited on the first miss cannot pass by accident. +func RunBatchGetterReportsMissingIDs(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + first := fixture.IssuePrefix + "-missing-real1" + ghost := fixture.IssuePrefix + "-missing-ghost" + second := fixture.IssuePrefix + "-missing-real2" + seedBatchGetterIssues(t, ctx, fixture, first, second) + + result := getMany(t, ctx, fixture, publicops.GetManyRequest{IDs: []string{first, ghost, second}}) + assertBatchGetterIssueIDs(t, result, first, second) + assertBatchGetterMissingIDs(t, result, ghost) +} + +// RunBatchGetterCollapsesRepeatedIDs pins GetManyRequest.IDs's repeats clause: +// an id named twice is one entry, at the position of its first mention. The +// repeat is placed AFTER a different id, RunGraphCounterCollapsesRepeatedAnchors' +// reason: a body that de-duplicated by sorting rather than by first mention +// would answer b, a instead of a, b. +func RunBatchGetterCollapsesRepeatedIDs(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + first := fixture.IssuePrefix + "-dup-b" + second := fixture.IssuePrefix + "-dup-a" + seedBatchGetterIssues(t, ctx, fixture, first, second) + + result := getMany(t, ctx, fixture, publicops.GetManyRequest{ + IDs: []string{first, second, first, second, first}, + }) + assertBatchGetterIssueIDs(t, result, first, second) +} + +// RunBatchGetterAnswersInRequestOrder pins GetManyResult.Issues' ordering +// clause: the answer comes back in the REQUEST's order, never the storage +// engine's natural order. The ids are seeded in the opposite order from the one +// requested, so a body that forwarded the storage engine's order would fail. +func RunBatchGetterAnswersInRequestOrder(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + first := fixture.IssuePrefix + "-order-c" + second := fixture.IssuePrefix + "-order-b" + third := fixture.IssuePrefix + "-order-a" + // Seeded in storage order third, second, first — the reverse of the + // request below — so a body that forwarded insertion order would fail. + seedBatchGetterIssues(t, ctx, fixture, third, second, first) + + result := getMany(t, ctx, fixture, publicops.GetManyRequest{IDs: []string{first, second, third}}) + assertBatchGetterIssueIDs(t, result, first, second, third) +} + +// RunBatchGetterResolvesIDsExactly pins the exactness GetManyRequest.IDs +// documents: a prefix of a real id and a real id padded with whitespace are +// both reported Missing rather than resolved, the same exactness +// RunGraphCounterResolvesIDsExactly pins for EdgeCountRequest.IDs. +func RunBatchGetterResolvesIDsExactly(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + real := fixture.IssuePrefix + "-exact-real" + seedBatchGetterIssues(t, ctx, fixture, real) + + prefix := real[:len(real)-2] + spaced := " " + real + " " + result := getMany(t, ctx, fixture, publicops.GetManyRequest{IDs: []string{real, prefix, spaced}}) + assertBatchGetterIssueIDs(t, result, real) + assertBatchGetterMissingIDs(t, result, prefix, spaced) +} + +// RunBatchGetterAnswersAnEmptyRequest pins GetManyRequest.IDs's empty-slice +// clause: no ids is not an error, it is an answer with no issues — and both +// slices are never nil, so a front door that marshals them emits [] rather +// than null. +func RunBatchGetterAnswersAnEmptyRequest(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + result, err := fixture.BatchGetter.GetMany(ctx, publicops.GetManyRequest{}) + if err != nil { + t.Fatalf("GetMany with no ids = %v, want an empty answer", err) + } + if len(result.Issues) != 0 { + t.Fatalf("GetMany with no ids returned %d issues, want none", len(result.Issues)) + } + if result.Issues == nil { + t.Error("Issues is nil; the contract promises it is never nil for a successful call") + } + if result.Missing == nil { + t.Error("Missing is nil; the contract promises it is never nil for a successful call") + } +} + +// RunBatchGetterRefusesAnUnusableRequest pins the request vocabulary +// ValidateGetManyRequest applies: an empty-string id is refused with +// ErrValidation. +func RunBatchGetterRefusesAnUnusableRequest(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + real := fixture.IssuePrefix + "-refuse-real" + seedBatchGetterIssues(t, ctx, fixture, real) + + _, err := fixture.BatchGetter.GetMany(ctx, publicops.GetManyRequest{IDs: []string{real, ""}}) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("GetMany with an empty id beside a real one = %v, want ErrValidation", err) + } +} + +// RunBatchGetterRefusesOverTheCap pins MaxGetManyIDs: a request naming more +// ids than the cap is refused with a *publicops.TooManyIDsError that wraps +// ErrValidation, counted on the request as sent, BEFORE deduplication — the +// request below repeats one id past the cap, so a body that checked the +// deduplicated count would wrongly let it through. +func RunBatchGetterRefusesOverTheCap(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + real := fixture.IssuePrefix + "-cap-real" + seedBatchGetterIssues(t, ctx, fixture, real) + + ids := make([]string, publicops.MaxGetManyIDs+1) + for i := range ids { + ids[i] = real + } + _, err := fixture.BatchGetter.GetMany(ctx, publicops.GetManyRequest{IDs: ids}) + var tooMany *publicops.TooManyIDsError + if !errors.As(err, &tooMany) { + t.Fatalf("GetMany over the cap = %v, want *publicops.TooManyIDsError", err) + } + if tooMany.Requested != len(ids) { + t.Errorf("TooManyIDsError.Requested = %d, want %d (the count before deduplication)", tooMany.Requested, len(ids)) + } + if tooMany.Cap != publicops.MaxGetManyIDs { + t.Errorf("TooManyIDsError.Cap = %d, want %d", tooMany.Cap, publicops.MaxGetManyIDs) + } + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("GetMany over the cap = %v, want it to also match ErrValidation", err) + } +} + +// RunBatchGetterAcceptsExactlyTheCap pins the boundary MaxGetManyIDs draws: +// a request naming EXACTLY the cap's worth of distinct ids is accepted and +// answered in full, not refused. RunBatchGetterRefusesOverTheCap pins the +// cap+1 side of this line; without this case a `>` to `>=` mutation on the +// comparison would still refuse a one-over request (cap+1 is still > cap-1) +// and pass that case while silently refusing every legitimate cap-sized +// request. +func RunBatchGetterAcceptsExactlyTheCap(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + ids := make([]string, publicops.MaxGetManyIDs) + for i := range ids { + ids[i] = fmt.Sprintf("%s-atcap-%d", fixture.IssuePrefix, i) + } + seedBatchGetterIssuesInBulk(t, ctx, fixture, ids...) + + result := getMany(t, ctx, fixture, publicops.GetManyRequest{IDs: ids}) + if len(result.Issues) != publicops.MaxGetManyIDs { + t.Fatalf("GetMany with exactly MaxGetManyIDs (%d) ids returned %d issues, want %d", + publicops.MaxGetManyIDs, len(result.Issues), publicops.MaxGetManyIDs) + } + assertBatchGetterMissingIDs(t, result) +} + +// RunBatchGetterHydratesLabels pins that a resolved issue's Labels come back +// populated: hydration for this role is LABELS ONLY (no dependencies, +// dependents or comments — issueops.GetManyResult.Issues documents the +// scope), so Labels is the one piece of relational data a regression here +// could silently drop without any other case noticing. +func RunBatchGetterHydratesLabels(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + id := fixture.IssuePrefix + "-labels-a" + seed := batchGetterSeed(id, false) + seed.Labels = []string{"alpha", "beta"} + if err := fixture.CreateIssue(ctx, seed, "batch-getter-seed"); err != nil { + t.Fatalf("seed issue %s: %v", id, err) + } + + result := getMany(t, ctx, fixture, publicops.GetManyRequest{IDs: []string{id}}) + assertBatchGetterIssueIDs(t, result, id) + got := result.Issues[0].Labels + want := []string{"alpha", "beta"} + if len(got) != len(want) { + t.Fatalf("GetMany(%s).Labels = %v, want %v", id, got, want) + } + seen := make(map[string]bool, len(got)) + for _, l := range got { + seen[l] = true + } + for _, l := range want { + if !seen[l] { + t.Errorf("GetMany(%s).Labels = %v, want it to include %q", id, got, l) + } + } +} + +// RunBatchGetterLeavesTheRequestAlone pins the no-mutation clause on +// BatchGetter: IDs is the one member a body could write through to the caller +// — de-duplication is exactly the step that would — and the contract says a +// body de-duplicates into its own copy. +func RunBatchGetterLeavesTheRequestAlone(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + first := fixture.IssuePrefix + "-immutable-a" + second := fixture.IssuePrefix + "-immutable-b" + seedBatchGetterIssues(t, ctx, fixture, first, second) + + ids := []string{first, first, second} + getMany(t, ctx, fixture, publicops.GetManyRequest{IDs: ids}) + + if len(ids) != 3 || ids[0] != first || ids[1] != first || ids[2] != second { + t.Errorf("the request's IDs slice is now %v; the contract says a body de-duplicates into its own copy", ids) + } +} + +// RunBatchGetterSharesOneReadStructurally pins the STRUCTURAL half of the +// one-snapshot clause on BatchGetter.GetMany: the existence check and the +// hydration are one call answering one found id and one missing id together +// against a STATIC fixture, which is consistent with — but does not by +// itself PROVE — the two sharing one transaction under a concurrent writer. +// A body that split the probe from the hydration into two round trips could +// still pass this case against a fixture nothing else is mutating, so it +// checks both halves of one GetManyResult instead of asserting on two +// separate calls the way RunBatchGetterFindsRequestedIssues and +// RunBatchGetterReportsMissingIDs do, but it is NOT a concurrency test: no +// writer races the read here. +// +// Renamed from RunBatchGetterReadsOneSnapshot, which overclaimed an +// atomicity guarantee this case alone does not empirically demonstrate. A +// real interleaving test — a concurrent writer racing GetMany's transaction +// so the case can show a found id and a racing create or delete resolve +// consistently with ONE snapshot boundary — needs a synchronization hook +// (e.g. "pause this leg's read transaction after its query, before it +// returns, so a second goroutine can write and commit") that roleFixtureKit +// does not expose today; that kit is FROZEN (see role_fixture_kit_test.go) +// and a role slice does not edit it. Adding the hook is tracked as follow-up +// work rather than done here, so this case stays honestly structural. +func RunBatchGetterSharesOneReadStructurally(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + present := fixture.IssuePrefix + "-snapshot-present" + ghost := fixture.IssuePrefix + "-snapshot-ghost" + seedBatchGetterIssues(t, ctx, fixture, present) + + result := getMany(t, ctx, fixture, publicops.GetManyRequest{IDs: []string{present, ghost}}) + if len(result.Issues) != 1 || len(result.Missing) != 1 { + t.Fatalf("GetMany([%s, %s]) = %d issues, %d missing; want exactly one of each from the same read", + present, ghost, len(result.Issues), len(result.Missing)) + } + assertBatchGetterIssueIDs(t, result, present) + assertBatchGetterMissingIDs(t, result, ghost) +} + +// RunBatchGetterCrossesBothPlanes pins that GetMany resolves ids regardless of +// which dependency plane stores them: a durable issue and an ephemeral wisp +// named in the same request both come back hydrated. +func RunBatchGetterCrossesBothPlanes(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + issue := fixture.IssuePrefix + "-plane-issue" + wisp := fixture.IssuePrefix + "-plane-wisp" + seedBatchGetterIssues(t, ctx, fixture, issue) + seedBatchGetterWisp(t, ctx, fixture, wisp) + + result := getMany(t, ctx, fixture, publicops.GetManyRequest{IDs: []string{issue, wisp}}) + assertBatchGetterIssueIDs(t, result, issue, wisp) +} + +// RunBatchGetterWritesNothing pins BatchGetter's read clause: a GetMany +// records no history entry. The delta is taken around the calls rather than as +// an absolute count, RunGraphCounterWritesNothing's reason: the seeds above it +// are versioned writes of their own. +func RunBatchGetterWritesNothing(t *testing.T, ctx context.Context, fixture BatchGetterFixture) { + t.Helper() + if fixture.CountHistory == nil { + t.Skip("this backend cannot observe history, so the writes-nothing clause cannot be checked here") + } + real := fixture.IssuePrefix + "-quiet-real" + ghost := fixture.IssuePrefix + "-quiet-ghost" + seedBatchGetterIssues(t, ctx, fixture, real) + + before, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory before: %v", err) + } + getMany(t, ctx, fixture, publicops.GetManyRequest{IDs: []string{real, ghost}}) + // A refusal changes nothing either, so the same delta covers both. + _, _ = fixture.BatchGetter.GetMany(ctx, publicops.GetManyRequest{IDs: []string{""}}) + after, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after: %v", err) + } + if after != before { + t.Fatalf("history entries went %d -> %d across two GetMany calls, want no change", before, after) + } +} + +func getMany(t *testing.T, ctx context.Context, fixture BatchGetterFixture, request publicops.GetManyRequest) publicops.GetManyResult { + t.Helper() + result, err := fixture.BatchGetter.GetMany(ctx, request) + if err != nil { + t.Fatalf("GetMany(%v): %v", request.IDs, err) + } + return result +} + +func seedBatchGetterIssues(t *testing.T, ctx context.Context, fixture BatchGetterFixture, ids ...string) { + t.Helper() + for _, id := range ids { + if err := fixture.CreateIssue(ctx, batchGetterSeed(id, false), "batch-getter-seed"); err != nil { + t.Fatalf("seed issue %s: %v", id, err) + } + } +} + +// seedBatchGetterIssuesInBulk seeds the same rows as seedBatchGetterIssues, +// through the fixture's CreateIssues hook when it has one. +func seedBatchGetterIssuesInBulk(t *testing.T, ctx context.Context, fixture BatchGetterFixture, ids ...string) { + t.Helper() + if fixture.CreateIssues == nil { + seedBatchGetterIssues(t, ctx, fixture, ids...) + return + } + issues := make([]*types.Issue, len(ids)) + for i, id := range ids { + issues[i] = batchGetterSeed(id, false) + } + if err := fixture.CreateIssues(ctx, issues, "batch-getter-seed"); err != nil { + t.Fatalf("seed %d issues: %v", len(issues), err) + } +} + +func seedBatchGetterWisp(t *testing.T, ctx context.Context, fixture BatchGetterFixture, id string) { + t.Helper() + if err := fixture.CreateWisp(ctx, batchGetterSeed(id, true), "batch-getter-seed"); err != nil { + t.Fatalf("seed wisp %s: %v", id, err) + } +} + +func batchGetterSeed(id string, ephemeral bool) *types.Issue { + return &types.Issue{ + ID: id, + Title: id, + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Ephemeral: ephemeral, + } +} + +func batchGetterIssueIDs(result publicops.GetManyResult) []string { + out := make([]string, 0, len(result.Issues)) + for _, issue := range result.Issues { + out = append(out, issue.ID) + } + return out +} + +func assertBatchGetterIssueIDs(t *testing.T, result publicops.GetManyResult, want ...string) { + t.Helper() + got := batchGetterIssueIDs(result) + if len(got) != len(want) { + t.Fatalf("issues = %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("issues = %v, want %v", got, want) + } + } +} + +func assertBatchGetterMissingIDs(t *testing.T, result publicops.GetManyResult, want ...string) { + t.Helper() + got := result.Missing + if len(got) != len(want) { + t.Fatalf("missing = %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("missing = %v, want %v", got, want) + } + } + if got == nil { + t.Error("Missing is nil; the contract promises it is never nil for a successful call") + } +} diff --git a/backend/conformance/blocked_lister_contract.go b/backend/conformance/blocked_lister_contract.go new file mode 100644 index 000000000..9313e3e76 --- /dev/null +++ b/backend/conformance/blocked_lister_contract.go @@ -0,0 +1,426 @@ +package conformance + +import ( + "context" + "fmt" + "reflect" + "slices" + "testing" + "time" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the semantic contract every implementation of +// publicops.BlockedLister must satisfy: what issueops/blockedlister.go +// promises, asserted on every leg (dolt, embedded dolt, unit of work, and the +// served HTTP client) so `bd blocked` answers one listing whichever route it +// takes. +// +// EVERY CASE IS SCOPED BY A LABEL: the blocked set is a property of the whole +// database, not of an id prefix, so a row seeded by one case is inside the +// next one's answer unless each asks through Labels. + +// BlockedListerFixture supplies adapter-specific storage access for the +// blocked-listing assertions. +type BlockedListerFixture struct { + // IssuePrefix namespaces the ids each case seeds, so several cases can + // share one database. + IssuePrefix string + // BlockedLister is the surface under test. + BlockedLister publicops.BlockedLister + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. + CreateWisp func(context.Context, *types.Issue, string) error + // AddDependency seeds ONE edge, recomputing the stored blocked flag the + // way every dependency write does. + AddDependency func(context.Context, *types.Dependency, string) error + // MarkBlocked sets the stored is_blocked flag on one durable issue + // directly, without the edge that would justify it: the stale flag `bd + // recompute-blocked` exists to repair. It must fail unless exactly one row + // changed. A nil hook means this leg cannot write the column, and the case + // that needs it skips with that reason. + MarkBlocked func(context.Context, string) error +} + +// RunBlockedLister runs every blocked-listing case as a subtest of t. +func RunBlockedLister(t *testing.T, ctx context.Context, fixture BlockedListerFixture) { + t.Helper() + t.Run("NamesADirectBlocker", func(t *testing.T) { runBlockedNamesADirectBlocker(t, ctx, fixture) }) + t.Run("AttributesAChildToItsBlockedParent", func(t *testing.T) { runBlockedAttributesAChildToItsParent(t, ctx, fixture) }) + t.Run("ClosedBlockerDoesNotBlock", func(t *testing.T) { runBlockedClosedBlockerDoesNotBlock(t, ctx, fixture) }) + t.Run("IncludesTheWispPlane", func(t *testing.T) { runBlockedIncludesTheWispPlane(t, ctx, fixture) }) + t.Run("ExcludesThePinnedStatus", func(t *testing.T) { runBlockedExcludesThePinnedStatus(t, ctx, fixture) }) + t.Run("ParentFilter", func(t *testing.T) { runBlockedParentFilter(t, ctx, fixture) }) + t.Run("LabelFilters", func(t *testing.T) { runBlockedLabelFilters(t, ctx, fixture) }) + t.Run("Order", func(t *testing.T) { runBlockedOrder(t, ctx, fixture) }) + t.Run("NamesWaitsForAndConditionalBlockers", func(t *testing.T) { runBlockedNamesWaitsForAndConditionalBlockers(t, ctx, fixture) }) + t.Run("OmitsAStaleFlagWithNoNameableBlocker", func(t *testing.T) { runBlockedOmitsAStaleFlag(t, ctx, fixture) }) + t.Run("HasNoTypeExclusions", func(t *testing.T) { runBlockedHasNoTypeExclusions(t, ctx, fixture) }) + t.Run("EmptyIsAnEmptySlice", func(t *testing.T) { runBlockedEmptyIsAnEmptySlice(t, ctx, fixture) }) + t.Run("DoesNotMutateTheCallerRequest", func(t *testing.T) { runBlockedDoesNotMutateTheRequest(t, ctx, fixture) }) +} + +// runBlockedNamesADirectBlocker: an issue with an open `blocks` target is +// listed with that target as its one blocker; the target itself is not. +func runBlockedNamesADirectBlocker(t *testing.T, ctx context.Context, f BlockedListerFixture) { + label := f.IssuePrefix + "-bl-direct" + blocked, blocker := blListerID(f, "direct-src"), blListerID(f, "direct-dst") + blListerSeedIssue(t, ctx, f, blListerIssue(blocked, 1, label)) + blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label)) + blListerSeedEdge(t, ctx, f, blocked, blocker, types.DepBlocks) + + items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}}) + blListerAssertRows(t, items, map[string][]string{blocked: {blocker}}) +} + +// runBlockedAttributesAChildToItsParent: a child of a blocked parent, with no +// blocker of its own, is listed with its parent named as the blocker. +func runBlockedAttributesAChildToItsParent(t *testing.T, ctx context.Context, f BlockedListerFixture) { + label := f.IssuePrefix + "-bl-child" + parent, child, blocker := blListerID(f, "child-parent"), blListerID(f, "child-child"), blListerID(f, "child-blocker") + blListerSeedIssue(t, ctx, f, blListerIssue(parent, 1, label)) + blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other")) + blListerSeedIssue(t, ctx, f, blListerIssue(child, 1, label)) + blListerSeedEdge(t, ctx, f, child, parent, types.DepParentChild) + blListerSeedEdge(t, ctx, f, parent, blocker, types.DepBlocks) + + items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}}) + blListerAssertRows(t, items, map[string][]string{parent: {blocker}, child: {parent}}) +} + +// runBlockedClosedBlockerDoesNotBlock: a `blocks` edge onto a closed target +// names no blocker, so the source is not listed. +func runBlockedClosedBlockerDoesNotBlock(t *testing.T, ctx context.Context, f BlockedListerFixture) { + label := f.IssuePrefix + "-bl-closed" + src, dst := blListerID(f, "closed-src"), blListerID(f, "closed-dst") + blListerSeedIssue(t, ctx, f, blListerIssue(src, 1, label)) + closed := blListerIssue(dst, 1, label) + closed.Status = types.StatusClosed + blListerSeedIssue(t, ctx, f, closed) + blListerSeedEdge(t, ctx, f, src, dst, types.DepBlocks) + + items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}}) + blListerAssertRows(t, items, map[string][]string{}) +} + +// runBlockedIncludesTheWispPlane: a blocked wisp is listed beside the issues. +func runBlockedIncludesTheWispPlane(t *testing.T, ctx context.Context, f BlockedListerFixture) { + label := f.IssuePrefix + "-bl-wisp" + wisp, blocker := blListerID(f, "wisp-src"), blListerID(f, "wisp-dst") + w := blListerIssue(wisp, 1, label) + w.Ephemeral = true + if err := f.CreateWisp(ctx, w, "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", wisp, err) + } + b := blListerIssue(blocker, 1, label) + b.Ephemeral = true + if err := f.CreateWisp(ctx, b, "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", blocker, err) + } + blListerSeedEdge(t, ctx, f, wisp, blocker, types.DepBlocks) + + items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}}) + blListerAssertRows(t, items, map[string][]string{wisp: {blocker}}) +} + +// runBlockedExcludesThePinnedStatus: a row whose status is pinned is never +// listed, whatever blocks it. +func runBlockedExcludesThePinnedStatus(t *testing.T, ctx context.Context, f BlockedListerFixture) { + label := f.IssuePrefix + "-bl-pinned" + pinned, open, blocker := blListerID(f, "pinned-src"), blListerID(f, "pinned-open"), blListerID(f, "pinned-dst") + p := blListerIssue(pinned, 1, label) + p.Status = types.StatusPinned + blListerSeedIssue(t, ctx, f, p) + blListerSeedIssue(t, ctx, f, blListerIssue(open, 1, label)) + blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other")) + blListerSeedEdge(t, ctx, f, pinned, blocker, types.DepBlocks) + blListerSeedEdge(t, ctx, f, open, blocker, types.DepBlocks) + + items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}}) + blListerAssertRows(t, items, map[string][]string{open: {blocker}}) +} + +// runBlockedParentFilter: ParentID narrows to the parent's direct children. +func runBlockedParentFilter(t *testing.T, ctx context.Context, f BlockedListerFixture) { + label := f.IssuePrefix + "-bl-parent" + parent, kid, stranger, blocker := blListerID(f, "pf-parent"), blListerID(f, "pf-kid"), blListerID(f, "pf-stranger"), blListerID(f, "pf-blocker") + blListerSeedIssue(t, ctx, f, blListerIssue(parent, 1, label+"-other")) + blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other")) + blListerSeedIssue(t, ctx, f, blListerIssue(kid, 1, label)) + blListerSeedIssue(t, ctx, f, blListerIssue(stranger, 1, label)) + blListerSeedEdge(t, ctx, f, kid, parent, types.DepParentChild) + blListerSeedEdge(t, ctx, f, kid, blocker, types.DepBlocks) + blListerSeedEdge(t, ctx, f, stranger, blocker, types.DepBlocks) + + all := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}}) + blListerAssertRows(t, all, map[string][]string{kid: {blocker}, stranger: {blocker}}) + narrowed := blListerList(t, ctx, f, publicops.BlockedRequest{ParentID: parent, Labels: []string{label}}) + blListerAssertRows(t, narrowed, map[string][]string{kid: {blocker}}) +} + +// runBlockedLabelFilters: Labels is AND, LabelsAny is OR, ExcludeLabels +// removes, and every value is trimmed with blanks dropped. +func runBlockedLabelFilters(t *testing.T, ctx context.Context, f BlockedListerFixture) { + base := f.IssuePrefix + "-bl-lab" + red, blue := base+"-red", base+"-blue" + both, onlyRed, onlyBlue, blocker := blListerID(f, "lab-both"), blListerID(f, "lab-red"), blListerID(f, "lab-blue"), blListerID(f, "lab-blocker") + blListerSeedIssue(t, ctx, f, blListerIssue(both, 1, base, red, blue)) + blListerSeedIssue(t, ctx, f, blListerIssue(onlyRed, 1, base, red)) + blListerSeedIssue(t, ctx, f, blListerIssue(onlyBlue, 1, base, blue)) + blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, base+"-other")) + for _, id := range []string{both, onlyRed, onlyBlue} { + blListerSeedEdge(t, ctx, f, id, blocker, types.DepBlocks) + } + want := func(ids ...string) map[string][]string { + m := map[string][]string{} + for _, id := range ids { + m[id] = []string{blocker} + } + return m + } + + blListerAssertRows(t, blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{" " + red + " ", "", blue}}), want(both)) + blListerAssertRows(t, blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{base}, LabelsAny: []string{red, blue}}), want(both, onlyRed, onlyBlue)) + blListerAssertRows(t, blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{base}, ExcludeLabels: []string{" " + blue}}), want(onlyRed)) +} + +// runBlockedOrder: priority ascending, then created_at descending, then id. +// +// The created_at values are seeded explicitly, so every key decides at least +// one pair: two rows share a priority and differ in created_at (newest first), +// and five share both priority and created_at (the id breaks the tie). The +// expected order is written out rather than recomputed from the answer. +func runBlockedOrder(t *testing.T, ctx context.Context, f BlockedListerFixture) { + label := f.IssuePrefix + "-bl-order" + blocker := blListerID(f, "order-blocker") + blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other")) + older := time.Date(2026, 1, 1, 10, 0, 0, 0, time.UTC) + newer := older.Add(time.Hour) + // Two of the five tied rows are wisps. The store body assembles rows + // issues-plane first, each plane in id order, so the ids alone would put + // the tied run in the wrong order (b, d, e, then a, c); only the id + // tiebreak puts it right. + rows := []struct { + name string + priority int + created time.Time + wisp bool + }{ + {"order-p3", 3, newer, false}, + {"order-p0-older", 0, older, false}, + {"order-p0-newer-e", 0, newer, false}, + {"order-p0-newer-c", 0, newer, true}, + {"order-p0-newer-a", 0, newer, true}, + {"order-p0-newer-d", 0, newer, false}, + {"order-p0-newer-b", 0, newer, false}, + {"order-p1", 1, older, false}, + } + for _, row := range rows { + issue := blListerIssue(blListerID(f, row.name), row.priority, label) + issue.CreatedAt = row.created + issue.UpdatedAt = row.created + if row.wisp { + issue.Ephemeral = true + if err := f.CreateWisp(ctx, issue, "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", issue.ID, err) + } + } else { + blListerSeedIssue(t, ctx, f, issue) + } + blListerSeedEdge(t, ctx, f, issue.ID, blocker, types.DepBlocks) + } + want := []string{ + blListerID(f, "order-p0-newer-a"), + blListerID(f, "order-p0-newer-b"), + blListerID(f, "order-p0-newer-c"), + blListerID(f, "order-p0-newer-d"), + blListerID(f, "order-p0-newer-e"), + blListerID(f, "order-p0-older"), + blListerID(f, "order-p1"), + blListerID(f, "order-p3"), + } + got := blListerIDs(blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}})) + if !slices.Equal(got, want) { + t.Errorf("listing order = %v, want %v (priority ascending, created_at descending, id)", got, want) + } +} + +// runBlockedNamesWaitsForAndConditionalBlockers: a waits-for onto a spawner +// whose child is still open, and a conditional-blocks onto an open target, +// each name their target, as a blocks edge does. +func runBlockedNamesWaitsForAndConditionalBlockers(t *testing.T, ctx context.Context, f BlockedListerFixture) { + label := f.IssuePrefix + "-bl-wf" + spawner, spawned := blListerID(f, "wf-spawner"), blListerID(f, "wf-spawned") + waiter := blListerID(f, "wf-waiter") + target, conditional := blListerID(f, "cb-target"), blListerID(f, "cb-src") + blListerSeedIssue(t, ctx, f, blListerIssue(spawner, 1, label+"-other")) + blListerSeedIssue(t, ctx, f, blListerIssue(spawned, 1, label+"-other")) + blListerSeedIssue(t, ctx, f, blListerIssue(target, 1, label+"-other")) + blListerSeedIssue(t, ctx, f, blListerIssue(waiter, 1, label)) + blListerSeedIssue(t, ctx, f, blListerIssue(conditional, 1, label)) + blListerSeedEdge(t, ctx, f, spawned, spawner, types.DepParentChild) + blListerSeedEdge(t, ctx, f, waiter, spawner, types.DepWaitsFor) + blListerSeedEdge(t, ctx, f, conditional, target, types.DepConditionalBlocks) + + items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}}) + blListerAssertRows(t, items, map[string][]string{waiter: {spawner}, conditional: {target}}) +} + +// runBlockedOmitsAStaleFlag: a row whose stored flag says blocked but which +// has no active blocker and no parent names no blocker, so it is not listed. +// This is the narrowing gc's readiness projection documents relying on. +func runBlockedOmitsAStaleFlag(t *testing.T, ctx context.Context, f BlockedListerFixture) { + if f.MarkBlocked == nil { + t.Skip("this leg cannot write the stored is_blocked flag directly") + } + label := f.IssuePrefix + "-bl-stale" + stale, real, blocker := blListerID(f, "stale-src"), blListerID(f, "stale-real"), blListerID(f, "stale-blocker") + blListerSeedIssue(t, ctx, f, blListerIssue(stale, 1, label)) + blListerSeedIssue(t, ctx, f, blListerIssue(real, 1, label)) + blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other")) + blListerSeedEdge(t, ctx, f, real, blocker, types.DepBlocks) + if err := f.MarkBlocked(ctx, stale); err != nil { + t.Fatalf("mark %s blocked: %v", stale, err) + } + + items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}}) + blListerAssertRows(t, items, map[string][]string{real: {blocker}}) +} + +// runBlockedHasNoTypeExclusions: a gate is listed like any other row; the +// blocked door excludes no issue type (unlike the ready front). +func runBlockedHasNoTypeExclusions(t *testing.T, ctx context.Context, f BlockedListerFixture) { + label := f.IssuePrefix + "-bl-type" + gate, epic, blocker := blListerID(f, "type-gate"), blListerID(f, "type-epic"), blListerID(f, "type-blocker") + g := blListerIssue(gate, 1, label) + g.IssueType = types.TypeGate + g.AwaitType = "human" + blListerSeedIssue(t, ctx, f, g) + e := blListerIssue(epic, 1, label) + e.IssueType = types.TypeEpic + blListerSeedIssue(t, ctx, f, e) + blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other")) + blListerSeedEdge(t, ctx, f, gate, blocker, types.DepBlocks) + blListerSeedEdge(t, ctx, f, epic, blocker, types.DepBlocks) + + items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}}) + blListerAssertRows(t, items, map[string][]string{gate: {blocker}, epic: {blocker}}) +} + +// runBlockedEmptyIsAnEmptySlice: nothing blocked is an empty, non-nil slice +// and a nil error. +func runBlockedEmptyIsAnEmptySlice(t *testing.T, ctx context.Context, f BlockedListerFixture) { + result, err := f.BlockedLister.ListBlocked(ctx, publicops.BlockedRequest{Labels: []string{f.IssuePrefix + "-bl-nothing"}}) + if err != nil { + t.Fatalf("ListBlocked: %v", err) + } + if result.Items == nil || len(result.Items) != 0 { + t.Fatalf("Items = %#v, want an empty non-nil slice", result.Items) + } +} + +// runBlockedDoesNotMutateTheRequest: the caller's label slices come back as +// they were sent, normalization notwithstanding. +func runBlockedDoesNotMutateTheRequest(t *testing.T, ctx context.Context, f BlockedListerFixture) { + req := publicops.BlockedRequest{ + ParentID: " ", + Labels: []string{" a ", "", "a"}, + LabelsAny: []string{" b"}, + ExcludeLabels: []string{"c "}, + } + before := publicops.BlockedRequest{ + ParentID: req.ParentID, + Labels: slices.Clone(req.Labels), + LabelsAny: slices.Clone(req.LabelsAny), + ExcludeLabels: slices.Clone(req.ExcludeLabels), + } + if _, err := f.BlockedLister.ListBlocked(ctx, req); err != nil { + t.Fatalf("ListBlocked: %v", err) + } + if !reflect.DeepEqual(req, before) { + t.Errorf("request after = %#v, before = %#v", req, before) + } +} + +func blListerID(f BlockedListerFixture, name string) string { + return fmt.Sprintf("%s-%s", f.IssuePrefix, name) +} + +func blListerIssue(id string, priority int, labels ...string) *types.Issue { + return &types.Issue{ + ID: id, + Title: id, + Status: types.StatusOpen, + Priority: priority, + IssueType: types.TypeTask, + Labels: labels, + } +} + +func blListerSeedIssue(t *testing.T, ctx context.Context, f BlockedListerFixture, issue *types.Issue) { + t.Helper() + if err := f.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed issue %s: %v", issue.ID, err) + } +} + +func blListerSeedEdge(t *testing.T, ctx context.Context, f BlockedListerFixture, from, to string, kind types.DependencyType) { + t.Helper() + if err := f.AddDependency(ctx, &types.Dependency{IssueID: from, DependsOnID: to, Type: kind}, "seed"); err != nil { + t.Fatalf("seed %s edge %s -> %s: %v", kind, from, to, err) + } +} + +func blListerList(t *testing.T, ctx context.Context, f BlockedListerFixture, req publicops.BlockedRequest) []*types.BlockedIssue { + t.Helper() + result, err := f.BlockedLister.ListBlocked(ctx, req) + if err != nil { + t.Fatalf("ListBlocked(%+v): %v", req, err) + } + if result.Items == nil { + t.Fatalf("ListBlocked(%+v) Items is nil; the role promises a non-nil slice", req) + } + return result.Items +} + +func blListerIDs(items []*types.BlockedIssue) []string { + ids := make([]string, 0, len(items)) + for _, item := range items { + ids = append(ids, item.ID) + } + return ids +} + +// assertBlockedRows requires the listing to be exactly want: the same ids, +// each naming exactly the blockers want gives it (in any order), with +// BlockedByCount equal to their number. +func blListerAssertRows(t *testing.T, items []*types.BlockedIssue, want map[string][]string) { + t.Helper() + got := map[string][]string{} + for _, item := range items { + if item == nil { + t.Fatalf("listing carries a nil row") + } + if _, dup := got[item.ID]; dup { + t.Errorf("row %s listed twice", item.ID) + } + blockers := slices.Clone(item.BlockedBy) + slices.Sort(blockers) + got[item.ID] = blockers + if item.BlockedByCount != len(item.BlockedBy) { + t.Errorf("row %s: BlockedByCount = %d, len(BlockedBy) = %d", item.ID, item.BlockedByCount, len(item.BlockedBy)) + } + } + normalized := map[string][]string{} + for id, blockers := range want { + b := slices.Clone(blockers) + slices.Sort(b) + normalized[id] = b + } + if !reflect.DeepEqual(got, normalized) { + t.Errorf("listing = %v, want %v", got, normalized) + } +} 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/counter_contract.go b/backend/conformance/counter_contract.go index e70e2e0f2..b18f5fd3f 100644 --- a/backend/conformance/counter_contract.go +++ b/backend/conformance/counter_contract.go @@ -57,6 +57,19 @@ type CounterFixture struct { // A nil hook means "this backend cannot observe history", and the case // that needs it SKIPS rather than passing quietly. CountHistory func(context.Context) (int, error) + // AddDependency seeds one dependency edge, the same hook + // ReaderFixture/DependencyEditorFixture take it from (role_fixture_kit's + // shared AddDependency). It exists here only for the ParentID/NoParent + // scope cases (S8): NoParent excludes by PARENT-CHILD EDGE alone + // (sqlbuild/filter.go), unlike ParentID's dotted-id-prefix fallback, so + // pinning it needs a real edge and not just a naming convention. + AddDependency func(context.Context, *types.Dependency, string) error + // List runs the List role's query directly (the store's IssueReader), so + // the storage-level parity cases below (S8 review, follow-up #5) can + // compare Count's answer against len(List's rows) for the same scope + // without going through a second builder. A nil hook skips those cases + // rather than failing: not every backend wiring has a Reader to hand. + List func(context.Context, publicops.ListRequest) (publicops.IssuePage, error) } // RunCounterCountsTheDurablePlaneByDefault pins counter.go:123-126 from the @@ -176,6 +189,323 @@ func RunCounterAnUnknownStatusMatchesNothing(t *testing.T, ctx context.Context, assertCounterTotal(t, ctx, fixture, scope, 0) } +// RunCounterParentIDScopesToChildren pins CountRequest.ParentID (counter.go, +// S8): restricted to ONE issue's children, reached two ways at once, exactly +// as ListRequest.ParentID is (sqlbuild/filter.go) — a parent-child dependency +// edge, OR (for a row with no such edge) a dotted-id prefix match. The parent +// itself, an unrelated row and a same-prefix DECOY (sibling id with no +// separator, e.g. "parent2") are all seeded so neither arm can pass by +// over-matching. +func RunCounterParentIDScopesToChildren(t *testing.T, ctx context.Context, fixture CounterFixture) { + t.Helper() + parent := fixture.IssuePrefix + "-parentid-parent" + byEdge := fixture.IssuePrefix + "-parentid-byedge" + byDotted := parent + ".1" + decoy := parent + "x" + unrelated := fixture.IssuePrefix + "-parentid-unrelated" + + for _, id := range []string{parent, byEdge, byDotted, decoy, unrelated} { + seedCounterIssue(t, ctx, fixture, counterSeed(id)) + } + requireCounterAddDependency(t, fixture) + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: byEdge, DependsOnID: parent, Type: types.DepParentChild, + }, "seed"); err != nil { + t.Fatalf("seed edge %s -> %s: %v", byEdge, parent, err) + } + + scope := counterScope(parent, byEdge, byDotted, decoy, unrelated) + scope.ParentID = parent + // Both children count; the parent, the decoy and the unrelated row do not. + assertCounterTotal(t, ctx, fixture, scope, 2) +} + +// RunCounterNoParentExcludesChildren pins CountRequest.NoParent +// (counter.go, S8): restricted to rows with NO parent-child edge. +// +// Unlike ParentID, NoParent's SQL clause (sqlbuild/filter.go) checks ONLY the +// parent-child dependency table, not the dotted-id convention — a row that is +// a dotted-id child with no edge at all still passes NoParent. That asymmetry +// is exactly what the "byDotted" row below pins: it is excluded from +// ParentID's answer by nothing (RunCounterParentIDScopesToChildren already +// admits it), but NoParent admits it too, because it carries no edge. +func RunCounterNoParentExcludesChildren(t *testing.T, ctx context.Context, fixture CounterFixture) { + t.Helper() + parent := fixture.IssuePrefix + "-noparent-parent" + child := fixture.IssuePrefix + "-noparent-child" + byDotted := parent + ".1" + + for _, id := range []string{parent, child, byDotted} { + seedCounterIssue(t, ctx, fixture, counterSeed(id)) + } + requireCounterAddDependency(t, fixture) + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: child, DependsOnID: parent, Type: types.DepParentChild, + }, "seed"); err != nil { + t.Fatalf("seed edge %s -> %s: %v", child, parent, err) + } + + scope := counterScope(parent, child, byDotted) + assertCounterTotal(t, ctx, fixture, scope, 3) + + scope.NoParent = true + // child is excluded (has an edge); parent and byDotted remain (neither + // carries a parent-child edge, and NoParent does not consult the dotted + // naming convention at all). + assertCounterTotal(t, ctx, fixture, scope, 2) +} + +// RunCounterExcludeTypesNarrowsThePredicate pins CountRequest.ExcludeTypes +// (counter.go, S8): named types are excluded from the count, composing with +// (rather than replacing) IncludeInfra's own "gate" exclusion. +func RunCounterExcludeTypesNarrowsThePredicate(t *testing.T, ctx context.Context, fixture CounterFixture) { + t.Helper() + task := fixture.IssuePrefix + "-extype-task" + chore := fixture.IssuePrefix + "-extype-chore" + gate := fixture.IssuePrefix + "-extype-gate" + seedCounterIssue(t, ctx, fixture, counterSeed(task)) + choreSeed := counterSeed(chore) + choreSeed.IssueType = types.TypeChore + seedCounterIssue(t, ctx, fixture, choreSeed) + gateSeed := counterSeed(gate) + gateSeed.IssueType = types.IssueType("gate") + seedCounterIssue(t, ctx, fixture, gateSeed) + + scope := counterScope(task, chore, gate) + assertCounterTotal(t, ctx, fixture, scope, 3) + + scope.ExcludeTypes = []string{"chore"} + assertCounterTotal(t, ctx, fixture, scope, 2) + + // Composes with IncludeInfra's own default gate exclusion: both the + // explicit chore exclusion and the include-infra gate exclusion apply at + // once, leaving only task. + scope.IncludeInfra = true + assertCounterTotal(t, ctx, fixture, scope, 1) +} + +// RunCounterExcludeStatusNarrowsThePredicate pins CountRequest.ExcludeStatus +// (counter.go, S8): a Count-only field with no List counterpart. Named +// statuses are excluded, and — UNLIKE Status — an unrecognized name is +// refused as ErrValidation rather than excluding nothing, because a typo +// would silently overcount (counter.go). +func RunCounterExcludeStatusNarrowsThePredicate(t *testing.T, ctx context.Context, fixture CounterFixture) { + t.Helper() + open := fixture.IssuePrefix + "-exstatus-open" + closed := fixture.IssuePrefix + "-exstatus-closed" + seedCounterIssue(t, ctx, fixture, counterSeed(open)) + closedSeed := counterSeed(closed) + closedSeed.Status = types.StatusClosed + seedCounterIssue(t, ctx, fixture, closedSeed) + + scope := counterScope(open, closed) + assertCounterTotal(t, ctx, fixture, scope, 2) + + scope.ExcludeStatus = []string{"closed"} + assertCounterTotal(t, ctx, fixture, scope, 1) + + // Unlike Status and IssueType, ExcludeStatus IS validated (S8 review, + // follow-up #3): a misspelled entry would silently exclude nothing and + // OVERCOUNT, so an unrecognized name is refused as ErrValidation instead + // of treated as a no-op. + scope.ExcludeStatus = []string{"no-such-status"} + if _, err := fixture.Counter.Count(ctx, scope); !errors.Is(err, publicops.ErrValidation) { + t.Errorf("Count with an unrecognized exclude-status = %v, want ErrValidation", err) + } +} + +// requireCounterAddDependency skips a case that needs a real parent-child +// edge when the fixture offers no way to create one, rather than failing with +// a nil-pointer call — mirroring counterHistoryCount's optional-hook pattern. +func requireCounterAddDependency(t *testing.T, fixture CounterFixture) { + t.Helper() + if fixture.AddDependency == nil { + t.Skip("fixture cannot seed a dependency edge: AddDependency is nil") + } +} + +// requireCounterList skips a case that needs the List role when the fixture +// offers no way to reach it, mirroring requireCounterAddDependency. +func requireCounterList(t *testing.T, fixture CounterFixture) { + t.Helper() + if fixture.List == nil { + t.Skip("fixture cannot run the List role: List is nil") + } +} + +// assertCounterMatchesList compares Count's Total against len(List's rows) +// for the same scope, with List's AllFlag and IncludeAllTypes both set so +// List's own default exclusions (status, pinned, template, gate, infra-plane) +// are lifted exactly as far as Count's own default lifts none of them +// (workapi.BuildCountFilter's doc, count.go) — the one combination that +// makes the two cardinalities comparable at all for an arbitrary scope. +// +// This is a DIFFERENT check than +// TestBuildCountFilterParentFieldsMatchListFilter +// (internal/workapi/count_test.go), which compares the two FILTERS a shared +// request builds without touching a store; this one runs both roles against +// a real backend and compares what they actually return (S8 review, follow-up +// #5). +func assertCounterMatchesList(t *testing.T, ctx context.Context, fixture CounterFixture, idFilter, parentID string, noParent bool, excludeTypes []string) { + t.Helper() + countReq := publicops.CountRequest{ + IDFilter: idFilter, + ParentID: parentID, + NoParent: noParent, + ExcludeTypes: excludeTypes, + } + total := counterTotal(t, ctx, fixture, countReq) + + listReq := publicops.ListRequest{ + IDFilter: idFilter, + ParentID: parentID, + NoParent: noParent, + ExcludeTypes: excludeTypes, + AllFlag: true, + IncludeAllTypes: true, + } + page, err := fixture.List(ctx, listReq) + if err != nil { + t.Fatalf("List(%+v): %v", listReq, err) + } + if got := int64(len(page.Items)); got != total { + t.Errorf("Count(%+v) = %d, len(List(%+v).Items) = %d, want equal", countReq, total, listReq, got) + } +} + +// RunCounterParentIDMatchesListCardinality pins the storage-level half of +// CountRequest.ParentID's promise (S8 review, follow-up #5a): for one scope, +// Count's Total equals len(List's rows) for the equivalent ParentID scope. +func RunCounterParentIDMatchesListCardinality(t *testing.T, ctx context.Context, fixture CounterFixture) { + t.Helper() + requireCounterList(t, fixture) + requireCounterAddDependency(t, fixture) + + parent := fixture.IssuePrefix + "-parity-parentid-parent" + byEdge := fixture.IssuePrefix + "-parity-parentid-byedge" + byDotted := parent + ".1" + unrelated := fixture.IssuePrefix + "-parity-parentid-unrelated" + + for _, id := range []string{parent, byEdge, byDotted, unrelated} { + seedCounterIssue(t, ctx, fixture, counterSeed(id)) + } + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: byEdge, DependsOnID: parent, Type: types.DepParentChild, + }, "seed"); err != nil { + t.Fatalf("seed edge %s -> %s: %v", byEdge, parent, err) + } + + idFilter := counterScope(parent, byEdge, byDotted, unrelated).IDFilter + assertCounterMatchesList(t, ctx, fixture, idFilter, parent, false, nil) +} + +// RunCounterNoParentMatchesListCardinality pins the storage-level half of +// CountRequest.NoParent's promise (S8 review, follow-up #5a). +func RunCounterNoParentMatchesListCardinality(t *testing.T, ctx context.Context, fixture CounterFixture) { + t.Helper() + requireCounterList(t, fixture) + requireCounterAddDependency(t, fixture) + + parent := fixture.IssuePrefix + "-parity-noparent-parent" + child := fixture.IssuePrefix + "-parity-noparent-child" + byDotted := parent + ".1" + + for _, id := range []string{parent, child, byDotted} { + seedCounterIssue(t, ctx, fixture, counterSeed(id)) + } + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: child, DependsOnID: parent, Type: types.DepParentChild, + }, "seed"); err != nil { + t.Fatalf("seed edge %s -> %s: %v", child, parent, err) + } + + idFilter := counterScope(parent, child, byDotted).IDFilter + assertCounterMatchesList(t, ctx, fixture, idFilter, "", true, nil) +} + +// RunCounterExcludeTypesMatchesListCardinality pins the storage-level half of +// CountRequest.ExcludeTypes' promise (S8 review, follow-up #5a). ExcludeStatus +// has no List counterpart (counter.go) so it is not part of this parity +// family; RunCounterExcludeStatusNarrowsThePredicate above is its only +// coverage. +func RunCounterExcludeTypesMatchesListCardinality(t *testing.T, ctx context.Context, fixture CounterFixture) { + t.Helper() + requireCounterList(t, fixture) + + task := fixture.IssuePrefix + "-parity-extype-task" + chore := fixture.IssuePrefix + "-parity-extype-chore" + seedCounterIssue(t, ctx, fixture, counterSeed(task)) + choreSeed := counterSeed(chore) + choreSeed.IssueType = types.TypeChore + seedCounterIssue(t, ctx, fixture, choreSeed) + + idFilter := counterScope(task, chore).IDFilter + assertCounterMatchesList(t, ctx, fixture, idFilter, "", false, []string{"chore"}) +} + +// RunCounterParentIDIncludesAWispChild pins that ParentID's edge match reaches +// into the wisp tier exactly as IncludeInfra's merge does (S8 review, +// follow-up #5b): a child seeded in the ephemeral/wisp tier, linked to its +// parent by the same parent-child edge ParentID matches on, is invisible to +// Count's durable-only default and counted once IncludeInfra merges the wisps +// table in. +func RunCounterParentIDIncludesAWispChild(t *testing.T, ctx context.Context, fixture CounterFixture) { + t.Helper() + requireCounterAddDependency(t, fixture) + + parent := fixture.IssuePrefix + "-wispchild-parent" + wispChild := fixture.IssuePrefix + "-wispchild-child" + seedCounterIssue(t, ctx, fixture, counterSeed(parent)) + seedCounterWisp(t, ctx, fixture, counterSeed(wispChild)) + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: wispChild, DependsOnID: parent, Type: types.DepParentChild, + }, "seed"); err != nil { + t.Fatalf("seed edge %s -> %s: %v", wispChild, parent, err) + } + + scope := counterScope(parent, wispChild) + scope.ParentID = parent + // Durable-only default (counter.go, RunCounterCountsTheDurablePlaneByDefault): + // the wisp child is invisible without IncludeInfra. + assertCounterTotal(t, ctx, fixture, scope, 0) + + scope.IncludeInfra = true + assertCounterTotal(t, ctx, fixture, scope, 1) +} + +// RunCounterParentIDAndExcludeStatusComposeOnAClosedChild pins that ParentID +// and ExcludeStatus apply as a conjunction, not alternatives (S8 review, +// follow-up #5b): a closed child under its parent is counted by ParentID +// alone (Count hides nothing by default), and excluded once ExcludeStatus +// names its status, leaving only the open child. +func RunCounterParentIDAndExcludeStatusComposeOnAClosedChild(t *testing.T, ctx context.Context, fixture CounterFixture) { + t.Helper() + requireCounterAddDependency(t, fixture) + + parent := fixture.IssuePrefix + "-closedchild-parent" + openChild := fixture.IssuePrefix + "-closedchild-open" + closedChild := fixture.IssuePrefix + "-closedchild-closed" + seedCounterIssue(t, ctx, fixture, counterSeed(parent)) + seedCounterIssue(t, ctx, fixture, counterSeed(openChild)) + closedSeed := counterSeed(closedChild) + closedSeed.Status = types.StatusClosed + seedCounterIssue(t, ctx, fixture, closedSeed) + for _, child := range []string{openChild, closedChild} { + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: child, DependsOnID: parent, Type: types.DepParentChild, + }, "seed"); err != nil { + t.Fatalf("seed edge %s -> %s: %v", child, parent, err) + } + } + + scope := counterScope(parent, openChild, closedChild) + scope.ParentID = parent + assertCounterTotal(t, ctx, fixture, scope, 2) + + scope.ExcludeStatus = []string{"closed"} + assertCounterTotal(t, ctx, fixture, scope, 1) +} + // RunCounterGroupsPartitionTheScalarSet pins counter.go:168-169 and :244-245 // for a dimension whose buckets do NOT overlap: the grouped Total is the same // number a scalar Count returns, and the buckets partition it exactly. diff --git a/backend/conformance/dependency_editor_contract.go b/backend/conformance/dependency_editor_contract.go index df2aacb75..4f5b33268 100644 --- a/backend/conformance/dependency_editor_contract.go +++ b/backend/conformance/dependency_editor_contract.go @@ -531,6 +531,96 @@ func RunDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp(t *testing.T, } } +// RunDependencyEditorSameTypeReAddWithChangedThreadMintsOneVersion is the +// thread_id twin of +// RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion. The row +// carries a thread as well as metadata, and the source issue's version snapshot +// carries each edge's thread_id, so a same-type re-add naming a thread the row +// does not carry is a real mutation on the same terms as a metadata change: +// the leaf updates the row in place, journals the replacement edge, and mints +// EXACTLY ONE version (#5898 leg 2). The re-add arm once compared metadata +// alone, which read that re-add as change-free and dropped the thread. +// +// The metadata is identical across every write, so the thread is the only +// thing that moves. A last re-add names no thread, and is the change-free +// no-op: an empty thread names none rather than asking for none, which is +// what keeps the callers that never carry a thread from erasing one. +// +// It drives the writes through fixture.AddDependency for the reason the +// metadata case gives: publicops.DependencyEdge carries no thread either. +func RunDependencyEditorSameTypeReAddWithChangedThreadMintsOneVersion(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + if fixture.AddDependency == nil { + t.Skip("fixture has no AddDependency hook: a thread is not settable through publicops.DependencyEdge") + } + fixture.SetJournalEnabled(true) + t.Cleanup(func() { fixture.SetJournalEnabled(false) }) + fixture.SetVersionedHistoryEnabled(true) + t.Cleanup(func() { fixture.SetVersionedHistoryEnabled(false) }) + source := fixture.IssuePrefix + "-idemthread-source" + target := fixture.IssuePrefix + "-idemthread-target" + seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, target) + + const metadata = `{"note":"v1"}` + add := func(thread, refusal string) { + t.Helper() + dep := &types.Dependency{IssueID: source, DependsOnID: target, Type: types.DepBlocks, Metadata: metadata, ThreadID: thread} + if err := fixture.AddDependency(ctx, dep, "writer"); err != nil { + t.Fatalf("%s: %v", refusal, err) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(types.DepBlocks), 1) + assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyAdded, 1) + } + storedThread := func() string { + t.Helper() + var thread string + if err := fixture.QueryScalar(ctx, + "SELECT COALESCE(thread_id, '') FROM dependencies WHERE issue_id = ? AND COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?", + []any{source, target}, &thread); err != nil { + t.Fatalf("read stored thread_id for %s -> %s: %v", source, target, err) + } + return thread + } + journalCount := func() int { + t.Helper() + var count int + if err := fixture.QueryScalar(ctx, + "SELECT COUNT(*) FROM bd_events_journal WHERE issue_id = ? AND op = ?", + []any{source, string(storeops.EventDepAdd)}, &count); err != nil { + t.Fatalf("count bd_events_journal dep_add rows for %s: %v", source, err) + } + return count + } + + add("", "AddDependency first") + assertDependencyEditorJournalCountIsOne(t, ctx, fixture, source, string(storeops.EventDepAdd)) + + versionsBefore := countDependencyEditorIssueVersions(t, ctx, fixture, source) + add("thread-conv-1", "re-adding the same edge with a new thread refused") + if got := storedThread(); got != "thread-conv-1" { + t.Errorf("stored thread_id = %q, want %q: the re-add must persist the new thread, not keep the old", got, "thread-conv-1") + } + if got := journalCount(); got != 2 { + t.Errorf("bd_events_journal dep_add rows for %s = %d, want 2: the thread-changed re-add must journal its own replacement-edge entry", source, got) + } + if delta := countDependencyEditorIssueVersions(t, ctx, fixture, source) - versionsBefore; delta != 1 { + t.Errorf("issue_versions rows for %s went %d -> %d (delta %d), want a delta of 1: the thread genuinely changed, so the re-add is a real mutation of the source issue and must mint exactly one version (#5898 leg 2)", source, versionsBefore, versionsBefore+delta, delta) + } + + versionsBefore = countDependencyEditorIssueVersions(t, ctx, fixture, source) + add("", "re-adding the same edge naming no thread refused") + if got := storedThread(); got != "thread-conv-1" { + t.Errorf("stored thread_id after a re-add naming no thread = %q, want %q kept", got, "thread-conv-1") + } + if got := journalCount(); got != 2 { + t.Errorf("bd_events_journal dep_add rows for %s = %d after a change-free re-add, want 2 still", source, got) + } + if delta := countDependencyEditorIssueVersions(t, ctx, fixture, source) - versionsBefore; delta != 0 { + t.Errorf("issue_versions rows for %s went %d -> %d (delta %d) on a re-add naming no thread, want a delta of 0: it keeps the stored thread, so nothing changed (#5898 R3)", source, versionsBefore, versionsBefore+delta, delta) + } +} + // RunDependencyEditorRepeatsWithinOneRequestCollapse pins the clause that // answers a request naming ONE PAIR TWICE. The same-type re-add rule is stated // for the pair rather than for the call, so the second occurrence inside a @@ -2541,3 +2631,82 @@ func dependencyEditorHistoryProbe(t *testing.T, ctx context.Context, fixture Dep assertDependencyEditorHistoryDelta(t, ctx, fixture, before, want, why) } } + +// RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent pins +// publicops.CheckDottedChildDependency on the role: an explicit edge from a +// dotted-id child to its own ancestor is refused as a +// *DottedChildDependencyError (ErrValidation) on every leg, and nothing is +// written. (It is decided before any per-edge probe, so the probe-skipped +// spelling, which the wire does not publish, adds nothing here.) It used to be +// enforced only by the CLI ahead of the role, so an HTTP or embedded caller +// could gate bd-abc.1 on bd-abc. +// +// POSITIVE HALF: the hierarchy itself — a parent-child edge to the IMMEDIATE +// dotted parent — is allowed, and so is an edge between siblings. A body that +// refused every edge touching a dotted id would satisfy the refusals alone. +// +// WITH THE HIERARCHY STORED: once that parent-child edge exists (the shape +// `bd create --parent` leaves), a blocking edge on the same pair is still this +// refusal, not the type or hierarchy conflict the stored edge would raise — the +// rule reads nothing, so it answers first — and the stored edge survives. +func RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + parent := fixture.IssuePrefix + "-dotted" + child := parent + ".1" + grandchild := child + ".2" + sibling := parent + ".3" + for _, id := range []string{parent, child, grandchild, sibling} { + seedDependencyEditorIssue(t, ctx, fixture, id) + } + + for _, refused := range []struct { + name string + edge publicops.DependencyEdge + }{ + {"child blocks on its parent", publicops.DependencyEdge{IssueID: child, DependsOnID: parent, Type: publicops.DepBlocks}}, + {"grandchild blocks on its grandparent", publicops.DependencyEdge{IssueID: grandchild, DependsOnID: parent, Type: publicops.DepBlocks}}, + {"grandchild parent-child to its grandparent", publicops.DependencyEdge{IssueID: grandchild, DependsOnID: parent, Type: publicops.DepParentChild}}, + {"child relates to its parent", publicops.DependencyEdge{IssueID: child, DependsOnID: parent, Type: publicops.DepRelated}}, + } { + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{refused.edge}, + }) + var dotted *publicops.DottedChildDependencyError + if !errors.As(err, &dotted) { + t.Errorf("%s: error = %v, want *DottedChildDependencyError", refused.name, err) + continue + } + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("%s: error = %v, want it to match ErrValidation", refused.name, err) + } + if dotted.IssueID != refused.edge.IssueID || dotted.DependsOnID != refused.edge.DependsOnID { + t.Errorf("%s: refusal names %s -> %s, want %s -> %s", refused.name, + dotted.IssueID, dotted.DependsOnID, refused.edge.IssueID, refused.edge.DependsOnID) + } + } + assertDependencyEditorNoEdgesFrom(t, ctx, fixture, child, grandchild) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: grandchild, DependsOnID: child, Type: publicops.DepParentChild}, + {IssueID: sibling, DependsOnID: child, Type: publicops.DepBlocks}, + }, + }); err != nil { + t.Fatalf("the immediate parent-child edge and a sibling edge: %v", err) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", grandchild, child, string(publicops.DepParentChild), 1) + assertDependencyEdgeCount(t, ctx, fixture, "dependencies", sibling, child, 1) + + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: grandchild, DependsOnID: child, Type: publicops.DepBlocks}}, + }) + var dotted *publicops.DottedChildDependencyError + if !errors.As(err, &dotted) || !errors.Is(err, publicops.ErrValidation) { + t.Errorf("blocks on a parent whose parent-child edge is stored: error = %v, want *DottedChildDependencyError matching ErrValidation", err) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", grandchild, child, string(publicops.DepParentChild), 1) + assertDependencyEdgeCount(t, ctx, fixture, "dependencies", grandchild, child, 1) +} diff --git a/backend/conformance/dualwrite_history_contract.go b/backend/conformance/dualwrite_history_contract.go index 8bfb55c56..e94a15d01 100644 --- a/backend/conformance/dualwrite_history_contract.go +++ b/backend/conformance/dualwrite_history_contract.go @@ -71,11 +71,13 @@ import ( // - PARTICIPATION-GENERATION GATING (design §16.2b). Whether an // update-shaped mutation on a legacy (participation_generation IS NULL) // row is correctly skipped is Phase 2 behavior this bead also owns, but -// it depends on migration 0068's participation_generation column, which -// does not exist when this contract is first written (0068 lands last in -// this bead's build order, by the mayor's explicit sequencing). It gets -// its own dedicated cases once 0068 lands, beside this file rather than -// inside it. +// it depends on migration 0070's participation_generation column, which +// does not exist when this contract is first written (0070 lands last in +// this bead's build order, by the mayor's explicit sequencing — steps 4-5 +// of design §16.3 moved to their own migration slot when 0068 shipped as +// attribution_status-only, see that migration's header). It gets its own +// dedicated cases once 0070 lands, beside this file rather than inside +// it. // - CONCURRENT WRITERS. Every case here is one writer, one issue, one // mutation at a time — the same restriction journal_contract.go states // for the same reason: a single-threaded case cannot exercise what only diff --git a/backend/conformance/dualwrite_participation_generation_contract.go b/backend/conformance/dualwrite_participation_generation_contract.go new file mode 100644 index 000000000..7943e7e4a --- /dev/null +++ b/backend/conformance/dualwrite_participation_generation_contract.go @@ -0,0 +1,644 @@ +package conformance + +import ( + "context" + "testing" +) + +// This file holds the write-fence cases dualwrite_history_contract.go's own +// "WHAT THIS CONTRACT DELIBERATELY DOES NOT PIN" section explicitly deferred: +// "PARTICIPATION-GENERATION GATING (design §16.2b)... It gets its own +// dedicated cases once 0070 lands, beside this file rather than inside it." +// Migration 0070 now carries participation_generation on both issues and +// wisps (design §16.3 steps 4-5, be-dt74u amendment, be-h89oq), so this is +// that file. +// +// Design §16.2b, verbatim substance: the flag-on writer does not increment +// current_revision or mint an issue_versions row for an UPDATE-shaped +// mutation against a record whose participation_generation is NULL — a skip, +// not a refusal (FR-2's zero-rows no-op shape). A CREATE-shaped mutation is +// different: a brand-new row has no prior legacy state to preserve, so if the +// flag is already on at creation time, the writer stamps +// participation_generation as part of the same insert that begins its +// history. A create with the flag off leaves the column NULL, indistinguishable +// from a true legacy row (FR-7's byte-identical requirement). +// +// WHY A SEPARATE FIXTURE RATHER THAN THREE MORE DualWriteFixture CLOSURES. +// DualWriteFixture's Mutate/MutateAsNoOp pair is deliberately flag-fixed-at- +// construction (see that file's SEEDING DISCIPLINE note and each leg's +// newXxxDualWriteFixture, which calls SetVersionedHistoryEnabled exactly +// once). The legacy-record case here is inherently "created while the flag +// was OFF, then mutated after the flag turns ON" — a fixture built once with +// one flag state cannot express that sequence, so SetFlag here is a toggle +// callable more than once per fixture, not a one-time constructor argument. +// +// THE FIXTURE'S CLOSURES ARE THE OBSERVABLE SURFACE, NOT THE SCHEMA — same +// discipline as DualWriteFixture: Mutate/MutateExisting drive CreateIssue and +// UpdateIssue (or their unit-of-work equivalents), never issue_versions or +// store_epoch directly. +// +// WHAT THIS CONTRACT DELIBERATELY DOES NOT PIN: +// - THE EXACT STAMPED VALUE. That a create-shaped mutation with the flag on +// stamps SOME non-NULL participation_generation is pinned here; that the +// value equals the current store_epoch.epoch is not — reaching +// store_epoch is the same one-column, two-of-three-legs-need-white-box- +// access problem dualwrite_history_contract.go's FR-6 note describes, and +// the same resolution applies: pinned per leg, dolt-only, alongside +// TestDualWriteStampsTheCurrentStoreEpochOnEachVersionRow. +// - wisps.participation_generation. FR-8 (carried by dualwrite_history_contract.go's +// exclusion list) applies here too: this fixture's Mutate front door is +// CreateIssue against the issues table, the wisp-arrival cases read only +// the issues row a wisp becomes, and no phase reads or writes the wisps +// column regardless. +type ParticipationGenerationFixture struct { + // IssuePrefix namespaces the id each case mints, the same discipline + // DualWriteFixture uses and for the same reason. + IssuePrefix string + // SetFlag toggles versioned history for every subsequent call through + // this fixture, and may be called more than once per case — unlike + // DualWriteFixture, whose flag is fixed at construction. + SetFlag func(ctx context.Context, enabled bool) error + // Mutate creates a new issue with the given id: a CREATE-shaped mutation + // in design §16.2b's sense. + Mutate func(ctx context.Context, id string) error + // MutateExisting applies a real (non-no-op) UPDATE-shaped mutation to an + // already-existing issue — a different value than Mutate gave it, so a + // vacuous no-op skip can never be mistaken for the fence. + MutateExisting func(ctx context.Context, id string) error + // CreateWisp creates a new wisp-plane (ephemeral) issue with the given + // id: the starting point for the two ways a record reaches the issues + // plane without being created there. A wisp is never versioned (FR-8) + // and never carries a participation declaration, in either flag state. + CreateWisp func(ctx context.Context, id string) error + // PromoteWisp promotes the wisp id onto the issues plane + // (PromoteFromEphemeral, or the unit-of-work leg's PromoteWisp). + PromoteWisp func(ctx context.Context, id string) error + // MovePersistent moves the wisp id onto the issues plane through a + // persistence-mode update (bd update --persistent). It is its own + // closure rather than a second spelling of PromoteWisp because it mints at + // a different site on every leg: the guarded update's one end-of-update + // mint on dolt and embeddeddolt, MoveIssuePersistenceInTx's own on uow. + // On an issues-plane row whose flags disagree with it (see + // CreateNoHistoryIssue) the same update repairs the flags in place, a + // same-plane normalize, rather than moving the row. + MovePersistent func(ctx context.Context, id string) error + // ClearWispFlag clears the wisp id's ephemeral flag IN PLACE: the untyped + // UpdateIssue of {"wisp": false} bd mol squash makes on a squashed root + // (UpdateWisp on the unit-of-work leg, the way its molecule writer routes + // it). The row stays in the wisps table, now carrying neither Ephemeral + // nor NoHistory. + ClearWispFlag func(ctx context.Context, id string) error + // SquashWispRoot closes the wisp id and then clears its flag as + // ClearWispFlag does, both in ONE transaction: the shape bd mol squash's + // root auto-close takes, where an error from either write aborts both. + SquashWispRoot func(ctx context.Context, id string) error + // CreateUnflaggedWisp creates id in the wisps table with neither + // Ephemeral nor NoHistory set: import's "wisp_plane" marker, which pins + // the plane whatever the flags say (WispPlaneOverride = &true, through + // the batch create import runs), or on the unit-of-work leg CreateWisp, + // which routes by the call rather than by the flags. + CreateUnflaggedWisp func(ctx context.Context, id string) error + // CreateNoHistoryIssue creates id in the ISSUES table carrying + // NoHistory=true: import's promoted-no-history shape (bd-r9uce), a + // durable row whose stray flag is preserved while WispPlaneOverride = + // &false pins its plane, through the batch create import runs; or on the + // unit-of-work leg CreateIssue, which routes by the call. + CreateNoHistoryIssue func(ctx context.Context, id string) error + // CurrentRevision reads issues.current_revision for id. + CurrentRevision func(ctx context.Context, id string) (int64, error) + // VersionRowCount reads how many issue_versions rows exist for id. + VersionRowCount func(ctx context.Context, id string) (int, error) + // ParticipationGeneration reads issues.participation_generation for id, + // returning nil for SQL NULL. + ParticipationGeneration func(ctx context.Context, id string) (*int64, error) + // InWispsTable reports whether the wisps table holds a row for id: the + // precondition the wisps-table cases check, so they cannot pass on a row + // that a step moved to the issues table. + InWispsTable func(ctx context.Context, id string) (bool, error) +} + +// RunParticipationGenerationCreateWithFlagOnStampsAValue pins design +// §16.2(a)/(b): a create-shaped mutation with the flag already on stamps a +// non-NULL participation_generation on the new row, as part of the same +// insert that begins its history — a brand-new row has no legacy state to +// preserve, so there is nothing to skip. +func RunParticipationGenerationCreateWithFlagOnStampsAValue(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + if err := fixture.SetFlag(ctx, true); err != nil { + t.Fatalf("enabling versioned history: %v", err) + } + id := fixture.IssuePrefix + "-create-stamps" + if err := fixture.Mutate(ctx, id); err != nil { + t.Fatalf("mutating %s: %v", id, err) + } + gen, err := fixture.ParticipationGeneration(ctx, id) + if err != nil { + t.Fatalf("reading participation_generation for %s: %v", id, err) + } + if gen == nil { + t.Errorf("participation_generation for %s is NULL immediately after a create-shaped mutation with "+ + "the flag on, want a stamped non-NULL value: design §16.2b requires the writer to declare "+ + "participation at insert time, since a brand-new row has no prior legacy state to preserve", id) + } +} + +// RunParticipationGenerationCreateWithFlagOffLeavesLegacyNull pins the other +// half of design §16.2(b): a create-shaped mutation with the flag off leaves +// participation_generation NULL, indistinguishable from a true legacy row — +// flag-off must stay byte-identical to pre-Phase-2 behavior (FR-7). +func RunParticipationGenerationCreateWithFlagOffLeavesLegacyNull(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + if err := fixture.SetFlag(ctx, false); err != nil { + t.Fatalf("disabling versioned history: %v", err) + } + id := fixture.IssuePrefix + "-create-flag-off" + if err := fixture.Mutate(ctx, id); err != nil { + t.Fatalf("mutating %s: %v", id, err) + } + gen, err := fixture.ParticipationGeneration(ctx, id) + if err != nil { + t.Fatalf("reading participation_generation for %s: %v", id, err) + } + if gen != nil { + t.Errorf("participation_generation for %s = %d with the flag off at creation, want NULL: a "+ + "flag-off create must remain indistinguishable from a true legacy row (design §16.2b)", id, *gen) + } +} + +// RunParticipationGenerationSkipsUpdateOnLegacyRecord pins the write fence's +// central claim, design §16.2(b): the flag-on writer does not increment +// current_revision or mint an issue_versions row for an update-shaped +// mutation against a record whose participation_generation is NULL. The +// record must be a REAL legacy record — created while the flag was off, not +// merely one the fixture asserts is NULL — so this also re-confirms that +// precondition before trusting the rest of the case. +func RunParticipationGenerationSkipsUpdateOnLegacyRecord(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + if err := fixture.SetFlag(ctx, false); err != nil { + t.Fatalf("disabling versioned history: %v", err) + } + id := fixture.IssuePrefix + "-legacy-skip" + if err := fixture.Mutate(ctx, id); err != nil { + t.Fatalf("mutating %s: %v", id, err) + } + if gen, err := fixture.ParticipationGeneration(ctx, id); err != nil { + t.Fatalf("reading participation_generation for %s: %v", id, err) + } else if gen != nil { + t.Fatalf("participation_generation for %s = %d before the flag was ever turned on, want NULL — "+ + "this case cannot test the legacy-record fence against a record that was never actually legacy", + id, *gen) + } + + if err := fixture.SetFlag(ctx, true); err != nil { + t.Fatalf("enabling versioned history: %v", err) + } + beforeRevision, err := fixture.CurrentRevision(ctx, id) + if err != nil { + t.Fatalf("reading current_revision for %s: %v", id, err) + } + beforeCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + + if err := fixture.MutateExisting(ctx, id); err != nil { + t.Fatalf("mutating existing %s: %v", id, err) + } + + afterRevision, err := fixture.CurrentRevision(ctx, id) + if err != nil { + t.Fatalf("reading current_revision for %s: %v", id, err) + } + afterCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + if afterCount != beforeCount { + t.Errorf("version row count for %s went from %d to %d across an update-shaped mutation on a "+ + "legacy (participation_generation IS NULL) record with the flag now on, want unchanged: "+ + "design §16.2b requires the writer to skip minting for a record it has not positively "+ + "promoted", id, beforeCount, afterCount) + } + if afterRevision != beforeRevision { + t.Errorf("current_revision for %s went from %d to %d across the same skipped mutation, want "+ + "unchanged: a skip means neither half of RecordVersionInTx's write runs, not just the "+ + "version-row half", id, beforeRevision, afterRevision) + } +} + +// RunParticipationGenerationProceedsForPromotedRecord is the fence's +// not-vacuous check: an update-shaped mutation against a record whose +// participation_generation is ALREADY stamped (created with the flag on, +// i.e. positively declared, not legacy) must mint normally. Without this +// case, an implementation that skips every update unconditionally would +// still pass RunParticipationGenerationSkipsUpdateOnLegacyRecord. +func RunParticipationGenerationProceedsForPromotedRecord(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + if err := fixture.SetFlag(ctx, true); err != nil { + t.Fatalf("enabling versioned history: %v", err) + } + id := fixture.IssuePrefix + "-promoted-proceeds" + if err := fixture.Mutate(ctx, id); err != nil { + t.Fatalf("mutating %s: %v", id, err) + } + if gen, err := fixture.ParticipationGeneration(ctx, id); err != nil { + t.Fatalf("reading participation_generation for %s: %v", id, err) + } else if gen == nil { + t.Fatalf("participation_generation for %s is NULL immediately after a create with the flag on — "+ + "this case cannot test the promoted-record path against a record that was never actually "+ + "promoted", id) + } + + beforeCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + if err := fixture.MutateExisting(ctx, id); err != nil { + t.Fatalf("mutating existing %s: %v", id, err) + } + afterCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + if afterCount != beforeCount+1 { + t.Errorf("version row count for %s went from %d to %d across an update-shaped mutation on an "+ + "already-promoted record, want exactly +1: the fence must skip only a legacy (NULL) record, "+ + "not every update (design §16.2b)", id, beforeCount, afterCount) + } +} + +// RunParticipationGenerationFlagOffSkipsUpdateOnParticipatingRecord pins the +// switch's off half for a record the fence would let through: created with +// the flag on (so participation_generation is stamped), then updated after +// the flag is turned back off, it must mint nothing. ProceedsForPromotedRecord +// shows the fence passes such a record, so only the flag stands between this +// update and a mint. No other case can see a writer that ignores the flag on +// updates: every other flag-off record is legacy, and the fence stops those +// first. +func RunParticipationGenerationFlagOffSkipsUpdateOnParticipatingRecord(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + if err := fixture.SetFlag(ctx, true); err != nil { + t.Fatalf("enabling versioned history: %v", err) + } + id := fixture.IssuePrefix + "-flag-off-skip" + if err := fixture.Mutate(ctx, id); err != nil { + t.Fatalf("mutating %s: %v", id, err) + } + if gen, err := fixture.ParticipationGeneration(ctx, id); err != nil { + t.Fatalf("reading participation_generation for %s: %v", id, err) + } else if gen == nil { + t.Fatalf("participation_generation for %s is NULL immediately after a create with the flag on — "+ + "this case cannot test the flag against a record the fence would have stopped anyway", id) + } + + if err := fixture.SetFlag(ctx, false); err != nil { + t.Fatalf("disabling versioned history: %v", err) + } + beforeRevision, err := fixture.CurrentRevision(ctx, id) + if err != nil { + t.Fatalf("reading current_revision for %s: %v", id, err) + } + beforeCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + + if err := fixture.MutateExisting(ctx, id); err != nil { + t.Fatalf("mutating existing %s: %v", id, err) + } + + afterRevision, err := fixture.CurrentRevision(ctx, id) + if err != nil { + t.Fatalf("reading current_revision for %s: %v", id, err) + } + afterCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + if afterCount != beforeCount { + t.Errorf("version row count for %s went from %d to %d across an update-shaped mutation with the "+ + "flag off, want unchanged: turning versioned history off stops minting for every record, "+ + "including one that already participates", id, beforeCount, afterCount) + } + if afterRevision != beforeRevision { + t.Errorf("current_revision for %s went from %d to %d across the same update with the flag off, "+ + "want unchanged", id, beforeRevision, afterRevision) + } +} + +// RunParticipationGenerationWispPromotionBeginsHistory pins that promoting a +// wisp onto the issues plane is CREATE-shaped in design §16.2b's sense. (This +// is wisp promotion, PromoteFromEphemeral: not R2.3's promotion of a legacy +// record, which is what ProceedsForPromotedRecord's name refers to.) The +// issues row a promotion inserts is brand new on that plane, and the wisp +// behind it was never versioned and never declared participation (FR-8), so +// there is no legacy state to preserve: with the flag on, the promotion stamps +// participation_generation and mints the record's first version, as a create +// there would. Treated as UPDATE-shaped, the fence finds the new row NULL and +// skips, and because nothing stamps the column afterwards every later update +// skips too, so a record created with the flag on is never versioned at all. +func RunParticipationGenerationWispPromotionBeginsHistory(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + runWispArrivalBeginsHistory(t, ctx, fixture, "promote", fixture.PromoteWisp) +} + +// RunParticipationGenerationWispPersistenceMoveBeginsHistory is +// RunParticipationGenerationWispPromotionBeginsHistory for the other way a +// wisp reaches the issues plane, a persistence-mode update (bd update +// --persistent). It needs its own case because it reaches a different mint +// site than promotion on every leg (see MovePersistent). +func RunParticipationGenerationWispPersistenceMoveBeginsHistory(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + runWispArrivalBeginsHistory(t, ctx, fixture, "move-persistent", fixture.MovePersistent) +} + +// runWispArrivalBeginsHistory is the body the two wisp-arrival cases share: +// with the flag on, a wisp that arrives on the issues plane through arrive +// carries a stamped participation_generation and exactly one version row, +// and the next update-shaped mutation mints normally. +func runWispArrivalBeginsHistory(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture, how string, arrive func(context.Context, string) error) { + t.Helper() + if err := fixture.SetFlag(ctx, true); err != nil { + t.Fatalf("enabling versioned history: %v", err) + } + id := fixture.IssuePrefix + "-" + how + if err := fixture.CreateWisp(ctx, id); err != nil { + t.Fatalf("creating wisp %s: %v", id, err) + } + if err := arrive(ctx, id); err != nil { + t.Fatalf("moving wisp %s onto the issues plane (%s): %v", id, how, err) + } + + gen, err := fixture.ParticipationGeneration(ctx, id) + if err != nil { + t.Fatalf("reading participation_generation for %s: %v", id, err) + } + if gen == nil { + t.Errorf("participation_generation for %s is NULL after the wisp reached the issues plane (%s) with "+ + "the flag on, want a stamped value: the issues row is new, so the arrival is create-shaped "+ + "(design §16.2b), and a NULL here leaves the record fenced as legacy for good", id, how) + } + arrivedCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + if arrivedCount != 1 { + t.Errorf("version row count for %s = %d after the wisp reached the issues plane (%s) with the flag "+ + "on, want 1: a wisp is never versioned (FR-8), so the arrival mints the record's first version", + id, arrivedCount, how) + } + + if err := fixture.MutateExisting(ctx, id); err != nil { + t.Fatalf("mutating existing %s: %v", id, err) + } + afterCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + if afterCount != arrivedCount+1 { + t.Errorf("version row count for %s went from %d to %d across an update-shaped mutation after the "+ + "wisp reached the issues plane (%s), want exactly +1: a record that arrived with the flag on is "+ + "not legacy, so the fence must let its updates mint", id, arrivedCount, afterCount, how) + } +} + +// RunParticipationGenerationWispFlagClearMintsNothing pins that the fence +// decides a row's plane by the TABLE that holds it, not by the row's flags. +// bd mol squash clears a wisp root's ephemeral flag in place, so the row +// stays in the wisps table carrying neither Ephemeral nor NoHistory, and a +// plane test read off those flags takes it for an issues-plane row. It is +// not one: a wisps-table row is never versioned (FR-8) and has no issues row +// whose participation_generation the fence could read. So the update must +// succeed and mint nothing. Read off the flags, the fence either aborts the +// whole update looking for an issues row that is not there, or, without the +// fence, mints a stray version for a wisp. +func RunParticipationGenerationWispFlagClearMintsNothing(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + runWispTableRowMintsNothing(t, ctx, fixture, "flag-clear", fixture.CreateWisp, fixture.ClearWispFlag) +} + +// RunParticipationGenerationWispRootSquashMintsNothing is +// RunParticipationGenerationWispFlagClearMintsNothing in the shape bd mol +// squash actually runs it: the root's close and its flag clear in one +// transaction, so a mint that fails on the cleared row takes the close down +// with it and the squash cannot complete. +func RunParticipationGenerationWispRootSquashMintsNothing(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + runWispTableRowMintsNothing(t, ctx, fixture, "squash", fixture.CreateWisp, fixture.SquashWispRoot) +} + +// RunParticipationGenerationUnflaggedWispCreateMintsNothing pins the +// create-shaped half of the same rule: a row CREATED in the wisps table +// without either flag (import's "wisp_plane" marker) reaches the +// create-shaped mint, and must come out of it with no error and no version, +// exactly as a flagged wisp does. +func RunParticipationGenerationUnflaggedWispCreateMintsNothing(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + runWispTableRowMintsNothing(t, ctx, fixture, "unflagged-create", fixture.CreateUnflaggedWisp) +} + +// runWispTableRowMintsNothing is the body the three wisps-table cases share: +// with the flag on, every step succeeds on id, the wisps table still holds id +// afterwards, and id ends with no issue_versions row. +func runWispTableRowMintsNothing(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture, how string, steps ...func(context.Context, string) error) { + t.Helper() + if err := fixture.SetFlag(ctx, true); err != nil { + t.Fatalf("enabling versioned history: %v", err) + } + id := fixture.IssuePrefix + "-" + how + for i, step := range steps { + if err := step(ctx, id); err != nil { + t.Fatalf("step %d of %s on wisps-table row %s with the flag on: %v — a row the wisps table "+ + "holds is never versioned (FR-8), so its mint must be a no-op, not an error that aborts "+ + "the mutation", i+1, how, id, err) + } + } + // The precondition, checked after the steps rather than assumed: a step + // that moved the row to the issues table would leave a NULL + // participation_generation there, the update-shaped mint would be fenced + // as legacy, and the zero count below would hold without saying anything + // about a wisps-table row. + if inWisps, err := fixture.InWispsTable(ctx, id); err != nil { + t.Fatalf("checking whether the wisps table holds %s: %v", id, err) + } else if !inWisps { + t.Fatalf("%s is not in the wisps table after %s — this case pins that a wisps-table row mints "+ + "nothing, and cannot say so about a row a step moved out of that table", id, how) + } + count, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + if count != 0 { + t.Errorf("version row count for wisps-table row %s = %d after %s with the flag on, want 0: a "+ + "wisp is never versioned (FR-8), whatever its flags say", id, count, how) + } +} + +// RunParticipationGenerationNoHistoryIssueCreateDeclaresParticipation pins +// that a create declares participation for every ISSUES-table row it makes +// with the flag on, a row carrying NoHistory included. Import keeps a +// promoted no-history wisp's durable row on the issues plane with its stray +// no_history=true (bd-r9uce). While the row says no-history it is not +// versioned, so the create mints nothing. But it was created with history +// on, so it is not legacy: once bd update --persistent repairs the flag in +// place (a same-plane normalize, update-shaped by design), the repair and +// every update after it must mint. Left NULL by the create, the column reads +// as legacy to the fence, and the row is never versioned at all. +func RunParticipationGenerationNoHistoryIssueCreateDeclaresParticipation(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + if err := fixture.SetFlag(ctx, true); err != nil { + t.Fatalf("enabling versioned history: %v", err) + } + id := fixture.IssuePrefix + "-no-history-create" + if err := fixture.CreateNoHistoryIssue(ctx, id); err != nil { + t.Fatalf("creating no-history issues-plane row %s: %v", id, err) + } + gen, err := fixture.ParticipationGeneration(ctx, id) + if err != nil { + t.Fatalf("reading participation_generation for %s: %v", id, err) + } + if gen == nil { + t.Errorf("participation_generation for %s is NULL after a create with the flag on, want a stamped "+ + "value: the row is new on the issues plane, so the create declares participation (design "+ + "§16.2b) even though its NoHistory flag keeps it unversioned for now", id) + } + if count, err := fixture.VersionRowCount(ctx, id); err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } else if count != 0 { + t.Errorf("version row count for %s = %d after a create carrying NoHistory, want 0: a no-history "+ + "row is not versioned while it says so", id, count) + } + + if err := fixture.MovePersistent(ctx, id); err != nil { + t.Fatalf("repairing %s to persistent: %v", id, err) + } + repairedCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + if repairedCount != 1 { + t.Errorf("version row count for %s = %d after the persistent repair, want 1: the row was created "+ + "with the flag on, so the fence must let the repair's update-shaped mint through", id, repairedCount) + } + + if err := fixture.MutateExisting(ctx, id); err != nil { + t.Fatalf("mutating existing %s: %v", id, err) + } + afterCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + if afterCount != repairedCount+1 { + t.Errorf("version row count for %s went from %d to %d across an update-shaped mutation after the "+ + "repair, want exactly +1", id, repairedCount, afterCount) + } +} + +// RunParticipationGenerationLegacyNoHistoryIssueStaysLegacy is +// RunParticipationGenerationNoHistoryIssueCreateDeclaresParticipation's +// negative twin, and pins R2.3: an ordinary write never promotes a legacy +// record. The same no-history issues-table row, created while the flag was +// OFF, is legacy. Only a create-shaped call stamps a flagged row, so once the +// flag is on, an update-shaped mutation must leave participation_generation +// NULL and mint nothing. So must the bd update --persistent repair that then +// clears the flag in place: that repair is update-shaped too (a same-plane +// normalize), so the row it leaves is an ordinary legacy row, still fenced. +func RunParticipationGenerationLegacyNoHistoryIssueStaysLegacy(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + if err := fixture.SetFlag(ctx, false); err != nil { + t.Fatalf("disabling versioned history: %v", err) + } + id := fixture.IssuePrefix + "-no-history-legacy" + if err := fixture.CreateNoHistoryIssue(ctx, id); err != nil { + t.Fatalf("creating no-history issues-plane row %s with the flag off: %v", id, err) + } + if gen, err := fixture.ParticipationGeneration(ctx, id); err != nil { + t.Fatalf("reading participation_generation for %s: %v", id, err) + } else if gen != nil { + t.Fatalf("participation_generation for %s = %d before the flag was ever turned on, want NULL — "+ + "this case cannot test that a legacy no-history row stays legacy against a row that was never "+ + "legacy", id, *gen) + } + + if err := fixture.SetFlag(ctx, true); err != nil { + t.Fatalf("enabling versioned history: %v", err) + } + beforeRevision, err := fixture.CurrentRevision(ctx, id) + if err != nil { + t.Fatalf("reading current_revision for %s: %v", id, err) + } + + assertStillLegacy := func(after string) { + t.Helper() + if gen, err := fixture.ParticipationGeneration(ctx, id); err != nil { + t.Fatalf("reading participation_generation for %s: %v", id, err) + } else if gen != nil { + t.Errorf("participation_generation for %s = %d after %s with the flag on, want NULL: the row "+ + "was created with the flag off, and an update-shaped write must not promote a legacy "+ + "record (R2.3), whatever its no-history flag says", id, *gen, after) + } + if count, err := fixture.VersionRowCount(ctx, id); err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } else if count != 0 { + t.Errorf("version row count for %s = %d after %s with the flag on, want 0: a legacy row's "+ + "update-shaped mint is fenced (design §16.2b)", id, count, after) + } + if revision, err := fixture.CurrentRevision(ctx, id); err != nil { + t.Fatalf("reading current_revision for %s: %v", id, err) + } else if revision != beforeRevision { + t.Errorf("current_revision for %s went from %d to %d after %s, want unchanged: a fenced "+ + "mint runs neither half of the seam's write", id, beforeRevision, revision, after) + } + } + + if err := fixture.MutateExisting(ctx, id); err != nil { + t.Fatalf("mutating existing %s: %v", id, err) + } + assertStillLegacy("an update-shaped mutation") + + if err := fixture.MovePersistent(ctx, id); err != nil { + t.Fatalf("repairing %s to persistent: %v", id, err) + } + assertStillLegacy("the persistent repair") +} + +// RunParticipationGenerationFenceIgnoresSchemaSkewHatch pins design §16.2(c): +// BD_IGNORE_SCHEMA_SKEW=1 downgrades CheckForwardDrift's refusal to a warning +// (internal/storage/schema/schema.go), but it must have no effect on this +// fence — the fence keys on the participation_generation column's real data, +// not on the migration cursor the hatch is about, so a write admitted through +// that hatch is still, correctly, skipped when the record is legacy. +func RunParticipationGenerationFenceIgnoresSchemaSkewHatch(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) { + t.Helper() + t.Setenv("BD_IGNORE_SCHEMA_SKEW", "1") + + if err := fixture.SetFlag(ctx, false); err != nil { + t.Fatalf("disabling versioned history: %v", err) + } + id := fixture.IssuePrefix + "-schema-skew-hatch" + if err := fixture.Mutate(ctx, id); err != nil { + t.Fatalf("mutating %s: %v", id, err) + } + if err := fixture.SetFlag(ctx, true); err != nil { + t.Fatalf("enabling versioned history: %v", err) + } + beforeCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + + if err := fixture.MutateExisting(ctx, id); err != nil { + t.Fatalf("mutating existing %s: %v", id, err) + } + + afterCount, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + if afterCount != beforeCount { + t.Errorf("version row count for %s went from %d to %d with BD_IGNORE_SCHEMA_SKEW=1 set, want "+ + "unchanged: the schema-skew hatch must not bypass the participation_generation fence — they "+ + "key on different planes (migration cursor vs. real column data) — so a write admitted "+ + "through the hatch against a legacy record must still be skipped", id, beforeCount, afterCount) + } +} diff --git a/backend/conformance/heartbeater_contract.go b/backend/conformance/heartbeater_contract.go new file mode 100644 index 000000000..bde6409f0 --- /dev/null +++ b/backend/conformance/heartbeater_contract.go @@ -0,0 +1,837 @@ +package conformance + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + storeops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the contract every implementation of publicops.Heartbeater +// must satisfy. Each case asserts what issueops/heartbeater.go PROMISES, cited +// by symbol. +// +// THREE LEGS, ONE BODY. dolt, embedded dolt and the unit-of-work provider all +// reach internal/storage/issueops.ExecuteHeartbeatInTx, so a per-leg failure +// here is a wrapper's failure: a commit the leg added, a hook it fired, a +// refusal that stopped matching errors.Is. +// +// THE QUIET CASE IS THE POINT. A heartbeat is the hottest write in a fleet and +// it is cheap because it writes the lease row and nothing else. Most of what +// RunHeartbeaterChangesNothingOnTheRow asserts is an ABSENCE — no revision, no +// version, no updated_at, no event, no journal entry, no history entry, no +// hook — and each absence is something a plausible wrapper would add. +// +// THE LIVE-CLAIM FENCE IS AN INVARIANT AND A PREDICATE. The RefusesAfter* +// cases hold the invariant: each ends a claim one way and asserts both that +// the lease row is gone and that the holder's next heartbeat is refused. The +// RefusesAnOrphanedLease* cases hold the predicate: a lease row that survives +// on an issue that is no longer claimed by its holder (what a re-arm racing a +// release or close can leave on Dolt) is refused AND deleted, never refreshed. +type HeartbeaterFixture struct { + // IssuePrefix namespaces the ids each assertion seeds, so several of them + // can share one database. + IssuePrefix string + // Heartbeater is the surface under test. + Heartbeater publicops.Heartbeater + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. A nil CreateWisp + // SKIPS the wisp case loudly. + CreateWisp func(context.Context, *types.Issue, string) error + // Claimer takes the claim, and with it the lease row, a heartbeat + // refreshes. + Claimer publicops.Claimer + // Lifecycle ends or moves a claim (close, a status move, a hand-doled + // claim) and performs the guarded write the revision case lands. + Lifecycle publicops.Lifecycle + // Releaser gives a claim up for the release case. Nil SKIPS that case. + Releaser publicops.Releaser + // LeaseReclaimer reverts an aged claim for the reclaim case. Nil, or a nil + // Exec, SKIPS that case. + LeaseReclaimer publicops.LeaseReclaimer + // Exec runs raw statements against the backing database: the cases use it + // to age a lease. + Exec func(ctx context.Context, statements []SQLStatement) error + // ExecUncommitted runs raw statements as ANOTHER writer that leaves its + // change uncommitted in the version-controlled working set (a batch-mode + // edit): SQL-committed, no version-control commit. Nil means Exec already + // behaves so. + ExecUncommitted func(ctx context.Context, statements []SQLStatement) error + // QueryScalar runs a single-row query and scans it, so the post-state is + // read RAW rather than through the role being tested. + QueryScalar func(context.Context, string, []any, ...any) error + // CountHistory reports how many version-control entries the fixture's + // branch has. Nil SKIPS that one assertion, loudly, in the quiet case. + CountHistory func(context.Context) (int, error) + // SetJournalEnabled turns on durable journaling, so the quiet case can + // observe that a heartbeat records nothing in bd_events_journal. Nil SKIPS + // that one assertion, loudly. + SetJournalEnabled func(enabled bool) + // SetVersionedHistoryEnabled turns on dual-write issue-version history, so + // the quiet case can observe that a heartbeat records no issue_versions + // row. Nil SKIPS that one assertion, loudly. + SetVersionedHistoryEnabled func(enabled bool) + // HookedHeartbeater is the same role taken off the leg's HOOK-FIRING chain + // (storage.HookFiringStore on the store legs, uow.NewNotifyingProvider on + // the unit-of-work leg), built over the runner FiredUpdates reads. Nil, + // with FiredUpdates, SKIPS the no-hook assertion loudly. + HookedHeartbeater publicops.Heartbeater + // FiredUpdates reports, in firing order, the issue id of every on_update + // the hooked chain ran so far. + FiredUpdates func(context.Context) ([]string, error) +} + +const ( + heartbeaterHolder = "hb-holder" + heartbeaterIntruder = "hb-intruder" + heartbeaterReaper = "hb-reaper" +) + +// RunHeartbeaterRefreshesTheHoldersLease pins the refresh itself +// (Heartbeater: "pushes the lease the caller holds forward by the store's +// TTL") and every member of the HeartbeatResult, against the row READ RAW. +func RunHeartbeaterRefreshesTheHoldersLease(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + requireHeartbeaterExec(t, fixture) + id := fixture.IssuePrefix + "-refresh" + heartbeaterSeedClaimed(t, ctx, fixture, id) + aged := time.Now().UTC().Add(-time.Minute).Truncate(time.Second) + if err := fixture.Exec(ctx, []SQLStatement{{ + Query: "UPDATE leases SET lease_expires_at = ?, heartbeat_at = ? WHERE issue_id = ?", + Args: []any{aged, aged, id}, + }}); err != nil { + t.Fatalf("age the lease on %s: %v", id, err) + } + + before := time.Now().UTC().Add(-time.Second) + result := heartbeat(t, ctx, fixture.Heartbeater, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id}) + after := time.Now().UTC().Add(time.Second) + + if result.IssueID != id || result.Holder != heartbeaterHolder || result.Rearmed { + t.Fatalf("result = %+v, want {IssueID:%s Holder:%s Rearmed:false}", result, id, heartbeaterHolder) + } + if result.HeartbeatAt.Before(before) || result.HeartbeatAt.After(after) { + t.Fatalf("HeartbeatAt = %v, want the server clock at the call (between %v and %v)", result.HeartbeatAt, before, after) + } + if ttl := result.LeaseExpiresAt.Sub(result.HeartbeatAt); heartbeaterAbs(ttl-storeops.DefaultLeaseTTL) > time.Second { + t.Fatalf("LeaseExpiresAt - HeartbeatAt = %v, want the store's lease TTL %v", ttl, storeops.DefaultLeaseTTL) + } + if moved := heartbeaterScalar[int](t, ctx, fixture, + "SELECT COUNT(*) FROM leases WHERE issue_id = ? AND holder = ? AND lease_expires_at > ? AND heartbeat_at > ?", + id, heartbeaterHolder, aged, aged); moved != 1 { + t.Fatal("the lease row's lease_expires_at and heartbeat_at did not move forward") + } + heartbeaterRequireStoredMatches(t, ctx, fixture, id, result, before, after) +} + +// RunHeartbeaterASameSecondHeartbeatIsNotARearm pins HeartbeatResult.Rearmed +// against the refresh that changes no value: a heartbeat landing in the same +// second as the claim or the previous heartbeat writes values identical to the +// row's (the lease columns hold whole seconds), which some engines report as +// zero rows affected. It is still a refresh of the caller's own row: Rearmed +// is false, and the lease's granted_at and granted_node do not move. +func RunHeartbeaterASameSecondHeartbeatIsNotARearm(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + requireHeartbeaterExec(t, fixture) + for i := 0; i < 3; i++ { + id := fixture.IssuePrefix + "-samesec-" + string(rune('a'+i)) + heartbeaterSeedClaimed(t, ctx, fixture, id) + granted := heartbeaterScalar[string](t, ctx, fixture, + "SELECT CONCAT(CAST(granted_at AS CHAR), '|', COALESCE(granted_node, '')) FROM leases WHERE issue_id = ?", id) + for beat := 0; beat < 2; beat++ { + result := heartbeat(t, ctx, fixture.Heartbeater, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id}) + if result.Rearmed { + t.Fatalf("heartbeat %d on %s right after the claim = %+v, want Rearmed:false: the holder's lease row existed", beat+1, id, result) + } + } + if got := heartbeaterScalar[string](t, ctx, fixture, + "SELECT CONCAT(CAST(granted_at AS CHAR), '|', COALESCE(granted_node, '')) FROM leases WHERE issue_id = ?", id); got != granted { + t.Fatalf("granted_at|granted_node on %s moved from %s to %s across refreshes; a refresh never re-grants", id, granted, got) + } + } +} + +// RunHeartbeaterChangesNothingOnTheRow pins the role's quiet promise +// (Heartbeater: "A REFRESH WRITES ONLY THE LEASE ROW"): the issue row's revision +// (row_lock), its current_revision, its updated_at, its events, the events +// journal, issue_versions, the version-control history and the hooks are all +// exactly where the claim left them. +func RunHeartbeaterChangesNothingOnTheRow(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + requireHeartbeaterExec(t, fixture) + if fixture.SetJournalEnabled != nil { + fixture.SetJournalEnabled(true) + defer fixture.SetJournalEnabled(false) + } else { + t.Log("HeartbeaterFixture.SetJournalEnabled is nil: the journal assertion is skipped on this backend") + } + if fixture.SetVersionedHistoryEnabled != nil { + fixture.SetVersionedHistoryEnabled(true) + defer fixture.SetVersionedHistoryEnabled(false) + } else { + t.Log("HeartbeaterFixture.SetVersionedHistoryEnabled is nil: the issue_versions assertion is skipped on this backend") + } + id := fixture.IssuePrefix + "-quiet" + heartbeaterSeedClaimed(t, ctx, fixture, id) + // updated_at is stored at second precision on some backends; step past + // the claim's second so a stamp the heartbeat added cannot hide in it. + time.Sleep(1100 * time.Millisecond) + + snapshot := func() heartbeaterRowSnapshot { + return heartbeaterSnapshot(t, ctx, fixture, id) + } + before := snapshot() + fired := heartbeaterFired(t, ctx, fixture, id) + + surface := fixture.Heartbeater + if fixture.HookedHeartbeater != nil && fixture.FiredUpdates != nil { + surface = fixture.HookedHeartbeater + } else { + t.Log("HeartbeaterFixture.HookedHeartbeater/FiredUpdates is nil: the no-hook assertion is skipped on this backend") + } + heartbeat(t, ctx, surface, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id}) + + after := snapshot() + if before != after { + t.Fatalf("a heartbeat changed the issue's durable state:\nbefore %+v\nafter %+v", before, after) + } + if got := heartbeaterFired(t, ctx, fixture, id); got != fired { + t.Fatalf("on_update fired %d time(s) for %s across a refresh, want 0: a refresh fires no hook", got-fired, id) + } +} + +// RunHeartbeaterAGuardedWriteWithThePreHeartbeatRevisionStillWins is the +// reason the quiet case matters to a caller: the holder's revision token +// survives its own heartbeats, so a guarded write it composed from the claim +// still lands. +func RunHeartbeaterAGuardedWriteWithThePreHeartbeatRevisionStillWins(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + if fixture.Lifecycle == nil { + t.Skip("HeartbeaterFixture.Lifecycle is nil: this backend cannot land a guarded write") + } + id := fixture.IssuePrefix + "-guarded" + revision := heartbeaterSeedClaimed(t, ctx, fixture, id) + + heartbeat(t, ctx, fixture.Heartbeater, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id}) + heartbeat(t, ctx, fixture.Heartbeater, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id}) + + if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: heartbeaterHolder, IssueID: id, ExpectedVersion: &revision, + Patch: publicops.IssuePatch{Notes: publicops.Field[string]{Set: true, Value: "after two heartbeats"}}, + }); err != nil { + t.Fatalf("guarded write with the claim's revision after heartbeats = %v, want it to land", err) + } +} + +// RunHeartbeaterRefusesAForeignHolder pins the fence (Heartbeater REFUSALS: +// "an issue another actor holds: a *LeaseConflictError naming the Holder, +// wrapping ErrAlreadyClaimed"), and that the refusal writes nothing. +func RunHeartbeaterRefusesAForeignHolder(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + requireHeartbeaterExec(t, fixture) + id := fixture.IssuePrefix + "-foreign" + heartbeaterSeedClaimed(t, ctx, fixture, id) + // Age the holder's lease first, so a heartbeat that ignored the holder + // fence would really CHANGE the row (some engines count only changed rows, + // and the columns hold whole seconds: an unaged row refreshed in the + // claim's second changes nothing and would hide the missing fence). + aged := time.Now().UTC().Add(-time.Minute).Truncate(time.Second) + if err := fixture.Exec(ctx, []SQLStatement{{ + Query: "UPDATE leases SET lease_expires_at = ?, heartbeat_at = ? WHERE issue_id = ?", + Args: []any{aged, aged, id}, + }}); err != nil { + t.Fatalf("age the lease on %s: %v", id, err) + } + lease := heartbeaterScalar[string](t, ctx, fixture, "SELECT CONCAT(CAST(lease_expires_at AS CHAR), '|', CAST(heartbeat_at AS CHAR), '|', holder) FROM leases WHERE issue_id = ?", id) + + _, err := fixture.Heartbeater.Heartbeat(ctx, publicops.HeartbeatRequest{Actor: heartbeaterIntruder, IssueID: id}) + if !errors.Is(err, publicops.ErrAlreadyClaimed) { + t.Fatalf("heartbeat by a non-holder = %v, want ErrAlreadyClaimed", err) + } + if errors.Is(err, publicops.ErrLeaseNotHeld) { + t.Fatalf("heartbeat by a non-holder = %v also matches ErrLeaseNotHeld; the two refusals must stay distinct", err) + } + conflict := heartbeaterConflict(t, err) + if conflict.IssueID != id || conflict.Holder != heartbeaterHolder || conflict.Status != types.StatusInProgress { + t.Fatalf("LeaseConflictError = %+v, want {IssueID:%s Holder:%s Status:%s}", conflict, id, heartbeaterHolder, types.StatusInProgress) + } + if got := heartbeaterScalar[string](t, ctx, fixture, "SELECT CONCAT(CAST(lease_expires_at AS CHAR), '|', CAST(heartbeat_at AS CHAR), '|', holder) FROM leases WHERE issue_id = ?", id); got != lease { + t.Fatalf("a refused heartbeat moved the holder's lease from %s to %s", lease, got) + } +} + +// RunHeartbeaterCommitsOnlyItsOwnTables pins the commit discipline against a +// DIRTY working set (Heartbeater: "A REFRESH WRITES ONLY THE LEASE ROW"; "A +// RE-ARM IS RECORDED AS A MUTATION"): another writer has left an uncommitted +// versioned change (a batch-mode edit, here a config row). A refresh and a +// refusal make no version-control commit and leave that change uncommitted; +// a re-arm makes exactly one commit, of its own tables, and still leaves the +// other writer's change uncommitted rather than sweeping it in under the +// heartbeat's message. +func RunHeartbeaterCommitsOnlyItsOwnTables(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + requireHeartbeaterExec(t, fixture) + if fixture.CountHistory == nil || fixture.Lifecycle == nil { + t.Skip("HeartbeaterFixture.CountHistory/Lifecycle is nil: this backend has no version-control history to observe") + } + refreshed := fixture.IssuePrefix + "-dirty-refresh" + heartbeaterSeedClaimed(t, ctx, fixture, refreshed) + refused := fixture.IssuePrefix + "-dirty-refused" + heartbeaterSeed(t, ctx, fixture, refused) + rearmed := fixture.IssuePrefix + "-dirty-rearm" + heartbeaterSeed(t, ctx, fixture, rearmed) + if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: heartbeaterHolder, IssueID: rearmed, + Patch: publicops.IssuePatch{ + Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusInProgress}, + Assignee: publicops.Field[string]{Set: true, Value: heartbeaterHolder}, + }, + }); err != nil { + t.Fatalf("hand-dole %s: %v", rearmed, err) + } + + probe := "heartbeat.dirty-probe." + fixture.IssuePrefix + dirty := fixture.Exec + if fixture.ExecUncommitted != nil { + dirty = fixture.ExecUncommitted + } + if err := dirty(ctx, []SQLStatement{{ + Query: "REPLACE INTO config (`key`, value) VALUES (?, ?)", Args: []any{probe, "uncommitted"}, + }}); err != nil { + t.Fatalf("dirty the working set: %v", err) + } + defer func() { + _ = dirty(ctx, []SQLStatement{{Query: "DELETE FROM config WHERE `key` = ?", Args: []any{probe}}}) + }() + foreignDirty := func(when string) { + t.Helper() + if n := heartbeaterScalar[int](t, ctx, fixture, + "SELECT COUNT(*) FROM dolt_status WHERE table_name = 'config'"); n == 0 { + t.Fatalf("%s: the other writer's uncommitted config change was committed; a heartbeat commits only its own tables", when) + } + } + history := func() int { + t.Helper() + n, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory: %v", err) + } + return n + } + foreignDirty("before any heartbeat") + before := history() + + heartbeat(t, ctx, fixture.Heartbeater, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: refreshed}) + if got := history(); got != before { + t.Fatalf("a refresh moved the version-control history %d -> %d; a refresh makes no commit", before, got) + } + foreignDirty("after a refresh") + + if _, err := fixture.Heartbeater.Heartbeat(ctx, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: refused}); err == nil { + t.Fatalf("heartbeat on unclaimed %s succeeded, want a refusal", refused) + } + if got := history(); got != before { + t.Fatalf("a refusal moved the version-control history %d -> %d; a refusal makes no commit", before, got) + } + foreignDirty("after a refusal") + + if result := heartbeat(t, ctx, fixture.Heartbeater, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: rearmed}); !result.Rearmed { + t.Fatalf("heartbeat on hand-doled %s = %+v, want Rearmed", rearmed, result) + } + if got := history(); got != before+1 { + t.Fatalf("a re-arm moved the version-control history %d -> %d, want exactly one commit", before, got) + } + foreignDirty("after a re-arm") +} + +// RunHeartbeaterRefusesAnOrphanedLeaseOnAReleasedIssue and +// ...OnAClosedIssue and ...OnAnIssueSomeoneElseHolds pin the live-claim +// predicate (Heartbeater: "THE LIVE-CLAIM FENCE IS A PREDICATE"): a lease row +// that names the caller but survives on an issue that is open, closed, or +// in_progress under another assignee is refused, never refreshed, and the +// refusal deletes it (Heartbeater: the one write a refusal makes). The row +// is planted raw: it is the state a re-arm racing a release or close leaves. +func RunHeartbeaterRefusesAnOrphanedLeaseOnAReleasedIssue(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + requireHeartbeaterExec(t, fixture) + id := fixture.IssuePrefix + "-orphan-open" + heartbeaterSeed(t, ctx, fixture, id) + heartbeaterRefusesAnOrphan(t, ctx, fixture, id, types.StatusOpen, "") +} + +func RunHeartbeaterRefusesAnOrphanedLeaseOnAClosedIssue(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + requireHeartbeaterExec(t, fixture) + if fixture.Lifecycle == nil { + t.Skip("HeartbeaterFixture.Lifecycle is nil: this backend cannot close the claim") + } + id := fixture.IssuePrefix + "-orphan-closed" + heartbeaterSeedClaimed(t, ctx, fixture, id) + if _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: heartbeaterHolder, IssueID: id, Reason: "done"}); err != nil { + t.Fatalf("close %s: %v", id, err) + } + heartbeaterRefusesAnOrphan(t, ctx, fixture, id, types.StatusClosed, "") +} + +func RunHeartbeaterRefusesAnOrphanedLeaseOnAnIssueSomeoneElseHolds(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + requireHeartbeaterExec(t, fixture) + if fixture.Lifecycle == nil { + t.Skip("HeartbeaterFixture.Lifecycle is nil: this backend cannot hand-dole a claim") + } + id := fixture.IssuePrefix + "-orphan-moved" + heartbeaterSeed(t, ctx, fixture, id) + if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: heartbeaterIntruder, IssueID: id, + Patch: publicops.IssuePatch{ + Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusInProgress}, + Assignee: publicops.Field[string]{Set: true, Value: heartbeaterIntruder}, + }, + }); err != nil { + t.Fatalf("hand-dole %s to %s: %v", id, heartbeaterIntruder, err) + } + heartbeaterRefusesAnOrphan(t, ctx, fixture, id, types.StatusInProgress, heartbeaterIntruder) +} + +// heartbeaterRefusesAnOrphan plants a lease row for heartbeaterHolder on id +// (which the holder does not hold), heartbeats as the holder, and asserts the +// refusal and that the row is gone. +func heartbeaterRefusesAnOrphan(t *testing.T, ctx context.Context, fixture HeartbeaterFixture, id string, status types.Status, foreign string) { + t.Helper() + now := time.Now().UTC().Truncate(time.Second) + if err := fixture.Exec(ctx, []SQLStatement{ + {Query: "DELETE FROM leases WHERE issue_id = ?", Args: []any{id}}, + { + Query: "INSERT INTO leases (issue_id, holder, granted_at, lease_expires_at, heartbeat_at, granted_node) VALUES (?, ?, ?, ?, ?, '')", + Args: []any{id, heartbeaterHolder, now.Add(-time.Minute), now.Add(time.Hour), now.Add(-time.Minute)}, + }, + }); err != nil { + t.Fatalf("plant an orphaned lease on %s: %v", id, err) + } + + _, err := fixture.Heartbeater.Heartbeat(ctx, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id}) + conflict := heartbeaterConflict(t, err) + if foreign != "" { + if !errors.Is(err, publicops.ErrAlreadyClaimed) || conflict.Holder != foreign { + t.Fatalf("heartbeat over an orphaned lease on an issue %s holds = %v (%+v), want ErrAlreadyClaimed naming %s", foreign, err, conflict, foreign) + } + } else if !errors.Is(err, publicops.ErrLeaseNotHeld) || conflict.Holder != "" { + t.Fatalf("heartbeat over an orphaned lease on a %s issue = %v (%+v), want ErrLeaseNotHeld", status, err, conflict) + } + if conflict.IssueID != id || conflict.Status != status || conflict.Ephemeral { + t.Fatalf("LeaseConflictError = %+v, want {IssueID:%s Status:%s Ephemeral:false}", conflict, id, status) + } + if n := heartbeaterScalar[int](t, ctx, fixture, "SELECT COUNT(*) FROM leases WHERE issue_id = ?", id); n != 0 { + t.Fatalf("lease rows on %s after the refusal = %d, want 0: a refusal deletes the caller's orphaned lease", id, n) + } + // And it stays refused: the next heartbeat finds no row to refresh. + if _, err := fixture.Heartbeater.Heartbeat(ctx, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id}); err == nil { + t.Fatalf("a second heartbeat on %s succeeded after the orphan was refused", id) + } +} + +// heartbeaterRequireStoredMatches pins the reported times to the stored row +// (LeaseRenewal: "exactly what the lease row now holds"): lease_expires_at and +// heartbeat_at as stored are the result's, within the columns' one-second +// precision, and the stored expiry is the call's clock plus the store's TTL. +func heartbeaterRequireStoredMatches(t *testing.T, ctx context.Context, fixture HeartbeaterFixture, id string, result publicops.HeartbeatResult, before, after time.Time) { + t.Helper() + window := func(at time.Time) (time.Time, time.Time) { return at.Add(-time.Second), at.Add(time.Second) } + hbLo, hbHi := window(result.HeartbeatAt) + exLo, exHi := window(result.LeaseExpiresAt) + if n := heartbeaterScalar[int](t, ctx, fixture, + "SELECT COUNT(*) FROM leases WHERE issue_id = ? AND holder = ? AND heartbeat_at BETWEEN ? AND ? AND lease_expires_at BETWEEN ? AND ?", + id, result.Holder, hbLo, hbHi, exLo, exHi); n != 1 { + t.Fatalf("the stored lease row on %s does not hold the reported heartbeat_at %v and lease_expires_at %v (within 1s)", + id, result.HeartbeatAt, result.LeaseExpiresAt) + } + ttlLo, ttlHi := before.Add(storeops.DefaultLeaseTTL), after.Add(storeops.DefaultLeaseTTL) + if n := heartbeaterScalar[int](t, ctx, fixture, + "SELECT COUNT(*) FROM leases WHERE issue_id = ? AND lease_expires_at BETWEEN ? AND ?", + id, ttlLo, ttlHi); n != 1 { + t.Fatalf("the stored lease_expires_at on %s is not the call's clock plus the lease TTL %v", id, storeops.DefaultLeaseTTL) + } + if !result.HeartbeatAt.Equal(result.HeartbeatAt.Truncate(time.Second)) || !result.LeaseExpiresAt.Equal(result.LeaseExpiresAt.Truncate(time.Second)) { + t.Fatalf("result times %v / %v carry sub-second digits the lease columns cannot hold", result.HeartbeatAt, result.LeaseExpiresAt) + } +} + +// RunHeartbeaterRefusesAfterClose, ...AfterRelease, ...AfterReclaim and +// ...AfterStatusMovedOffInProgress pin the in_progress fence through the +// lease-row invariant (Heartbeater: "a lease row exists only while its issue +// is in_progress with that holder as assignee"): each ends the claim one way, +// asserts the lease row went with it, and that the former holder's heartbeat +// is refused with ErrLeaseNotHeld, which also matches ErrNotClaimable. +func RunHeartbeaterRefusesAfterClose(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + if fixture.Lifecycle == nil { + t.Skip("HeartbeaterFixture.Lifecycle is nil: this backend cannot close the claim") + } + heartbeaterRefusesAfter(t, ctx, fixture, "closed", types.StatusClosed, func(id string) error { + _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: heartbeaterHolder, IssueID: id, Reason: "done"}) + return err + }) +} + +func RunHeartbeaterRefusesAfterRelease(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + if fixture.Releaser == nil { + t.Skip("HeartbeaterFixture.Releaser is nil: this backend cannot release the claim") + } + heartbeaterRefusesAfter(t, ctx, fixture, "released", types.StatusOpen, func(id string) error { + _, err := fixture.Releaser.Release(ctx, publicops.ReleaseRequest{Actor: heartbeaterHolder, IssueID: id}) + return err + }) +} + +func RunHeartbeaterRefusesAfterReclaim(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + if fixture.LeaseReclaimer == nil || fixture.Exec == nil { + t.Skip("HeartbeaterFixture.LeaseReclaimer/Exec is nil: this backend cannot reclaim the claim") + } + heartbeaterRefusesAfter(t, ctx, fixture, "reclaimed", types.StatusOpen, func(id string) error { + if err := fixture.Exec(ctx, []SQLStatement{{ + Query: "UPDATE leases SET lease_expires_at = ? WHERE issue_id = ?", + Args: []any{time.Now().UTC().Add(-time.Hour), id}, + }}); err != nil { + return err + } + result, err := fixture.LeaseReclaimer.Reclaim(ctx, publicops.ReclaimRequest{ + Actor: heartbeaterReaper, Filter: publicops.ReclaimFilter{IDs: []string{id}}, + }) + if err == nil && len(result.Reclaimed) != 1 { + t.Fatalf("Reclaimed = %+v, want exactly %s", result.Reclaimed, id) + } + return err + }) +} + +func RunHeartbeaterRefusesAfterStatusMovedOffInProgress(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + if fixture.Lifecycle == nil { + t.Skip("HeartbeaterFixture.Lifecycle is nil: this backend cannot move the status") + } + heartbeaterRefusesAfter(t, ctx, fixture, "blocked", types.StatusBlocked, func(id string) error { + _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: heartbeaterHolder, IssueID: id, + Patch: publicops.IssuePatch{Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusBlocked}}, + }) + return err + }) +} + +// RunHeartbeaterRefusesAWisp pins the plane rule (Heartbeater REFUSALS: "a +// wisp ... ErrLeaseNotHeld"): wisps are never leased, so even a wisp the +// caller holds in_progress is refused, and no lease row appears for it. +func RunHeartbeaterRefusesAWisp(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + if fixture.CreateWisp == nil || fixture.QueryScalar == nil { + t.Skip("HeartbeaterFixture.CreateWisp/QueryScalar is nil: this backend cannot seed a wisp") + } + id := fixture.IssuePrefix + "-wisp" + if err := fixture.CreateWisp(ctx, &types.Issue{ + ID: id, Title: id, Status: types.StatusInProgress, Assignee: heartbeaterHolder, + Priority: 2, IssueType: types.TypeTask, Ephemeral: true, + }, "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", id, err) + } + + _, err := fixture.Heartbeater.Heartbeat(ctx, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id}) + if !errors.Is(err, publicops.ErrLeaseNotHeld) || !errors.Is(err, publicops.ErrNotClaimable) { + t.Fatalf("heartbeat on a wisp = %v, want ErrLeaseNotHeld matching ErrNotClaimable", err) + } + if !strings.Contains(err.Error(), "ephemeral") { + t.Fatalf("heartbeat on a wisp = %q, want the refusal to say the issue is ephemeral", err) + } + if conflict := heartbeaterConflict(t, err); conflict.IssueID != id || conflict.Holder != "" { + t.Fatalf("LeaseConflictError = %+v, want {IssueID:%s Holder:\"\"}", conflict, id) + } + if n := heartbeaterScalar[int](t, ctx, fixture, "SELECT COUNT(*) FROM leases WHERE issue_id = ?", id); n != 0 { + t.Fatalf("lease rows for wisp %s = %d, want 0: wisps are never leased", id, n) + } +} + +// RunHeartbeaterRearmsAHandDoledClaim pins the self-heal (HeartbeatResult. +// Rearmed): an issue put in_progress with the caller as assignee by a generic +// update holds no lease row, and the holder's heartbeat grants one rather than +// refusing. The re-arm is recorded as a mutation (Heartbeater: "A RE-ARM IS +// RECORDED AS A MUTATION"): it remints the revision, which is what makes it +// collide with a racing release or close, and records a lease_rearmed event; +// the refresh after it does neither. +func RunHeartbeaterRearmsAHandDoledClaim(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + if fixture.Lifecycle == nil || fixture.QueryScalar == nil { + t.Skip("HeartbeaterFixture.Lifecycle/QueryScalar is nil: this backend cannot hand-dole a claim") + } + id := fixture.IssuePrefix + "-doled" + heartbeaterSeed(t, ctx, fixture, id) + if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: heartbeaterHolder, IssueID: id, + Patch: publicops.IssuePatch{ + Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusInProgress}, + Assignee: publicops.Field[string]{Set: true, Value: heartbeaterHolder}, + }, + }); err != nil { + t.Fatalf("hand-dole %s: %v", id, err) + } + if n := heartbeaterScalar[int](t, ctx, fixture, "SELECT COUNT(*) FROM leases WHERE issue_id = ?", id); n != 0 { + t.Fatalf("lease rows after a generic update = %d, want 0: the case needs a claim with no lease", n) + } + revision := heartbeaterScalar[int64](t, ctx, fixture, "SELECT row_lock FROM issues WHERE id = ?", id) + + before := time.Now().UTC().Add(-time.Second) + result := heartbeat(t, ctx, fixture.Heartbeater, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id}) + after := time.Now().UTC().Add(time.Second) + if !result.Rearmed || result.Holder != heartbeaterHolder { + t.Fatalf("result = %+v, want Rearmed:true Holder:%s", result, heartbeaterHolder) + } + heartbeaterRequireStoredMatches(t, ctx, fixture, id, result, before, after) + if n := heartbeaterScalar[int](t, ctx, fixture, + "SELECT COUNT(*) FROM leases WHERE issue_id = ? AND holder = ? AND lease_expires_at > ?", + id, heartbeaterHolder, time.Now().UTC()); n != 1 { + t.Fatal("the re-armed heartbeat left no live lease row for the holder") + } + rearmed := heartbeaterScalar[int64](t, ctx, fixture, "SELECT row_lock FROM issues WHERE id = ?", id) + if rearmed == revision { + t.Fatalf("row_lock stayed %d across a re-arming heartbeat; a re-arm remints it so a racing release or close collides with it", revision) + } + rearmEvents := func() int { + return heartbeaterScalar[int](t, ctx, fixture, + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", id, string(types.EventLeaseRearmed)) + } + if n := rearmEvents(); n != 1 { + t.Fatalf("lease_rearmed events on %s after a re-arm = %d, want 1: a re-arm is recorded as a mutation", id, n) + } + // The next heartbeat refreshes the lease it just granted: no re-arm, and + // no revision change. + if again := heartbeat(t, ctx, fixture.Heartbeater, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id}); again.Rearmed { + t.Fatalf("second heartbeat after the re-arm = %+v, want Rearmed:false", again) + } + if got := heartbeaterScalar[int64](t, ctx, fixture, "SELECT row_lock FROM issues WHERE id = ?", id); got != rearmed { + t.Fatalf("row_lock moved from %d to %d across a refresh after the re-arm", rearmed, got) + } + if n := rearmEvents(); n != 1 { + t.Fatalf("lease_rearmed events on %s after a refresh = %d, want still 1: a refresh records nothing", id, n) + } +} + +// RunHeartbeaterAnswersNotFoundForAnAbsentID pins Heartbeater REFUSALS: "an +// IssueID that names no row on either plane: ErrNotFound". +func RunHeartbeaterAnswersNotFoundForAnAbsentID(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + _, err := fixture.Heartbeater.Heartbeat(ctx, publicops.HeartbeatRequest{ + Actor: heartbeaterHolder, IssueID: fixture.IssuePrefix + "-absent", + }) + if !errors.Is(err, publicops.ErrNotFound) { + t.Fatalf("heartbeat on an absent id = %v, want ErrNotFound", err) + } +} + +// RunHeartbeaterRefusesABlankOrOverLongActor pins the request rules +// (HeartbeatRequest.Actor, Heartbeater REFUSALS): each is a +// *HeartbeatFieldError naming its field, matching ErrValidation. +func RunHeartbeaterRefusesABlankOrOverLongActor(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + id := fixture.IssuePrefix + "-refusals" + for _, test := range []struct { + name string + request publicops.HeartbeatRequest + field string + }{ + {"an empty actor", publicops.HeartbeatRequest{IssueID: id}, publicops.HeartbeatFieldActor}, + {"a blank actor", publicops.HeartbeatRequest{Actor: " \t", IssueID: id}, publicops.HeartbeatFieldActor}, + {"an over-long actor", publicops.HeartbeatRequest{Actor: strings.Repeat("a", types.MaxFieldLen+1), IssueID: id}, publicops.HeartbeatFieldActor}, + {"an empty id", publicops.HeartbeatRequest{Actor: heartbeaterHolder}, publicops.HeartbeatFieldIssueID}, + } { + t.Run(test.name, func(t *testing.T) { + _, err := fixture.Heartbeater.Heartbeat(ctx, test.request) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("Heartbeat(%s) = %v, want ErrValidation", test.name, err) + } + var field *publicops.HeartbeatFieldError + if !errors.As(err, &field) || field.Field != test.field { + t.Fatalf("Heartbeat(%s) = %v, want a *HeartbeatFieldError naming %q", test.name, err, test.field) + } + }) + } +} + +// RunHeartbeaterDoesNotMutateTheRequest pins the role's "never mutate +// caller-owned request values". +func RunHeartbeaterDoesNotMutateTheRequest(t *testing.T, ctx context.Context, fixture HeartbeaterFixture) { + t.Helper() + id := fixture.IssuePrefix + "-nomutate" + heartbeaterSeedClaimed(t, ctx, fixture, id) + request := publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id} + want := request + heartbeat(t, ctx, fixture.Heartbeater, request) + if request != want { + t.Fatalf("request after Heartbeat = %+v, want %+v", request, want) + } +} + +// heartbeaterRefusesAfter seeds and claims one issue, ends the claim with end, +// and asserts the invariant and the refusal. +func heartbeaterRefusesAfter(t *testing.T, ctx context.Context, fixture HeartbeaterFixture, suffix string, status types.Status, end func(id string) error) { + t.Helper() + if fixture.QueryScalar == nil { + t.Skip("HeartbeaterFixture.QueryScalar is nil: this backend cannot read the lease row") + } + id := fixture.IssuePrefix + "-after-" + suffix + heartbeaterSeedClaimed(t, ctx, fixture, id) + if n := heartbeaterScalar[int](t, ctx, fixture, "SELECT COUNT(*) FROM leases WHERE issue_id = ?", id); n != 1 { + t.Fatalf("lease rows for claimed %s = %d, want 1", id, n) + } + if err := end(id); err != nil { + t.Fatalf("end the claim on %s (%s): %v", id, suffix, err) + } + if n := heartbeaterScalar[int](t, ctx, fixture, "SELECT COUNT(*) FROM leases WHERE issue_id = ?", id); n != 0 { + t.Fatalf("lease rows for %s %s = %d, want 0: the path that ended the claim left its lease row", suffix, id, n) + } + + _, err := fixture.Heartbeater.Heartbeat(ctx, publicops.HeartbeatRequest{Actor: heartbeaterHolder, IssueID: id}) + if !errors.Is(err, publicops.ErrLeaseNotHeld) || !errors.Is(err, publicops.ErrNotClaimable) { + t.Fatalf("heartbeat after the claim was %s = %v, want ErrLeaseNotHeld matching ErrNotClaimable", suffix, err) + } + if errors.Is(err, publicops.ErrAlreadyClaimed) { + t.Fatalf("heartbeat after the claim was %s = %v also matches ErrAlreadyClaimed", suffix, err) + } + conflict := heartbeaterConflict(t, err) + if conflict.IssueID != id || conflict.Holder != "" || conflict.Status != status { + t.Fatalf("LeaseConflictError = %+v, want {IssueID:%s Holder:\"\" Status:%s}", conflict, id, status) + } + if n := heartbeaterScalar[int](t, ctx, fixture, "SELECT COUNT(*) FROM leases WHERE issue_id = ?", id); n != 0 { + t.Fatalf("a refused heartbeat left %d lease row(s) for %s", n, id) + } +} + +// heartbeaterRowSnapshot is every durable trace a heartbeat must not leave. +// A field the backend cannot observe holds -1. +type heartbeaterRowSnapshot struct { + RowLock int64 + CurrentRevision int64 + UpdatedAt string + Events int + JournalMaxSeq int64 + IssueVersions int + History int +} + +func heartbeaterSnapshot(t *testing.T, ctx context.Context, fixture HeartbeaterFixture, id string) heartbeaterRowSnapshot { + t.Helper() + snap := heartbeaterRowSnapshot{ + RowLock: heartbeaterScalar[int64](t, ctx, fixture, "SELECT row_lock FROM issues WHERE id = ?", id), + CurrentRevision: heartbeaterScalar[int64](t, ctx, fixture, "SELECT current_revision FROM issues WHERE id = ?", id), + UpdatedAt: heartbeaterScalar[string](t, ctx, fixture, "SELECT CAST(updated_at AS CHAR) FROM issues WHERE id = ?", id), + Events: heartbeaterScalar[int](t, ctx, fixture, "SELECT COUNT(*) FROM events WHERE issue_id = ?", id), + JournalMaxSeq: -1, + IssueVersions: -1, + History: -1, + } + if fixture.SetJournalEnabled != nil { + snap.JournalMaxSeq = heartbeaterScalar[int64](t, ctx, fixture, "SELECT COALESCE(MAX(seq), 0) FROM bd_events_journal") + } + if fixture.SetVersionedHistoryEnabled != nil { + snap.IssueVersions = heartbeaterScalar[int](t, ctx, fixture, "SELECT COUNT(*) FROM issue_versions WHERE issue_id = ?", id) + } + if fixture.CountHistory != nil { + n, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory: %v", err) + } + snap.History = n + } + return snap +} + +func heartbeaterFired(t *testing.T, ctx context.Context, fixture HeartbeaterFixture, id string) int { + t.Helper() + if fixture.HookedHeartbeater == nil || fixture.FiredUpdates == nil { + return 0 + } + ids, err := fixture.FiredUpdates(ctx) + if err != nil { + t.Fatalf("FiredUpdates: %v", err) + } + n := 0 + for _, fired := range ids { + if fired == id { + n++ + } + } + return n +} + +func requireHeartbeaterExec(t *testing.T, fixture HeartbeaterFixture) { + t.Helper() + if fixture.Exec == nil || fixture.QueryScalar == nil { + t.Skip("HeartbeaterFixture.Exec/QueryScalar is nil: this backend cannot read or age a lease row") + } +} + +func heartbeaterSeed(t *testing.T, ctx context.Context, fixture HeartbeaterFixture, id string) { + t.Helper() + if err := fixture.CreateIssue(ctx, &types.Issue{ + ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + }, "seed"); err != nil { + t.Fatalf("seed %s: %v", id, err) + } +} + +// heartbeaterSeedClaimed creates id and claims it as heartbeaterHolder through +// the leg's Claimer, answering the claim's row version. +func heartbeaterSeedClaimed(t *testing.T, ctx context.Context, fixture HeartbeaterFixture, id string) int64 { + t.Helper() + if fixture.Claimer == nil { + t.Skip("HeartbeaterFixture.Claimer is nil: this backend cannot take the claim a heartbeat refreshes") + } + heartbeaterSeed(t, ctx, fixture, id) + claimed, err := fixture.Claimer.Claim(ctx, publicops.ClaimRequest{Actor: heartbeaterHolder, IssueID: id}) + if err != nil { + t.Fatalf("claim %s as %s: %v", id, heartbeaterHolder, err) + } + if claimed.Issue == nil { + t.Fatalf("claim %s answered no issue", id) + } + return claimed.Issue.RowVersion +} + +func heartbeat(t *testing.T, ctx context.Context, surface publicops.Heartbeater, request publicops.HeartbeatRequest) publicops.HeartbeatResult { + t.Helper() + result, err := surface.Heartbeat(ctx, request) + if err != nil { + t.Fatalf("Heartbeat(%+v): %v", request, err) + } + return result +} + +func heartbeaterConflict(t *testing.T, err error) *publicops.LeaseConflictError { + t.Helper() + var conflict *publicops.LeaseConflictError + if !errors.As(err, &conflict) { + t.Fatalf("refusal %v (%T) is not a *LeaseConflictError", err, err) + } + return conflict +} + +func heartbeaterScalar[T any](t *testing.T, ctx context.Context, fixture HeartbeaterFixture, query string, args ...any) T { + t.Helper() + var value T + if err := fixture.QueryScalar(ctx, query, args, &value); err != nil { + t.Fatalf("%s %v: %v", query, args, err) + } + return value +} + +func heartbeaterAbs(d time.Duration) time.Duration { + if d < 0 { + return -d + } + return d +} diff --git a/backend/conformance/lease_reclaimer_contract.go b/backend/conformance/lease_reclaimer_contract.go new file mode 100644 index 000000000..eadc6c176 --- /dev/null +++ b/backend/conformance/lease_reclaimer_contract.go @@ -0,0 +1,625 @@ +package conformance + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "slices" + "sort" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads/internal/hooks" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the contract every implementation of publicops.LeaseReclaimer +// must satisfy. Each case asserts what issueops/leasereclaimer.go PROMISES, +// cited by symbol. +// +// FOUR LEGS, ONE BODY. dolt, embedded dolt and the unit-of-work provider all +// reach internal/storage/issueops.ExecuteReclaimInTx, and the http leg reaches +// the same body on the far side of POST /v0/beads/issues:reclaim. So a per-leg +// failure here is a wrapper's failure — a lost scope, a revision that never +// reached the caller, a refusal that stopped matching errors.Is — and the +// cases are written to catch exactly those. +// +// EVERY SWEEP HERE IS SCOPED. The legs share one database per suite with every +// other role's cases, and an UNSCOPED reclaim would revert whatever stale lease +// another case left behind. Every call below names its ids, or an assignee or +// label this case alone uses, so a case can never reach outside what it seeded. +// The workspace-wide form is the same SQL with the scope clause absent, which +// sqlbuild.ReclaimScopeSQL's own tests pin. +// +// STALENESS IS MANUFACTURED, NOT WAITED FOR. The role refuses a negative +// OlderThan (the raw method's -time.Hour trick is exactly what it rules out), +// so a case claims through the leg's real Claimer — which writes the lease row +// every reclaim reads — and then moves that row's lease_expires_at into the +// past through Exec. +type LeaseReclaimerFixture struct { + // IssuePrefix namespaces the ids each assertion seeds, so several of them + // can share one database. + IssuePrefix string + // LeaseReclaimer is the surface under test. + LeaseReclaimer publicops.LeaseReclaimer + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // Claimer takes the claim, and with it the lease row, a reclaim reverts. It + // is the leg's own role rather than a raw insert so the lease is the shape + // a real claim leaves, granted_node included. + Claimer publicops.Claimer + // Lifecycle performs the guarded write the revision case races against the + // reclaim. A nil Lifecycle SKIPS that case loudly. + Lifecycle publicops.Lifecycle + // Exec runs raw statements against the backing database: the cases use it + // to age a lease and to attach labels. A nil Exec SKIPS every case that + // needs a stale lease, which is nearly all of them, so every leg supplies + // one. + Exec func(ctx context.Context, statements []SQLStatement) error + // QueryScalar runs a single-row query and scans it, so the post-state is + // read RAW rather than through the role being tested. + QueryScalar func(context.Context, string, []any, ...any) error + // HookedLeaseReclaimer is the same role taken off the leg's HOOK-FIRING + // chain (storage.HookFiringStore on the store legs and the http leg, + // uow.NewNotifyingProvider on the unit-of-work leg), built over the runner + // FiredUpdates reads. Nil, with FiredUpdates, SKIPS the hook case loudly. + HookedLeaseReclaimer publicops.LeaseReclaimer + // FiredUpdates reports, in firing order, the issue id of every on_update + // the hooked chain ran so far. It must not return before the hooks it is + // asked about have finished. + FiredUpdates func(context.Context) ([]string, error) +} + +const ( + leaseReclaimerReaper = "reaper" + leaseReclaimerHolder = "lr-holder" +) + +// RunLeaseReclaimerRevertsAStaleLease pins the post-state the role names +// (issueops/leasereclaimer.go, LeaseReclaimer: "each reclaimed row moves +// in_progress -> open and the assignee is cleared") and the three members of +// the ReclaimedLease it reports, each READ RAW. +func RunLeaseReclaimerRevertsAStaleLease(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + requireLeaseReclaimerExec(t, fixture) + id := fixture.IssuePrefix + "-revert" + leaseReclaimerSeedStale(t, ctx, fixture, leaseReclaimerHolder, id) + + result := leaseReclaim(t, ctx, fixture, publicops.ReclaimRequest{ + Actor: leaseReclaimerReaper, + Filter: publicops.ReclaimFilter{IDs: []string{id}}, + }) + if len(result.Reclaimed) != 1 { + t.Fatalf("Reclaimed = %+v, want exactly %s", result.Reclaimed, id) + } + got := result.Reclaimed[0] + if got.ID != id || got.PreviousOwner != leaseReclaimerHolder { + t.Fatalf("Reclaimed[0] = %+v, want {ID:%s PreviousOwner:%s}", got, id, leaseReclaimerHolder) + } + + if status := leaseReclaimerScalar[string](t, ctx, fixture, "SELECT status FROM issues WHERE id = ?", id); status != string(types.StatusOpen) { + t.Fatalf("status after reclaim = %q, want %q", status, types.StatusOpen) + } + if held := leaseReclaimerScalar[int](t, ctx, fixture, + "SELECT COUNT(*) FROM issues WHERE id = ? AND (COALESCE(assignee, '') <> '' OR started_at IS NOT NULL)", id); held != 0 { + t.Fatal("reclaim left the assignee or started_at set; the row is still held by a dead worker") + } + if leases := leaseReclaimerScalar[int](t, ctx, fixture, "SELECT COUNT(*) FROM leases WHERE issue_id = ?", id); leases != 0 { + t.Fatalf("lease rows after reclaim = %d, want 0", leases) + } + stored := leaseReclaimerScalar[int64](t, ctx, fixture, "SELECT row_lock FROM issues WHERE id = ?", id) + if got.Revision != types.RevisionToken(stored) { + t.Fatalf("Reclaimed[0].Revision = %q, want the row's own token %q", got.Revision, types.RevisionToken(stored)) + } +} + +// RunLeaseReclaimerMintsARevisionThatFencesTheFormerHolder is the reason the +// revision is minted at all (LeaseReclaimer: "a racing holder's guarded write +// fails with ErrVersionMismatch"). A worker that lost its lease and wakes up +// holding the token its claim handed it must NOT be able to land a guarded +// write over the issue another worker may already have taken; the token the +// reclaim reported, and only it, lands. +func RunLeaseReclaimerMintsARevisionThatFencesTheFormerHolder(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + requireLeaseReclaimerExec(t, fixture) + if fixture.Lifecycle == nil { + t.Skip("LeaseReclaimerFixture.Lifecycle is nil: this backend cannot race a guarded write against the reclaim") + } + id := fixture.IssuePrefix + "-fence" + claimed := leaseReclaimerSeedStale(t, ctx, fixture, leaseReclaimerHolder, id)[id] + + result := leaseReclaim(t, ctx, fixture, publicops.ReclaimRequest{ + Actor: leaseReclaimerReaper, + Filter: publicops.ReclaimFilter{IDs: []string{id}}, + }) + if len(result.Reclaimed) != 1 { + t.Fatalf("Reclaimed = %+v, want exactly %s", result.Reclaimed, id) + } + minted, err := types.ParseRevisionToken(result.Reclaimed[0].Revision) + if err != nil { + t.Fatalf("Reclaimed[0].Revision %q is not a revision token: %v", result.Reclaimed[0].Revision, err) + } + if minted == claimed { + t.Fatalf("reclaim reported revision %d, the claim's own token: nothing was minted", minted) + } + + stale := claimed + _, err = fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: leaseReclaimerHolder, IssueID: id, ExpectedVersion: &stale, + Patch: publicops.IssuePatch{Notes: publicops.Field[string]{Set: true, Value: "late write"}}, + }) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("guarded write with the pre-reclaim token = %v, want ErrVersionMismatch", err) + } + + fresh := minted + if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: leaseReclaimerReaper, IssueID: id, ExpectedVersion: &fresh, + Patch: publicops.IssuePatch{Notes: publicops.Field[string]{Set: true, Value: "after reclaim"}}, + }); err != nil { + t.Fatalf("guarded write with the token the reclaim reported = %v, want it to land", err) + } +} + +// RunLeaseReclaimerLeavesALiveLeaseAlone pins staleness as the gate: a lease +// that has not expired is not eligible, even when its id is named, and naming +// it is not an error (ReclaimRequest.Filter: "FILTER.IDS IS NOT AN ERROR WHEN +// IT NAMES A NON-STALE OR UNKNOWN ISSUE"). +func RunLeaseReclaimerLeavesALiveLeaseAlone(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + requireLeaseReclaimerExec(t, fixture) + id := fixture.IssuePrefix + "-live" + leaseReclaimerSeedClaimed(t, ctx, fixture, leaseReclaimerHolder, id) + + result := leaseReclaim(t, ctx, fixture, publicops.ReclaimRequest{ + Actor: leaseReclaimerReaper, + Filter: publicops.ReclaimFilter{IDs: []string{id}}, + }) + if len(result.Reclaimed) != 0 { + t.Fatalf("Reclaimed = %+v, want nothing: the lease has not expired", result.Reclaimed) + } + leaseReclaimerRequireHeld(t, ctx, fixture, id) +} + +// RunLeaseReclaimerHonorsTheGraceWindow pins ReclaimRequest.OlderThan: a lease +// expired less than OlderThan ago is left alone, and the same lease is +// reclaimed once the window is narrower than its age. +func RunLeaseReclaimerHonorsTheGraceWindow(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + requireLeaseReclaimerExec(t, fixture) + id := fixture.IssuePrefix + "-grace" + leaseReclaimerSeedClaimed(t, ctx, fixture, leaseReclaimerHolder, id) + leaseReclaimerAge(t, ctx, fixture, 10*time.Minute, id) + + request := publicops.ReclaimRequest{ + Actor: leaseReclaimerReaper, + OlderThan: time.Hour, + Filter: publicops.ReclaimFilter{IDs: []string{id}}, + } + if result := leaseReclaim(t, ctx, fixture, request); len(result.Reclaimed) != 0 { + t.Fatalf("OlderThan 1h over a lease 10m stale: Reclaimed = %+v, want nothing", result.Reclaimed) + } + leaseReclaimerRequireHeld(t, ctx, fixture, id) + + request.OlderThan = time.Minute + if got := leaseReclaimerIDs(leaseReclaim(t, ctx, fixture, request)); !slices.Equal(got, []string{id}) { + t.Fatalf("OlderThan 1m over a lease 10m stale: Reclaimed = %v, want [%s]", got, id) + } +} + +// RunLeaseReclaimerScopesToTheNamedIDs pins the IDs scope from both sides: an +// id that is not named is never reverted though it is stale, and an id that is +// named but absent or live is simply missing from Reclaimed — the call does +// not fail and does not report it. +func RunLeaseReclaimerScopesToTheNamedIDs(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + requireLeaseReclaimerExec(t, fixture) + named := fixture.IssuePrefix + "-scope-named" + unnamed := fixture.IssuePrefix + "-scope-unnamed" + live := fixture.IssuePrefix + "-scope-live" + ghost := fixture.IssuePrefix + "-scope-ghost" + leaseReclaimerSeedStale(t, ctx, fixture, leaseReclaimerHolder, named, unnamed) + leaseReclaimerSeedClaimed(t, ctx, fixture, leaseReclaimerHolder, live) + + result := leaseReclaim(t, ctx, fixture, publicops.ReclaimRequest{ + Actor: leaseReclaimerReaper, + Filter: publicops.ReclaimFilter{IDs: []string{ghost, live, named}}, + }) + if got := leaseReclaimerIDs(result); !slices.Equal(got, []string{named}) { + t.Fatalf("Reclaimed = %v, want [%s]: only the named stale lease", got, named) + } + leaseReclaimerRequireHeld(t, ctx, fixture, unnamed) + leaseReclaimerRequireHeld(t, ctx, fixture, live) +} + +// RunLeaseReclaimerAnswersAnAbsentIDWithAnEmptyResult pins the empty answer: +// a sweep scoped only to ids that name no row is not a refusal, and its +// Reclaimed is empty and NON-NIL (ReclaimResult.Reclaimed: "Never nil for a +// successful call"). +func RunLeaseReclaimerAnswersAnAbsentIDWithAnEmptyResult(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + result, err := fixture.LeaseReclaimer.Reclaim(ctx, publicops.ReclaimRequest{ + Actor: leaseReclaimerReaper, + Filter: publicops.ReclaimFilter{IDs: []string{fixture.IssuePrefix + "-absent-a", fixture.IssuePrefix + "-absent-b"}}, + }) + if err != nil { + t.Fatalf("Reclaim scoped to absent ids = %v, want an empty answer", err) + } + if result.Reclaimed == nil { + t.Fatal("Reclaimed is nil; the role promises an empty, non-nil slice") + } + if len(result.Reclaimed) != 0 { + t.Fatalf("Reclaimed = %+v, want nothing", result.Reclaimed) + } +} + +// RunLeaseReclaimerScopesToAssigneesAndLabels re-homes the raw method's scope +// cases (testReclaimScoped) onto the role: assignee, label (AND), label-any +// (OR) and exclude-label each narrow the sweep and never widen it. +func RunLeaseReclaimerScopesToAssigneesAndLabels(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + requireLeaseReclaimerExec(t, fixture) + p := fixture.IssuePrefix + a1, a2, b1, c1 := p+"-lbl-a1", p+"-lbl-a2", p+"-lbl-b1", p+"-lbl-c1" + laneA, laneB, opus := p+"-lane-a", p+"-lane-b", p+"-tier-opus" + workerA, workerB, workerC := p+"-wa", p+"-wb", p+"-wc" + leaseReclaimerSeedStale(t, ctx, fixture, workerA, a1, a2) + leaseReclaimerSeedStale(t, ctx, fixture, workerB, b1) + leaseReclaimerSeedStale(t, ctx, fixture, workerC, c1) + leaseReclaimerLabel(t, ctx, fixture, a1, laneA) + leaseReclaimerLabel(t, ctx, fixture, a2, laneA) + leaseReclaimerLabel(t, ctx, fixture, a2, opus) + leaseReclaimerLabel(t, ctx, fixture, b1, laneB) + + reclaim := func(filter publicops.ReclaimFilter) []string { + t.Helper() + return leaseReclaimerIDs(leaseReclaim(t, ctx, fixture, publicops.ReclaimRequest{Actor: leaseReclaimerReaper, Filter: filter})) + } + + if got := reclaim(publicops.ReclaimFilter{Labels: []string{laneB}}); !slices.Equal(got, []string{b1}) { + t.Fatalf("reclaim(labels %s) = %v, want [%s]", laneB, got, b1) + } + if got := reclaim(publicops.ReclaimFilter{Assignees: []string{workerC}}); !slices.Equal(got, []string{c1}) { + t.Fatalf("reclaim(assignees %s) = %v, want [%s]", workerC, got, c1) + } + if got := reclaim(publicops.ReclaimFilter{Labels: []string{laneA}, ExcludeLabels: []string{opus}}); !slices.Equal(got, []string{a1}) { + t.Fatalf("reclaim(labels %s, exclude %s) = %v, want [%s]", laneA, opus, got, a1) + } + leaseReclaimerRequireHeld(t, ctx, fixture, a2) + if got := reclaim(publicops.ReclaimFilter{LabelsAny: []string{p + "-lane-z", opus}}); !slices.Equal(got, []string{a2}) { + t.Fatalf("reclaim(labels-any lane-z,%s) = %v, want [%s]", opus, got, a2) + } +} + +// RunLeaseReclaimerAttributesTheRecoveryEvent pins ReclaimRequest.Actor: the +// recovery event each reverted row records names the actor who ran the sweep, +// with the lease's former holder beside it. +func RunLeaseReclaimerAttributesTheRecoveryEvent(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + requireLeaseReclaimerExec(t, fixture) + id := fixture.IssuePrefix + "-event" + leaseReclaimerSeedStale(t, ctx, fixture, leaseReclaimerHolder, id) + leaseReclaim(t, ctx, fixture, publicops.ReclaimRequest{ + Actor: leaseReclaimerReaper, + Filter: publicops.ReclaimFilter{IDs: []string{id}}, + }) + if n := leaseReclaimerScalar[int](t, ctx, fixture, + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND actor = ? AND old_value = ?", + id, string(types.EventLeaseReclaimed), leaseReclaimerReaper, leaseReclaimerHolder); n != 1 { + t.Fatalf("lease_reclaimed events by %s naming %s = %d, want 1", leaseReclaimerReaper, leaseReclaimerHolder, n) + } +} + +// RunLeaseReclaimerFiresOnUpdateOncePerReclaimedRow pins the hook the role +// names (LeaseReclaimer: "ITS HOOK IS on_update, once per reverted row"): each +// reverted row fires on_update exactly once, and a row the sweep did not +// revert — named but live — fires nothing. +func RunLeaseReclaimerFiresOnUpdateOncePerReclaimedRow(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + requireLeaseReclaimerExec(t, fixture) + if fixture.HookedLeaseReclaimer == nil || fixture.FiredUpdates == nil { + t.Skip("LeaseReclaimerFixture.HookedLeaseReclaimer/FiredUpdates is nil: this backend cannot observe its hooks") + } + first := fixture.IssuePrefix + "-hook-a" + second := fixture.IssuePrefix + "-hook-b" + live := fixture.IssuePrefix + "-hook-live" + leaseReclaimerSeedStale(t, ctx, fixture, leaseReclaimerHolder, first, second) + leaseReclaimerSeedClaimed(t, ctx, fixture, leaseReclaimerHolder, live) + before, err := fixture.FiredUpdates(ctx) + if err != nil { + t.Fatalf("FiredUpdates before: %v", err) + } + + result, err := fixture.HookedLeaseReclaimer.Reclaim(ctx, publicops.ReclaimRequest{ + Actor: leaseReclaimerReaper, + Filter: publicops.ReclaimFilter{IDs: []string{first, second, live}}, + }) + if err != nil { + t.Fatalf("hooked Reclaim: %v", err) + } + if got := leaseReclaimerIDs(result); !slices.Equal(got, []string{first, second}) { + t.Fatalf("Reclaimed = %v, want [%s %s]", got, first, second) + } + + after, err := fixture.FiredUpdates(ctx) + if err != nil { + t.Fatalf("FiredUpdates after: %v", err) + } + fired := map[string]int{} + for _, id := range after[len(before):] { + fired[id]++ + } + for _, id := range []string{first, second} { + if fired[id] != 1 { + t.Fatalf("on_update fired %d time(s) for %s, want exactly 1 (fired: %v)", fired[id], id, after[len(before):]) + } + } + if fired[live] != 0 { + t.Fatalf("on_update fired for %s, which the sweep did not revert", live) + } +} + +// RunLeaseReclaimerRefusesAMalformedRequest pins every refusal the role lists, +// each as ErrValidation (the cap as *TooManyReclaimIDsError), and that a +// refusal changes nothing: the stale lease every request names survives all of +// them. +func RunLeaseReclaimerRefusesAMalformedRequest(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + requireLeaseReclaimerExec(t, fixture) + id := fixture.IssuePrefix + "-malformed" + leaseReclaimerSeedStale(t, ctx, fixture, leaseReclaimerHolder, id) + + tooMany := make([]string, publicops.MaxReclaimIDs+1) + for i := range tooMany { + tooMany[i] = id + } + for _, test := range []struct { + name string + request publicops.ReclaimRequest + tooMany bool + }{ + {"an empty actor", publicops.ReclaimRequest{Filter: publicops.ReclaimFilter{IDs: []string{id}}}, false}, + // One past the column every reverted row's recovery event records it + // in: a typed refusal before the sweep, never the backend's own error + // from the first row it would have reverted. + {"an over-long actor", publicops.ReclaimRequest{Actor: strings.Repeat("r", types.MaxFieldLen+1), + Filter: publicops.ReclaimFilter{IDs: []string{id}}}, false}, + {"a negative grace window", publicops.ReclaimRequest{Actor: leaseReclaimerReaper, OlderThan: -time.Second, + Filter: publicops.ReclaimFilter{IDs: []string{id}}}, false}, + {"a blank scoped id", publicops.ReclaimRequest{Actor: leaseReclaimerReaper, + Filter: publicops.ReclaimFilter{IDs: []string{id, ""}}}, false}, + {"more ids than the cap", publicops.ReclaimRequest{Actor: leaseReclaimerReaper, + Filter: publicops.ReclaimFilter{IDs: tooMany}}, true}, + } { + _, err := fixture.LeaseReclaimer.Reclaim(ctx, test.request) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("%s: Reclaim error = %v, want ErrValidation", test.name, err) + } + if test.tooMany { + var capErr *publicops.TooManyReclaimIDsError + if !errors.As(err, &capErr) || capErr.Requested != len(tooMany) || capErr.Cap != publicops.MaxReclaimIDs { + t.Fatalf("%s: Reclaim error = %v, want *TooManyReclaimIDsError{Requested:%d Cap:%d}", + test.name, err, len(tooMany), publicops.MaxReclaimIDs) + } + } + leaseReclaimerRequireHeld(t, ctx, fixture, id) + } +} + +// RunLeaseReclaimerRefusesABlankScopeEntry pins the blank-entry refusal on +// the scopes that are not ids: an empty or all-blank assignee or label is +// ErrValidation as a *ReclaimFieldError naming its field, and changes +// nothing — the stale lease every request names survives. +func RunLeaseReclaimerRefusesABlankScopeEntry(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + requireLeaseReclaimerExec(t, fixture) + id := fixture.IssuePrefix + "-blankscope" + leaseReclaimerSeedStale(t, ctx, fixture, leaseReclaimerHolder, id) + + for _, test := range []struct { + field string + filter publicops.ReclaimFilter + }{ + {publicops.ReclaimFieldAssignees, publicops.ReclaimFilter{IDs: []string{id}, Assignees: []string{leaseReclaimerHolder, " "}}}, + {publicops.ReclaimFieldLabels, publicops.ReclaimFilter{IDs: []string{id}, Labels: []string{""}}}, + {publicops.ReclaimFieldLabelsAny, publicops.ReclaimFilter{IDs: []string{id}, LabelsAny: []string{"\t"}}}, + {publicops.ReclaimFieldExcludeLabels, publicops.ReclaimFilter{IDs: []string{id}, ExcludeLabels: []string{"x", " "}}}, + } { + _, err := fixture.LeaseReclaimer.Reclaim(ctx, publicops.ReclaimRequest{Actor: leaseReclaimerReaper, Filter: test.filter}) + var fieldErr *publicops.ReclaimFieldError + if !errors.Is(err, publicops.ErrValidation) || !errors.As(err, &fieldErr) || fieldErr.Field != test.field { + t.Fatalf("blank %s entry: Reclaim error = %v, want a *ReclaimFieldError naming %s", test.field, err, test.field) + } + leaseReclaimerRequireHeld(t, ctx, fixture, id) + } +} + +// RunLeaseReclaimerAcceptsExactlyTheCap pins the cap's boundary: MaxReclaimIDs +// entries is a request, one more is a refusal (the case above). +func RunLeaseReclaimerAcceptsExactlyTheCap(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + ids := make([]string, publicops.MaxReclaimIDs) + for i := range ids { + ids[i] = fmt.Sprintf("%s-cap-%04d", fixture.IssuePrefix, i) + } + result, err := fixture.LeaseReclaimer.Reclaim(ctx, publicops.ReclaimRequest{ + Actor: leaseReclaimerReaper, Filter: publicops.ReclaimFilter{IDs: ids}, + }) + if err != nil { + t.Fatalf("Reclaim with exactly MaxReclaimIDs ids = %v, want an answer", err) + } + if len(result.Reclaimed) != 0 { + t.Fatalf("Reclaimed = %+v, want nothing: none of the ids exist", result.Reclaimed) + } +} + +// RunLeaseReclaimerDoesNotMutateTheCallerRequest pins the role's "never mutate +// caller-owned request values": the scope slices come back as they were sent. +func RunLeaseReclaimerDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture) { + t.Helper() + requireLeaseReclaimerExec(t, fixture) + id := fixture.IssuePrefix + "-nomut" + leaseReclaimerSeedStale(t, ctx, fixture, leaseReclaimerHolder, id) + ids := []string{fixture.IssuePrefix + "-nomut-ghost", id} + assignees := []string{leaseReclaimerHolder} + request := publicops.ReclaimRequest{ + Actor: leaseReclaimerReaper, + Filter: publicops.ReclaimFilter{IDs: ids, Assignees: assignees}, + } + leaseReclaim(t, ctx, fixture, request) + if !slices.Equal(ids, []string{fixture.IssuePrefix + "-nomut-ghost", id}) || !slices.Equal(assignees, []string{leaseReclaimerHolder}) { + t.Fatalf("Reclaim rewrote the caller's scope: ids=%v assignees=%v", ids, assignees) + } +} + +// NewUpdateHookLog plants an on_update script that appends the id of every +// issue it fires for, and returns the runner a hook-firing chain is built over +// plus a reader for LeaseReclaimerFixture.FiredUpdates. The reader waits for +// in-flight hooks before reading, so it answers for every hook already fired. +// +// It answers (nil, nil) where a shell hook cannot run, so a fixture built from +// it leaves the hook case to skip rather than fail. +func NewUpdateHookLog(t *testing.T) (*hooks.Runner, func(context.Context) ([]string, error)) { + t.Helper() + if runtime.GOOS == "windows" { + return nil, nil + } + dir := t.TempDir() + log := filepath.Join(t.TempDir(), "on_update.log") + script := "#!/bin/sh\necho \"$1\" >> " + log + "\n" + if err := os.WriteFile(filepath.Join(dir, "on_update"), []byte(script), 0o755); err != nil { //nolint:gosec // G306: a hook must be executable to run at all + t.Fatalf("plant the on_update hook: %v", err) + } + runner := hooks.NewRunner(dir) + return runner, func(context.Context) ([]string, error) { + if !runner.Wait(30 * time.Second) { + return nil, errors.New("on_update hooks still running after 30s") + } + data, err := os.ReadFile(log) // #nosec G304 -- this helper's own temp file + if errors.Is(err, os.ErrNotExist) { + return []string{}, nil + } + if err != nil { + return nil, err + } + var ids []string + for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") { + if line = strings.TrimSpace(line); line != "" { + ids = append(ids, line) + } + } + return ids, nil + } +} + +func requireLeaseReclaimerExec(t *testing.T, fixture LeaseReclaimerFixture) { + t.Helper() + if fixture.Exec == nil || fixture.Claimer == nil || fixture.QueryScalar == nil { + t.Skip("LeaseReclaimerFixture.Exec/Claimer/QueryScalar is nil: this backend cannot manufacture a stale lease") + } +} + +// leaseReclaimerSeedClaimed creates each id and claims it as holder through the +// leg's Claimer, answering each claim's row version. +func leaseReclaimerSeedClaimed(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture, holder string, ids ...string) map[string]int64 { + t.Helper() + versions := map[string]int64{} + for _, id := range ids { + if err := fixture.CreateIssue(ctx, &types.Issue{ + ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + }, "seed"); err != nil { + t.Fatalf("seed %s: %v", id, err) + } + claimed, err := fixture.Claimer.Claim(ctx, publicops.ClaimRequest{Actor: holder, IssueID: id}) + if err != nil { + t.Fatalf("claim %s as %s: %v", id, holder, err) + } + if claimed.Issue == nil { + t.Fatalf("claim %s answered no issue", id) + } + versions[id] = claimed.Issue.RowVersion + } + return versions +} + +// leaseReclaimerSeedStale claims each id and ages its lease an hour past +// expiry, far beyond any grace window a case below uses by default. +func leaseReclaimerSeedStale(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture, holder string, ids ...string) map[string]int64 { + t.Helper() + versions := leaseReclaimerSeedClaimed(t, ctx, fixture, holder, ids...) + leaseReclaimerAge(t, ctx, fixture, time.Hour, ids...) + return versions +} + +// leaseReclaimerAge moves each id's lease expiry to age in the past. +func leaseReclaimerAge(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture, age time.Duration, ids ...string) { + t.Helper() + expired := time.Now().UTC().Add(-age) + statements := make([]SQLStatement, 0, len(ids)) + for _, id := range ids { + statements = append(statements, SQLStatement{ + Query: "UPDATE leases SET lease_expires_at = ? WHERE issue_id = ?", + Args: []any{expired, id}, + }) + } + if err := fixture.Exec(ctx, statements); err != nil { + t.Fatalf("age leases %v: %v", ids, err) + } + for _, id := range ids { + if n := leaseReclaimerScalar[int](t, ctx, fixture, "SELECT COUNT(*) FROM leases WHERE issue_id = ?", id); n != 1 { + t.Fatalf("lease rows for %s = %d, want 1: the claim wrote no lease to reclaim", id, n) + } + } +} + +func leaseReclaimerLabel(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture, id, label string) { + t.Helper() + if err := fixture.Exec(ctx, []SQLStatement{{ + Query: "INSERT INTO labels (issue_id, label) VALUES (?, ?)", + Args: []any{id, label}, + }}); err != nil { + t.Fatalf("label %s %s: %v", id, label, err) + } +} + +func leaseReclaimerRequireHeld(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture, id string) { + t.Helper() + if status := leaseReclaimerScalar[string](t, ctx, fixture, "SELECT status FROM issues WHERE id = ?", id); status != string(types.StatusInProgress) { + t.Fatalf("%s status = %q, want it still %q", id, status, types.StatusInProgress) + } +} + +func leaseReclaim(t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture, request publicops.ReclaimRequest) publicops.ReclaimResult { + t.Helper() + result, err := fixture.LeaseReclaimer.Reclaim(ctx, request) + if err != nil { + t.Fatalf("Reclaim(%+v): %v", request.Filter, err) + } + if result.Reclaimed == nil { + t.Fatal("Reclaimed is nil; the role promises a non-nil slice for a successful call") + } + return result +} + +func leaseReclaimerIDs(result publicops.ReclaimResult) []string { + ids := make([]string, 0, len(result.Reclaimed)) + for _, r := range result.Reclaimed { + ids = append(ids, r.ID) + } + sort.Strings(ids) + return ids +} + +func leaseReclaimerScalar[T any](t *testing.T, ctx context.Context, fixture LeaseReclaimerFixture, query string, args ...any) T { + t.Helper() + var value T + if err := fixture.QueryScalar(ctx, query, args, &value); err != nil { + t.Fatalf("%s %v: %v", query, args, err) + } + return value +} diff --git a/backend/conformance/lifecycle_close_reopen_contract.go b/backend/conformance/lifecycle_close_reopen_contract.go index ca40fe53a..c11556181 100644 --- a/backend/conformance/lifecycle_close_reopen_contract.go +++ b/backend/conformance/lifecycle_close_reopen_contract.go @@ -846,11 +846,12 @@ func RunLifecycleCloseAndReopenSpanTheConfiguredDoneCategory(t *testing.T, ctx c // RunLifecycleExpectedVersionIsCheckedBeforeTheNoOps pins the ORDERING clause // both requests spell out. CloseRequest.ExpectedVersion "requires the current -// row version to match and is checked before an idempotent close" -// (issueops/issueops.go:295-300); ReopenRequest.ExpectedVersion is "checked -// before a non-done no-op" (:272-275); and Close's own doc adds "ExpectedVersion +// row version to match, and is checked BEFORE the idempotent close" +// (issueops/issueops.go:362-373); ReopenRequest.ExpectedVersion is "checked +// before a non-done no-op" (:390-391); and Close's own doc adds "ExpectedVersion // is checked first, including for an idempotent close", with Force bypassing -// "blocker and open-child policy" and nothing else (:364-365). +// "the pin, the assignee fence, and blocker and open-child policy" and nothing +// else (:485-498). // // The dangerous shape is not a stale version on a live mutation — it is a stale // version on the request that would have done nothing anyway. An implementation @@ -1092,6 +1093,87 @@ func RunLifecycleResultsAreHydratedPostStateSnapshots(t *testing.T, ctx context. lifecycleCloseReopenAssertSnapshot(t, "reopen result", reopened.Issue, peer) } +// RunLifecycleResultsCarryThePostWriteRowVersion pins that every write this +// role owns — Update, Close and Reopen — hands back a result whose +// Issue.RowVersion is the row's REAL post-write optimistic-concurrency token, +// not a zero value. types.Issue.RowVersion is `json:"-"`: an implementation +// that forgot to populate it on the way back from its own storage would still +// compile and would still pass every content assertion elsewhere in this +// file, because none of them read RowVersion. +// +// The assertion is a CHAIN rather than three independent zero-checks, because +// a zero-check alone cannot tell a dropped token from a WRONG one (an +// implementation could answer a nonzero constant, or the PRE-write version, +// and still clear it). Each step feeds the token the previous write answered +// with straight into the next write's ExpectedVersion, with no intervening +// read: the claim's token guards the Notes update, Update's token guards +// Close, and Close's token guards Reopen. A guard only passes if the token it +// was given equals the row's actual current version at the instant the next +// write runs, so a wrong or stale token fails closed — the next write +// refuses with ErrVersionMismatch — rather than silently succeeding. Any one +// dropped member breaks the chain at that link. +// +// The chain's first link is a CLAIM-ONLY request (Claim: true, no Patch), +// deliberately unguarded (UpdateRequest.Claim forbids combining Claim with +// ExpectedVersion — see issueops.UpdateRequest's doc): a backend that answers +// Lifecycle.Update's generic patch wire but special-cases a bare claim onto a +// different internal path (the http leg once dialed the Claimer role directly +// for one; it now folds the claim into updateIssue, keeping claimIssue only as +// the fallback for a server that predates updateIssue's `claim` member) could +// easily populate RowVersion on one path and not the other; this exercises +// the claim-only shape specifically, not just the Patch shape the rest of the +// chain already covered. +func RunLifecycleResultsCarryThePostWriteRowVersion(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-lcr-rowversion" + lifecycleCloseReopenSeedIssue(t, ctx, fixture, id, types.StatusOpen, nil) + + claimed, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", IssueID: id, Claim: true, + }) + if err != nil { + t.Fatalf("claim %s: %v", id, err) + } + if claimed.Issue == nil || claimed.Issue.RowVersion == 0 { + t.Fatalf("claim result RowVersion = %+v, want a nonzero post-write token", claimed.Issue) + } + claimVersion := claimed.Issue.RowVersion + + updated, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", IssueID: id, ExpectedVersion: &claimVersion, + Patch: publicops.IssuePatch{Notes: publicops.Field[string]{Set: true, Value: "rowversion chain"}}, + }) + if err != nil { + t.Fatalf("update %s guarded by the claim's own token: %v — the claim result's RowVersion was not the row's real current version", id, err) + } + if updated.Issue == nil || updated.Issue.RowVersion == 0 { + t.Fatalf("update result RowVersion = %+v, want a nonzero post-write token", updated.Issue) + } + updateVersion := updated.Issue.RowVersion + + closed, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{ + Actor: "writer", IssueID: id, ExpectedVersion: &updateVersion, + }) + if err != nil { + t.Fatalf("close %s guarded by the update's own token: %v — the update result's RowVersion was not the row's real current version", id, err) + } + if closed.Issue == nil || closed.Issue.RowVersion == 0 { + t.Fatalf("close result RowVersion = %+v, want a nonzero post-write token", closed.Issue) + } + closeVersion := closed.Issue.RowVersion + + reopened, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{ + Actor: "writer", IssueID: id, ExpectedVersion: &closeVersion, + }) + if err != nil { + t.Fatalf("reopen %s guarded by the close's own token: %v — the close result's RowVersion was not the row's real current version", id, err) + } + if reopened.Issue == nil || reopened.Issue.RowVersion == 0 { + t.Fatalf("reopen result RowVersion = %+v, want a nonzero post-write token", reopened.Issue) + } +} + // RunLifecycleCloseAndReopenRequireActorAndIssueID pins the deterministic // validation floor both verbs sit on. The Lifecycle doc states "Deterministic // request validation failures match ErrValidation" and "Refusals and @@ -1302,13 +1384,14 @@ func RunLifecycleCloseSettlesItsTransitiveAndCrossPlaneDependers(t *testing.T, c // RunLifecycleCloseAdmitsATransitivelyBlockedTarget uses clears the first and // not the second, and closing the child to clear the second would take the // second subject with it, since a closed row cannot be blocked and so has -// nothing left to flip. Force waives close policy and nothing else — -// CloseRequest.Force "bypasses only blocker and open-child close policy" and -// "never bypasses validation, ExpectedVersion, or lifecycle rules" -// (issueops/issueops.go:310-311) — so it is the shape that keeps both subjects -// observable, and it is not exotic: it is the same forced close of a -// blocked issue that RunLifecycleCloseIsIdempotentOnAClosedRowThatStillLooksBlocked -// is built on. +// nothing left to flip. Force waives close policy, the pin and the assignee +// fence, and nothing else — CloseRequest.Force "bypasses blocker and +// open-child close policy and the two close guards a force has always waived +// in bd" and "never bypasses the template guard, validation, ExpectedVersion, +// or lifecycle rules" (issueops/issueops.go:357-360) — so it is the shape that +// keeps both subjects observable, and it is not exotic: it is the same forced +// close of a blocked issue that +// RunLifecycleCloseIsIdempotentOnAClosedRowThatStillLooksBlocked is built on. // // All three legs reach ONE body here (internal/storage/issueops.closeIssueInTx), // so this is a wrapper and engine check rather than a third vote, exactly as @@ -1741,3 +1824,175 @@ func (c *lifecycleCloseReopenEventCounter) assertNoneAdded(t *testing.T, label s } c.total = total } + +// RunLifecycleCloseEnforcesTheCloseGuards pins the three close guards +// issueops.Lifecycle.Close states before close policy — template read-only, +// the pin, and the assignee authority fence (be-035) — on the role itself, so +// every caller of it is held to them and not only `bd close`, which used to +// apply them as a CLI pre-read the served and library routes skipped. +// +// Each refusal is asserted at the level a caller acts on: the typed error with +// its fields, its sentinel, and the sentence bd prints — read off the typed +// error, because a served refusal wraps it in the problem envelope — plus the +// row and the event stream left untouched. Force is asserted as the bypass for +// exactly the two guards it has always waived, and NOT for the template. +// +// The controls are load-bearing too: an unassigned issue and one held by the +// closing actor under a different spelling both close unforced, so a guard +// that refused every assigned row, or compared verbatim, fails here. A wisp +// case proves the guard reads the plane the close writes. A pinned issue with +// an open child reads the PIN's refusal, pinning the order (guards before +// policy). And a forced close of a boolean-pinned issue leaves the pin set, so +// the plain retry must stay the idempotent no-op (ga-ktn9pe.4.8) rather than +// refuse on the residue. +func RunLifecycleCloseEnforcesTheCloseGuards(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + template := fixture.IssuePrefix + "-lcg-template" + statusPinned := fixture.IssuePrefix + "-lcg-status-pinned" + flagPinned := fixture.IssuePrefix + "-lcg-flag-pinned" + held := fixture.IssuePrefix + "-lcg-held" + respelled := fixture.IssuePrefix + "-lcg-respelled" + unassigned := fixture.IssuePrefix + "-lcg-unassigned" + pinnedParent := fixture.IssuePrefix + "-lcg-pinned-parent" + pinnedChild := fixture.IssuePrefix + "-lcg-pinned-child" + wisp := fixture.IssuePrefix + "-lcg-wisp-held" + + seed := func(issue *types.Issue) { + t.Helper() + issue.Title, issue.Priority, issue.IssueType = issue.ID, 2, types.TypeTask + if issue.Status == "" { + issue.Status = types.StatusOpen + } + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", issue.ID, err) + } + } + seed(&types.Issue{ID: template, IsTemplate: true}) + seed(&types.Issue{ID: statusPinned, Status: types.StatusPinned}) + seed(&types.Issue{ID: flagPinned, Pinned: true}) + seed(&types.Issue{ID: held, Assignee: "holder"}) + seed(&types.Issue{ID: respelled, Assignee: "gastown.closer"}) + seed(&types.Issue{ID: unassigned}) + seed(&types.Issue{ID: pinnedParent, Pinned: true}) + seed(&types.Issue{ID: pinnedChild}) + lifecycleCloseReopenSeedEdge(t, ctx, fixture, pinnedChild, pinnedParent, types.DepParentChild) + + refuses := func(id string, force bool, label string, check func(error)) { + t.Helper() + before := lifecycleCloseReopenReadRow(t, ctx, fixture, id) + events := newLifecycleCloseReopenEventCounter(t, ctx, fixture, id) + _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "closer", IssueID: id, Force: force}) + check(err) + lifecycleCloseReopenAssertRow(t, ctx, fixture, id, "after the "+label+" refusal", before) + events.assertNoneAdded(t, label+" refusal") + } + + // The template refuses, forced or not: no flag waives read-only. + for _, force := range []bool{false, true} { + refuses(template, force, "template", func(err error) { + var refusal *publicops.TemplateReadOnlyError + if !errors.As(err, &refusal) { + t.Fatalf("close of template %s (force=%v): err = %v, want *TemplateReadOnlyError", template, force, err) + } + if refusal.IssueID != template || !errors.Is(err, publicops.ErrTemplateReadOnly) { + t.Errorf("template refusal = %#v (%v), want IssueID %q matching ErrTemplateReadOnly", refusal, err, template) + } + want := "cannot modify template " + template + ": templates are read-only; use 'bd mol pour' to create a work item" + if refusal.Error() != want { + t.Errorf("template refusal reads %q, want %q", refusal.Error(), want) + } + }) + } + + // Both pin spellings refuse unforced (ga-z3vht). + for _, id := range []string{statusPinned, flagPinned} { + refuses(id, false, "pin", func(err error) { + var refusal *publicops.PinnedError + if !errors.As(err, &refusal) { + t.Fatalf("unforced close of pinned %s: err = %v, want *PinnedError", id, err) + } + if refusal.IssueID != id || !errors.Is(err, publicops.ErrPinned) { + t.Errorf("pin refusal = %#v (%v), want IssueID %q matching ErrPinned", refusal, err, id) + } + if want := "cannot modify pinned issue " + id + " (use --force to override)"; refusal.Error() != want { + t.Errorf("pin refusal reads %q, want %q", refusal.Error(), want) + } + }) + } + + // Another actor's bead refuses unforced, naming holder and actor. + refuses(held, false, "assignee", func(err error) { + var refusal *publicops.CloseNotAssigneeError + if !errors.As(err, &refusal) { + t.Fatalf("unforced close of %s held by another actor: err = %v, want *CloseNotAssigneeError", held, err) + } + if refusal.IssueID != held || refusal.Assignee != "holder" || refusal.Actor != "closer" { + t.Errorf("assignee refusal = %#v, want IssueID %q, Assignee holder, Actor closer", refusal, held) + } + if !errors.Is(err, publicops.ErrNotOwner) { + t.Errorf("assignee refusal %v does not match ErrNotOwner", err) + } + if want := `cannot close ` + held + `: assignee is "holder", actor is "closer"; reclaim or use --force to override`; refusal.Error() != want { + t.Errorf("assignee refusal reads %q, want %q", refusal.Error(), want) + } + }) + + // The guard runs before close policy: a pinned parent with an open child + // reads the pin, not the open children. + refuses(pinnedParent, false, "pin-before-policy", func(err error) { + if !errors.Is(err, publicops.ErrPinned) { + t.Fatalf("unforced close of pinned parent %s with an open child: err = %v, want ErrPinned first", pinnedParent, err) + } + }) + + // The controls: an unassigned bead and the actor's own bead under another + // spelling of its identity close unforced. + for _, tc := range []struct{ id, actor string }{{unassigned, "closer"}, {respelled, "gastown_closer"}} { + result, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: tc.actor, IssueID: tc.id}) + if err != nil { + t.Fatalf("unforced close of %s by %s: %v, want it to land", tc.id, tc.actor, err) + } + if !result.Changed || result.Issue.Status != types.StatusClosed { + t.Errorf("unforced close of %s = %#v, want a committed close", tc.id, result) + } + } + + // Force bypasses the pin and the assignee fence. + for _, id := range []string{statusPinned, flagPinned, held} { + result, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "closer", IssueID: id, Force: true}) + if err != nil { + t.Fatalf("forced close of %s: %v, want force to bypass the guard", id, err) + } + if !result.Changed || result.Issue.Status != types.StatusClosed { + t.Errorf("forced close of %s = %#v, want a committed close", id, result) + } + } + + // The forced close left pinned=true on the flag-pinned row; the plain retry + // is the idempotent re-close, not a pin refusal. + retry, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "closer", IssueID: flagPinned}) + if err != nil { + t.Fatalf("plain re-close of the already-closed, still-pinned %s: %v, want the idempotent no-op", flagPinned, err) + } + if retry.Changed { + t.Errorf("plain re-close of %s reported Changed = true, want the no-op", flagPinned) + } + + // The guard reads the plane the close writes. + if err := fixture.CreateWisp(ctx, &types.Issue{ + ID: wisp, Title: wisp, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Assignee: "holder", Ephemeral: true, + }, "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", wisp, err) + } + if _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "closer", IssueID: wisp}); !errors.As(err, new(*publicops.CloseNotAssigneeError)) { + t.Fatalf("unforced close of wisp %s held by another actor: err = %v, want *CloseNotAssigneeError", wisp, err) + } + var status string + if err := fixture.QueryScalar(ctx, "SELECT status FROM wisps WHERE id = ?", []any{wisp}, &status); err != nil { + t.Fatalf("read wisp %s status: %v", wisp, err) + } + if types.Status(status) != types.StatusOpen { + t.Errorf("wisp %s status after the refusal = %q, want it still open", wisp, status) + } +} diff --git a/backend/conformance/lifecycle_create_contract.go b/backend/conformance/lifecycle_create_contract.go index ca906424a..5d728a6c8 100644 --- a/backend/conformance/lifecycle_create_contract.go +++ b/backend/conformance/lifecycle_create_contract.go @@ -490,6 +490,12 @@ func RunLifecycleCreateWritesEveryScalarField(t *testing.T, ctx context.Context, t.Errorf("%s created_at = %v after a create that named none, want a stamp between %v and %v — a bare non-empty check would accept the zero time", stamped, autoStamp, lower, upper) } + // And no created_by: the request's actor is the creator (CreateRequest.Issue), + // stamped by the role itself, so a library caller and every front door store + // the same value for the same request. + if got := lifecycleCreateRow(t, ctx, fixture, stamped).CreatedBy; got != "writer" { + t.Errorf("%s created_by = %q after a create that named none, want the request's actor %q", stamped, got, "writer") + } want := []lifecycleCreateMember{ {"title", "created title"}, @@ -804,3 +810,54 @@ func lifecycleCreatePlaneName(ephemeral bool) string { } return "durable" } + +// RunLifecycleCreateAppliesTheDefaultPriority pins +// CreateRequest.DefaultPriority: a create that asks for the default stores +// publicops.DefaultCreatePriority, and one that names priority 0 stores P0 — +// the zero value is a real priority, never "absent". Asking for the default +// while naming a priority is ErrValidation and writes nothing. +// +// It is the one place the default lives: `bd create` without --priority and an +// HTTP create without `priority` both reach it through this flag, so a backend +// that dropped it would store P0 (critical) for every such create. +func RunLifecycleCreateAppliesTheDefaultPriority(t *testing.T, ctx context.Context, fixture LifecycleCreateFixture) { + t.Helper() + defaulted := fixture.IssuePrefix + "-prio-default" + critical := fixture.IssuePrefix + "-prio-zero" + conflict := fixture.IssuePrefix + "-prio-conflict" + + for _, tc := range []struct { + id string + priority int + useDefault bool + want int + }{ + {id: defaulted, useDefault: true, want: publicops.DefaultCreatePriority}, + {id: critical, priority: 0, want: 0}, + } { + created, err := fixture.Lifecycle.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + DefaultPriority: tc.useDefault, + Issue: &types.Issue{ID: tc.id, Title: tc.id, Priority: tc.priority, IssueType: types.TypeTask}, + }) + if err != nil { + t.Fatalf("create %s: %v", tc.id, err) + } + if created.Issue.Priority != tc.want { + t.Errorf("create %s result priority = %d, want %d", tc.id, created.Issue.Priority, tc.want) + } + if got := lifecycleCreateRow(t, ctx, fixture, tc.id).Priority; got != tc.want { + t.Errorf("stored %s priority = %d, want %d", tc.id, got, tc.want) + } + } + + _, err := fixture.Lifecycle.Create(ctx, publicops.CreateRequest{ + Actor: "writer", + DefaultPriority: true, + Issue: &types.Issue{ID: conflict, Title: conflict, Priority: 3, IssueType: types.TypeTask}, + }) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("DefaultPriority with priority 3: err = %v, want ErrValidation", err) + } + assertLifecycleCreateAbsent(t, ctx, fixture, conflict, "after the conflicting priority create") +} diff --git a/backend/conformance/lifecycle_create_gate_contract.go b/backend/conformance/lifecycle_create_gate_contract.go new file mode 100644 index 000000000..4f5c22d30 --- /dev/null +++ b/backend/conformance/lifecycle_create_gate_contract.go @@ -0,0 +1,170 @@ +package conformance + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file and its two siblings (lifecycle_update_gate_contract.go, +// batch_apply_gate_contract.go) hold the gate-member clauses of Lifecycle.Create, +// Lifecycle.Update and BatchApplier: await_type, await_id, timeout and waiters +// on a create, await_id and waiters on a patch, and the one set of bounds every +// route refuses with a *publicops.GateFieldError. +// +// THE BOUNDS ARE THE COLUMNS', and the boundary is asserted from both sides: a +// value AT the bound lands whole, a value one past it is refused naming its +// member and writes nothing. await_type is VARCHAR(32) and await_id +// VARCHAR(255), both counted in characters, so each at-bound value is +// multi-byte — a byte count would refuse it. waiters is a TEXT column holding +// a JSON array, bounded in BYTES. A negative timeout is the one refusal that is +// not a width. +// +// NOTHING ELSE IS A RULE, and two cases say so: a gate member lands on an +// issue of any type (local `bd update --await-id` has always worked on any +// row), and waiters are stored as given, duplicates included (deduplication is +// the CLI's). A backend that grew a stricter rule fails here. + +// gateFieldAtBoundAwaitType is a 32-character, 64-byte await_type. +var gateFieldAtBoundAwaitType = strings.Repeat("é", 32) + +// gateFieldAtBoundAwaitID is a 255-character, 510-byte await_id. +var gateFieldAtBoundAwaitID = strings.Repeat("é", types.MaxFieldLen) + +// gateFieldAtBoundWaiters is one waiter whose JSON array encoding is exactly +// types.MaxTextBytes bytes: the entry plus `["` and `"]`. +func gateFieldAtBoundWaiters() []string { + return []string{strings.Repeat("w", types.MaxTextBytes-4)} +} + +// gateFieldOverBoundWaiters encodes to one byte past the TEXT column. +func gateFieldOverBoundWaiters() []string { + return []string{strings.Repeat("w", types.MaxTextBytes-3)} +} + +// assertGateFieldError checks err is ErrValidation carried by a +// *publicops.GateFieldError naming field. +func assertGateFieldError(t *testing.T, err error, label, field string) { + t.Helper() + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("%s: error = %v, want ErrValidation", label, err) + } + var fieldErr *publicops.GateFieldError + if !errors.As(err, &fieldErr) { + t.Fatalf("%s: error = %v, want a *GateFieldError naming %s", label, err, field) + } + if fieldErr.Field != field { + t.Errorf("%s: GateFieldError.Field = %q, want %q", label, fieldErr.Field, field) + } +} + +// gateMembers renders the four gate members off an issue for comparison. +func gateMembers(issue *types.Issue) string { + waiters := issue.Waiters + if len(waiters) == 0 { + waiters = nil + } + return fmt.Sprintf("await_type=%q await_id=%q timeout=%s waiters=%q", issue.AwaitType, issue.AwaitID, issue.Timeout, waiters) +} + +func assertGateMembers(t *testing.T, id, label string, issue *types.Issue, awaitType, awaitID string, timeout time.Duration, waiters []string) { + t.Helper() + if issue == nil { + t.Fatalf("%s %s: no issue to read the gate members off", id, label) + } + if len(waiters) == 0 { + waiters = nil + } + want := fmt.Sprintf("await_type=%q await_id=%q timeout=%s waiters=%q", awaitType, awaitID, timeout, waiters) + if got := gateMembers(issue); got != want { + // The at-bound values are long; report sizes rather than the values. + if len(got)+len(want) > 2000 { + t.Errorf("%s %s gate members differ (got %d bytes, want %d bytes; await_type %d/%d runes, await_id %d/%d runes, waiters %d/%d entries)", + id, label, len(got), len(want), + len([]rune(issue.AwaitType)), len([]rune(awaitType)), len([]rune(issue.AwaitID)), len([]rune(awaitID)), + len(issue.Waiters), len(waiters)) + return + } + t.Errorf("%s %s gate members = %s, want %s", id, label, got, want) + } +} + +// RunLifecycleCreateWritesTheGateMembers pins that Lifecycle.Create stores all +// four gate members (CreateRequest.Issue's "gate" fields) on the row and +// answers them on the result, with the waiter list stored as given, duplicate +// included, and on an issue that is not of the gate type. +func RunLifecycleCreateWritesTheGateMembers(t *testing.T, ctx context.Context, fixture LifecycleCreateFixture) { + t.Helper() + + gate := fixture.IssuePrefix + "-lcg-gate" + issue := lifecycleCreateIssue(gate) + issue.IssueType = types.TypeGate + issue.AwaitType = "gh:run" + issue.AwaitID = "12345" + issue.Timeout = 90 * time.Minute + issue.Waiters = []string{"rig/workers/a", "rig/workers/b", "rig/workers/a"} + created, err := fixture.Lifecycle.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: issue}) + if err != nil { + t.Fatalf("create gate %s: %v", gate, err) + } + want := []string{"rig/workers/a", "rig/workers/b", "rig/workers/a"} + assertGateMembers(t, gate, "in the create result", created.Issue, "gh:run", "12345", 90*time.Minute, want) + assertGateMembers(t, gate, "in the stored row", lifecycleCreateRow(t, ctx, fixture, gate), "gh:run", "12345", 90*time.Minute, want) + + // Any type carries them: no gate-type-only rule. + task := fixture.IssuePrefix + "-lcg-task" + carrier := lifecycleCreateIssue(task) + carrier.AwaitType = "formula-defined" + carrier.AwaitID = "bead:" + gate + carrier.Waiters = []string{"mail:someone"} + if _, err := fixture.Lifecycle.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: carrier}); err != nil { + t.Fatalf("create task %s carrying gate members: %v", task, err) + } + assertGateMembers(t, task, "in the stored row", lifecycleCreateRow(t, ctx, fixture, task), "formula-defined", "bead:"+gate, 0, []string{"mail:someone"}) +} + +// RunLifecycleCreateBoundsTheGateMembers pins the four GateFieldError bounds +// on create from both sides: each at-bound value lands whole, each value one +// past it is refused as ErrValidation naming its member, and the refused +// create leaves no row. +func RunLifecycleCreateBoundsTheGateMembers(t *testing.T, ctx context.Context, fixture LifecycleCreateFixture) { + t.Helper() + + atBound := fixture.IssuePrefix + "-lcg-atbound" + issue := lifecycleCreateIssue(atBound) + issue.IssueType = types.TypeGate + issue.AwaitType = gateFieldAtBoundAwaitType + issue.AwaitID = gateFieldAtBoundAwaitID + issue.Timeout = 0 + issue.Waiters = gateFieldAtBoundWaiters() + if _, err := fixture.Lifecycle.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: issue}); err != nil { + t.Fatalf("create %s with every gate member at its bound: %v", atBound, err) + } + assertGateMembers(t, atBound, "in the stored row", lifecycleCreateRow(t, ctx, fixture, atBound), + gateFieldAtBoundAwaitType, gateFieldAtBoundAwaitID, 0, gateFieldAtBoundWaiters()) + + for _, test := range []struct { + name string + field string + mutate func(*types.Issue) + }{ + {"await_type", publicops.GateFieldAwaitType, func(i *types.Issue) { i.AwaitType = gateFieldAtBoundAwaitType + "x" }}, + {"await_id", publicops.GateFieldAwaitID, func(i *types.Issue) { i.AwaitID = gateFieldAtBoundAwaitID + "x" }}, + {"timeout", publicops.GateFieldTimeout, func(i *types.Issue) { i.Timeout = -time.Nanosecond }}, + {"waiters", publicops.GateFieldWaiters, func(i *types.Issue) { i.Waiters = gateFieldOverBoundWaiters() }}, + } { + id := fixture.IssuePrefix + "-lcg-over-" + strings.ReplaceAll(test.name, "_", "") + refused := lifecycleCreateIssue(id) + refused.IssueType = types.TypeGate + test.mutate(refused) + _, err := fixture.Lifecycle.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: refused}) + assertGateFieldError(t, err, "create with "+test.name+" past its bound", test.field) + assertLifecycleCreateAbsent(t, ctx, fixture, id, "after the refused "+test.name) + } +} diff --git a/backend/conformance/lifecycle_update_contract.go b/backend/conformance/lifecycle_update_contract.go index 8d7155a3a..ae5e0a420 100644 --- a/backend/conformance/lifecycle_update_contract.go +++ b/backend/conformance/lifecycle_update_contract.go @@ -4,8 +4,11 @@ import ( "context" "encoding/json" "errors" + "fmt" "reflect" + "slices" "sort" + "sync" "testing" "time" @@ -905,6 +908,385 @@ func RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits(t *testing.T, ctx cont maskedEvents.assert(t, "guard masked by the one before it", 0) } +// RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency pins A8's +// (gastownhall/beads#4682) headline claim about Lifecycle.Update's +// ExpectedVersion guard, for `bd update/close/assign/delete --if-revision`: +// the compare and the write are ONE atomic operation, not a read-then-write a +// concurrent writer can slip between (T4.4, BEADS-JOURNAL-PLAN.md Item 4). N +// goroutines race the SAME token — the row's version as of before any of them +// run — against the same row; exactly one may apply it, every other goroutine +// must see ErrVersionMismatch (never a second silent success), and the row +// that is left behind must be exactly the single winner's content, never a +// torn write belonging to neither the seed nor any one racer. +// +// THIS IS A GENUINE CONCURRENCY TEST, not N sequential attempts dressed up as +// parallel ones. cmd/bd's embedded-mode backend admits only one `bd` process +// at a time (an exclusive flock — see acquireEmbeddedLock in +// cmd/bd/store_factory.go), which would make "exactly one winner" trivially +// true even of a buggy read-then-write implementation with no atomicity at +// all, because no second process could ever observe the first one's +// in-flight state. That is why the CLI-level --if-revision tests +// (cmd/bd/if_revision_embedded_test.go) assert the match/mismatch CONTRACT +// sequentially and leave the race to this fixture: goroutines sharing one +// already-open Lifecycle are the one shape in this suite that can actually +// interleave at the transaction level, independent of whatever process-level +// serialization a given CLI backend layers on top. +func RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + + const racers = 16 + + id := fixture.IssuePrefix + "-lup-singlewinner" + seedLifecycleUpdateIssue(t, ctx, fixture, lifecycleUpdateIssue(id)) + + seed := lifecycleUpdateRow(t, ctx, fixture, id) + racedToken := seed.RowVersion + + // Priority is a small enum (0-4, see validation.ValidatePriority); each + // racer's own index would overflow it past four racers, so the index rides + // in Notes instead (free-text, nothing else writes it in this test) and + // priority merely alternates, giving the final-state check two independent + // columns that must agree on which one racer actually landed. + var wg sync.WaitGroup + won := make([]bool, racers) + errs := make([]error, racers) + wg.Add(racers) + for i := 0; i < racers; i++ { + i := i + go func() { + defer wg.Done() + version := racedToken + result, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: "racer", + IssueID: id, + Patch: publicops.IssuePatch{ + Priority: publicops.Field[int]{Set: true, Value: i % 5}, + Notes: publicops.Field[string]{Set: true, Value: fmt.Sprintf("racer-%d", i)}, + }, + ExpectedVersion: &version, + }) + errs[i] = err + won[i] = err == nil && result.Changed + }() + } + wg.Wait() + + winners := 0 + winner := -1 + for i, win := range won { + if win { + winners++ + winner = i + continue + } + if !errors.Is(errs[i], storage.ErrVersionMismatch) { + t.Errorf("racer %d: err = %v, want nil (won) or ErrVersionMismatch (lost the race)", i, errs[i]) + } + } + if winners != 1 { + t.Fatalf("%d racers shared one --if-revision token %d; got %d winners, want exactly 1 (errs=%v)", + racers, racedToken, winners, errs) + } + + final := lifecycleUpdateRow(t, ctx, fixture, id) + wantNotes := fmt.Sprintf("racer-%d", winner) + if final.Notes != wantNotes { + t.Errorf("final notes = %q, want the single winner's %q — a torn or lost write", final.Notes, wantNotes) + } + if final.Priority != winner%5 { + t.Errorf("final priority = %d, want the single winner's %d — a torn or lost write", final.Priority, winner%5) + } + if final.RowVersion == racedToken { + t.Errorf("final row version = %d, want it to have advanced past the raced token %d", final.RowVersion, racedToken) + } +} + +// RunLifecycleUpdateExpectedVersionSingleWinnerWithDisjointColumnsUnderConcurrency +// is RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency's sibling, +// and the reason that one is not enough on its own (mc-zndi7.76, gap 1). +// +// Every racer there writes the SAME two cells (Priority and Notes), so a +// backend whose storage layer auto-merges disjoint-cell changes from a common +// base — Dolt's native behavior — could pass that test on native cell-level +// conflict detection ALONE, with the ExpectedVersion/row_lock compare-and-swap +// doing nothing at all: sixteen racers colliding on one cell look identical to +// sixteen racers colliding on one ROW VERSION. A hand-applied mutant that +// reminted row_lock to an unconditional fresh random value on every write +// (rather than deriving it from, and checking it against, ExpectedVersion) +// still passed the shared-cell test on this suite's in-tree backends 3 of 3 +// runs each, and only showed its true colors — 3 to 7 winners per round — on a +// real Dolt server CLI race with disjoint-column patches, which is the shape +// this case restores. +// +// Each racer here writes a column NO OTHER RACER TOUCHES, so Dolt's per-cell +// auto-merge cannot provide false mutual exclusion for any pair of them: +// whatever excludes all but one racer here has to be the row_lock/ +// ExpectedVersion compare-and-swap itself, not an accident of which cells +// collide. +func RunLifecycleUpdateExpectedVersionSingleWinnerWithDisjointColumnsUnderConcurrency(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + + type disjointField struct { + name string + apply func(*publicops.IssuePatch, string) + read func(*types.Issue) string + } + fields := []disjointField{ + {"Description", func(p *publicops.IssuePatch, v string) { p.Description = publicops.Field[string]{Set: true, Value: v} }, func(i *types.Issue) string { return i.Description }}, + {"Design", func(p *publicops.IssuePatch, v string) { p.Design = publicops.Field[string]{Set: true, Value: v} }, func(i *types.Issue) string { return i.Design }}, + {"AcceptanceCriteria", func(p *publicops.IssuePatch, v string) { + p.AcceptanceCriteria = publicops.Field[string]{Set: true, Value: v} + }, func(i *types.Issue) string { return i.AcceptanceCriteria }}, + {"Notes", func(p *publicops.IssuePatch, v string) { p.Notes = publicops.Field[string]{Set: true, Value: v} }, func(i *types.Issue) string { return i.Notes }}, + {"SpecID", func(p *publicops.IssuePatch, v string) { p.SpecID = publicops.Field[string]{Set: true, Value: v} }, func(i *types.Issue) string { return i.SpecID }}, + {"AwaitID", func(p *publicops.IssuePatch, v string) { p.AwaitID = publicops.Field[string]{Set: true, Value: v} }, func(i *types.Issue) string { return i.AwaitID }}, + {"Owner", func(p *publicops.IssuePatch, v string) { p.Owner = publicops.Field[string]{Set: true, Value: v} }, func(i *types.Issue) string { return i.Owner }}, + // Assignee rides the same Update/ExpectedVersion machinery `bd assign` + // dispatches onto (cmd/bd/mutate_proxied_server.go's proxiedAssign, and + // its direct-route twin), so a disjoint racer on this column is this + // suite's single-winner coverage for assign (mc-zndi7.76, gap 3): there + // is no separate Assign method on Lifecycle to race independently. + {"Assignee", func(p *publicops.IssuePatch, v string) { p.Assignee = publicops.Field[string]{Set: true, Value: v} }, func(i *types.Issue) string { return i.Assignee }}, + } + racers := len(fields) + + id := fixture.IssuePrefix + "-lup-singlewinner-disjoint" + seedLifecycleUpdateIssue(t, ctx, fixture, lifecycleUpdateIssue(id)) + + seed := lifecycleUpdateRow(t, ctx, fixture, id) + racedToken := seed.RowVersion + + var wg sync.WaitGroup + won := make([]bool, racers) + errs := make([]error, racers) + wg.Add(racers) + for i := 0; i < racers; i++ { + i := i + go func() { + defer wg.Done() + version := racedToken + var patch publicops.IssuePatch + fields[i].apply(&patch, fmt.Sprintf("racer-%d-%s", i, fields[i].name)) + result, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: "racer", + IssueID: id, + Patch: patch, + ExpectedVersion: &version, + }) + errs[i] = err + won[i] = err == nil && result.Changed + }() + } + wg.Wait() + + winners := 0 + winner := -1 + for i, win := range won { + if win { + winners++ + winner = i + continue + } + if !errors.Is(errs[i], storage.ErrVersionMismatch) { + t.Errorf("racer %d (%s): err = %v, want nil (won) or ErrVersionMismatch (lost the race)", i, fields[i].name, errs[i]) + } + } + if winners != 1 { + t.Fatalf("%d racers on disjoint columns shared one --if-revision token %d; got %d winners, want exactly 1 (errs=%v)", + racers, racedToken, winners, errs) + } + + final := lifecycleUpdateRow(t, ctx, fixture, id) + wantValue := fmt.Sprintf("racer-%d-%s", winner, fields[winner].name) + for i, f := range fields { + got := f.read(final) + if i == winner { + if got != wantValue { + t.Errorf("final %s = %q, want the single winner's %q — a torn or lost write", f.name, got, wantValue) + } + continue + } + if got != "" { + t.Errorf("final %s = %q, want empty — a disjoint loser's write was not supposed to apply (false mutual exclusion from native cell-merge, not the version guard)", f.name, got) + } + } + if final.RowVersion == racedToken { + t.Errorf("final row version = %d, want it to have advanced past the raced token %d", final.RowVersion, racedToken) + } +} + +// RunLifecycleCloseExpectedVersionSingleWinnerUnderConcurrency is +// RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency's Close twin +// (mc-zndi7.76, gap 3): CloseRequest.ExpectedVersion rides the same row_lock +// compare-and-swap Update's does (CloseRequest.ExpectedVersion's doc), and +// until now nothing proved that under real concurrency for Close specifically. +// N racers close the SAME open issue racing the SAME pre-close token; exactly +// one may apply its close, every other racer must see ErrVersionMismatch (not +// the idempotent-reclose no-op — the token is stale by the time it would +// observe that), and the row left behind must be exactly the single winner's. +func RunLifecycleCloseExpectedVersionSingleWinnerUnderConcurrency(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + + const racers = 16 + + id := fixture.IssuePrefix + "-lup-close-singlewinner" + seedLifecycleUpdateIssue(t, ctx, fixture, lifecycleUpdateIssue(id)) + + seed := lifecycleUpdateRow(t, ctx, fixture, id) + racedToken := seed.RowVersion + + var wg sync.WaitGroup + won := make([]bool, racers) + errs := make([]error, racers) + wg.Add(racers) + for i := 0; i < racers; i++ { + i := i + go func() { + defer wg.Done() + version := racedToken + result, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{ + Actor: "racer", + IssueID: id, + Reason: fmt.Sprintf("racer-%d", i), + ExpectedVersion: &version, + }) + errs[i] = err + won[i] = err == nil && result.Changed + }() + } + wg.Wait() + + winners := 0 + winner := -1 + for i, win := range won { + if win { + winners++ + winner = i + continue + } + if !errors.Is(errs[i], storage.ErrVersionMismatch) { + t.Errorf("racer %d: err = %v, want nil (won) or ErrVersionMismatch (lost the race)", i, errs[i]) + } + } + if winners != 1 { + t.Fatalf("%d racers shared one close --if-revision token %d; got %d winners, want exactly 1 (errs=%v)", + racers, racedToken, winners, errs) + } + + final := lifecycleUpdateRow(t, ctx, fixture, id) + if final.Status != types.StatusClosed { + t.Errorf("final status = %q, want closed", final.Status) + } + wantReason := fmt.Sprintf("racer-%d", winner) + if final.CloseReason != wantReason { + t.Errorf("final close reason = %q, want the single winner's %q — a torn or lost write", final.CloseReason, wantReason) + } + if final.RowVersion == racedToken { + t.Errorf("final row version = %d, want it to have advanced past the raced token %d", final.RowVersion, racedToken) + } +} + +// RunLifecycleUpdateExpectedVersionSingleWinnerAcrossUpdateAndCloseUnderConcurrency +// is this suite's mixed-verb single-winner case (mc-zndi7.76, gap 3): Update +// and Close share one row_lock compare-and-swap, so a token raced across BOTH +// verbs at once must still admit exactly one winner, whichever verb it turns +// out to be — an exclusion mechanism keyed to the row rather than to a given +// verb's own code path. Delete is deliberately NOT a racer here: delete's +// production code does not remint row_lock on a deletion (nothing is left to +// remint), so it does not share this exclusion at all today. That is a real, +// separately tracked bug (the sibling delete bead, mc-zndi7.73) and not a gap +// in this test — folding Delete in here would either mask the bug behind +// Update/Close's real exclusion winning the race, or make this case flake +// red on current main, neither of which belongs in a test pinning what DOES +// work. +func RunLifecycleUpdateExpectedVersionSingleWinnerAcrossUpdateAndCloseUnderConcurrency(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + + const racers = 8 // four Update racers, four Close racers, interleaved. + + id := fixture.IssuePrefix + "-lup-mixed-singlewinner" + seedLifecycleUpdateIssue(t, ctx, fixture, lifecycleUpdateIssue(id)) + + seed := lifecycleUpdateRow(t, ctx, fixture, id) + racedToken := seed.RowVersion + + type outcome struct { + kind string + changed bool + err error + } + outcomes := make([]outcome, racers) + var wg sync.WaitGroup + wg.Add(racers) + for i := 0; i < racers; i++ { + i := i + go func() { + defer wg.Done() + version := racedToken + if i%2 == 0 { + result, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: "racer", + IssueID: id, + Patch: publicops.IssuePatch{ + Owner: publicops.Field[string]{Set: true, Value: fmt.Sprintf("update-racer-%d", i)}, + }, + ExpectedVersion: &version, + }) + outcomes[i] = outcome{kind: "update", changed: err == nil && result.Changed, err: err} + return + } + result, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{ + Actor: "racer", + IssueID: id, + Reason: fmt.Sprintf("close-racer-%d", i), + ExpectedVersion: &version, + }) + outcomes[i] = outcome{kind: "close", changed: err == nil && result.Changed, err: err} + }() + } + wg.Wait() + + winners := 0 + winner := -1 + for i, o := range outcomes { + if o.changed { + winners++ + winner = i + continue + } + if !errors.Is(o.err, storage.ErrVersionMismatch) { + t.Errorf("racer %d (%s): err = %v, want nil (won) or ErrVersionMismatch (lost the race)", i, o.kind, o.err) + } + } + if winners != 1 { + t.Fatalf("%d update/close racers shared one --if-revision token %d; got %d winners, want exactly 1 (outcomes=%+v)", + racers, racedToken, winners, outcomes) + } + + final := lifecycleUpdateRow(t, ctx, fixture, id) + switch outcomes[winner].kind { + case "update": + wantOwner := fmt.Sprintf("update-racer-%d", winner) + if final.Owner != wantOwner { + t.Errorf("final owner = %q, want the single winner's %q — a torn or lost write", final.Owner, wantOwner) + } + if final.Status == types.StatusClosed { + t.Errorf("the winning racer was an update, not a close; final status must not be closed") + } + case "close": + if final.Status != types.StatusClosed { + t.Errorf("final status = %q, want closed — the winning racer was a close", final.Status) + } + wantReason := fmt.Sprintf("close-racer-%d", winner) + if final.CloseReason != wantReason { + t.Errorf("final close reason = %q, want the single winner's %q — a torn or lost write", final.CloseReason, wantReason) + } + } + if final.RowVersion == racedToken { + t.Errorf("final row version = %d, want it to have advanced past the raced token %d", final.RowVersion, racedToken) + } +} + // RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee pins the // ga-5ksp5 fix beside RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits // above rather than inside it: that test's later "order-dependent composition" @@ -1538,10 +1920,10 @@ func RunLifecycleUpdateParentIDReplacesEveryParent(t *testing.T, ctx context.Con // RunLifecycleUpdatePersistentPreservesUnversionedClass pins the half of the // Persistence clause nobody else asserts: "Persistent preserves an existing -// durable unversioned class" (issueops/issueops.go:135-136). The refusal beside -// it — an unversioned row cannot be demoted to a wisp mode — is pinned -// elsewhere; this clause says the legal direction is a no-op that does NOT -// normalize the row into versioned storage. +// durable unversioned class" (issueops/issueops.go:149). The refusal beside +// it — an unversioned row cannot be demoted to a wisp mode — is +// RunLifecycleUpdateWispModesRefuseAnUnversionedRow; this clause says the legal +// direction is a no-op that does NOT normalize the row into versioned storage. // // WHAT A PERSISTENCE RESTATEMENT MUST NOT DO is where the two observations come // in. A persistence MOVE deletes the row from one plane and re-inserts it into @@ -1582,6 +1964,90 @@ func RunLifecycleUpdatePersistentPreservesUnversionedClass(t *testing.T, ctx con assertLifecycleUpdateWispAbsent(t, ctx, fixture, id, "after the persistent restatement") } +// RunLifecycleUpdateWispModesRefuseAnUnversionedRow pins the refusal beside +// that clause: Ephemeral and NoHistory "select wisp retention modes, never +// durable unversioned storage" (issueops/issueops.go:150-151), so an +// unversioned row asked for either is refused. The refusal is the request's, +// a deterministic validation failure, so it matches ErrValidation on every +// leg — over http that is the 400 naming the patch rather than a 500 that +// drops the reason and alerts the operator — and it leaves the row where it +// was: durable, still unversioned, and absent from the wisp plane. +func RunLifecycleUpdateWispModesRefuseAnUnversionedRow(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-lup-unversioned-wisp" + seeded := lifecycleUpdateIssue(id) + seeded.StorageClass = types.StorageClassUnversioned + seedLifecycleUpdateIssue(t, ctx, fixture, seeded) + + for _, mode := range []publicops.PersistenceMode{publicops.PersistenceModeEphemeral, publicops.PersistenceModeNoHistory} { + label := "after the refused " + string(mode) + " move" + before := lifecycleUpdateRow(t, ctx, fixture, id) + if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: mode}, + }}); !errors.Is(err, storage.ErrValidation) { + t.Fatalf("move unversioned %s to %s: error = %v, want ErrValidation", id, mode, err) + } + assertLifecycleUpdateRowUnchanged(t, ctx, fixture, id, label, before) + after := lifecycleUpdateRow(t, ctx, fixture, id) + if after.Ephemeral || after.NoHistory || after.StorageClass != types.StorageClassUnversioned { + t.Errorf("%s %s = {ephemeral %v, no-history %v, class %q}, want the durable unversioned row it was", + id, label, after.Ephemeral, after.NoHistory, after.StorageClass) + } + assertLifecycleUpdateWispAbsent(t, ctx, fixture, id, label) + } +} + +// RunLifecycleUpdatePersistentPromotesAWisp pins the move `bd promote` makes +// (issueops.Promote): Persistence = persistent on an ephemeral wisp is a +// MUTATION that leaves the row on the durable plane under the same id, with +// its labels carried across and nothing left behind on the wisp plane. A +// second identical request is the no-op the "same current mode" clause +// promises, which is how Promote tells a lost race from a promotion. +func RunLifecycleUpdatePersistentPromotesAWisp(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + if fixture.CreateWisp == nil { + t.Skip("fixture has no CreateWisp: this backend has no wisp plane to promote from") + } + + id := fixture.IssuePrefix + "-lup-promote" + seedLifecycleUpdateWisp(t, ctx, fixture, lifecycleUpdateIssue(id, "keep-me")) + if got := lifecycleUpdateRow(t, ctx, fixture, id); !got.Ephemeral { + t.Fatalf("seeded %s is not ephemeral; the case has nothing to promote", id) + } + + promote := publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: publicops.PersistenceModePersistent}, + }} + promoted, err := fixture.Lifecycle.Update(ctx, promote) + if err != nil { + t.Fatalf("promote %s: %v", id, err) + } + if !promoted.Changed { + t.Errorf("promoting wisp %s reported Changed = false, want a mutation", id) + } + if promoted.Issue == nil || promoted.Issue.ID != id || promoted.Issue.Ephemeral { + t.Errorf("promote result issue = %+v, want %s on the durable plane", promoted.Issue, id) + } + + after := lifecycleUpdateRow(t, ctx, fixture, id) + if after.Ephemeral || after.NoHistory { + t.Errorf("%s came back {ephemeral %v, no-history %v} after the promotion, want a durable-plane row", id, after.Ephemeral, after.NoHistory) + } + if !slices.Contains(after.Labels, "keep-me") { + t.Errorf("%s labels after the promotion = %v, want the wisp's label carried across", id, after.Labels) + } + assertLifecycleUpdateWispAbsent(t, ctx, fixture, id, "after the promotion") + + again, err := fixture.Lifecycle.Update(ctx, promote) + if err != nil { + t.Fatalf("re-promote %s: %v", id, err) + } + if again.Changed { + t.Errorf("re-promoting durable %s reported Changed = true, want the same-mode no-op", id) + } +} + // RunLifecycleUpdateProvenanceLabelsHistory pins UpdateRequest.Provenance // against the history the backend actually writes // (issueops/issueops.go:261-270): the entry reads as the caller's own string, @@ -2138,3 +2604,134 @@ func lifecycleUpdateHasEdge(dependencies []*types.Dependency, wantTarget string) } return false } + +// RunLifecycleUpdateRefusesATemplate pins Lifecycle.Update's template guard: +// templates are read-only, so EVERY update naming one refuses with +// *TemplateReadOnlyError — a field edit, a label edit, a claim, a status +// crossing — whatever force flags ride along, and nothing is written. It is the +// guard `bd update` used to apply as a CLI pre-read, which left bd serve and +// library callers editing templates bd refused. +// +// The refusal is asserted at the level a caller acts on — the typed error, its +// sentinel and the sentence bd prints, read off the typed error because a +// served refusal wraps it — and the row is read back to prove nothing moved. +// Two controls: the same patches land on an ordinary sibling, so the guard is +// not refusing the patch shapes; and a stale ExpectedVersion on the template +// still reports the mismatch, so the guard runs after the compare-and-set +// preconditions like every other update fence. +func RunLifecycleUpdateRefusesATemplate(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + template := fixture.IssuePrefix + "-lut-template" + sibling := fixture.IssuePrefix + "-lut-sibling" + for _, issue := range []*types.Issue{ + {ID: template, IsTemplate: true}, + {ID: sibling}, + } { + issue.Title, issue.Status, issue.Priority, issue.IssueType = issue.ID, types.StatusOpen, 2, types.TypeTask + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", issue.ID, err) + } + } + before, err := fixture.GetIssue(ctx, template) + if err != nil { + t.Fatalf("read seeded template %s: %v", template, err) + } + + requests := []struct { + name string + request publicops.UpdateRequest + }{ + {name: "field edit", request: publicops.UpdateRequest{ + Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "edited"}}, + }}, + {name: "label edit", request: publicops.UpdateRequest{ + Patch: publicops.IssuePatch{Labels: publicops.LabelPatch{Add: []string{"lut-tag"}}}, + }}, + {name: "claim", request: publicops.UpdateRequest{Claim: true}}, + {name: "forced status crossing", request: publicops.UpdateRequest{ + Patch: publicops.IssuePatch{Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusClosed}}, + ForceClosePolicy: true, + }}, + {name: "forced assignee transfer", request: publicops.UpdateRequest{ + Patch: publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "someone"}}, + ForceAssigneeTransfer: true, + }}, + } + for _, tc := range requests { + request := tc.request + request.Actor, request.IssueID = "writer", template + _, err := fixture.Lifecycle.Update(ctx, request) + var refusal *publicops.TemplateReadOnlyError + if !errors.As(err, &refusal) { + t.Fatalf("%s on template %s: err = %v, want *TemplateReadOnlyError", tc.name, template, err) + } + if refusal.IssueID != template || !errors.Is(err, publicops.ErrTemplateReadOnly) { + t.Errorf("%s refusal = %#v (%v), want IssueID %q matching ErrTemplateReadOnly", tc.name, refusal, err, template) + } + if want := "cannot modify template " + template + ": templates are read-only; use 'bd mol pour' to create a work item"; refusal.Error() != want { + t.Errorf("%s refusal reads %q, want %q", tc.name, refusal.Error(), want) + } + after, err := fixture.GetIssue(ctx, template) + if err != nil { + t.Fatalf("read template %s after the %s refusal: %v", template, tc.name, err) + } + if after.RowVersion != before.RowVersion || after.Title != before.Title || after.Status != before.Status || + after.Assignee != before.Assignee || len(after.Labels) != len(before.Labels) { + t.Errorf("template %s after the %s refusal = %+v, want it unchanged from %+v", template, tc.name, after, before) + } + + control := tc.request + control.Actor, control.IssueID = "writer", sibling + if _, err := fixture.Lifecycle.Update(ctx, control); err != nil { + t.Errorf("%s on the ordinary sibling %s: %v, want it to land", tc.name, sibling, err) + } + } + + stale := before.RowVersion + 1 + _, err = fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", IssueID: template, ExpectedVersion: &stale, + Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "edited"}}, + }) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Errorf("stale-guarded update of template %s: err = %v, want ErrVersionMismatch ahead of the template guard", template, err) + } +} + +// RunLifecycleUpdateAllowTemplateEditsATemplate pins the template guard's one +// stand-down: an update with AllowTemplate — what bd label and bd set-state +// send, since they have always edited templates — lands on a template, and +// only that request is waived (the same patch without it still refuses). +func RunLifecycleUpdateAllowTemplateEditsATemplate(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + template := fixture.IssuePrefix + "-lua-template" + issue := &types.Issue{ID: template, Title: template, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, IsTemplate: true} + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", template, err) + } + + result, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", IssueID: template, AllowTemplate: true, + Patch: publicops.IssuePatch{Labels: publicops.LabelPatch{Add: []string{"lua-tag"}}}, + }) + if err != nil { + t.Fatalf("AllowTemplate label edit on template %s: %v, want it to land", template, err) + } + if !result.Changed || result.Issue == nil || !lifecycleUpdateHasLabel(result.Issue.Labels, "lua-tag") { + t.Errorf("AllowTemplate label edit on template %s = %+v, want a change carrying lua-tag", template, result) + } + after, err := fixture.GetIssue(ctx, template) + if err != nil { + t.Fatalf("read template %s: %v", template, err) + } + if !after.IsTemplate { + t.Errorf("template %s is no longer a template after an AllowTemplate edit", template) + } + + _, err = fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", IssueID: template, + Patch: publicops.IssuePatch{Labels: publicops.LabelPatch{Add: []string{"lua-other"}}}, + }) + if !errors.Is(err, publicops.ErrTemplateReadOnly) { + t.Errorf("the same edit without AllowTemplate: err = %v, want ErrTemplateReadOnly", err) + } +} diff --git a/backend/conformance/lifecycle_update_gate_contract.go b/backend/conformance/lifecycle_update_gate_contract.go new file mode 100644 index 000000000..06c730625 --- /dev/null +++ b/backend/conformance/lifecycle_update_gate_contract.go @@ -0,0 +1,133 @@ +package conformance + +import ( + "context" + "testing" + "time" + + publicops "github.com/steveyegge/beads/issueops" +) + +// The patch half of the gate-member clauses; see lifecycle_create_gate_contract.go. + +// RunLifecycleUpdatePatchesTheGateMembers pins IssuePatch.AwaitID and +// IssuePatch.Waiters: a set value lands and is answered on the result, waiters +// is a WHOLE-VALUE replacement stored as given (duplicates kept), a same-value +// patch is a no-op, a clear (empty await_id, nil waiters) empties both, and a +// second clear is a no-op. await_type and timeout are not patch members, so +// they ride through every edit untouched. The row is a task: no gate-type-only +// rule. +func RunLifecycleUpdatePatchesTheGateMembers(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-lug-gate" + seeded := lifecycleUpdateIssue(id) + seeded.AwaitType = "timer" + seeded.AwaitID = "seeded-await" + seeded.Timeout = time.Minute + seeded.Waiters = []string{"seeded"} + seedLifecycleUpdateIssue(t, ctx, fixture, seeded) + + patch := publicops.IssuePatch{ + AwaitID: publicops.Field[string]{Set: true, Value: "run-42"}, + Waiters: publicops.Field[[]string]{Set: true, Value: []string{"w1", "w2", "w1"}}, + } + wantWaiters := []string{"w1", "w2", "w1"} + updated, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: patch}) + if err != nil { + t.Fatalf("patch the gate members of %s: %v", id, err) + } + if !updated.Changed { + t.Errorf("patching the gate members of %s reported Changed = false, want a committed edit", id) + } + assertGateMembers(t, id, "in the update result", updated.Issue, "timer", "run-42", time.Minute, wantWaiters) + assertGateMembers(t, id, "in the stored row", lifecycleUpdateRow(t, ctx, fixture, id), "timer", "run-42", time.Minute, wantWaiters) + + after := lifecycleUpdateRow(t, ctx, fixture, id) + again, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: patch}) + if err != nil { + t.Fatalf("re-apply the same gate patch to %s: %v", id, err) + } + if again.Changed { + t.Errorf("re-applying the same gate patch to %s reported Changed = true, want false", id) + } + assertLifecycleUpdateRowUnchanged(t, ctx, fixture, id, "after the same-value gate patch", after) + + clear := publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + AwaitID: publicops.Field[string]{Set: true}, + Waiters: publicops.Field[[]string]{Set: true}, + }} + cleared, err := fixture.Lifecycle.Update(ctx, clear) + if err != nil { + t.Fatalf("clear the gate members of %s: %v", id, err) + } + if !cleared.Changed { + t.Errorf("clearing the gate members of %s reported Changed = false, want a committed edit", id) + } + assertGateMembers(t, id, "in the clear's result", cleared.Issue, "timer", "", time.Minute, nil) + assertGateMembers(t, id, "in the cleared row", lifecycleUpdateRow(t, ctx, fixture, id), "timer", "", time.Minute, nil) + + afterClear := lifecycleUpdateRow(t, ctx, fixture, id) + reclear, err := fixture.Lifecycle.Update(ctx, clear) + if err != nil { + t.Fatalf("re-clear the gate members of %s: %v", id, err) + } + if reclear.Changed { + t.Errorf("re-clearing the already-empty gate members of %s reported Changed = true, want false", id) + } + assertLifecycleUpdateRowUnchanged(t, ctx, fixture, id, "after the re-clear", afterClear) + + // An explicitly empty list clears exactly as a nil one does. + if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Waiters: publicops.Field[[]string]{Set: true, Value: []string{"back"}}, + }}); err != nil { + t.Fatalf("re-set the waiters of %s: %v", id, err) + } + if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Waiters: publicops.Field[[]string]{Set: true, Value: []string{}}, + }}); err != nil { + t.Fatalf("clear the waiters of %s with an empty list: %v", id, err) + } + assertGateMembers(t, id, "after the empty-list clear", lifecycleUpdateRow(t, ctx, fixture, id), "timer", "", time.Minute, nil) +} + +// RunLifecycleUpdateBoundsTheGateMembers pins the patch half of the +// GateFieldError bounds from both sides: at-bound await_id and waiters land +// whole, one past either is refused as ErrValidation naming its member, and +// the refusal writes nothing — not the gate member, and not an ordinary member +// riding in the same patch. +func RunLifecycleUpdateBoundsTheGateMembers(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-lug-bounds" + seedLifecycleUpdateIssue(t, ctx, fixture, lifecycleUpdateIssue(id)) + + if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + AwaitID: publicops.Field[string]{Set: true, Value: gateFieldAtBoundAwaitID}, + Waiters: publicops.Field[[]string]{Set: true, Value: gateFieldAtBoundWaiters()}, + }}); err != nil { + t.Fatalf("patch %s with await_id and waiters at their bounds: %v", id, err) + } + assertGateMembers(t, id, "in the stored row", lifecycleUpdateRow(t, ctx, fixture, id), "", gateFieldAtBoundAwaitID, 0, gateFieldAtBoundWaiters()) + + before := lifecycleUpdateRow(t, ctx, fixture, id) + for _, test := range []struct { + name string + field string + patch publicops.IssuePatch + }{ + {"await_id", publicops.GateFieldAwaitID, publicops.IssuePatch{ + Title: publicops.Field[string]{Set: true, Value: "must not land"}, + AwaitID: publicops.Field[string]{Set: true, Value: gateFieldAtBoundAwaitID + "x"}, + }}, + {"waiters", publicops.GateFieldWaiters, publicops.IssuePatch{ + Title: publicops.Field[string]{Set: true, Value: "must not land"}, + Waiters: publicops.Field[[]string]{Set: true, Value: gateFieldOverBoundWaiters()}, + }}, + } { + _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: test.patch}) + assertGateFieldError(t, err, "patch with "+test.name+" past its bound", test.field) + assertLifecycleUpdateRowUnchanged(t, ctx, fixture, id, "after the refused "+test.name, before) + assertGateMembers(t, id, "after the refused "+test.name, lifecycleUpdateRow(t, ctx, fixture, id), "", gateFieldAtBoundAwaitID, 0, gateFieldAtBoundWaiters()) + } +} diff --git a/backend/conformance/memories_contract.go b/backend/conformance/memories_contract.go index c7b33221c..dc45191f4 100644 --- a/backend/conformance/memories_contract.go +++ b/backend/conformance/memories_contract.go @@ -233,14 +233,11 @@ func RunMemoriesRememberWithExplicitKeyStoresVerbatim(t *testing.T, ctx context. } // RunMemoriesRememberReplacesAndReportsIt pins -// memoryops.RememberResult.Replaced, including the leg that makes it different -// from RecallResult.Found. +// memoryops.RememberResult.Replaced against row presence. // // Three legs: a first write reports false, a second reports true and REPLACES -// rather than appends, and a write over an out-of-band EMPTY row reports true -// even though a Recall of that key would have reported Found false. The third -// is the divergence the leaf doc states — Replaced is about the ROW — and it is -// the one a body computing `previous != ""` gets wrong. +// rather than appends, and a write over an out-of-band EMPTY row reports true. +// The third is the one a body computing `previous != ""` gets wrong. func RunMemoriesRememberReplacesAndReportsIt(t *testing.T, ctx context.Context, fixture MemoriesFixture) { t.Helper() neighbors := seedMemoriesAllFourClasses(t, ctx, fixture) @@ -262,7 +259,7 @@ func RunMemoriesRememberReplacesAndReportsIt(t *testing.T, ctx context.Context, if err := fixture.SetConfig(ctx, "kv.memory."+emptied, ""); err != nil { t.Fatalf("seed an empty memory row out of band: %v", err) } - assertMemoriesRecall(t, ctx, fixture, emptied, "", false) + assertMemoriesRecall(t, ctx, fixture, emptied, "", true) overEmpty := rememberMemory(t, ctx, fixture, memoryops.RememberRequest{Key: emptied, Content: "now it has content"}) if !overEmpty.Replaced { t.Fatalf("Remember over a row stored EMPTY reported Replaced false: Replaced is about the row, " + @@ -374,8 +371,8 @@ func RunMemoriesRecallAnswersTheStoredValue(t *testing.T, ctx context.Context, f } // RunMemoriesRecallReportsAMissAsNotFoundNotAnError pins the decision recorded -// in memoryops/errors.go: there is no ErrNotFound on this role, because the -// seam beneath it cannot see the difference the error would claim. +// in memoryops/errors.go: absence is a result callers inspect, not an +// operational error they must classify. func RunMemoriesRecallReportsAMissAsNotFoundNotAnError(t *testing.T, ctx context.Context, fixture MemoriesFixture) { t.Helper() seedMemoriesAllFourClasses(t, ctx, fixture) @@ -401,33 +398,70 @@ func RunMemoriesRecallReportsAMissAsNotFoundNotAnError(t *testing.T, ctx context } } -// RunMemoriesRecallConflatesStoredEmptyWithAbsent pins -// memoryops.RecallResult.Found's central claim, and the one asymmetry that lets -// a caller see past it: List enumerates the key, because the ROW exists. +// RunMemoriesEmptyRowIsPresentUntilForgotten pins presence to the ROW rather +// than to whether its value is non-empty. No front door creates an empty +// memory, but out-of-band config writes and older workspaces can contain one, +// and it must remain addressable through Recall and Forget. // -// That is the same same-answer-different-row shape the settings contract pins -// for `bd config get`, and stating it is what keeps a backend from "fixing" it -// on one leg and making the answer depend on the route. -func RunMemoriesRecallConflatesStoredEmptyWithAbsent(t *testing.T, ctx context.Context, fixture MemoriesFixture) { +// The second Forget is the retry leg: after the first call deletes the row, it +// reports a genuine miss and records no further history. +func RunMemoriesEmptyRowIsPresentUntilForgotten(t *testing.T, ctx context.Context, fixture MemoriesFixture) { t.Helper() - seedMemoriesAllFourClasses(t, ctx, fixture) + neighbors := seedMemoriesAllFourClasses(t, ctx, fixture) emptied := fixture.IssuePrefix + "-stored-empty" never := fixture.IssuePrefix + "-never-stored" if err := fixture.SetConfig(ctx, "kv.memory."+emptied, ""); err != nil { t.Fatalf("seed an empty memory row out of band: %v", err) } - assertMemoriesRecall(t, ctx, fixture, emptied, "", false) + assertMemoriesRecall(t, ctx, fixture, emptied, "", true) assertMemoriesRecall(t, ctx, fixture, never, "", false) plane := listMemories(t, ctx, fixture, "") if value, ok := plane[emptied]; !ok || value != "" { - t.Fatalf("List[%q] = %q (present=%v), want an empty value that IS enumerated: "+ - "the row exists even though Recall denies it", emptied, value, ok) + t.Fatalf("List[%q] = %q (present=%v), want an enumerated empty value", emptied, value, ok) } if _, ok := plane[never]; ok { t.Fatalf("List carries %q, which nothing stored", never) } + + first := forgetMemory(t, ctx, fixture, emptied) + if !first.Found || first.Value != "" { + t.Fatalf("first Forget(%q) = %+v, want Found true with the empty stored value", emptied, first) + } + assertMemoriesRawAbsent(t, ctx, fixture, "kv.memory."+emptied) + assertMemoriesNeighborsSurvived(t, ctx, fixture, neighbors) + + var afterFirst int + if fixture.CountHistory != nil { + var err error + afterFirst, err = fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after first Forget: %v", err) + } + } + + second := forgetMemory(t, ctx, fixture, emptied) + if second.Found || second.Value != "" { + t.Fatalf("second Forget(%q) = %+v, want Found false with no value", emptied, second) + } + assertMemoriesRawAbsent(t, ctx, fixture, "kv.memory."+emptied) + assertMemoriesNeighborsSurvived(t, ctx, fixture, neighbors) + + // The no-write half of the retry is the only leg that needs history, which + // is why it comes last: a backend that cannot observe history has run every + // other leg by here, and SKIPS this one with that reason, as the + // MemoriesFixture.CountHistory doc promises, rather than passing quietly. + if fixture.CountHistory == nil { + t.Skip("this backend cannot observe history, so the no-write half of the retry is unobservable here") + } + afterSecond, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after second Forget: %v", err) + } + if afterSecond != afterFirst { + t.Fatalf("history entries went %d -> %d across the second Forget, want no write", afterFirst, afterSecond) + } } // RunMemoriesForgetRemovesExactlyTheNamedRow IS THE QUADRANT CASE, and the @@ -528,13 +562,7 @@ func RunMemoriesForgetReportsTheForgottenValue(t *testing.T, ctx context.Context // RunMemoriesForgetOfAnAbsentKeyIsNotFoundAndDeletesNothing pins that a miss is // a RESULT and not an error, that it changes no row anywhere in the table, that // the second call — the one a retrying caller actually makes — answers the same -// way, and that the SECOND kind of miss behaves like the first: a memory stored -// as the empty string is Found false, and its row is left standing. -// -// That last leg is memoryops.ForgetResult.Found's parenthesis, and it keeps -// Forget's answer and Recall's answer the same statement. A body that deleted -// on "the row is there" rather than on "Recall would find it" would report -// nothing removed while removing something. +// way. // // The whole-table row count is the assertion that matters: "the key is still // absent" would pass on a delete that swept a neighboring plane. @@ -542,10 +570,6 @@ func RunMemoriesForgetOfAnAbsentKeyIsNotFoundAndDeletesNothing(t *testing.T, ctx t.Helper() neighbors := seedMemoriesAllFourClasses(t, ctx, fixture) key := fixture.IssuePrefix + "-never-stored-forget" - emptied := fixture.IssuePrefix + "-empty-forget" - if err := fixture.SetConfig(ctx, "kv.memory."+emptied, ""); err != nil { - t.Fatalf("seed an empty memory row out of band: %v", err) - } var before int if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM config", nil, &before); err != nil { @@ -553,14 +577,12 @@ func RunMemoriesForgetOfAnAbsentKeyIsNotFoundAndDeletesNothing(t *testing.T, ctx } for attempt := 1; attempt <= 2; attempt++ { - for _, miss := range []string{key, emptied} { - result, err := fixture.Memories.Forget(ctx, memoryops.ForgetRequest{Key: miss}) - if err != nil { - t.Fatalf("Forget(%q) attempt %d = %v, want success with Found false", miss, attempt, err) - } - if result.Found || result.Value != "" { - t.Fatalf("Forget(%q) attempt %d = %+v, want Found false and no value", miss, attempt, result) - } + result, err := fixture.Memories.Forget(ctx, memoryops.ForgetRequest{Key: key}) + if err != nil { + t.Fatalf("Forget(%q) attempt %d = %v, want success with Found false", key, attempt, err) + } + if result.Found || result.Value != "" { + t.Fatalf("Forget(%q) attempt %d = %+v, want Found false and no value", key, attempt, result) } } @@ -569,11 +591,8 @@ func RunMemoriesForgetOfAnAbsentKeyIsNotFoundAndDeletesNothing(t *testing.T, ctx t.Fatalf("count config rows after: %v", err) } if after != before { - t.Fatalf("config rows went %d -> %d across four forgets that found nothing, want no change", before, after) + t.Fatalf("config rows went %d -> %d across two forgets that found nothing, want no change", before, after) } - // The stored-empty row is specifically still there: Found false said nothing - // was removed, and that has to be true of the row as well as of the answer. - assertMemoriesRawValue(t, ctx, fixture, "kv.memory."+emptied, "") assertMemoriesNeighborsSurvived(t, ctx, fixture, neighbors) // The empty key is a refusal, not a miss. diff --git a/backend/conformance/molecule_contract.go b/backend/conformance/molecule_contract.go new file mode 100644 index 000000000..36021d53a --- /dev/null +++ b/backend/conformance/molecule_contract.go @@ -0,0 +1,480 @@ +package conformance + +import ( + "context" + "errors" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the contract for the molecule operations every backend +// serves through one library entry each: +// +// - CloseRequest.AutoCloseMolecule / CloseBatchRequest.AutoCloseMolecule — +// the close closes the molecule root it completed IN ITS OWN TRANSACTION +// (internal/storage/issueops.CloseCompletedMoleculeInTx on the store +// backends, uow.CloseCompletedMoleculeInUOW on the unit of work, the +// server's own on http). Opt-in; unforced; guarded on the root revision. +// - issueops.MoleculeStepper — the advance behind `bd close --continue`, +// whose claim is a real claim (assignee = Actor) that never takes a step +// another actor holds. +// +// THE LEAF DOC COMMENTS ARE THE SPEC (issueops/issueops.go CloseRequest, +// issueops/batchcloser.go, issueops/moleculestepper.go, issueops/molecule.go). + +// MoleculeFixture supplies adapter-specific storage access for the molecule +// assertions. +type MoleculeFixture struct { + // IssuePrefix namespaces the ids each assertion seeds. + IssuePrefix string + Lifecycle publicops.Lifecycle + BatchCloser publicops.BatchCloser + Stepper publicops.MoleculeStepper + // CreateIssue and CreateWisp seed one row in the issues and wisps plane. + CreateIssue func(context.Context, *types.Issue, string) error + CreateWisp func(context.Context, *types.Issue, string) error + // AddDependency seeds one edge. + AddDependency func(context.Context, *types.Dependency, string) error + // QueryScalar runs a single-row query and scans it. + QueryScalar func(context.Context, string, []any, ...any) error +} + +const moleculeActor = "molecule-contract" + +type moleculeSeed struct { + t *testing.T + ctx context.Context + fixture MoleculeFixture +} + +func (s moleculeSeed) issue(id string, typ types.IssueType, status types.Status, ephemeral bool, labels ...string) { + s.t.Helper() + issue := &types.Issue{ID: id, Title: "molecule " + id, IssueType: typ, Status: status, Priority: 2, Labels: labels, Ephemeral: ephemeral} + if status == types.StatusClosed { + issue.CloseReason = "seeded closed" + } + create := s.fixture.CreateIssue + if ephemeral { + create = s.fixture.CreateWisp + } + if err := create(s.ctx, issue, moleculeActor); err != nil { + s.t.Fatalf("seed %s: %v", id, err) + } +} + +func (s moleculeSeed) edge(from, to string, typ types.DependencyType) { + s.t.Helper() + if err := s.fixture.AddDependency(s.ctx, &types.Dependency{IssueID: from, DependsOnID: to, Type: typ}, moleculeActor); err != nil { + s.t.Fatalf("seed edge %s -> %s: %v", from, to, err) + } +} + +// row reads id's status and assignee from whichever plane holds it. +func (s moleculeSeed) row(id string) (status, assignee string) { + s.t.Helper() + err := s.fixture.QueryScalar(s.ctx, + `SELECT status, COALESCE(assignee, '') FROM issues WHERE id = ? + UNION ALL SELECT status, COALESCE(assignee, '') FROM wisps WHERE id = ?`, + []any{id, id}, &status, &assignee) + if err != nil { + s.t.Fatalf("read %s: %v", id, err) + } + return status, assignee +} + +// molecule seeds root <- step1 (closed), step2 (open) and answers the ids. +func (s moleculeSeed) molecule(name string, rootType types.IssueType, ephemeral bool, labels ...string) (root, done, last string) { + s.t.Helper() + root = s.fixture.IssuePrefix + "-" + name + done, last = root+".1", root+".2" + s.issue(root, rootType, types.StatusOpen, ephemeral, labels...) + s.issue(done, types.TypeTask, types.StatusClosed, ephemeral) + s.issue(last, types.TypeTask, types.StatusOpen, ephemeral) + s.edge(done, root, types.DepParentChild) + s.edge(last, root, types.DepParentChild) + return root, done, last +} + +func (s moleculeSeed) closeStep(id string, autoClose bool) publicops.CloseResult { + s.t.Helper() + res, err := s.fixture.Lifecycle.Close(s.ctx, publicops.CloseRequest{ + Actor: moleculeActor, IssueID: id, Reason: "step done", Session: "molecule-session", AutoCloseMolecule: autoClose, + }) + if err != nil { + s.t.Fatalf("close %s: %v", id, err) + } + return res +} + +// RunMoleculeCloseAutoClosesTheCompletedRoot pins CloseRequest.AutoCloseMolecule: +// closing the last open step closes an auto-closing root in the same call, +// reports it, and records the auto-close reason. +func RunMoleculeCloseAutoClosesTheCompletedRoot(t *testing.T, ctx context.Context, fixture MoleculeFixture) { + t.Helper() + s := moleculeSeed{t, ctx, fixture} + for _, shape := range []struct { + name string + rootType types.IssueType + labels []string + }{ + {"poured", types.TypeMolecule, nil}, + {"template", types.TypeEpic, []string{publicops.MoleculeTemplateLabel}}, + } { + root, _, last := s.molecule("auto-"+shape.name, shape.rootType, false, shape.labels...) + res := s.closeStep(last, true) + if !res.Changed || res.Issue == nil || res.Issue.Status != types.StatusClosed { + t.Fatalf("%s: close %s = %+v, want the step closed", shape.name, last, res) + } + if res.AutoClosedMolecule == nil || res.AutoClosedMolecule.ID != root { + t.Fatalf("%s: AutoClosedMolecule = %+v, want %s", shape.name, res.AutoClosedMolecule, root) + } + if res.MoleculeAutoCloseRefusal != "" { + t.Errorf("%s: MoleculeAutoCloseRefusal = %q, want none", shape.name, res.MoleculeAutoCloseRefusal) + } + if status, _ := s.row(root); status != string(types.StatusClosed) { + t.Errorf("%s: root %s status = %s, want closed", shape.name, root, status) + } + var reason string + if err := fixture.QueryScalar(ctx, `SELECT close_reason FROM issues WHERE id = ?`, []any{root}, &reason); err != nil { + t.Fatalf("read %s close_reason: %v", root, err) + } + if reason != publicops.MoleculeAutoCloseReason { + t.Errorf("%s: root close_reason = %q, want %q", shape.name, reason, publicops.MoleculeAutoCloseReason) + } + } +} + +// RunMoleculeAutoCloseIsOptInAndRuleBound pins the opt-in default and the +// three roots the auto-close must leave open: one a request did not ask for, +// an incomplete one, and an ordinary epic (explicit close-eligible work). +func RunMoleculeAutoCloseIsOptInAndRuleBound(t *testing.T, ctx context.Context, fixture MoleculeFixture) { + t.Helper() + s := moleculeSeed{t, ctx, fixture} + + root, _, last := s.molecule("optin", types.TypeMolecule, false) + if res := s.closeStep(last, false); res.AutoClosedMolecule != nil { + t.Errorf("close without AutoCloseMolecule reported %s auto-closed", res.AutoClosedMolecule.ID) + } + if status, _ := s.row(root); status != string(types.StatusOpen) { + t.Errorf("root %s status after an un-flagged close = %s, want open", root, status) + } + + root, _, last = s.molecule("plain", types.TypeEpic, false) + if res := s.closeStep(last, true); res.AutoClosedMolecule != nil { + t.Errorf("an ordinary epic auto-closed: %s", res.AutoClosedMolecule.ID) + } + if status, _ := s.row(root); status != string(types.StatusOpen) { + t.Errorf("ordinary epic %s status = %s, want open", root, status) + } + + root, done, last := s.molecule("incomplete", types.TypeMolecule, false) + if res := s.closeStep(done, true); res.AutoClosedMolecule != nil { + t.Errorf("an incomplete molecule auto-closed: %s", res.AutoClosedMolecule.ID) + } + if status, _ := s.row(root); status != string(types.StatusOpen) { + t.Errorf("incomplete molecule %s status = %s, want open (%s still open)", root, status, last) + } +} + +// RunMoleculeRecloseHealsAStrandedRoot pins the replay clause: an idempotent +// re-close of the last step still closes a root left open. +func RunMoleculeRecloseHealsAStrandedRoot(t *testing.T, ctx context.Context, fixture MoleculeFixture) { + t.Helper() + s := moleculeSeed{t, ctx, fixture} + root := fixture.IssuePrefix + "-stranded" + step := root + ".1" + s.issue(root, types.TypeMolecule, types.StatusOpen, false) + s.issue(step, types.TypeTask, types.StatusClosed, false) + s.edge(step, root, types.DepParentChild) + + res := s.closeStep(step, true) + if res.Changed { + t.Errorf("re-close of %s reported Changed", step) + } + if res.AutoClosedMolecule == nil || res.AutoClosedMolecule.ID != root { + t.Fatalf("re-close AutoClosedMolecule = %+v, want %s healed", res.AutoClosedMolecule, root) + } + if status, _ := s.row(root); status != string(types.StatusClosed) { + t.Errorf("stranded root %s status = %s, want closed", root, status) + } +} + +// RunMoleculeBatchCloseAutoClosesTheRootOnce pins the batch clause: a batch +// that closes the remaining steps closes the root once, on one outcome. +func RunMoleculeBatchCloseAutoClosesTheRootOnce(t *testing.T, ctx context.Context, fixture MoleculeFixture) { + t.Helper() + s := moleculeSeed{t, ctx, fixture} + root, _, last := s.molecule("batch", types.TypeMolecule, false) + other := root + ".3" + s.issue(other, types.TypeTask, types.StatusOpen, false) + s.edge(other, root, types.DepParentChild) + + res, err := fixture.BatchCloser.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: moleculeActor, + Items: []publicops.BatchCloseItem{{IssueID: last, Reason: "done"}, {IssueID: other, Reason: "done"}}, + AutoCloseMolecule: true, + }) + if err != nil { + t.Fatalf("CloseBatch: %v", err) + } + reported := 0 + for _, outcome := range res.Outcomes { + if outcome.Err != nil { + t.Fatalf("outcome %s: %v", outcome.IssueID, outcome.Err) + } + if outcome.AutoClosedMolecule != nil { + reported++ + if outcome.AutoClosedMolecule.ID != root { + t.Errorf("outcome %s auto-closed %s, want %s", outcome.IssueID, outcome.AutoClosedMolecule.ID, root) + } + } + } + if reported != 1 { + t.Errorf("the root was reported on %d outcomes, want exactly one", reported) + } + if status, _ := s.row(root); status != string(types.StatusClosed) { + t.Errorf("root %s status = %s, want closed", root, status) + } +} + +// RunMoleculeRefusedRootKeepsTheStepClose pins the refusal clause: a root its +// own close policy refuses (a live blocker) stays open and is reported in the +// policy's own sentence, and the step close it followed stands. +func RunMoleculeRefusedRootKeepsTheStepClose(t *testing.T, ctx context.Context, fixture MoleculeFixture) { + t.Helper() + s := moleculeSeed{t, ctx, fixture} + root, _, last := s.molecule("blocked", types.TypeMolecule, false) + blocker := root + "-blocker" + s.issue(blocker, types.TypeTask, types.StatusOpen, false) + s.edge(root, blocker, types.DepBlocks) + + res := s.closeStep(last, true) + if res.AutoClosedMolecule != nil { + t.Errorf("a blocked root auto-closed: %s", res.AutoClosedMolecule.ID) + } + if want := publicops.NewCloseBlockedError(root, []string{blocker}).Error(); res.MoleculeAutoCloseRefusal != want { + t.Errorf("MoleculeAutoCloseRefusal = %q, want the policy's own sentence %q", res.MoleculeAutoCloseRefusal, want) + } + if status, _ := s.row(last); status != string(types.StatusClosed) { + t.Errorf("step %s status = %s, want closed (the refusal must not undo it)", last, status) + } + if status, _ := s.row(root); status != string(types.StatusOpen) { + t.Errorf("blocked root %s status = %s, want open", root, status) + } +} + +// RunMoleculeGuardedRootKeepsTheStepClose pins the guard clause: the root close +// is unforced, so a root a direct close would refuse — assigned to someone +// other than Actor, pinned, or a template — stays open and is reported in the +// guard's own sentence, on a single close and on a batch, and the step's close +// (and a batch's other items) stand. +func RunMoleculeGuardedRootKeepsTheStepClose(t *testing.T, ctx context.Context, fixture MoleculeFixture) { + t.Helper() + s := moleculeSeed{t, ctx, fixture} + for _, guard := range []struct { + name string + apply func(*types.Issue) + // refusal is the guard's own error for root, whose sentence + // MoleculeAutoCloseRefusal reports. + refusal func(root string) error + }{ + {"assigned", func(root *types.Issue) { root.Assignee = "someone-else" }, func(root string) error { + return &publicops.CloseNotAssigneeError{IssueID: root, Assignee: "someone-else", Actor: moleculeActor} + }}, + {"pinned", func(root *types.Issue) { root.Pinned = true }, func(root string) error { + return &publicops.PinnedError{IssueID: root} + }}, + {"template", func(root *types.Issue) { root.IsTemplate = true }, func(root string) error { + return &publicops.TemplateReadOnlyError{IssueID: root} + }}, + } { + for _, batch := range []bool{false, true} { + name := guard.name + if batch { + name += "-batch" + } + root := fixture.IssuePrefix + "-guarded-" + name + last := root + ".2" + rootIssue := &types.Issue{ID: root, Title: "molecule " + root, IssueType: types.TypeMolecule, Status: types.StatusOpen, Priority: 2} + guard.apply(rootIssue) + if err := fixture.CreateIssue(ctx, rootIssue, moleculeActor); err != nil { + t.Fatalf("%s: seed %s: %v", name, root, err) + } + s.issue(root+".1", types.TypeTask, types.StatusClosed, false) + s.issue(last, types.TypeTask, types.StatusOpen, false) + s.edge(root+".1", root, types.DepParentChild) + s.edge(last, root, types.DepParentChild) + + var ( + autoClosed *publicops.Issue + refusal string + closed = []string{last} + ) + if batch { + other := root + "-other" + s.issue(other, types.TypeTask, types.StatusOpen, false) + closed = append(closed, other) + res, err := fixture.BatchCloser.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: moleculeActor, + Items: []publicops.BatchCloseItem{{IssueID: last, Reason: "done"}, {IssueID: other, Reason: "done"}}, + AutoCloseMolecule: true, + }) + if err != nil { + t.Fatalf("%s: CloseBatch: %v", name, err) + } + for _, outcome := range res.Outcomes { + if outcome.Err != nil { + t.Fatalf("%s: outcome %s: %v", name, outcome.IssueID, outcome.Err) + } + if outcome.IssueID == last { + autoClosed, refusal = outcome.AutoClosedMolecule, outcome.MoleculeAutoCloseRefusal + } + } + } else { + res := s.closeStep(last, true) + autoClosed, refusal = res.AutoClosedMolecule, res.MoleculeAutoCloseRefusal + } + + if autoClosed != nil { + t.Errorf("%s: a guarded root auto-closed: %s", name, autoClosed.ID) + } + if want := guard.refusal(root).Error(); refusal != want { + t.Errorf("%s: MoleculeAutoCloseRefusal = %q, want the guard's own sentence %q", name, refusal, want) + } + for _, id := range closed { + if status, _ := s.row(id); status != string(types.StatusClosed) { + t.Errorf("%s: %s status = %s, want closed (the refusal must not undo it)", name, id, status) + } + } + if status, _ := s.row(root); status != string(types.StatusOpen) { + t.Errorf("%s: guarded root %s status = %s, want open", name, root, status) + } + } + } +} + +// RunMoleculeStepperClaimsTheNextReadyStepForTheActor pins the advance and its +// claim: the next ready step becomes in progress AND assigned to Actor; without +// AutoClaim nothing is written. +func RunMoleculeStepperClaimsTheNextReadyStepForTheActor(t *testing.T, ctx context.Context, fixture MoleculeFixture) { + t.Helper() + s := moleculeSeed{t, ctx, fixture} + root := fixture.IssuePrefix + "-advance" + a, b, c := root+".1", root+".2", root+".3" + s.issue(root, types.TypeMolecule, types.StatusOpen, false) + s.issue(a, types.TypeTask, types.StatusClosed, false) + s.issue(b, types.TypeTask, types.StatusOpen, false) + s.issue(c, types.TypeTask, types.StatusOpen, false) + for _, id := range []string{a, b, c} { + s.edge(id, root, types.DepParentChild) + } + s.edge(c, b, types.DepBlocks) + + res, err := fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: a}) + if err != nil { + t.Fatalf("Advance: %v", err) + } + if res.MoleculeID != root || res.Claimed || res.NextStep == nil || res.NextStep.ID != b { + t.Fatalf("Advance without a claim = %+v, want next %s in %s, unclaimed", res, b, root) + } + if status, assignee := s.row(b); status != string(types.StatusOpen) || assignee != "" { + t.Errorf("%s after an unclaimed advance = %s/%q, want open and unassigned", b, status, assignee) + } + + res, err = fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: a, AutoClaim: true}) + if err != nil { + t.Fatalf("Advance with a claim: %v", err) + } + if !res.Claimed || res.NextStep == nil || res.NextStep.ID != b || res.NextStep.Assignee != moleculeActor { + t.Fatalf("Advance with a claim = %+v, want %s claimed for %s", res, b, moleculeActor) + } + if status, assignee := s.row(b); status != string(types.StatusInProgress) || assignee != moleculeActor { + t.Errorf("%s after the claim = %s/%q, want in_progress assigned to %s", b, status, assignee, moleculeActor) + } + if status, _ := s.row(c); status != string(types.StatusOpen) { + t.Errorf("%s (blocked) status = %s, want open", c, status) + } +} + +// RunMoleculeStepperNeverTakesAStepAnotherActorHolds pins the refusal the claim +// carries: a ready step assigned to someone else is skipped for the next one, +// and left exactly as it was. +func RunMoleculeStepperNeverTakesAStepAnotherActorHolds(t *testing.T, ctx context.Context, fixture MoleculeFixture) { + t.Helper() + s := moleculeSeed{t, ctx, fixture} + root := fixture.IssuePrefix + "-held" + a, held, free := root+".1", root+".2", root+".3" + s.issue(root, types.TypeMolecule, types.StatusOpen, false) + s.issue(a, types.TypeTask, types.StatusClosed, false) + heldIssue := &types.Issue{ID: held, Title: "held", IssueType: types.TypeTask, Status: types.StatusOpen, Priority: 2, Assignee: "someone-else"} + if err := fixture.CreateIssue(ctx, heldIssue, moleculeActor); err != nil { + t.Fatalf("seed %s: %v", held, err) + } + s.issue(free, types.TypeTask, types.StatusOpen, false) + for _, id := range []string{a, held, free} { + s.edge(id, root, types.DepParentChild) + } + + res, err := fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: a, AutoClaim: true}) + if err != nil { + t.Fatalf("Advance: %v", err) + } + if !res.Claimed || res.NextStep == nil || res.NextStep.ID != free { + t.Fatalf("Advance = %+v, want %s skipped (held) and %s claimed", res, held, free) + } + if status, assignee := s.row(held); status != string(types.StatusOpen) || assignee != "someone-else" { + t.Errorf("held step %s = %s/%q, want untouched (open, someone-else)", held, status, assignee) + } +} + +// RunMoleculeStepperAnswersCompleteAndOutsideAMolecule pins the two answers +// that claim nothing. +func RunMoleculeStepperAnswersCompleteAndOutsideAMolecule(t *testing.T, ctx context.Context, fixture MoleculeFixture) { + t.Helper() + s := moleculeSeed{t, ctx, fixture} + orphan := fixture.IssuePrefix + "-orphan" + s.issue(orphan, types.TypeTask, types.StatusClosed, false) + res, err := fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: orphan, AutoClaim: true}) + if err != nil { + t.Fatalf("Advance(orphan): %v", err) + } + if res.MoleculeID != "" || res.NextStep != nil || res.Claimed || res.ClosedStep == nil || res.ClosedStep.ID != orphan { + t.Errorf("Advance(orphan) = %+v, want the step and no molecule", res) + } + + root := fixture.IssuePrefix + "-complete" + s.issue(root, types.TypeEpic, types.StatusOpen, false) + s.issue(root+".1", types.TypeTask, types.StatusClosed, false) + s.edge(root+".1", root, types.DepParentChild) + res, err = fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: root + ".1", AutoClaim: true}) + if err != nil { + t.Fatalf("Advance(complete): %v", err) + } + if res.MoleculeID != root || !res.Complete || res.NextStep != nil || res.Claimed { + t.Errorf("Advance(complete) = %+v, want %s complete", res, root) + } + + if _, err := fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: fixture.IssuePrefix + "-absent"}); !errors.Is(err, publicops.ErrNotFound) { + t.Errorf("Advance(absent) = %v, want ErrNotFound", err) + } +} + +// RunMoleculeStepperClaimsAWispStep pins the wisp plane: a wisp molecule's next +// step is claimed for the actor too. +func RunMoleculeStepperClaimsAWispStep(t *testing.T, ctx context.Context, fixture MoleculeFixture) { + t.Helper() + s := moleculeSeed{t, ctx, fixture} + root, done, last := s.molecule("wisp", types.TypeMolecule, true) + res, err := fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: done, AutoClaim: true}) + if err != nil { + t.Fatalf("Advance: %v", err) + } + if res.MoleculeID != root || !res.Claimed || res.NextStep == nil || res.NextStep.ID != last { + t.Fatalf("Advance over a wisp molecule = %+v, want %s claimed", res, last) + } + if status, assignee := s.row(last); status != string(types.StatusInProgress) || assignee != moleculeActor { + t.Errorf("wisp step %s = %s/%q, want in_progress assigned to %s", last, status, assignee, moleculeActor) + } +} diff --git a/backend/conformance/portable.go b/backend/conformance/portable.go index 050b7f008..488c02593 100644 --- a/backend/conformance/portable.go +++ b/backend/conformance/portable.go @@ -42,6 +42,7 @@ func RunPortableMethods(t *testing.T, factory Factory) { t.Run("ImportIssueComment", func(t *testing.T) { testImportIssueComment(t, factory) }) t.Run("AddIssueCommentBurstOrder", func(t *testing.T) { testAddIssueCommentBurstOrder(t, factory) }) t.Run("PromoteFromEphemeral", func(t *testing.T) { testPromoteFromEphemeral(t, factory) }) + t.Run("PromoteClosedWispPreservesSession", func(t *testing.T) { testPromoteClosedWispPreservesSession(t, factory) }) t.Run("UpdateIssueID", func(t *testing.T) { testUpdateIssueID(t, factory) }) t.Run("DeleteIssuesBySourceRepo", func(t *testing.T) { testDeleteIssuesBySourceRepo(t, factory) }) t.Run("CreateIssuesWithFullOptions", func(t *testing.T) { testCreateIssuesWithFullOptions(t, factory) }) @@ -577,6 +578,36 @@ func testPromoteFromEphemeral(t *testing.T, f Factory) { } } +// testPromoteClosedWispPreservesSession verifies that promoting a *closed* +// ephemeral wisp preserves its closed_by_session provenance. Before the fix +// (GH#4662), closed_by_session was absent from the shared issue select/scan +// and insert column set, so promotion (read wisp -> insert issue) hydrated a +// zero value and dropped the original closing session. Promotion re-inserts +// through that shared (classic) writer, so this case guards GH#4662's path +// only; the domain writer's copy of the column (db.insertIssueRow) is pinned +// by the domain/db Insert tests. +func testPromoteClosedWispPreservesSession(t *testing.T, f Factory) { + s := f(t) + c := ctx() + + must(t, s.CreateIssue(c, withDefaults(&types.Issue{ID: "test-cw", Title: "Closed wisp", Ephemeral: true}), "a")) + must(t, s.CloseIssue(c, "test-cw", "done", "a", "sess-xyz")) + + must(t, s.PromoteFromEphemeral(c, "test-cw", "a")) + + got, err := s.GetIssue(c, "test-cw") + must(t, err) + if got.Ephemeral { + t.Error("promoted issue still Ephemeral") + } + if got.Status != types.StatusClosed { + t.Errorf("promoted issue status = %q, want %q", got.Status, types.StatusClosed) + } + if got.ClosedBySession != "sess-xyz" { + t.Errorf("closed_by_session after promote = %q, want %q (GH#4662)", got.ClosedBySession, "sess-xyz") + } +} + // --- Id rekey / source-repo purge / batch create --- func testUpdateIssueID(t *testing.T, f Factory) { diff --git a/backend/conformance/reader_contract.go b/backend/conformance/reader_contract.go index 6910a5bbb..245a9efaa 100644 --- a/backend/conformance/reader_contract.go +++ b/backend/conformance/reader_contract.go @@ -113,6 +113,10 @@ type ReaderFixture struct { AddDependency func(context.Context, *types.Dependency, string) error // AddComment puts one comment on a durable issue. AddComment func(ctx context.Context, issueID, author, text string) error + // PromoteWisp moves a seeded wisp into the durable plane. It is the only + // way to seed a DURABLE row of an infra type: creating one routes it to the + // wisps plane on every backend. + PromoteWisp func(ctx context.Context, id, actor string) error } // RunReaderReadyDefaultTypeExclusionsYieldToAnExplicitType pins @@ -786,6 +790,112 @@ func RunReaderListReadyFlagRefusesAFilterItCannotCarry(t *testing.T, ctx context assertReaderPageIDs(t, "List --id without --ready", page, []string{one}) } +// RunReaderListQueryMatchesTheTitleOrTheID pins ListRequest.Query: `bd +// search`'s text, which matches a row whose title OR id contains it, case +// insensitively, and which narrows without lifting a default exclusion — and +// issueops.SearchListRequest, the request every `bd search` route sends, which +// does lift them. +// +// EVERY KIND OF ROW the search scope promises is seeded with the text, because +// a scope that silently loses one kind answers every other row correctly: a +// template, a gate, a wisp of an infra type, and a DURABLE row of that type — +// a promoted wisp, which a type filter that narrows an infra type to its +// ephemeral rows drops with no error. Each must come back under the bare scope +// and under its own type. +// +// It scopes itself with a label rather than an id set, so the served leg runs +// it as written: listIssues publishes no id parameter. +func RunReaderListQueryMatchesTheTitleOrTheID(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + if fixture.PromoteWisp == nil { + t.Fatal("fixture has no PromoteWisp: a durable row of an infra type cannot be seeded, and it is the row a narrowed type filter drops") + } + scope := readerLabel(fixture, "lsquery") + needle := strings.ToLower(fixture.IssuePrefix) + "qneedle" + titleHit := readerID(fixture, "lsquery", "title") + idHit := readerID(fixture, "lsquery", "idhit") + closedHit := readerID(fixture, "lsquery", "closed") + miss := readerID(fixture, "lsquery", "miss") + template := readerID(fixture, "lsquery", "template") + gate := readerID(fixture, "lsquery", "gate") + wispMessage := readerID(fixture, "lsquery", "wispmsg") + promotedMessage := readerID(fixture, "lsquery", "promotedmsg") + + // The title carries the needle in UPPER case and the request asks in lower, + // so a case-sensitive match finds nothing. + titleIssue := readerIssue(titleHit, types.TypeTask, scope) + titleIssue.Title = "fix the " + strings.ToUpper(needle) + " path" + // The id-hit's title says nothing about it: only its id can match. + idIssue := readerIssue(idHit, types.TypeTask, scope) + idIssue.Title = "unrelated words" + closedIssue := readerIssue(closedHit, types.TypeTask, scope) + closedIssue.Title = "old " + needle + closedIssue.Status = types.StatusClosed + missIssue := readerIssue(miss, types.TypeTask, scope) + missIssue.Title = "nothing to see" + templateIssue := readerIssue(template, types.TypeTask, scope) + templateIssue.Title = needle + " template" + templateIssue.IsTemplate = true + gateIssue := readerIssue(gate, types.TypeGate, scope) + gateIssue.Title = needle + " gate" + for _, issue := range []*types.Issue{titleIssue, idIssue, closedIssue, missIssue, templateIssue, gateIssue} { + seedReaderIssue(t, ctx, fixture, issue) + } + // Two rows of the same infra type, one per plane. `message` is built in, + // so the type is valid on every backend without configuration. + for _, id := range []string{wispMessage, promotedMessage} { + message := readerIssue(id, types.TypeMessage, scope) + message.Title = needle + " message" + message.Ephemeral = true + seedReaderWisp(t, ctx, fixture, message) + } + if err := fixture.PromoteWisp(ctx, promotedMessage, "seed"); err != nil { + t.Fatalf("promote wisp %s: %v", promotedMessage, err) + } + + searchType := func(issueType types.IssueType) publicops.ListRequest { + req := searchScoped(needle, scope) + req.IssueType = string(issueType) + return req + } + + for _, tc := range []struct { + name string + req publicops.ListRequest + want []string + }{ + {"a title match, case-insensitively, under the default exclusions", publicops.ListRequest{Labels: []string{scope}, Query: needle}, []string{titleHit}}, + {"AllFlag takes the closed match back", publicops.ListRequest{Labels: []string{scope}, Query: needle, AllFlag: true}, []string{titleHit, closedHit}}, + {"an id match whose title does not contain the text", publicops.ListRequest{Labels: []string{scope}, Query: idHit, AllFlag: true}, []string{idHit}}, + {"text nothing contains", publicops.ListRequest{Labels: []string{scope}, Query: needle + "-absent", AllFlag: true}, nil}, + {"no text narrows nothing", publicops.ListRequest{Labels: []string{scope}}, []string{titleHit, idHit, miss}}, + {"SearchListRequest, `bd search`'s scope, takes every status and every kind of row back", searchScoped(needle, scope), []string{titleHit, closedHit, template, gate, wispMessage, promotedMessage}}, + {"SearchListRequest under an infra type keeps both planes' rows of it", searchType(types.TypeMessage), []string{wispMessage, promotedMessage}}, + {"SearchListRequest under the gate type", searchType(types.TypeGate), []string{gate}}, + {"SearchListRequest under a plain type keeps its templates", searchType(types.TypeTask), []string{titleHit, closedHit, template}}, + // Outside the search scope an infra type alone reads only its + // ephemeral rows, which is where creating one puts it; IncludeEphemeral + // is what lifts that narrowing to the durable rows as well. + {"an infra type alone reads only its ephemeral rows", publicops.ListRequest{Labels: []string{scope}, Query: needle, IssueType: string(types.TypeMessage)}, []string{wispMessage}}, + {"IncludeEphemeral lifts that narrowing", publicops.ListRequest{Labels: []string{scope}, Query: needle, IssueType: string(types.TypeMessage), IncludeEphemeral: true}, []string{wispMessage, promotedMessage}}, + } { + page, err := fixture.Reader.List(ctx, tc.req) + if err != nil { + t.Errorf("List %s: %v", tc.name, err) + continue + } + assertReaderPageIDSet(t, "List "+tc.name, page, tc.want) + } +} + +// searchScoped is the library's search request narrowed to one case's label, +// the request every `bd search` route sends. +func searchScoped(query, label string) publicops.ListRequest { + req := publicops.SearchListRequest(query) + req.Labels = []string{label} + return req +} + // RunReaderListEmptyPageIsWellFormed pins the page shape when nothing matches // (reader.go:376-381). Items is never nil for a successful call, so no caller // has to tell null from empty to learn that nothing matched, and an empty page @@ -3065,6 +3175,335 @@ func assertReaderBriefRow(t *testing.T, what string, brief, full *types.Issue) { } } +// RunReaderListTimeBoundsAreStrictAndWholeSecond pins the eight time bounds +// ListRequest carries beside the created pair — UpdatedAfter/Before, +// ClosedAfter/Before, DeferAfter/Before and DueAfter/Before — at their exact +// boundaries (reader.go: each is a strict bound on its column). +// +// THE BOUNDARY IS THE ASSERTION. Three rows sit one second apart around an +// instant T, so a body that compared inclusively, swapped the two ends, or +// bound the wrong column fails on a row rather than on nothing: +// +// - after=T selects exactly the T+1s row and before=T exactly the T-1s row, +// so the row AT T is excluded by both; +// - a bound carrying a sub-second remainder (T+900ms) behaves as T on both +// ends, because the bound is compared at whole-second precision (the +// storage builder formats it as RFC 3339 without a fraction); +// - a row whose column is NULL — an open row's closed_at, an unset +// defer_until or due_at — never matches either bound; +// - a bound spelled in a non-UTC zone selects exactly what the same instant +// spelled in UTC does. An offset is part of the instant, not decoration, +// and a body that dropped it would move the bound by the offset. +// +// Every family scopes itself by id and seeds no labels, so no write after the +// insert can move updated_at off the instant it was seeded at; AllFlag keeps +// the closed rows in view. +func RunReaderListTimeBoundsAreStrictAndWholeSecond(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + at := time.Now().UTC().Truncate(time.Second).Add(-3 * time.Hour) + created := at.Add(-time.Hour) + instants := []struct { + tag string + at time.Time + }{ + {"early", at.Add(-time.Second)}, + {"exact", at}, + {"late", at.Add(time.Second)}, + } + + for _, family := range []struct { + name string + // set stamps the family's column onto a seed. + set func(issue *types.Issue, v time.Time) + // nullable seeds a fourth row with the column NULL. + nullable bool + after func(*publicops.ListRequest, *time.Time) + before func(*publicops.ListRequest, *time.Time) + }{ + { + name: "updated", + set: func(issue *types.Issue, v time.Time) { issue.UpdatedAt = v }, + after: func(r *publicops.ListRequest, v *time.Time) { r.UpdatedAfter = v }, + before: func(r *publicops.ListRequest, v *time.Time) { r.UpdatedBefore = v }, + }, + { + name: "closed", + set: func(issue *types.Issue, v time.Time) { + issue.Status = types.StatusClosed + issue.UpdatedAt = v + issue.ClosedAt = &v + }, + nullable: true, + after: func(r *publicops.ListRequest, v *time.Time) { r.ClosedAfter = v }, + before: func(r *publicops.ListRequest, v *time.Time) { r.ClosedBefore = v }, + }, + { + name: "defer", + set: func(issue *types.Issue, v time.Time) { issue.DeferUntil = &v }, + nullable: true, + after: func(r *publicops.ListRequest, v *time.Time) { r.DeferAfter = v }, + before: func(r *publicops.ListRequest, v *time.Time) { r.DeferBefore = v }, + }, + { + name: "due", + set: func(issue *types.Issue, v time.Time) { issue.DueAt = &v }, + nullable: true, + after: func(r *publicops.ListRequest, v *time.Time) { r.DueAfter = v }, + before: func(r *publicops.ListRequest, v *time.Time) { r.DueBefore = v }, + }, + } { + caseTag := "ltb" + family.name + ids := map[string]string{} + var scope []string + for _, inst := range instants { + id := readerID(fixture, caseTag, inst.tag) + ids[inst.tag] = id + scope = append(scope, id) + issue := readerIssue(id, types.TypeTask, "") + issue.CreatedAt, issue.UpdatedAt = created, created + family.set(issue, inst.at) + seedReaderIssue(t, ctx, fixture, issue) + } + if family.nullable { + id := readerID(fixture, caseTag, "null") + scope = append(scope, id) + issue := readerIssue(id, types.TypeTask, "") + issue.CreatedAt, issue.UpdatedAt = created, created + seedReaderIssue(t, ctx, fixture, issue) + } + idScope := readerIDFilter(scope...) + + list := func(what string, apply func(*publicops.ListRequest, *time.Time), bound time.Time) []string { + t.Helper() + req := publicops.ListRequest{IDFilter: idScope, AllFlag: true} + apply(&req, &bound) + page, err := fixture.Reader.List(ctx, req) + if err != nil { + t.Fatalf("List (%s %s): %v", family.name, what, err) + } + assertReaderPageNotNil(t, "List ("+family.name+" "+what+")", page) + got := readerPageIDs(page) + slices.Sort(got) + return got + } + expect := func(what string, apply func(*publicops.ListRequest, *time.Time), bound time.Time, want string) { + t.Helper() + if got := list(what, apply, bound); !slices.Equal(got, []string{want}) { + t.Errorf("List (%s %s %s) = %v, want exactly [%s]", family.name, what, bound.Format(time.RFC3339Nano), got, want) + } + } + + plus2 := time.FixedZone("UTC+2", 2*60*60) + for _, bound := range []struct { + what string + v time.Time + }{ + {"at T", at}, + {"at T with a sub-second remainder", at.Add(900 * time.Millisecond)}, + {"at T spelled in a +02:00 zone", at.In(plus2)}, + } { + expect("after "+bound.what, family.after, bound.v, ids["late"]) + expect("before "+bound.what, family.before, bound.v, ids["early"]) + } + + // The NULL row is outside even the widest bounds on both ends. + if family.nullable { + wide := at.Add(-24 * time.Hour) + if got, want := list("after a day earlier", family.after, wide), sortedCopy(ids["early"], ids["exact"], ids["late"]); !slices.Equal(got, want) { + t.Errorf("List (%s after a day earlier) = %v, want %v — a NULL column never matches", family.name, got, want) + } + if got, want := list("before a day later", family.before, at.Add(24*time.Hour)), sortedCopy(ids["early"], ids["exact"], ids["late"]); !slices.Equal(got, want) { + t.Errorf("List (%s before a day later) = %v, want %v — a NULL column never matches", family.name, got, want) + } + } + } +} + +// RunReaderListFilterFamiliesNarrowToTheirRows pins one included and one +// excluded row for each remaining ListRequest filter family that `bd list` +// publishes beyond the scope filters: the priority trio, the three text +// substrings, the empty-description and no-labels predicates, the top-level +// predicate, the type exclusion, the spec prefix, the label pattern and +// regex, the external-ref pair, the pinned-flag pair, the deferred and +// overdue predicates, the status exclusion and the molecule type. +// +// Each row is scoped by id and every arm asks AllFlag (the pinned arms +// excepted, which are about that interplay), so an arm whose filter the body +// dropped answers its whole scope and fails, and one whose filter the body +// inverted answers the other row. +// +// PinnedFlag with NoPinnedFlag is a contradiction, and the role refuses it as +// a validation error rather than letting one of the two silently win. +// ParentID with NoParent is refused the same way, as CountRequest refuses it. +func RunReaderListFilterFamiliesNarrowToTheirRows(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + id := func(name string) string { return readerID(fixture, "lff", name) } + seed := func(name string, mutate func(*types.Issue)) string { + t.Helper() + issue := readerIssue(id(name), types.TypeTask, "") + if mutate != nil { + mutate(issue) + } + seedReaderIssue(t, ctx, fixture, issue) + return issue.ID + } + intp := func(v int) *int { return &v } + past := time.Now().UTC().Truncate(time.Second).Add(-48 * time.Hour) + future := time.Now().UTC().Truncate(time.Second).Add(48 * time.Hour) + label := readerLabel(fixture, "lffpat") + external := fixture.IssuePrefix + "-LFF-ext-17" + spec := "docs/" + fixture.IssuePrefix + "-lff/" + + p0 := seed("p0", func(i *types.Issue) { i.Priority = 0 }) + p2 := seed("p2", func(i *types.Issue) { i.Priority = 2 }) + p4 := seed("p4", func(i *types.Issue) { i.Priority = 4 }) + + textT := seed("text-t", func(i *types.Issue) { i.Title = "a title carrying ttok-lff" }) + textD := seed("text-d", func(i *types.Issue) { i.Description = "a description carrying dtok-lff" }) + textN := seed("text-n", func(i *types.Issue) { i.Notes = "notes carrying ntok-lff" }) + + labeled := seed("labeled", func(i *types.Issue) { i.Labels = []string{label} }) + unlabeled := seed("unlabeled", nil) + + parent := seed("parent", func(i *types.Issue) { i.IssueType = types.TypeEpic }) + child := seed("child", nil) + if err := fixture.AddDependency(ctx, &types.Dependency{IssueID: child, DependsOnID: parent, Type: types.DepParentChild}, "seed"); err != nil { + t.Fatalf("seed edge %s -> %s: %v", child, parent, err) + } + loose := seed("loose", nil) + + typeTask := seed("type-task", nil) + typeBug := seed("type-bug", func(i *types.Issue) { i.IssueType = types.TypeBug }) + typeChore := seed("type-chore", func(i *types.Issue) { i.IssueType = types.TypeChore }) + + specced := seed("specced", func(i *types.Issue) { i.SpecID = spec + "design.md" }) + unspecced := seed("unspecced", nil) + + extRow := seed("ext", func(i *types.Issue) { i.ExternalRef = &external }) + extOther := seed("ext-other", func(i *types.Issue) { + other := fixture.IssuePrefix + "-other-99" + i.ExternalRef = &other + }) + + pinned := seed("pinned", func(i *types.Issue) { i.Pinned = true }) + unpinned := seed("unpinned", nil) + + deferred := seed("deferred", func(i *types.Issue) { i.DeferUntil = &future }) + undeferred := seed("undeferred", nil) + + overdue := seed("overdue", func(i *types.Issue) { i.DueAt = &past }) + dueLater := seed("due-later", func(i *types.Issue) { i.DueAt = &future }) + closedOverdue := seed("closed-overdue", func(i *types.Issue) { + i.Status = types.StatusClosed + closedAt := time.Now().UTC().Truncate(time.Second).Add(-time.Hour) + i.ClosedAt = &closedAt + i.DueAt = &past + }) + noDue := seed("no-due", nil) + + swarm := seed("mol-swarm", func(i *types.Issue) { i.MolType = types.MolTypeSwarm }) + patrol := seed("mol-patrol", func(i *types.Issue) { i.MolType = types.MolTypePatrol }) + + stOpen := seed("st-open", nil) + stProgress := seed("st-progress", func(i *types.Issue) { i.Status = types.StatusInProgress }) + stBlocked := seed("st-blocked", func(i *types.Issue) { i.Status = types.StatusBlocked }) + stClosed := seed("st-closed", func(i *types.Issue) { + i.Status = types.StatusClosed + closedAt := time.Now().UTC().Truncate(time.Second).Add(-time.Hour) + i.ClosedAt = &closedAt + }) + statusScope := readerIDFilter(stOpen, stProgress, stBlocked, stClosed) + + molType := func(m types.MolType) *publicops.MolType { return &m } + scoped := func(ids ...string) publicops.ListRequest { + return publicops.ListRequest{IDFilter: readerIDFilter(ids...), AllFlag: true} + } + with := func(req publicops.ListRequest, mutate func(*publicops.ListRequest)) publicops.ListRequest { + mutate(&req) + return req + } + + for _, test := range []struct { + name string + req publicops.ListRequest + want []string + }{ + {"Priority is exact", with(scoped(p0, p2, p4), func(r *publicops.ListRequest) { r.Priority = intp(2) }), []string{p2}}, + {"Priority 0 is a value, not unset", with(scoped(p0, p2, p4), func(r *publicops.ListRequest) { r.Priority = intp(0) }), []string{p0}}, + {"PriorityMin is inclusive", with(scoped(p0, p2, p4), func(r *publicops.ListRequest) { r.PriorityMin = intp(2) }), []string{p2, p4}}, + {"PriorityMax is inclusive", with(scoped(p0, p2, p4), func(r *publicops.ListRequest) { r.PriorityMax = intp(2) }), []string{p0, p2}}, + {"PriorityMin and PriorityMax compose", with(scoped(p0, p2, p4), func(r *publicops.ListRequest) { r.PriorityMin, r.PriorityMax = intp(1), intp(3) }), []string{p2}}, + + {"TitleContains is a case-insensitive substring", with(scoped(textT, textD, textN), func(r *publicops.ListRequest) { r.TitleContains = "TTOK-LFF" }), []string{textT}}, + {"DescContains reads the description only", with(scoped(textT, textD, textN), func(r *publicops.ListRequest) { r.DescContains = "dtok-lff" }), []string{textD}}, + {"NotesContains reads the notes only", with(scoped(textT, textD, textN), func(r *publicops.ListRequest) { r.NotesContains = "ntok-lff" }), []string{textN}}, + {"EmptyDesc keeps the rows with no description", with(scoped(textT, textD, textN), func(r *publicops.ListRequest) { r.EmptyDesc = true }), []string{textT, textN}}, + + {"NoLabels keeps the unlabeled row", with(scoped(labeled, unlabeled), func(r *publicops.ListRequest) { r.NoLabels = true }), []string{unlabeled}}, + {"LabelPattern is a glob", with(scoped(labeled, unlabeled), func(r *publicops.ListRequest) { r.LabelPattern = fixture.IssuePrefix + "-scope-lff*" }), []string{labeled}}, + {"LabelRegex is a regular expression", with(scoped(labeled, unlabeled), func(r *publicops.ListRequest) { r.LabelRegex = "-scope-lffp.t$" }), []string{labeled}}, + + {"NoParent keeps the top-level rows", with(scoped(parent, child, loose), func(r *publicops.ListRequest) { r.NoParent = true }), []string{parent, loose}}, + + {"ExcludeTypes drops the named type", with(scoped(typeTask, typeBug, typeChore), func(r *publicops.ListRequest) { r.ExcludeTypes = []string{"bug"} }), []string{typeTask, typeChore}}, + {"ExcludeTypes takes a comma-separated value", with(scoped(typeTask, typeBug, typeChore), func(r *publicops.ListRequest) { r.ExcludeTypes = []string{"bug,chore"} }), []string{typeTask}}, + + {"SpecPrefix is a prefix", with(scoped(specced, unspecced), func(r *publicops.ListRequest) { r.SpecPrefix = spec }), []string{specced}}, + + {"ExternalContains is a case-insensitive substring", with(scoped(extRow, extOther), func(r *publicops.ListRequest) { r.ExternalContains = "lff-EXT" }), []string{extRow}}, + {"ExternalRef is exact", with(scoped(extRow, extOther), func(r *publicops.ListRequest) { r.ExternalRef = external }), []string{extRow}}, + + {"AllFlag alone admits both pinned-flag states", scoped(pinned, unpinned), []string{pinned, unpinned}}, + {"PinnedFlag selects the flagged row", publicops.ListRequest{IDFilter: readerIDFilter(pinned, unpinned), PinnedFlag: true}, []string{pinned}}, + {"NoPinnedFlag holds the unflagged predicate under AllFlag", with(scoped(pinned, unpinned), func(r *publicops.ListRequest) { r.NoPinnedFlag = true }), []string{unpinned}}, + + {"DeferredFlag keeps the deferred row", with(scoped(deferred, undeferred), func(r *publicops.ListRequest) { r.DeferredFlag = true }), []string{deferred}}, + + {"OverdueFlag keeps the open row past its due date", with(scoped(overdue, dueLater, closedOverdue, noDue), func(r *publicops.ListRequest) { r.OverdueFlag = true }), []string{overdue}}, + + {"ExcludeStatus under AllFlag keeps every status not named", with(scoped(stOpen, stProgress, stBlocked, stClosed), func(r *publicops.ListRequest) { r.ExcludeStatus = []string{"closed"} }), []string{stOpen, stProgress, stBlocked}}, + {"ExcludeStatus takes repeated and comma-separated values", with(scoped(stOpen, stProgress, stBlocked, stClosed), func(r *publicops.ListRequest) { r.ExcludeStatus = []string{"blocked,in_progress", " closed "} }), []string{stOpen}}, + {"ExcludeStatus adds to the default exclusions rather than replacing them", publicops.ListRequest{IDFilter: statusScope, ExcludeStatus: []string{"blocked"}}, []string{stOpen, stProgress}}, + {"ExcludeStatus narrows an explicit Status", publicops.ListRequest{IDFilter: statusScope, Status: "open,blocked,closed", ExcludeStatus: []string{"blocked"}}, []string{stOpen, stClosed}}, + + {"MolType is exact", with(scoped(swarm, patrol), func(r *publicops.ListRequest) { r.MolType = molType(types.MolTypeSwarm) }), []string{swarm}}, + } { + page, err := fixture.Reader.List(ctx, test.req) + if err != nil { + t.Errorf("List (%s): %v", test.name, err) + continue + } + assertReaderPageIDSet(t, "List ("+test.name+")", page, test.want) + } + + // An exclusion naming no status in the workspace vocabulary is refused, + // never an exclusion that silently excludes nothing. + if _, err := fixture.Reader.List(ctx, publicops.ListRequest{IDFilter: statusScope, ExcludeStatus: []string{"clsoed"}}); !errors.Is(err, publicops.ErrValidation) { + t.Errorf("List with ExcludeStatus naming an unknown status = %v, want an error wrapping ErrValidation", err) + } + + _, err := fixture.Reader.List(ctx, publicops.ListRequest{ + IDFilter: readerIDFilter(pinned, unpinned), PinnedFlag: true, NoPinnedFlag: true, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("List with PinnedFlag and NoPinnedFlag = %v, want an error wrapping ErrValidation", err) + } + + _, err = fixture.Reader.List(ctx, publicops.ListRequest{ + IDFilter: readerIDFilter(parent, child, loose), ParentID: parent, NoParent: true, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("List with ParentID and NoParent = %v, want an error wrapping ErrValidation", err) + } +} + +// sortedCopy returns its arguments as a sorted slice. +func sortedCopy(ids ...string) []string { + out := slices.Clone(ids) + slices.Sort(out) + return out +} + // readerIssue builds the seed every case starts from: an open, unassigned, // unblocked task that qualifies for ready work. A case that needs it to fail one // of those tests changes the field it means to test and nothing else. diff --git a/backend/conformance/retention_epoch_contract.go b/backend/conformance/retention_epoch_contract.go index 472b7a896..b2c0d100e 100644 --- a/backend/conformance/retention_epoch_contract.go +++ b/backend/conformance/retention_epoch_contract.go @@ -769,7 +769,21 @@ type EpochFixture struct { // Version now resolves to under the new epoch. A nil hook means this // backend cannot report that, and the case that needs it skips with // that reason. + // + // It only reads: it mints nothing and changes no state. It returns the + // address it was given when nothing carried the Version to a new one, + // and an error for an address the store does not serve. CurrentAddressFor func(ctx context.Context, storeID string, oldAddress Address) (Address, error) + + // LoseVersion records that storeID no longer serves the Version named by + // address. That address, and every address the same Version was carried + // to or from by a token-scheme change, resolves GoneReorganization from + // then on, in every later epoch: an epoch voids what the store lost, + // never what it still serves (R20-n). It is idempotent, never revives + // anything, and returns an error for an address storeID never minted. A + // nil LoseVersion means this backend cannot record a loss, and the cases + // that need one skip with that reason. + LoseVersion func(ctx context.Context, storeID string, address Address) error } // RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange pins R20-m: a @@ -819,94 +833,258 @@ func RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange(t *testing.T, ct // RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed pins R20-n — "Rev7 // tightening... the clause most likely to be gotten wrong" in the -// architecture doc's own words. A prior-epoch Address goes -// GoneReorganization UNLESS the backend still serves that Version, in which -// case it must stay Live AND additionally report the Address it now -// resolves to under the new epoch. +// architecture doc's own words: an epoch voids what the store lost, never +// what it still serves. // -// StillServes is an ORACLE here, not a control: this case cannot make a real -// backend keep serving one address and drop another, since Phase 0 wires no -// real backend. It asks StillServes what the fixture (once real) decided, -// and checks the rest of the contract's promise against that decision for -// both outcomes. +// Survival is RECORDED, never inferred (gastownhall/beads#6664, bee-ghosttrack +// review 5360880888, Major 1). An earlier form of this case made a Version +// survive by minting it again in every later epoch, and treated a Version +// nobody minted again as lost. That reads loss off the absence of a mint, so +// it could not express a Version the store lost after minting it, and it +// voided every survivor that nobody happened to mint again. Here a restore or +// a destructive reinit leaves every address row alone: an address the store +// still serves stays Live at its own address with no upkeep, and the only way +// an address goes Gone is LoseVersion saying so. +// +// Each phase is a named subtest, so a backend that cannot record a loss skips +// only the phases that need LoseVersion, and a failure names its phase. func RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t *testing.T, ctx context.Context, fixture EpochFixture) { t.Helper() - if fixture.MintUnderEpoch == nil { - t.Skip("this backend has no way to mint a Version under a known epoch (MintUnderEpoch is nil)") - } - if fixture.BumpEpoch == nil { - t.Skip("this backend has no epoch concept yet (BumpEpoch is nil)") - } - if fixture.StillServes == nil { - t.Skip("this backend cannot report whether it still serves a prior-epoch Version (StillServes is nil)") - } - if fixture.Resolve == nil { - t.Skip("this backend does not yet report retention state (Resolve is nil)") - } - if fixture.CurrentAddressFor == nil { - t.Skip("this backend cannot report a still-served Version's new Address (CurrentAddressFor is nil)") - } - store := epochStore(fixture, "voids") + epochSkipUnlessReady(t, fixture, false) - addrA, err := fixture.MintUnderEpoch(ctx, store, "record-a") - if err != nil { - t.Fatalf("MintUnderEpoch(record-a): %v", err) + // survivor-and-lost: of two Versions minted before a transition, the one + // the store loses goes Gone and the other stays Live at the address it + // already had, with no re-mint, for both triggers that leave addresses + // alone. + t.Run("survivor-and-lost", func(t *testing.T) { + if fixture.LoseVersion == nil { + t.Skip(epochLoseVersionSkip) + } + for _, trigger := range []EpochBumpTrigger{EpochBumpTriggerRestore, EpochBumpTriggerDestructiveReinit} { + t.Run(trigger.String(), func(t *testing.T) { + store := epochStore(fixture, "survivor-"+trigger.String()) + addrA := epochMintAddress(t, ctx, fixture, store, "record-a") + addrB := epochMintAddress(t, ctx, fixture, store, "record-b") + + newEpoch := epochBumpTo(t, ctx, fixture, store, trigger) + epochLoseAddress(t, ctx, fixture, store, addrB) + + epochRequireLive(t, ctx, fixture, store, addrA, newEpoch, + "record-a was never lost, so the transition leaves it served at its own address with no re-mint (R20-n's exception)") + epochRequireGone(t, ctx, fixture, store, addrB, newEpoch, + "record-b was lost, so the transition voids it (R20-n)") + + current := epochCurrentAddress(t, ctx, fixture, store, addrA) + epochRequireLive(t, ctx, fixture, store, current, newEpoch, + "the address CurrentAddressFor reports for a survivor must be served") + epochRequireLive(t, ctx, fixture, store, addrA, newEpoch, + "asking CurrentAddressFor must not retire or move the survivor's address") + + if lostCurrent, err := fixture.CurrentAddressFor(ctx, store, addrB); err == nil { + t.Errorf("CurrentAddressFor(a lost address) = %s with no error, want an error: a lost Version has no current address", lostCurrent) + } + epochRequireGone(t, ctx, fixture, store, addrB, newEpoch, + "CurrentAddressFor on a lost address must not bring it back") + }) + } + }) + + // gone-is-terminal: once an address is lost it stays lost. A later mint of + // the same id starts a new lineage under a new address, and neither that + // mint nor CurrentAddressFor revives the lost one (bee-ghosttrack's + // assertion for Major 1: a read-only lookup must not mint a replacement + // that makes a lost address look served). + t.Run("gone-is-terminal", func(t *testing.T) { + if fixture.LoseVersion == nil { + t.Skip(epochLoseVersionSkip) + } + store := epochStore(fixture, "terminal") + lost := epochMintAddress(t, ctx, fixture, store, "record-g") + epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) + epochLoseAddress(t, ctx, fixture, store, lost) + laterEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) + + fresh := epochMintAddress(t, ctx, fixture, store, "record-g") + if fresh == lost { + t.Fatalf("MintUnderEpoch(record-g) returned %s, the address already lost: a lost address is never handed out again", lost) + } + epochRequireLive(t, ctx, fixture, store, fresh, laterEpoch, + "a fresh mint of the id is a new lineage and is served") + epochRequireGone(t, ctx, fixture, store, lost, laterEpoch, + "a later mint of the same id must not revive a lost address") + + if replacement, err := fixture.CurrentAddressFor(ctx, store, lost); err == nil { + t.Errorf("CurrentAddressFor(a lost address) = %s with no error, want an error: asking where a lost address resolves must not mint a replacement", replacement) + } + epochRequireGone(t, ctx, fixture, store, lost, laterEpoch, + "CurrentAddressFor on a lost address must not revive it") + + // Losing it a second time is a no-op that leaves the fresh lineage + // alone. + epochLoseAddress(t, ctx, fixture, store, lost) + epochRequireLive(t, ctx, fixture, store, fresh, laterEpoch, + "losing the old address again must leave the fresh lineage served") + }) + + // survival-needs-no-upkeep: with nothing lost, an address stays Live across + // any number of counter-only transitions without being minted again, and a + // later mint of the same id neither retires it nor revives anything. This + // is the phase the earlier, mint-driven form failed: it answered Gone for + // every survivor nobody minted again. + t.Run("survival-needs-no-upkeep", func(t *testing.T) { + store := epochStore(fixture, "upkeep") + kept := epochMintAddress(t, ctx, fixture, store, "record-c") + epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) + epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerDestructiveReinit) + finalEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) + + epochRequireLive(t, ctx, fixture, store, kept, finalEpoch, + "nothing was lost, so three counter-only transitions leave the address served without a re-mint") + + fresh := epochMintAddress(t, ctx, fixture, store, "record-c") + if fresh == kept { + t.Fatalf("MintUnderEpoch(record-c) returned %s again after three bumps, want a new address for the new epoch", kept) + } + epochRequireLive(t, ctx, fixture, store, kept, finalEpoch, + "a later mint of the same id must not retire a served address") + epochRequireLive(t, ctx, fixture, store, fresh, finalEpoch, + "the fresh mint is served") + + current := epochCurrentAddress(t, ctx, fixture, store, kept) + epochRequireLive(t, ctx, fixture, store, current, finalEpoch, + "the current address of a survivor must be served") + epochRequireLive(t, ctx, fixture, store, kept, finalEpoch, + "asking for the current address must not change the survivor") + }) +} + +// RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose pins R20-n's retained +// mapping for the one trigger that changes how addresses are encoded. A +// token-scheme-change bump gives every Version the store still serves a new +// address under the new epoch and keeps the old address resolving, so a holder +// of the old address is neither stranded nor pointed at something else. A +// Version the store already lost gets no new address and stays Gone. +func RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose(t *testing.T, ctx context.Context, fixture EpochFixture) { + t.Helper() + epochSkipUnlessReady(t, fixture, true) + store := epochStore(fixture, "scheme-change") + + addrA := epochMintAddress(t, ctx, fixture, store, "record-a") + addrB := epochMintAddress(t, ctx, fixture, store, "record-b") + // record-b is lost in the epoch it was minted in, which a store may do. + epochLoseAddress(t, ctx, fixture, store, addrB) + + newEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange) + + epochRequireLive(t, ctx, fixture, store, addrA, newEpoch, + "record-a is still served after the scheme change, through the retained mapping") + epochRequireGone(t, ctx, fixture, store, addrB, newEpoch, + "record-b was lost before the scheme change, which must not carry it") + + carried := epochCurrentAddress(t, ctx, fixture, store, addrA) + if carried == addrA { + t.Errorf("CurrentAddressFor(%s) = the same address after a token-scheme change, want a new one: a scheme change re-encodes every served address, which is what tells a carry from a no-op", addrA) } - addrB, err := fixture.MintUnderEpoch(ctx, store, "record-b") - if err != nil { - t.Fatalf("MintUnderEpoch(record-b): %v", err) + epochRequireLive(t, ctx, fixture, store, carried, newEpoch, + "the carried address must be served under the new epoch") + epochRequireLive(t, ctx, fixture, store, addrA, newEpoch, + "the old address must keep resolving after its carried address is looked up") + + if again := epochCurrentAddress(t, ctx, fixture, store, carried); again != carried { + t.Errorf("CurrentAddressFor(%s) = %s, want the carried address itself: from the newest address the mapping is already current", carried, again) + } + if lostCurrent, err := fixture.CurrentAddressFor(ctx, store, addrB); err == nil { + t.Errorf("CurrentAddressFor(a lost address) = %s with no error, want an error: a lost Version is not carried", lostCurrent) + } +} + +// RunACarriedAddressKeepsResolvingAcrossLaterBumps pins that a carried mapping +// is recorded once and then simply persists: later counter-only transitions do +// not change it, and a second token-scheme change extends it to the newest +// address without breaking any older one. Every address of the Version points +// directly at the newest address (one hop from any member), never along a +// chain. +func RunACarriedAddressKeepsResolvingAcrossLaterBumps(t *testing.T, ctx context.Context, fixture EpochFixture) { + t.Helper() + epochSkipUnlessReady(t, fixture, false) + store := epochStore(fixture, "carried-later") + + addrA := epochMintAddress(t, ctx, fixture, store, "record-a") + epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) + epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange) + addrA1 := epochCurrentAddress(t, ctx, fixture, store, addrA) + if addrA1 == addrA { + t.Fatalf("CurrentAddressFor(%s) = the same address after a token-scheme change, want a new one", addrA) } - newEpoch, err := fixture.BumpEpoch(ctx, store, EpochBumpTriggerRestore) - if err != nil { - t.Fatalf("BumpEpoch: %v", err) + // Two counter-only transitions, with nothing minted in between. + epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) + counterEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerDestructiveReinit) + epochRequireLive(t, ctx, fixture, store, addrA, counterEpoch, + "the original address must still resolve after counter-only transitions") + epochRequireLive(t, ctx, fixture, store, addrA1, counterEpoch, + "the carried address must still resolve after counter-only transitions") + if got := epochCurrentAddress(t, ctx, fixture, store, addrA); got != addrA1 { + t.Errorf("CurrentAddressFor(%s) = %s, want %s: a counter-only transition does not change the mapping", addrA, got, addrA1) } - servesA, err := fixture.StillServes(ctx, store, addrA) - if err != nil { - t.Fatalf("StillServes(%s): %v", addrA, err) + // A second scheme change carries the Version again. + secondEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange) + addrA2 := epochCurrentAddress(t, ctx, fixture, store, addrA) + if addrA2 == addrA || addrA2 == addrA1 { + t.Fatalf("CurrentAddressFor(%s) = %s after a second scheme change, want an address different from %s and %s", addrA, addrA2, addrA, addrA1) } - servesB, err := fixture.StillServes(ctx, store, addrB) - if err != nil { - t.Fatalf("StillServes(%s): %v", addrB, err) + for _, member := range []Address{addrA, addrA1, addrA2} { + epochRequireLive(t, ctx, fixture, store, member, secondEpoch, + "every address of a carried Version must resolve after a second scheme change") } - if servesA == servesB { - t.Skip("this scenario needs one still-served and one no-longer-served address to exercise both halves of R20-n; StillServes reported the same answer for both, so this fixture gives this case nothing to contrast") + if got := epochCurrentAddress(t, ctx, fixture, store, addrA1); got != addrA2 { + t.Errorf("CurrentAddressFor(%s) = %s, want %s: every address of the Version points straight at the newest one", addrA1, got, addrA2) } - stillServed, noLongerServed := addrA, addrB - if servesB && !servesA { - stillServed, noLongerServed = addrB, addrA + finalEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) + epochRequireLive(t, ctx, fixture, store, addrA2, finalEpoch, + "the newest carried address must still resolve after a later restore") +} + +// RunALostAddressStaysGoneAcrossASchemeChange pins that loss is terminal even +// across a token-scheme change. Losing a Version loses every address of its +// lineage at once, and a later scheme change must not carry a lost lineage +// back into service. +func RunALostAddressStaysGoneAcrossASchemeChange(t *testing.T, ctx context.Context, fixture EpochFixture) { + t.Helper() + epochSkipUnlessReady(t, fixture, true) + store := epochStore(fixture, "lost-scheme-change") + + addrA := epochMintAddress(t, ctx, fixture, store, "record-a") + epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange) + addrA1 := epochCurrentAddress(t, ctx, fixture, store, addrA) + lostEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore) + + // One lineage, two addresses: losing either loses both. + epochLoseAddress(t, ctx, fixture, store, addrA) + epochRequireGone(t, ctx, fixture, store, addrA, lostEpoch, + "the original address of a lost Version must be Gone") + epochRequireGone(t, ctx, fixture, store, addrA1, lostEpoch, + "the carried address of a lost Version must be Gone too") + + schemeEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange) + epochRequireGone(t, ctx, fixture, store, addrA, schemeEpoch, + "a later scheme change must not carry a lost lineage back into service") + epochRequireGone(t, ctx, fixture, store, addrA1, schemeEpoch, + "a later scheme change must not carry a lost lineage back into service") + for _, lostAddress := range []Address{addrA, addrA1} { + if current, err := fixture.CurrentAddressFor(ctx, store, lostAddress); err == nil { + t.Errorf("CurrentAddressFor(%s) = %s with no error, want an error: a lost lineage has no current address", lostAddress, current) + } } - voidedAnswer, err := fixture.Resolve(ctx, store, noLongerServed) - if err != nil { - t.Fatalf("Resolve(no-longer-served): %v", err) - } - if voidedAnswer.Restriction != RestrictionGoneReorganization { - t.Errorf("Resolve(a prior-epoch Address no longer served) = %s, want RestrictionGoneReorganization (R20-n)", voidedAnswer.Restriction) - } - if voidedAnswer.Epoch == nil { - t.Fatal("Resolve(a prior-epoch Address no longer served).Epoch = nil, want the current epoch populated (R20-n: the answer must name the current epoch, not just Restriction alone)") - } else if *voidedAnswer.Epoch != newEpoch { - t.Errorf("Resolve(a prior-epoch Address no longer served).Epoch = %d, want the current epoch %d", *voidedAnswer.Epoch, newEpoch) - } - - keptAnswer, err := fixture.Resolve(ctx, store, stillServed) - if err != nil { - t.Fatalf("Resolve(still-served): %v", err) - } - if keptAnswer.Restriction != RestrictionLive { - t.Errorf("Resolve(a prior-epoch Address the backend still serves) = %s, want RestrictionLive (R20-n's exception)", keptAnswer.Restriction) - } - - newAddr, err := fixture.CurrentAddressFor(ctx, store, stillServed) - if err != nil { - t.Fatalf("CurrentAddressFor(%s): %v", stillServed, err) - } - if newAddr == "" { - t.Error("CurrentAddressFor(a still-served prior-epoch Address) returned an empty Address, want a real one under the new epoch") + fresh := epochMintAddress(t, ctx, fixture, store, "record-a") + if fresh == addrA || fresh == addrA1 { + t.Fatalf("MintUnderEpoch(record-a) returned %s, an address of the lost lineage: a lost address is never handed out again", fresh) } + epochRequireLive(t, ctx, fixture, store, fresh, schemeEpoch, + "a fresh mint of the id after the loss is a new lineage and is served") } // --- fixture helpers ------------------------------------------------------- @@ -953,6 +1131,137 @@ func epochStore(fixture EpochFixture, tag string) string { return fixture.IssuePrefix + "-epoch-store-" + tag } +// epochLoseVersionSkip is the skip reason of every phase that needs +// EpochFixture.LoseVersion. +const epochLoseVersionSkip = "this backend cannot record that the store lost a Version (LoseVersion is nil)" + +// epochSkipUnlessReady skips the case when the fixture lacks a capability the +// epoch cases need. The cases that record a loss also need LoseVersion. The +// all-nil wiring test runs every case against an empty fixture, so each case +// must call this before it touches any of them. +func epochSkipUnlessReady(t *testing.T, fixture EpochFixture, needsLoseVersion bool) { + t.Helper() + if fixture.MintUnderEpoch == nil { + t.Skip("this backend has no way to mint a Version under a known epoch (MintUnderEpoch is nil)") + } + if fixture.BumpEpoch == nil { + t.Skip("this backend has no epoch concept yet (BumpEpoch is nil)") + } + if fixture.StillServes == nil { + t.Skip("this backend cannot report whether it still serves a prior-epoch Version (StillServes is nil)") + } + if fixture.Resolve == nil { + t.Skip("this backend does not yet report retention state (Resolve is nil)") + } + if fixture.CurrentAddressFor == nil { + t.Skip("this backend cannot report a still-served Version's new Address (CurrentAddressFor is nil)") + } + if needsLoseVersion && fixture.LoseVersion == nil { + t.Skip(epochLoseVersionSkip) + } +} + +// epochMintAddress mints id on store, failing the case if minting fails. +func epochMintAddress(t *testing.T, ctx context.Context, fixture EpochFixture, store, id string) Address { + t.Helper() + address, err := fixture.MintUnderEpoch(ctx, store, id) + if err != nil { + t.Fatalf("MintUnderEpoch(%s, %s): %v", store, id, err) + } + return address +} + +// epochBumpTo bumps store's epoch for trigger and returns the epoch it +// reports. Epochs are captured from the return value, never assumed: the +// counter is one per database, shared by every store the suite uses. +func epochBumpTo(t *testing.T, ctx context.Context, fixture EpochFixture, store string, trigger EpochBumpTrigger) int { + t.Helper() + epoch, err := fixture.BumpEpoch(ctx, store, trigger) + if err != nil { + t.Fatalf("BumpEpoch(%s, %s): %v", store, trigger, err) + } + return epoch +} + +// epochLoseAddress records that store lost the Version behind address. +func epochLoseAddress(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address) { + t.Helper() + if err := fixture.LoseVersion(ctx, store, address); err != nil { + t.Fatalf("LoseVersion(%s, %s): %v", store, address, err) + } +} + +// epochCurrentAddress asks where address now resolves, failing the case on an +// error or an empty answer. +func epochCurrentAddress(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address) Address { + t.Helper() + current, err := fixture.CurrentAddressFor(ctx, store, address) + if err != nil { + t.Fatalf("CurrentAddressFor(%s, %s): %v", store, address, err) + } + if current == "" { + t.Fatalf("CurrentAddressFor(%s, %s) returned an empty Address, want a real one", store, address) + } + return current +} + +// epochRequireLive asserts that address is served at epoch: StillServes is true +// and Resolve answers RestrictionLive naming that epoch. why says what the +// assertion is checking, for the failure message. +func epochRequireLive(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address, epoch int, why string) { + t.Helper() + serves, err := fixture.StillServes(ctx, store, address) + if err != nil { + t.Fatalf("StillServes(%s): %v", address, err) + } + if !serves { + t.Errorf("StillServes(%s) = false, want true: %s", address, why) + } + answer, err := fixture.Resolve(ctx, store, address) + if err != nil { + t.Fatalf("Resolve(%s): %v", address, err) + } + if answer.Restriction != RestrictionLive { + t.Errorf("Resolve(%s) = %s, want RestrictionLive: %s", address, answer.Restriction, why) + } + epochRequireAnswerEpoch(t, answer, address, epoch, why) +} + +// epochRequireGone asserts that address is no longer served at epoch: +// StillServes is false and Resolve answers RestrictionGoneReorganization +// naming that epoch. +func epochRequireGone(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address, epoch int, why string) { + t.Helper() + serves, err := fixture.StillServes(ctx, store, address) + if err != nil { + t.Fatalf("StillServes(%s): %v", address, err) + } + if serves { + t.Errorf("StillServes(%s) = true, want false: %s", address, why) + } + answer, err := fixture.Resolve(ctx, store, address) + if err != nil { + t.Fatalf("Resolve(%s): %v", address, err) + } + if answer.Restriction != RestrictionGoneReorganization { + t.Errorf("Resolve(%s) = %s, want RestrictionGoneReorganization: %s", address, answer.Restriction, why) + } + epochRequireAnswerEpoch(t, answer, address, epoch, why) +} + +// epochRequireAnswerEpoch asserts that a Live or Gone answer names the current +// epoch (R20-n: the answer carries the epoch, not just the Restriction). +func epochRequireAnswerEpoch(t *testing.T, answer RetentionAnswer, address Address, epoch int, why string) { + t.Helper() + if answer.Epoch == nil { + t.Errorf("Resolve(%s).Epoch = nil, want the current epoch %d: %s", address, epoch, why) + return + } + if *answer.Epoch != epoch { + t.Errorf("Resolve(%s).Epoch = %d, want the current epoch %d: %s", address, *answer.Epoch, epoch, why) + } +} + // sameRetentionAnswer compares two RetentionAnswer values by content rather // than identity, so a case can assert "this did not change" without // depending on the concrete Restriction the backend happened to pick. diff --git a/backend/conformance/role_bundle_cases.go b/backend/conformance/role_bundle_cases.go index b92a747f7..1c5e2cf00 100644 --- a/backend/conformance/role_bundle_cases.go +++ b/backend/conformance/role_bundle_cases.go @@ -44,6 +44,10 @@ var roleContractCases = []roleContract{ RunBatchApplyRefusesACrossPlaneEdgeBetweenRowsItCreated, RunBatchApplyAcceptsAnExternalEdgeTarget, RunBatchApplyNormalizesTheWaitsForGate, + RunBatchApplyStampsSpawnerIDOnlyWhenNamed, + RunBatchApplyCarriesThreadIDOntoTheStoredEdge, + RunBatchApplyCarriesThreadIDOntoAnExistingEdge, + RunBatchApplyRefusesAThreadIDLongerThanItsColumn, RunBatchApplySplicesAForwardMetadataRef, RunBatchApplySplicesASelfMetadataRef, RunBatchApplyRefusesAMetadataRefNoItemDeclares, @@ -54,6 +58,12 @@ var roleContractCases = []roleContract{ RunBatchApplyReplayMintsANewSetOfRows, RunBatchApplyDoesNotMutateTheCallerRequest, RunBatchApplyRefusesAnUnusableRequest, + RunBatchApplyUpdateItemsRefuseATemplate, + RunBatchApplySplicesTheMetadataOfATemplateItCreates, + RunBatchApplyCloseItemsAnswerToTheCloseGuards, + RunBatchApplyRefusesADottedChildGatedOnItsOwnParent, + RunBatchApplyAppliesTheDefaultPriority, + RunBatchApplyCarriesTheGateMembers, ), roleCases("BatchCloser", "BatchCloser()", oncePerRole, @@ -78,6 +88,7 @@ var roleContractCases = []roleContract{ RunBatchCloserAllRefusedBatchRecordsNoHistory, RunBatchCloserDoesNotMutateTheCallerRequest, RunBatchCloserSettlesTheDependersOfWhatItClosed, + RunBatchCloserItemsAnswerToTheCloseGuards, ), roleCases("BatchCreator", "BatchCreator()", oncePerRole, @@ -95,6 +106,7 @@ var roleContractCases = []roleContract{ RunBatchCreatorRecordsNoHistoryForAnEphemeralBatch, RunBatchCreatorDoesNotMutateTheCallerRequest, RunBatchCreatorEchoesSubSecondTimestamps, + RunBatchCreatorAppliesTheDefaultPriority, ), roleCases("BlockingAnnotator", "BlockingAnnotator()", oncePerRole, @@ -116,6 +128,7 @@ var roleContractCases = []roleContract{ RunBlockingAnnotatorRefusesAnEmptyID, RunBlockingAnnotatorLeavesTheRequestAlone, RunBlockingAnnotatorWritesNothing, + RunBlockingAnnotatorReportsTheTransitiveBlockedFlag, ), // One contract file covers both halves of workspace identity: the eight @@ -186,6 +199,15 @@ var roleContractCases = []roleContract{ RunCounterIncludeInfraExcludesGates, RunCounterCountsClosedRows, RunCounterAnUnknownStatusMatchesNothing, + RunCounterParentIDScopesToChildren, + RunCounterNoParentExcludesChildren, + RunCounterExcludeTypesNarrowsThePredicate, + RunCounterExcludeStatusNarrowsThePredicate, + RunCounterParentIDMatchesListCardinality, + RunCounterNoParentMatchesListCardinality, + RunCounterExcludeTypesMatchesListCardinality, + RunCounterParentIDIncludesAWispChild, + RunCounterParentIDAndExcludeStatusComposeOnAClosedChild, RunCounterGroupsPartitionTheScalarSet, RunCounterLabelBucketsOverlapSoTotalIsNotTheirSum, RunCounterNamesTheEmptyBuckets, @@ -250,6 +272,7 @@ var roleContractCases = []roleContract{ RunDependencyEditorSameTypeReAddIsIdempotent, RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion, RunDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp, + RunDependencyEditorSameTypeReAddWithChangedThreadMintsOneVersion, RunDependencyEditorRepeatsWithinOneRequestCollapse, RunDependencyEditorAttributesItsEventsToTheActor, RunDependencyEditorRetypeRefusalLeavesTheOriginalEdge, @@ -283,6 +306,7 @@ var roleContractCases = []roleContract{ RunDependencyEditorAcceptsADiamond, RunDependencyEditorGateScopeFollowsTheEdgeType, RunDependencyEditorAcceptsBlockingAcrossIssueTypes, + RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent, ), // The accessor named here is not an accessor at all, alone among these @@ -419,12 +443,14 @@ var roleContractCases = []roleContract{ RunLifecycleExpectedVersionIsCheckedBeforeTheNoOps, RunLifecycleReopenRecordsItsReason, RunLifecycleResultsAreHydratedPostStateSnapshots, + RunLifecycleResultsCarryThePostWriteRowVersion, RunLifecycleCloseAndReopenRequireActorAndIssueID, RunLifecycleReopenProvenanceLabelsHistory, RunLifecycleCloseSettlesItsTransitiveAndCrossPlaneDependers, RunLifecycleCloseSettlesTheClosedRowItselfAndItsChild, RunLifecycleCloseOnASpawnersLastChildSatisfiesAWaitsForGate, RunLifecycleReopenReblocksItsDependers, + RunLifecycleCloseEnforcesTheCloseGuards, ), // The accessor-reachable half of Lifecycle.Create, moved out of the staging @@ -437,6 +463,9 @@ var roleContractCases = []roleContract{ RunLifecycleCreateInheritsParentLabels, RunLifecycleCreateWritesEveryScalarField, RunLifecycleCreateEchoesSubSecondTimestamps, + RunLifecycleCreateAppliesTheDefaultPriority, + RunLifecycleCreateWritesTheGateMembers, + RunLifecycleCreateBoundsTheGateMembers, ), roleCases("LifecycleUpdate", "IssueLifecycle()", oncePerRole, @@ -451,6 +480,10 @@ var roleContractCases = []roleContract{ RunLifecycleUpdateRefusesUnknownIDsAndActorlessRequests, RunLifecycleUpdateRefusalWritesNoMemberOfThePatch, RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits, + RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency, + RunLifecycleUpdateExpectedVersionSingleWinnerWithDisjointColumnsUnderConcurrency, + RunLifecycleCloseExpectedVersionSingleWinnerUnderConcurrency, + RunLifecycleUpdateExpectedVersionSingleWinnerAcrossUpdateAndCloseUnderConcurrency, RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee, RunLifecycleUpdateMetadataPatchOrdersMergeSetUnset, RunLifecycleUpdateClosePolicy, @@ -459,7 +492,13 @@ var roleContractCases = []roleContract{ RunLifecycleUpdateParentIDReplacesTheParentEdge, RunLifecycleUpdateParentIDReplacesEveryParent, RunLifecycleUpdatePersistentPreservesUnversionedClass, + RunLifecycleUpdateWispModesRefuseAnUnversionedRow, + RunLifecycleUpdatePersistentPromotesAWisp, RunLifecycleUpdateProvenanceLabelsHistory, + RunLifecycleUpdateRefusesATemplate, + RunLifecycleUpdateAllowTemplateEditsATemplate, + RunLifecycleUpdatePatchesTheGateMembers, + RunLifecycleUpdateBoundsTheGateMembers, ), roleCases("Memories", "Memories()", oncePerRole, @@ -474,7 +513,7 @@ var roleContractCases = []roleContract{ RunMemoriesRememberRefusesAnUnderivableKey, RunMemoriesRecallAnswersTheStoredValue, RunMemoriesRecallReportsAMissAsNotFoundNotAnError, - RunMemoriesRecallConflatesStoredEmptyWithAbsent, + RunMemoriesEmptyRowIsPresentUntilForgotten, RunMemoriesForgetRemovesExactlyTheNamedRow, RunMemoriesForgetNeverTouchesTheSettingsPlane, RunMemoriesForgetReportsTheForgottenValue, @@ -537,6 +576,7 @@ var roleContractCases = []roleContract{ RunReaderListKeysetPositionResumesTheCreatedDescIDAscOrder, RunReaderListReadyFlagAnswersTheBlockerAwareSet, RunReaderListReadyFlagRefusesAFilterItCannotCarry, + RunReaderListQueryMatchesTheTitleOrTheID, RunReaderListEmptyPageIsWellFormed, RunReaderListMaxRowsIsHonored, RunReaderListMaxRowsBoundaryIsLimitPlusOffset, @@ -564,6 +604,8 @@ var roleContractCases = []roleContract{ RunReaderListWispTypeNarrowsTheAdmittedPlaneRatherThanAdmittingIt, RunReaderListBriefDropsTheFreeFormTextAndNothingElse, RunReaderReadyBriefDropsTheFreeFormTextAndNothingElse, + RunReaderListTimeBoundsAreStrictAndWholeSecond, + RunReaderListFilterFamiliesNarrowToTheirRows, ), roleCases("ReadyClaimer", "ReadyClaimer() and IssueReader()", oncePerRole, @@ -666,6 +708,7 @@ var roleContractCases = []roleContract{ RunSweeperWispsPlaneClearsTheWholeWispsTable, RunSweeperWispsPlaneRequiresAFilter, RunSweeperProtectsLiveDependents, + RunSweeperProtectsTransitiveLiveDependents, RunSweeperProtectsLiveDependentsAcrossPlanes, RunSweeperLimitTakesTheOldestClosedFirst, ), diff --git a/backend/conformance/sweeper_contract.go b/backend/conformance/sweeper_contract.go index bae89c58d..8cbf6225a 100644 --- a/backend/conformance/sweeper_contract.go +++ b/backend/conformance/sweeper_contract.go @@ -747,6 +747,49 @@ func RunSweeperProtectsLiveDependents(t *testing.T, ctx context.Context, fixture sweeperAssertWispRows(t, ctx, fixture, 4, openChild, convoy, hooked, relater) } +// RunSweeperProtectsTransitiveLiveDependents pins that protection propagates +// through closed candidates: an open grandchild keeps both its closed parent +// and closed grandparent. Otherwise sweeping the grandparent orphans a live +// hierarchy even though the direct parent was correctly retained. +func RunSweeperProtectsTransitiveLiveDependents(t *testing.T, ctx context.Context, fixture SweeperFixture) { + t.Helper() + if fixture.AddDependencies == nil { + t.Skip("fixture has no AddDependencies hook; cannot wire the hierarchy this case needs") + } + root := sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "transitive", "root", true), nil) + middle := sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "transitive", "middle", true), nil) + leafIssue := sweeperIssue(fixture, "transitive", "leaf", true) + leafIssue.Status = types.StatusOpen + leafIssue.ClosedAt = nil + leaf := sweeperSeed(t, ctx, fixture, leafIssue, nil) + + if err := fixture.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "sweeper-seed", + Edges: []publicops.DependencyEdge{ + {IssueID: middle, DependsOnID: root, Type: publicops.DepParentChild}, + {IssueID: leaf, DependsOnID: middle, Type: publicops.DepParentChild}, + }, + }); err != nil { + t.Fatalf("wiring transitive hierarchy: %v", err) + } + + request := publicops.SweepRequest{ + Tier: publicops.SweepWispsPlane, + IDPattern: sweeperPattern(fixture, "transitive"), + ClosedBefore: &sweeperCutoff, + ProtectLiveDependents: true, + } + preview := sweeperSweep(t, ctx, fixture, sweeperAsDryRun(request)) + if preview.Swept != 0 || preview.Skipped.LiveDependent != 2 { + t.Fatalf("dry run: Swept = %d, LiveDependent = %d; want 0 and 2", preview.Swept, preview.Skipped.LiveDependent) + } + result := sweeperSweep(t, ctx, fixture, request) + if result.Swept != 0 || result.Skipped.LiveDependent != 2 { + t.Fatalf("sweep: Swept = %d, LiveDependent = %d; want 0 and 2", result.Swept, result.Skipped.LiveDependent) + } + sweeperAssertWispRows(t, ctx, fixture, 3, root, middle, leaf) +} + // RunSweeperProtectsLiveDependentsAcrossPlanes pins that the live-dependent // protection reads BOTH dependency tables: a closed wisp that a live DURABLE // (issues-table) bead depends on through parent-child, tracks or blocks is diff --git a/backend/conformance/versioned_history_wiring_test.go b/backend/conformance/versioned_history_wiring_test.go index 08eed2b53..b022b716e 100644 --- a/backend/conformance/versioned_history_wiring_test.go +++ b/backend/conformance/versioned_history_wiring_test.go @@ -129,5 +129,14 @@ func TestVersionedHistoryPhase0RunsInFullSkipMode(t *testing.T) { t.Run("EpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed", func(t *testing.T) { RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t, ctx, fixture) }) + t.Run("TokenSchemeChangeCarriesLiveAddressesAndOnlyThose", func(t *testing.T) { + RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose(t, ctx, fixture) + }) + t.Run("ACarriedAddressKeepsResolvingAcrossLaterBumps", func(t *testing.T) { + RunACarriedAddressKeepsResolvingAcrossLaterBumps(t, ctx, fixture) + }) + t.Run("ALostAddressStaysGoneAcrossASchemeChange", func(t *testing.T) { + RunALostAddressStaysGoneAcrossASchemeChange(t, ctx, fixture) + }) }) } diff --git a/backend/conformance/versioned_read_contract.go b/backend/conformance/versioned_read_contract.go new file mode 100644 index 000000000..0e187117c --- /dev/null +++ b/backend/conformance/versioned_read_contract.go @@ -0,0 +1,356 @@ +package conformance + +import ( + "context" + "testing" + "time" +) + +// This file holds the contract for R7.1 (gastownhall/beads#6136, design doc +// gastownhall/beads#5898 revision 9): the as-of read — the "versioned +// reads" half of Phase 3's title, authored here from scratch, since no +// fixture for it exists anywhere in this package to un-skip. +// +// R7.1, VERBATIM (design doc #5898 rev 9): "An as-of read is a named read +// whose selector is an instant. Given an instant T or a version address, a +// store returns one Bead's durable state as of that point — the latest +// version it holds that was accepted at or before T, with everything later +// excluded — under R7's record shape, marking the address it served, or +// refuses as gone or unknown with the reason (R8, R20). Like every history +// answer it is complete for the answering store's holdings and may change +// after a sync (TC3)." +// +// ADDRESS, RESTRICTION, AND CHANGEATTRIBUTION ARE DECLARED IN +// expected_revision_contract.go — see that file's package-level note on +// where this suite's shared vocabulary lives and why. This file reuses +// Restriction's five values as-is for the gone-or-unknown refusal outcome +// (R8): an as-of read never invents a sixth state, and never distinguishes +// "gone" from "unknown" any differently than R20 already does. +// +// EVERY HOOK ON THE FIXTURE BELOW IS INDEPENDENTLY NILABLE — see the +// package-level note in expected_revision_contract.go. Every case +// nil-checks every hook it uses and SKIPS BY NAME when one is missing. No +// backend implements as-of reads yet — the implementation is +// the child this suite is written ahead of. +// +// EXPLICIT NON-GOAL: MEMORY-PLANE CONSUMER POLICY IS NOT PART OF THIS +// PRIMITIVE. R7.1's own text is explicit that a closed-before-T boundary, +// sibling exclusion, and supersession exclusion "are Memory-plane policies +// a consumer layers on this primitive (#5877), not part of it." This suite +// does not implement or assert any of the three — a future reader who finds +// them absent should read that as this file honoring R7.1's own scope, not +// as an oversight. This is the read-side analog of the R16/R16.1 boundary +// risk already recorded in expected_revision_contract.go: do not conflate +// the primitive with policy layered on top of it. +// +// THIS SUITE ASSERTS LOCAL COMPLETENESS ONLY (TC3). Nothing below requires, +// or even checks, that two stores asked about the same lineage agree — R7.1 +// itself says an as-of answer "may change after a sync," so two stores at +// different sync points are expected to answer differently, and neither is +// wrong. RunAsOfReadIsCompleteOnlyForTheAnsweringStoresHoldings is the one +// case that touches more than one store, and what it asserts is exactly +// this: each store answers strictly from its own holdings, never a +// sibling's — not that the two agree. + +// AsOfSelector names the point R7.1 resolves against: either a wall-clock +// instant, or a specific version Address treated as the selector itself — +// "the read that names its own answer" (R7.1: "an instant T or a version +// address"). Exactly one of At/Version is populated in every case this file +// exercises; R7.1 does not speak to the shape where both or neither are +// set, so this suite does not either. +type AsOfSelector struct { + At *time.Time + Version *Address +} + +// AsOfReadRefusal is R8's typed outcome for an as-of read that cannot be +// answered. Restriction is always one of the four Gone*/Unknown values, +// never RestrictionLive — a live answer is a served AsOfReadResult, not a +// refusal. Reason explains why (R8). +type AsOfReadRefusal struct { + Restriction Restriction + Reason string +} + +// AsOfReadResult is the outcome of an as-of read (R7.1). Address/State and +// Refusal are mutually exclusive: read Address/State only when Refusal is +// nil. +type AsOfReadResult struct { + // Address is the version this read served, marking "the address it + // served" (R7.1). Populated only when Refusal is nil. + Address Address + // State is the served version's durable state under R7's record shape. + // Opaque to this suite: the fixture adapter translates a backend's real + // record shape into this map, and no case here asserts its field-level + // content — only that a served result carries an Address. + State map[string]any + // Refusal is populated instead of Address/State when the read cannot be + // answered (R8). Nil means the read was served. + Refusal *AsOfReadRefusal +} + +// AsOfRead resolves storeID's answer to an as-of read against id's lineage, +// at selector (R7.1). +type AsOfRead func(ctx context.Context, storeID, id string, selector AsOfSelector) (AsOfReadResult, error) + +// AsOfReadFixture supplies the capability under test for R7.1: a read whose +// selector is an instant or a version address, resolving to the latest +// version accepted at or before that point, or a typed refusal. +type AsOfReadFixture struct { + IssuePrefix string + + // Resolve performs the as-of read under test (R7.1). A nil hook means + // this backend does not implement as-of reads yet, and every case in + // this file skips with that reason. + Resolve AsOfRead + + // MintAt mints a fresh version for id under storeID, recorded as + // accepted at the given instant, and returns its Address. Cases use + // this to build a lineage with known accept-times to resolve an as-of + // read against. A nil hook means this backend has no way to mint a + // version at a controlled accept-time, and cases that need one skip + // with that reason. + MintAt func(ctx context.Context, storeID, id string, acceptedAt time.Time) (Address, error) + + // MakeUnanswerable arranges for id to be unanswerable at storeID for + // the given Restriction (one of RestrictionGoneRetention/GoneErasure/ + // GoneReorganization/Unknown) — independently of + // RetentionFixture/EpochFixture's own removal machinery, since R7.1's + // refusal is a sibling contract to R17/R20, not a dependent of them. A + // nil hook means this backend has no way to arrange this, and the case + // that needs it skips with that reason. + MakeUnanswerable func(ctx context.Context, storeID, id string, restriction Restriction) error +} + +// RunAsOfReadSelectorAcceptsEitherAnInstantOrAVersionAddress pins R7.1's +// selector shape: an instant T and the version address that instant +// resolves to are two names for the same answer, and a store must accept +// either. +func RunAsOfReadSelectorAcceptsEitherAnInstantOrAVersionAddress(t *testing.T, ctx context.Context, fixture AsOfReadFixture) { + t.Helper() + if fixture.Resolve == nil { + t.Skip("this backend does not implement as-of reads (Resolve is nil)") + } + if fixture.MintAt == nil { + t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)") + } + store := asOfReadStore(fixture, "selector-kinds") + id := fixture.IssuePrefix + "-asof-selector" + t0 := time.Now().UTC().Add(-time.Hour) + asOfReadMint(t, ctx, fixture, store, id, t0) + t1 := t0.Add(time.Minute) + second := asOfReadMint(t, ctx, fixture, store, id, t1) + + byInstant, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &t1}) + if err != nil { + t.Fatalf("Resolve(selector=instant): %v", err) + } + if byInstant.Refusal != nil { + t.Fatalf("Resolve(selector=instant) = %+v, want a served result", byInstant) + } + + byVersion, err := fixture.Resolve(ctx, store, id, AsOfSelector{Version: &second}) + if err != nil { + t.Fatalf("Resolve(selector=version address): %v", err) + } + if byVersion.Refusal != nil { + t.Fatalf("Resolve(selector=version address) = %+v, want a served result", byVersion) + } + + if byInstant.Address != second { + t.Errorf("Resolve(selector=instant matching a version's own accept-time).Address = %s, want %s", byInstant.Address, second) + } + if byVersion.Address != second { + t.Errorf("Resolve(selector=version address).Address = %s, want the same address named %s", byVersion.Address, second) + } + if byInstant.Address != byVersion.Address { + t.Errorf("an instant selector (served %s) and a version-address selector naming the same version (served %s) resolved to different addresses; R7.1 accepts either as a name for the same answer", byInstant.Address, byVersion.Address) + } +} + +// RunAsOfReadReturnsTheLatestVersionAtOrBeforeTStrictlyExcludingLater pins +// R7.1's ordering promise: resolving at T returns the latest version +// accepted at or before T, and a version accepted after T is excluded even +// when its own instant is close by. +func RunAsOfReadReturnsTheLatestVersionAtOrBeforeTStrictlyExcludingLater(t *testing.T, ctx context.Context, fixture AsOfReadFixture) { + t.Helper() + if fixture.Resolve == nil { + t.Skip("this backend does not implement as-of reads (Resolve is nil)") + } + if fixture.MintAt == nil { + t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)") + } + store := asOfReadStore(fixture, "ordering") + id := fixture.IssuePrefix + "-asof-ordering" + t0 := time.Now().UTC().Add(-time.Hour) + asOfReadMint(t, ctx, fixture, store, id, t0) + t1 := t0.Add(time.Minute) + middle := asOfReadMint(t, ctx, fixture, store, id, t1) + t2 := t0.Add(2 * time.Minute) + asOfReadMint(t, ctx, fixture, store, id, t2) + + atExactly, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &t1}) + if err != nil { + t.Fatalf("Resolve(T=middle's own instant): %v", err) + } + if atExactly.Refusal != nil || atExactly.Address != middle { + t.Errorf("Resolve(T=middle's own instant) = %+v, want the version accepted exactly at T (%s), not a later one", atExactly, middle) + } + + between := t1.Add(30 * time.Second) + betweenResult, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &between}) + if err != nil { + t.Fatalf("Resolve(T strictly between two versions): %v", err) + } + if betweenResult.Refusal != nil || betweenResult.Address != middle { + t.Errorf("Resolve(T strictly between two versions) = %+v, want the latest version at-or-before T (%s); the version accepted after T must be strictly excluded", betweenResult, middle) + } +} + +// RunAsOfReadReportsTheAddressItServed pins R7.1's "marking the address it +// served": a served result names the exact Address of the version it +// returned, not merely a truthy success. +func RunAsOfReadReportsTheAddressItServed(t *testing.T, ctx context.Context, fixture AsOfReadFixture) { + t.Helper() + if fixture.Resolve == nil { + t.Skip("this backend does not implement as-of reads (Resolve is nil)") + } + if fixture.MintAt == nil { + t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)") + } + store := asOfReadStore(fixture, "reports-address") + id := fixture.IssuePrefix + "-asof-reports-address" + at := time.Now().UTC() + address := asOfReadMint(t, ctx, fixture, store, id, at) + + result, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &at}) + if err != nil { + t.Fatalf("Resolve: %v", err) + } + if result.Refusal != nil { + t.Fatalf("Resolve = %+v, want a served result", result) + } + if result.Address == "" { + t.Fatal("Resolve returned an empty Address on a served result, want the address of the version it served (R7.1)") + } + if result.Address != address { + t.Errorf("Resolve(...).Address = %s, want the served version's own address %s", result.Address, address) + } +} + +// RunAsOfReadRefusesAsGoneOrUnknownNeverSubstitutingAnotherVersion pins R8: +// a read that cannot be answered refuses as a typed Gone or Unknown outcome +// with a reason, and never silently returns a neighboring version, the +// nearest surviving version, or current state as a substitute — R8's own +// text names all three as non-answers. +func RunAsOfReadRefusesAsGoneOrUnknownNeverSubstitutingAnotherVersion(t *testing.T, ctx context.Context, fixture AsOfReadFixture) { + t.Helper() + if fixture.Resolve == nil { + t.Skip("this backend does not implement as-of reads (Resolve is nil)") + } + if fixture.MintAt == nil { + t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)") + } + if fixture.MakeUnanswerable == nil { + t.Skip("this backend has no way to make a lineage unanswerable (MakeUnanswerable is nil)") + } + + for _, restriction := range []Restriction{ + RestrictionGoneRetention, + RestrictionGoneErasure, + RestrictionGoneReorganization, + RestrictionUnknown, + } { + t.Run(restriction.String(), func(t *testing.T) { + store := asOfReadStore(fixture, "unanswerable-"+restriction.String()) + id := fixture.IssuePrefix + "-asof-unanswerable-" + restriction.String() + at := time.Now().UTC() + address := asOfReadMint(t, ctx, fixture, store, id, at) + + if err := fixture.MakeUnanswerable(ctx, store, id, restriction); err != nil { + t.Fatalf("MakeUnanswerable(%s, %s): %v", id, restriction, err) + } + + result, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &at}) + if err != nil { + t.Fatalf("Resolve after MakeUnanswerable(%s): %v", restriction, err) + } + if result.Refusal == nil { + t.Fatalf("Resolve after MakeUnanswerable(%s) = %+v, want a Refusal, not a served result (R8)", restriction, result) + } + if result.Refusal.Restriction != restriction { + t.Errorf("Refusal.Restriction = %s, want %s", result.Refusal.Restriction, restriction) + } + if result.Refusal.Reason == "" { + t.Error("Refusal.Reason is empty, want a reason (R8)") + } + if result.Address != "" { + t.Errorf("Resolve on a refusal returned Address = %s, want empty: R8 forbids silently substituting a neighboring version, the nearest surviving version, or current state (the pre-refusal address was %s)", result.Address, address) + } + }) + } +} + +// RunAsOfReadIsCompleteOnlyForTheAnsweringStoresHoldings pins R7.1's closing +// clause and TC3: an as-of answer "is complete for the answering store's +// holdings and may change after a sync." This case asserts NOTHING about +// agreement between two stores asked about the same lineage — proving that +// absence is the point, not a gap. It mints a lineage into exactly one of +// two stores and confirms each store answers strictly from its own +// holdings: the store that holds the lineage serves it, and the store that +// never received it answers Unknown (FR-06, reused from R20) rather than +// reaching across to a sibling store's knowledge, erroring, or answering +// Gone — which would claim knowledge of a lineage it never held. +func RunAsOfReadIsCompleteOnlyForTheAnsweringStoresHoldings(t *testing.T, ctx context.Context, fixture AsOfReadFixture) { + t.Helper() + if fixture.Resolve == nil { + t.Skip("this backend does not implement as-of reads (Resolve is nil)") + } + if fixture.MintAt == nil { + t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)") + } + holds := asOfReadStore(fixture, "tc3-holds-the-lineage") + neverSynced := asOfReadStore(fixture, "tc3-never-synced") + id := fixture.IssuePrefix + "-asof-tc3" + at := time.Now().UTC() + address := asOfReadMint(t, ctx, fixture, holds, id, at) + + local, err := fixture.Resolve(ctx, holds, id, AsOfSelector{At: &at}) + if err != nil { + t.Fatalf("Resolve on the store that holds the lineage: %v", err) + } + if local.Refusal != nil || local.Address != address { + t.Fatalf("Resolve on the store that holds the lineage = %+v, want it served from that store's own holdings (%s)", local, address) + } + + remote, err := fixture.Resolve(ctx, neverSynced, id, AsOfSelector{At: &at}) + if err != nil { + t.Fatalf("Resolve on a store that never received this lineage: %v", err) + } + if remote.Refusal == nil { + t.Fatalf("Resolve on a store that never received this lineage = %+v, want a Refusal: an as-of answer is complete for the answering store's own holdings, not a sibling's (TC3)", remote) + } + if remote.Refusal.Restriction != RestrictionUnknown { + t.Errorf("Refusal.Restriction on the never-synced store = %s, want RestrictionUnknown: no lineage knowledge is Unknown, not Gone (FR-06)", remote.Refusal.Restriction) + } +} + +// --- fixture helpers ------------------------------------------------------- + +// asOfReadStore names a storeID namespaced by the fixture's IssuePrefix and +// tag, so cases that need more than one store (e.g. the TC3 local- +// completeness case) get independent ones. +func asOfReadStore(fixture AsOfReadFixture, tag string) string { + return fixture.IssuePrefix + "-asof-store-" + tag +} + +// asOfReadMint mints a version for id on store at the given instant via +// fixture.MintAt, fataling the case if minting fails. +func asOfReadMint(t *testing.T, ctx context.Context, fixture AsOfReadFixture, store, id string, at time.Time) Address { + t.Helper() + address, err := fixture.MintAt(ctx, store, id, at) + if err != nil { + t.Fatalf("MintAt(%s, %s, %s): %v", store, id, at, err) + } + return address +} diff --git a/backend/http/BUILD.bazel b/backend/http/BUILD.bazel new file mode 100644 index 000000000..f6359f820 --- /dev/null +++ b/backend/http/BUILD.bazel @@ -0,0 +1,192 @@ +load("@rules_go//go:def.bzl", "go_library", "go_test") +load("@rules_shell//shell:sh_test.bzl", "sh_test") + +go_library( + name = "http", + srcs = [ + "attach.go", + "credential.go", + "errors.go", + "http.go", + "target.go", + ], + importpath = "github.com/steveyegge/beads/backend/http", + visibility = ["//visibility:public"], + deps = [ + "//backend", + "//internal/configfile", + "//internal/gitignore", + "//internal/httpapi/apigen", + "//internal/httpclient", + "//internal/httpclient/wire", + "//internal/storage/backends", + ], +) + +go_test( + name = "http_test", + # The served e2e cases run ~4-5 min on the farm under + # BEADS_TEST_EMBEDDED_DOLT=1, past the medium 300s action limit. + size = "large", + timeout = "long", + srcs = [ + "attach_test.go", + "e2e_blocked_flags_test.go", + "e2e_blocked_test.go", + "e2e_cli_test.go", + "e2e_export_test.go", + "e2e_gates_test.go", + "e2e_heartbeat_test.go", + "e2e_link_test.go", + "e2e_list_filters_test.go", + "e2e_list_page_edges_test.go", + "e2e_mol_test.go", + "e2e_promote_test.go", + "e2e_read_your_own_write_test.go", + "e2e_recompute_blocked_test.go", + "e2e_remote_roles_test.go", + "e2e_request_budget_test.go", + "e2e_search_test.go", + "e2e_show_current_test.go", + "e2e_show_single_fetch_test.go", + "open_test.go", + "per_open_credential_test.go", + "register_test.go", + ], + # The e2e files exec the real bd (bazeltest.PrebuiltBD); they run under + # BEADS_TEST_EMBEDDED_DOLT=1 and skip otherwise. + data = ["//cmd/bd:bd_for_tests"], + env = {"BEADS_TEST_BD_BINARY": "$(rlocationpath //cmd/bd:bd_for_tests)"}, + deps = [ + ":http", + "//backend", + "//internal/configfile", + "//internal/httpapi", + "//internal/httpclient", + "//internal/storage", + "//internal/storage/backends", + "//internal/storage/domain", + "//internal/storage/embeddeddolt", + "//internal/storage/issueops", + "//internal/testutil/bazeltest", + ], +) + +# http_test again, with the e2e tier on: BEADS_TEST_EMBEDDED_DOLT=1 starts the +# in-process server over embedded Dolt and BEADS_HTTP_TEST_REQUIRED=1 turns a +# skip of that tier into a failure. http_test alone skips the TestE2E_* cases +# in every lane, because no lane sets those variables for it. It repeats +# http_test's `env` (go_test_pinned_shard.sh, like go_test_variant.sh, does +# not inherit it). +# +# Shard count: the package's tests are serial, and as one shard the target +# ran 235-394s on the lane's executors (2026-10-10..13), the embedded lane's +# longest action in most runs where it executed; the lane's other shards end +# by ~90-125s. The 19 TestE2E_* cases that take >= 3s are pinned +# (tools/bazel/go_test_pinned_shard.sh, served_pinned_shards.txt from +# tools/bazel/pin_shards.py --shards 6 --min-seconds 3) onto 6 shards, and +# the binary's round-robin runs the other ~28 (well under a second +# together) in the 7th. The durations are the maximum over two sharded runs +# of the lane (bazel.yml's bazel-embedded-served-testxml artifact): 11-90s +# each, ~770s together. The same test's time varied 2-5x between those runs +# with the executors' load, and sharded runs took up to 2x what the +# single-shard runs did, so size the pins from sharded runs of the lane, +# never from a single-shard or local one. +# Regenerate the manifest from PR runs' bazel-embedded-served-testxml +# artifacts (each http_served_test directory holds shard_*_of_7/test.xml; +# pass several runs, pin_shards.py takes each test's maximum): +# python3 tools/bazel/pin_shards.py --shards 6 --min-seconds 3 \ +# --write backend/http/served_pinned_shards.txt \ +# /http_served_test /http_served_test +# +# Tags: +# embedded: the embedded-Dolt tier; excluded from --config=prcore/ci, +# selected by --config=embedded. +sh_test( + name = "http_served_test", + size = "large", + # -test.timeout=19m fires (with a goroutine dump) before Bazel's 1200s + # action limit (eternal under --config=embedded). + timeout = "eternal", + srcs = ["//tools/bazel:go_test_pinned_shard.sh"], + args = [ + "$(rootpath :served_pinned_shards.txt)", + "$(rootpath :http_test)", + "-test.v", + "-test.count=1", + "-test.timeout=19m", + ], + data = [ + "served_pinned_shards.txt", + ":http_test", + "//cmd/bd:bd_for_tests", + ], + env = { + "BEADS_HTTP_TEST_REQUIRED": "1", + "BEADS_TEST_BD_BINARY": "$(rlocationpath //cmd/bd:bd_for_tests)", + "BEADS_TEST_EMBEDDED_DOLT": "1", + }, + shard_count = 7, + tags = ["embedded"], +) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/backend/http/attach.go b/backend/http/attach.go new file mode 100644 index 000000000..f2175ff5f --- /dev/null +++ b/backend/http/attach.go @@ -0,0 +1,133 @@ +// Written fresh for OSS beads S6 (no bd-enterprise source copied): closes the +// S6 review's MED-8 finding, which asked for one public helper an embedder +// (or `bd connect`) can call to activate a workspace for this backend, +// instead of each caller hand-assembling the two-file write itself. +package bdhttp + +import ( + "context" + "fmt" + + "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/gitignore" + "github.com/steveyegge/beads/internal/httpclient" +) + +// Attach activates the http backend for the workspace at beadsDir: it writes +// the per-user activation sidecar (SaveTarget) pinning target's server and +// project, then sets the workspace's git-tracked backend selection in +// metadata.json to this backend, preserving every other configured field +// (database, project id, ...) and creating a fresh default metadata.json only +// when none exists yet. Both files are written atomically (temp file plus +// rename, 0600): see SaveTarget and configfile.Config.Save. +// +// Unless the caller already set target.PreviousBackend, Attach fills it in +// from the workspace's PRIOR backend selection, so `bd connect --clear` can +// restore it later; see that field's doc. +// +// Attach does NOT verify target itself — it has no network access and takes +// target on faith. A caller MUST call Handshake (or httpclient.Handshake) +// against target first and only call Attach once that succeeds; attaching an +// unverified target lets a workspace record a server that is wrong, hostile, +// or simply never answers. Connect, below, does both in the right order and +// is the easier door for a caller that does not need them split. +// +// Attach does not create beadsDir itself — MkdirAll is the caller's job, same +// as SaveTarget's own precondition. It DOES ensure both of this backend's +// per-user filenames are covered by beadsDir's .gitignore +// (gitignore.EnsurePatternIgnored): the sidecar, and +// httpclient.LocalMetadataFileName, which the store writes on first use. That +// is the same guarantee `bd connect` makes via doctor.EnsureGitignoreForBeadsDir +// — but through a small, independent implementation here rather than +// importing cmd/bd/doctor, whose package as a whole pulls in dolt and +// git-process dependencies that would break backend/http's promise of a +// minimal dependency footprint for an embedder. The two are complementary and +// idempotent together. +// +// It is the one place that writes BOTH of the files that activate beads/http +// (the sidecar and metadata.json's backend selection; the local metadata file +// is the store's own), so a caller that used to hand-assemble the pair +// (`bd connect`'s own connectCmd.RunE, test/embedder's linkage proof) can call +// this instead and stay correct across a future change to either file's shape. +func Attach(beadsDir string, target Target) error { + cfg, err := configfile.Load(beadsDir) + if err != nil { + return fmt.Errorf("reading %s: %w", configfile.ConfigFileName, err) + } + if cfg == nil { + cfg = configfile.DefaultConfig() + } + // target.PreviousBackend (bee-ghosttrack CHANGES_REQUESTED on #7288, + // should-fix 1) is what `bd connect --clear` restores metadata.json's + // backend selection to. A caller rarely sets it itself (connect.go + // doesn't), so fill it in here unless the workspace is ALREADY on this + // backend — a re-connect (a new URL, or re-pinning the same one) must + // not overwrite an earlier recorded previous backend with "http" itself, + // or a chain of reconnects would forget what to restore and --clear + // would land back on http with no sidecar. Carry the ALREADY-recorded + // value forward instead; a failed or missing read just leaves it "", + // the same as a workspace with nothing to restore. The check reads the + // raw field: in a process that never ran Register, GetBackend() reports an + // http workspace as the dolt default, and the reconnect would record that. + if target.PreviousBackend == "" { + if cfg.Backend == httpclient.Backend { + if prior, err := httpclient.LoadTarget(beadsDir); err == nil { + target.PreviousBackend = prior.PreviousBackend + } + } else { + target.PreviousBackend = cfg.GetBackend() + } + } + if err := SaveTarget(beadsDir, target); err != nil { + return fmt.Errorf("writing %s: %w", httpclient.TargetFileName, err) + } + // Both of this backend's per-user files: the sidecar just written, and + // the local metadata file the store itself writes on first use, which + // never passes through here and so must be covered in advance. + for _, name := range []string{httpclient.TargetFileName, httpclient.LocalMetadataFileName} { + if err := gitignore.EnsurePatternIgnored(beadsDir, name); err != nil { + return fmt.Errorf("ensuring %s is gitignored: %w", name, err) + } + } + // Only the backend SELECTION changes here. cfg.Database/cfg.ProjectID (if + // an existing metadata.json carried them for a different, prior backend) + // are left exactly as loaded — see connect.go's own comment on this same + // hazard: this backend's identity lives entirely in the sidecar just + // written above, and clobbering those fields would corrupt a future + // `bd connect --clear` back to a different backend. + cfg.Backend = httpclient.Backend + if err := cfg.Save(beadsDir); err != nil { + return fmt.Errorf("writing %s: %w", configfile.ConfigFileName, err) + } + return nil +} + +// Connect is Handshake followed by Attach: it verifies target — the same +// server-identity check `bd connect` performs before it ever writes +// anything — and only then activates the workspace. It is the convenience +// door for a caller that wants Attach's ordering guarantee (never attach a +// workspace to a server this process has not handshaken) without composing +// Handshake and Attach itself. +// +// Mirroring `bd connect`'s own project-id pinning: if target.ExpectProjectID +// is empty, Connect pins it to whatever project the server answered with +// before calling Attach, so the workspace is tied to that project from this +// call on. If it is already set, Handshake itself refuses a mismatch and +// Connect returns that error without calling Attach at all. Connect does not +// replicate `bd connect`'s other CLI-level policy — --force re-pinning an +// already-attached workspace, or refusing to switch a workspace from a +// different backend — those stay the command's own job; Connect's contract +// is exactly "handshake, then attach". +func Connect(ctx context.Context, beadsDir string, target Target, opts Options) (*ServerSnapshot, error) { + snapshot, err := Handshake(ctx, target, opts) + if err != nil { + return nil, err + } + if target.ExpectProjectID == "" { + target.ExpectProjectID = snapshot.ProjectID + } + if err := Attach(beadsDir, target); err != nil { + return nil, err + } + return snapshot, nil +} diff --git a/backend/http/attach_test.go b/backend/http/attach_test.go new file mode 100644 index 000000000..7594b3240 --- /dev/null +++ b/backend/http/attach_test.go @@ -0,0 +1,180 @@ +package bdhttp_test + +// Written fresh for OSS beads S6: pins the bee-ghosttrack CHANGES_REQUESTED +// finding on #7288, should-fix 1 — `bd connect --clear` restoring a +// workspace's previous backend selection needs Attach to have recorded what +// that previous backend WAS, onto the sidecar, at connect time. + +import ( + "net/url" + "os" + "path/filepath" + "strings" + "testing" + + bdhttp "github.com/steveyegge/beads/backend/http" + "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/httpclient" +) + +func mustAttachTestURL(t *testing.T, raw string) *url.URL { + t.Helper() + u, err := url.Parse(raw) + if err != nil { + t.Fatalf("url.Parse(%q): %v", raw, err) + } + return u +} + +// TestAttachRecordsThePriorBackendAsPreviousBackend is the first-connect +// case: a workspace that selected "dolt" before ever running `bd connect` +// must have Attach record "dolt" as PreviousBackend, so --clear can restore +// it later. +func TestAttachRecordsThePriorBackendAsPreviousBackend(t *testing.T) { + beadsDir := t.TempDir() + cfg := &configfile.Config{Backend: "dolt", Database: "beads.db"} + if err := cfg.Save(beadsDir); err != nil { + t.Fatalf("seed metadata.json: %v", err) + } + + target := bdhttp.Target{BaseURL: mustAttachTestURL(t, "http://127.0.0.1:8080")} + if err := bdhttp.Attach(beadsDir, target); err != nil { + t.Fatalf("Attach: %v", err) + } + + got, err := bdhttp.LoadTarget(beadsDir) + if err != nil { + t.Fatalf("LoadTarget: %v", err) + } + if got.PreviousBackend != "dolt" { + t.Errorf("PreviousBackend = %q, want %q", got.PreviousBackend, "dolt") + } + + after, err := configfile.Load(beadsDir) + if err != nil { + t.Fatalf("reload metadata.json: %v", err) + } + // Asserts on the raw stored field, not GetBackend(): GetBackend() falls + // back to BackendDolt for any name backendnames.Has doesn't recognize + // (TestGetBackendAllowlist in internal/configfile), and "http" is only + // ever added there by bdhttp.Register/httpclient.Register — a + // once-per-process, panics-on-duplicate production wiring call this test + // package must not make. The raw field is exactly what Attach controls. + if after.Backend != httpclient.Backend { + t.Errorf("metadata.json backend = %q after Attach, want %q", after.Backend, httpclient.Backend) + } +} + +// TestAttachOnAFreshWorkspaceRecordsTheImplicitDoltDefault covers a +// workspace with no metadata.json at all: GetBackend()'s own default +// ("dolt") is what a future --clear restores to, matching what every other +// backend-selection read in this codebase already treats as this +// workspace's backend. +func TestAttachOnAFreshWorkspaceRecordsTheImplicitDoltDefault(t *testing.T) { + beadsDir := t.TempDir() + target := bdhttp.Target{BaseURL: mustAttachTestURL(t, "http://127.0.0.1:8080")} + if err := bdhttp.Attach(beadsDir, target); err != nil { + t.Fatalf("Attach: %v", err) + } + got, err := bdhttp.LoadTarget(beadsDir) + if err != nil { + t.Fatalf("LoadTarget: %v", err) + } + if got.PreviousBackend != "dolt" { + t.Errorf("PreviousBackend = %q, want %q (configfile.BackendDolt)", got.PreviousBackend, "dolt") + } +} + +// TestAttachOnAReconnectKeepsTheEarlierPreviousBackend covers a workspace +// ALREADY on http (a bare re-connect, or --force re-pinning the same +// backend): Attach must not overwrite an already-recorded PreviousBackend +// with "http" itself, or a chain of reconnects would forget what --clear is +// supposed to restore. +func TestAttachOnAReconnectKeepsTheEarlierPreviousBackend(t *testing.T) { + beadsDir := t.TempDir() + // Not dolt: an unregistered "http" reads back through GetBackend() as the + // dolt default, so a dolt prior could not tell carrying it forward from + // recording that default. + cfg := &configfile.Config{Backend: "postgres", Database: "beads.db"} + if err := cfg.Save(beadsDir); err != nil { + t.Fatalf("seed metadata.json: %v", err) + } + + first := bdhttp.Target{BaseURL: mustAttachTestURL(t, "http://127.0.0.1:8080")} + if err := bdhttp.Attach(beadsDir, first); err != nil { + t.Fatalf("first Attach: %v", err) + } + + // A second connect to a different url, same workspace, same backend + // ("http", already selected) — the shape `bd connect --force` to a new + // server produces for an already-http workspace. + second := bdhttp.Target{BaseURL: mustAttachTestURL(t, "http://127.0.0.1:9090")} + if err := bdhttp.Attach(beadsDir, second); err != nil { + t.Fatalf("second Attach: %v", err) + } + + got, err := bdhttp.LoadTarget(beadsDir) + if err != nil { + t.Fatalf("LoadTarget: %v", err) + } + if got.PreviousBackend != "postgres" { + t.Errorf("PreviousBackend after a reconnect = %q, want the original %q carried forward, not the just-left \"http\"", got.PreviousBackend, "postgres") + } + if got.BaseURL.String() != "http://127.0.0.1:9090" { + t.Errorf("BaseURL = %q, want the second connect's url", got.BaseURL.String()) + } +} + +// TestAttachHonorsACallerSuppliedPreviousBackend covers Connect's doc +// contract: a caller that already set target.PreviousBackend itself (none +// of this package's own callers do today) must have that value win over +// Attach's own inference. +func TestAttachHonorsACallerSuppliedPreviousBackend(t *testing.T) { + beadsDir := t.TempDir() + cfg := &configfile.Config{Backend: "dolt", Database: "beads.db"} + if err := cfg.Save(beadsDir); err != nil { + t.Fatalf("seed metadata.json: %v", err) + } + + target := bdhttp.Target{BaseURL: mustAttachTestURL(t, "http://127.0.0.1:8080"), PreviousBackend: "mysql"} + if err := bdhttp.Attach(beadsDir, target); err != nil { + t.Fatalf("Attach: %v", err) + } + got, err := bdhttp.LoadTarget(beadsDir) + if err != nil { + t.Fatalf("LoadTarget: %v", err) + } + if got.PreviousBackend != "mysql" { + t.Errorf("PreviousBackend = %q, want the caller-supplied %q to win over the inferred %q", got.PreviousBackend, "mysql", "dolt") + } +} + +// TestAttachGitignoresBothPerUserFiles pins Attach's .gitignore guarantee for +// both files this backend keeps per user in beadsDir: the sidecar Attach +// writes, and the local metadata file the store writes later, on first use. +// `bd connect` also covers the second through doctor's required patterns, +// but an embedder activating through Attach alone has only this. A reconnect +// must not duplicate either line. +func TestAttachGitignoresBothPerUserFiles(t *testing.T) { + beadsDir := t.TempDir() + for _, raw := range []string{"http://127.0.0.1:8080", "http://127.0.0.1:9090"} { + if err := bdhttp.Attach(beadsDir, bdhttp.Target{BaseURL: mustAttachTestURL(t, raw)}); err != nil { + t.Fatalf("Attach(%s): %v", raw, err) + } + } + content, err := os.ReadFile(filepath.Join(beadsDir, ".gitignore")) + if err != nil { + t.Fatalf("read .gitignore after Attach: %v", err) + } + for _, name := range []string{httpclient.TargetFileName, httpclient.LocalMetadataFileName} { + count := 0 + for _, line := range strings.Split(string(content), "\n") { + if strings.TrimSpace(line) == name { + count++ + } + } + if count != 1 { + t.Errorf(".gitignore names %s %d time(s) after two Attaches, want exactly 1:\n%s", name, count, content) + } + } +} diff --git a/backend/http/corpus/BUILD.bazel b/backend/http/corpus/BUILD.bazel new file mode 100644 index 000000000..ee8631077 --- /dev/null +++ b/backend/http/corpus/BUILD.bazel @@ -0,0 +1,146 @@ +load("@rules_go//go:def.bzl", "go_test") +load("@rules_shell//shell:sh_test.bzl", "sh_test") + +go_test( + name = "corpus_test", + # The corpus runs every shape through the real bd (bazeltest.PrebuiltBD), + # served and embedded, under BEADS_TEST_EMBEDDED_DOLT=1 (corpus_served_test + # below); it skips otherwise. + size = "large", + timeout = "long", + srcs = [ + "corpus_parts_test.go", + "corpus_test.go", + "gate_check_served_test.go", + "harness_test.go", + "reference_proxy_test.go", + "required_corpus_tier_test.go", + ], + data = glob(["testdata/**"]) + ["//cmd/bd:bd_for_tests"], + env = {"BEADS_TEST_BD_BINARY": "$(rlocationpath //cmd/bd:bd_for_tests)"}, + deps = [ + "//internal/httpapi", + "//internal/httpapi/apigen", + "//internal/storage", + "//internal/storage/domain", + "//internal/storage/embeddeddolt", + "//internal/testutil/bazeltest", + "//internal/types", + "@in_gopkg_yaml_v3//:yaml_v3", + ], +) + +# corpus_test again, with the corpus tier on: BEADS_TEST_EMBEDDED_DOLT=1 runs +# TestServedCorpusPart1..N and BEADS_HTTP_TEST_REQUIRED=1 turns a skip of +# them into a failure. corpus_test alone skips them in every lane, because no +# lane sets those variables for it. It repeats corpus_test's `env` +# (go_test_pinned_shard.sh, like go_test_variant.sh, does not inherit it). +# +# Shard count: as one shard (one TestServedCorpus over every shape) the +# target ran 292-597s on the lane's executors (2026-10-11..13), the embedded +# lane's longest action in most runs where it executed. About 100s of that +# is the per-process server and seed, the rest the ~130 shapes (~1.9s each, +# serial, ~242s together). The shapes are now dealt round robin across +# corpusParts = 4 parts (corpus_test.go), each a top-level test with its own +# server and seed, and served_pinned_shards.txt pins part k to shard k; the +# 5th shard runs the package's other tests through the binary's +# round-robin (the engine-free ones, plus +# TestServedGateCheckOverAwaitTypedGates, which seeds its own small served +# store). Each part pays the setup again, though it seeds the served +# and embedded sides concurrently (~62-76s on the lane's executors), so a +# part's shard is that plus ~60s of shapes: 114-146s measured. Three parts +# ran 170-180s each; they save one setup (~75 test-seconds a run) but +# lengthen the lane's served long pole, which is on the gate's critical +# path, by ~34s. +# +# Tags: +# embedded: the embedded-Dolt tier; excluded from --config=prcore/ci, +# selected by --config=embedded. +sh_test( + name = "corpus_served_test", + size = "large", + # -test.timeout=19m fires (with a goroutine dump) before Bazel's 1200s + # action limit (eternal under --config=embedded). + timeout = "eternal", + srcs = ["//tools/bazel:go_test_pinned_shard.sh"], + args = [ + "$(rootpath :served_pinned_shards.txt)", + "$(rootpath :corpus_test)", + "-test.v", + "-test.count=1", + "-test.timeout=19m", + ], + data = [ + "served_pinned_shards.txt", + ":corpus_test", + "//cmd/bd:bd_for_tests", + ], + env = { + "BEADS_HTTP_TEST_REQUIRED": "1", + "BEADS_TEST_BD_BINARY": "$(rlocationpath //cmd/bd:bd_for_tests)", + "BEADS_TEST_EMBEDDED_DOLT": "1", + }, + shard_count = 5, + tags = ["embedded"], +) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/backend/http/corpus/README.md b/backend/http/corpus/README.md new file mode 100644 index 000000000..28451a0cf --- /dev/null +++ b/backend/http/corpus/README.md @@ -0,0 +1,154 @@ +# Served command corpus + +This suite is the working definition of "bd fully supports a remote HTTP +backend". It runs every distinct `bd` command shape that an orchestrator (gc) +and its packs and formulas issue against a work store. Each shape runs +against a served workspace and is compared with the same command on an +embedded workspace. + +## What runs + +The shapes are dealt round robin, in corpus order, across `corpusParts` +parts (`corpus_test.go`). Each part is a top-level test, +`TestServedCorpusPart1` .. `TestServedCorpusPartN`, and each does the +following for its share of the shapes: + +1. Builds `bd` from this tree. `BEADS_TEST_BD_BINARY=` reuses a prebuilt + binary instead. +2. Starts an in-process `bd serve` (`httpapi.Listen` over embedded Dolt) the + way a deployed server is bound: `AllowNonLoopback` plus a bearer token + file. The socket is still `127.0.0.1`, but the bind mode decides every + behaviour the server keys on, including its refusal of unlimited reads. +3. Puts a reference proxy in front of the server. The proxy makes it answer + like the deployed reference server described in + `testdata/reference_server.json`: + - the context handshake publishes exactly that server's capability set and + its `ContextResponse` members (so no `wire_revision`); + - an operation the reference server does not publish gets the server's own + 404; + - a query parameter or top-level request member it does not declare gets + the server's own 400 `unknown_parameter`. +4. Runs `bd connect` on one workspace and `bd init` on another. Both get the + `seed` from `testdata/corpus.yaml`: one graph of named rows, plus bulk + graphs that put more than one server page of ready rows and wisps in the + store. Both sides use `BEADS_ACTOR=worker` and set `CLAUDE_SESSION_ID`. + The embedded side is initialized and seeded on its own goroutine while + steps 2 and 3 run and the served side is seeded (`prepareSide`): the two + sides share no directory, env or process, and each runs the seed in + order, so the seeded data does not depend on the overlap. +5. Runs each of its shapes as a subtest, on both sides. The embedded run must + exit with the shape's `expect_exit` and match its `expect_stderr`. If it does + not, the shape is wrong or bd changed, and the subtest fails as a corpus + bug that no pending mark or allowlist entry hides. The served run must: + - exit like the embedded run; + - carry no refusal (`ErrUnsupported`, a v0-wire refusal, the + loopback-only 400, or a reference-profile 404/400); + - match the embedded output under the shape's `compare` mode, after + timestamps and revision tokens are dropped (but not `defer_until` or + `due_at`: a shape sets those itself, as absolute dates, and they must + match exactly); + - for writes, give the same JSON from every `verify` read on both sides + afterwards. + +A part takes its own server, workspaces and seed, so no shape can see +another part's writes. That is safe because no shape depends on another +shape's effects: +- every check compares the served run with the embedded run after the same + commands, so it holds whatever ran before it on both sides; +- each part keeps corpus order, so its reads still run on the bare seed, + before any of its writes; +- each write owns its target ids (`e2e-t-*`, or ids it creates). + +`TestCorpusPartsDealEveryShapeOnce` checks that every shape is in exactly one +part, in corpus order. A new shape must keep that independence: it may rely on +the seed and its own `setup`, never on another shape having run. + +Every part seeds again, so running all the parts in one process takes +longer than one run over every shape did; each part logs its setup time +(`part N setup ...`). Run one part with +`-run 'TestServedCorpusPart2$'`. + +There are four parts. In the embedded lane each part's setup (server start +plus both seeds, run concurrently) takes ~62-76s and the shapes ~242s in +total. Four parts ran 114-146s each and three ran 170-180s. Three would save +one setup (~75 test-seconds a run), but the longest part is the lane's +served long pole and sits on the CI gate's critical path, so four parts win. +To change the count, update `corpusParts`, `servedCorpusParts`, +`served_pinned_shards.txt` and the target's `shard_count` together. + +``` +CGO_ENABLED=1 BEADS_TEST_EMBEDDED_DOLT=1 BEADS_HTTP_TEST_REQUIRED=1 \ + go test -tags gms_pure_go -run 'TestServedCorpus|TestCorpus' ./backend/http/corpus/ +``` + +In CI, `//backend/http/corpus:corpus_served_test` runs the suite with both +variables set, in the Embedded Dolt lane (`--config=embedded`; see +[engdocs/TESTING.md](../../../engdocs/TESTING.md)). Its +`served_pinned_shards.txt` pins part k to Bazel shard k, so the parts run +concurrently. `corpus_test` on its own sets neither variable, so it skips +the parts. + +Two environment variables change the run: +- `BEADS_CORPUS_REPORT=` writes a JSON summary with per-shape status + and request counts. +- `BEADS_CORPUS_SKIP_PENDING=1` skips pending shapes without running them. + +## The data + +| File | Holds | +|---|---| +| `testdata/corpus.yaml` | assets, the seed, and the shapes | +| `testdata/allowlist.yaml` | permanent refusals, each with its reason and the refusal text the served run must match | +| `testdata/reference_server.json` | the reference server's wire surface | + +Each shape in `corpus.yaml` has these fields: + +| Field | Meaning | +|---|---| +| `id` | `gc-*` for orchestrator subprocess shapes, `mc-*` for pack/formula/prompt shapes | +| `source` | where the shape comes from | +| `args` | the argv; `{file:NAME}` expands to an asset path and `{rev:ID}` to that side's current revision of `ID` | +| `stdin` | text piped to `bd` on both sides | +| `setup` | commands run on both sides before the shape; one that fails fails the shape | +| `compare` | `json` (default), `ids`, `count`, `text` or `exit` | +| `ordered` | under `json` and `ids`, array order is significant; by default arrays are sorted before comparing | +| `prefix_of` | for a limited `ids` listing: its unlimited form. Each side's limited rows must be a prefix, in order, of that side's own unlimited listing, both sides return as many rows, and the two unlimited listings hold the same ids. A limit that cuts through a tie set (same priority, `created_at` in the same second) lands on different rows on two workspaces seeded seconds apart, so the limited rows are not compared across sides directly | +| `verify` | reads run after the shape | +| `ignore_fields` | JSON keys dropped, at any depth, before a `json` comparison and before `verify` output is compared; for example comment ids, which each workspace mints itself | +| `expect_exit`, `expect_stderr` | expected outcome on both sides (exit 0 by default). An allowlisted shape must state `expect_exit`; only its embedded run is held to these | +| `pending` | a known failure | +| `requests` | exactly how many requests the served run of `args` makes through the reference proxy, not counting `setup`, `verify` or `{rev:ID}` reads. Each request is a sequential round trip, so the count is the shape's latency floor over a gateway. A change that makes the shape cheaper updates the pin | + +`pending: {slice, reason}` marks a known failure and names the slice or +slices that fix it, for example `S6c+S15`. A pending shape **still runs**: +- while it fails, the subtest is skipped and the skip records what was + observed; +- once it passes, the subtest fails with "now passes; remove the pending + mark". + +So removing a mark is how a slice proves itself, and any other failure is +unexpected and fails the suite. + +## Updating the reference profile + +`reference_server.json` was derived from two things: +- the deployed server's live `GET /v0/beads/context` capabilities; +- its published OpenAPI document (bd 1.3.0, no `wire_revision`). For each + operation the profile keeps the method, the path template, the query + parameter names, and the top-level request members. + +When the deployed server is upgraded (SRV-1), regenerate the file the same +way. Then remove the `SRV-1` pending marks that now pass. + +## Known fidelity limits + +- Responses pass through unfiltered. A response member the reference server + would not send still reaches the client. +- Only top-level request members are checked; nested members (for example + `batchApply` items) are not. +- The served backend underneath is embedded Dolt, not the reference + deployment's storage backend. +- Out of scope, because they are local by design or never touch a remote + store: `init`, `bootstrap`, `migrate`, `doctor`, `flatten`, `gc`, and the + `dolt` subcommands. `context`, `version`, `backup status` and `prime` + are in the corpus, but only checked for exit codes. diff --git a/backend/http/corpus/corpus_parts_test.go b/backend/http/corpus/corpus_parts_test.go new file mode 100644 index 000000000..e8c3ec84f --- /dev/null +++ b/backend/http/corpus/corpus_parts_test.go @@ -0,0 +1,211 @@ +//go:build cgo + +package corpus_test + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "sync" + "testing" +) + +// TestCorpusPartsDealEveryShapeOnce runs without the embedded engine. It +// holds the deal TestServedCorpusPart1..N run to what makes splitting the +// corpus safe: every shape lands in exactly one part, each part keeps corpus +// order (so a part's reads still run before its writes, on its own fresh +// seed), no part is empty, and there is one TestServedCorpusPartN per part. +func TestCorpusPartsDealEveryShapeOnce(t *testing.T) { + if len(servedCorpusParts) != corpusParts { + t.Fatalf("servedCorpusParts has %d tests, want corpusParts = %d", len(servedCorpusParts), corpusParts) + } + c, _ := loadCorpus(t) + index := map[string]int{} + for i, s := range c.Shapes { + index[s.ID] = i + } + seen := map[string]int{} + for part := 1; part <= corpusParts; part++ { + shapes := corpusPart(c.Shapes, part) + if len(shapes) == 0 { + t.Errorf("part %d runs no shapes", part) + } + last := -1 + for _, s := range shapes { + if prev, dup := seen[s.ID]; dup { + t.Errorf("shape %s is in part %d and part %d", s.ID, prev, part) + } + seen[s.ID] = part + i, ok := index[s.ID] + if !ok { + t.Errorf("part %d runs %s, which is not a corpus shape", part, s.ID) + continue + } + if i <= last { + t.Errorf("part %d runs %s out of corpus order", part, s.ID) + } + last = i + } + } + for _, s := range c.Shapes { + if _, ok := seen[s.ID]; !ok { + t.Errorf("shape %s is in no part", s.ID) + } + } +} + +// The deal itself, on a corpus of 10 against 4 parts: round robin in corpus +// order. +func TestCorpusPartIsRoundRobinInOrder(t *testing.T) { + var shapes []shape + for i := 0; i < 10; i++ { + shapes = append(shapes, shape{ID: fmt.Sprint(i)}) + } + want := map[int]string{1: "[0 4 8]", 2: "[1 5 9]", 3: "[2 6]", 4: "[3 7]"} + for part, w := range want { + var ids []string + for _, s := range corpusPartOf(shapes, part, 4) { + ids = append(ids, s.ID) + } + if got := fmt.Sprint(ids); got != w { + t.Errorf("part %d of 4 = %s, want %s", part, got, w) + } + } +} + +// fakeBD writes a stand-in for bd that appends its arguments, one call per +// line, to calls.log in its working directory, and exits 3 when an argument +// is "boom". +func fakeBD(t *testing.T) string { + t.Helper() + bin := filepath.Join(t.TempDir(), "bd") + script := "#!/bin/sh\necho \"$*\" >> calls.log\nfor a in \"$@\"; do [ \"$a\" = boom ] && { echo boom >&2; exit 3; }; done\nexit 0\n" + if err := os.WriteFile(bin, []byte(script), 0o700); err != nil { + t.Fatal(err) + } + return bin +} + +func calls(t *testing.T, sd *side) []string { + t.Helper() + raw, err := os.ReadFile(filepath.Join(sd.dir, "calls.log")) + if err != nil { + t.Fatal(err) + } + return strings.Split(strings.TrimSpace(string(raw)), "\n") +} + +// prepareSide is what lets testServedCorpus seed the served and embedded +// sides at once: each side attaches, writes its assets and runs the seed in +// its own directories, in seed order, and a failure comes back as an error +// rather than a t.Fatal from a goroutine that is not the test's. +func TestPrepareSideSeedsBothSidesConcurrently(t *testing.T) { + bin := fakeBD(t) + c := &corpusFile{ + Files: []corpusAsset{{Name: "plan.json", Content: "{}"}}, + Seed: [][]string{{"create", "--graph", "{file:plan.json}"}, {"close", "e2e-x"}}, + } + a := &side{name: "served", dir: t.TempDir(), files: t.TempDir()} + b := &side{name: "embedded", dir: t.TempDir(), files: t.TempDir()} + var wg sync.WaitGroup + errs := make([]error, 2) + for i, sd := range []*side{a, b} { + wg.Add(1) + go func() { + defer wg.Done() + errs[i] = prepareSide(context.Background(), t, bin, c, sd, []string{"init", sd.name}) + }() + } + wg.Wait() + for i, sd := range []*side{a, b} { + if errs[i] != nil { + t.Fatalf("%s: %v", sd.name, errs[i]) + } + want := []string{"init " + sd.name, "create --graph " + filepath.Join(sd.files, "plan.json"), "close e2e-x"} + if got := calls(t, sd); !reflect.DeepEqual(got, want) { + t.Errorf("%s ran %q, want %q", sd.name, got, want) + } + if _, err := os.Stat(filepath.Join(sd.files, "plan.json")); err != nil { + t.Errorf("%s: asset not written: %v", sd.name, err) + } + } +} + +func TestPrepareSideReportsAFailedStepAsAnError(t *testing.T) { + bin := fakeBD(t) + c := &corpusFile{Seed: [][]string{{"create", "boom"}, {"close", "e2e-x"}}} + sd := &side{name: "embedded", dir: t.TempDir(), files: t.TempDir()} + err := prepareSide(context.Background(), t, bin, c, sd, []string{"init"}) + if err == nil || !strings.Contains(err.Error(), "seed [create boom] on embedded failed") || !strings.Contains(err.Error(), "exit=3") { + t.Fatalf("err = %v, want the failed seed step with its exit", err) + } + if got := calls(t, sd); !reflect.DeepEqual(got, []string{"init", "create boom"}) { + t.Errorf("ran %q; the seed must stop at the failed step", got) + } + + sd = &side{name: "served", dir: t.TempDir(), files: t.TempDir()} + if err := prepareSide(context.Background(), t, bin, c, sd, []string{"connect", "boom"}); err == nil || !strings.Contains(err.Error(), "bd connect boom on served") { + t.Fatalf("err = %v, want the failed attach", err) + } +} + +// Once the other side has failed, the test cancels: a side stops before its +// next step instead of seeding on for nothing. +func TestPrepareSideStopsWhenCancelled(t *testing.T) { + bin := fakeBD(t) + c := &corpusFile{Seed: [][]string{{"create", "e2e-x"}}} + sd := &side{name: "embedded", dir: t.TempDir(), files: t.TempDir()} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := prepareSide(ctx, t, bin, c, sd, []string{"init"}); !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v, want context.Canceled", err) + } + if _, err := os.Stat(filepath.Join(sd.dir, "calls.log")); !os.IsNotExist(err) { + t.Errorf("bd ran after the cancel (calls.log: %v)", err) + } +} + +// A part test wired to another part's number would run that part's shapes +// twice and drop its own without a word; testServedCorpus refuses to run +// unless the test's name is its part's (corpusPartNameErr). +func TestCorpusPartNameMustMatchItsPart(t *testing.T) { + if err := corpusPartNameErr("TestServedCorpusPart3", 3); err != nil { + t.Errorf("matching name: %v", err) + } + for _, c := range []struct { + name string + part int + }{ + {"TestServedCorpusPart3", 2}, + {"TestServedCorpusPart1", 10}, + {"TestServedCorpusPart10", 1}, + {"TestServedCorpusPart3/sub", 3}, + {"TestServedCorpus", 1}, + // A stray part past corpusParts would run no shapes at all. + {fmt.Sprintf("TestServedCorpusPart%d", corpusParts+1), corpusParts + 1}, + {"TestServedCorpusPart0", 0}, + } { + if err := corpusPartNameErr(c.name, c.part); err == nil { + t.Errorf("corpusPartNameErr(%q, %d) = nil, want a mismatch", c.name, c.part) + } + } + // Every wired part test passes the guard: run each with the engine + // off, so the guard (which comes first) is all that can fail it. + for k, fn := range servedCorpusParts { + want := fmt.Sprintf("TestServedCorpusPart%d", k+1) + if got := testFuncName(fn); got != want { + t.Errorf("servedCorpusParts[%d] is %s, want %s", k, got, want) + } + } +} + +// testFuncName is fn's unqualified function name. +func testFuncName(fn func(*testing.T)) string { + full := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name() + return full[strings.LastIndex(full, ".")+1:] +} diff --git a/backend/http/corpus/corpus_test.go b/backend/http/corpus/corpus_test.go new file mode 100644 index 000000000..ee4c30331 --- /dev/null +++ b/backend/http/corpus/corpus_test.go @@ -0,0 +1,968 @@ +//go:build cgo + +// Package corpus_test is the served command-corpus suite: every distinct bd +// command shape an orchestrator (gc) and its packs/formulas issue, run by the +// real bd binary against an in-process bd serve masked to a reference +// deployment's wire surface, and compared with the same command on an embedded +// workspace. See README.md. +package corpus_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "sync" + "testing" + "time" + + "gopkg.in/yaml.v3" +) + +// corpusFile is testdata/corpus.yaml. +type corpusFile struct { + Files []corpusAsset `yaml:"files"` + Seed [][]string `yaml:"seed"` + Shapes []shape `yaml:"shapes"` +} + +// corpusAsset is a file the shapes reference as {file:NAME}. Exactly one of +// Content and Bulk is set. +type corpusAsset struct { + Name string `yaml:"name"` + Content string `yaml:"content"` + Bulk *bulkGraph `yaml:"bulk"` +} + +// bulkGraph generates a `bd create --graph` plan of Count independent tasks +// with ids IDPrefix-001.. so the suite can hold more rows than one server page +// without a 100-line literal in the corpus. +type bulkGraph struct { + IDPrefix string `yaml:"id_prefix"` + Count int `yaml:"count"` + Priority int `yaml:"priority"` + Ephemeral bool `yaml:"ephemeral"` + Metadata map[string]string `yaml:"metadata"` +} + +type shape struct { + ID string `yaml:"id"` + Source string `yaml:"source"` + // Args is the bd argv. Tokens may carry {file:NAME} (the side's copy of a + // corpus asset) and {rev:ID} (that side's current revision of ID). + Args []string `yaml:"args"` + Stdin string `yaml:"stdin"` + Setup [][]string `yaml:"setup"` + // Compare is how the served stdout is held to the embedded stdout: + // json (default), ids, count, text, or exit (exit code only). + Compare string `yaml:"compare"` + // Ordered keeps array order significant under json/ids. + Ordered bool `yaml:"ordered"` + // PrefixOf is the unlimited form of a limited listing (compare: ids). A + // limit cut through a tie set (same priority, created_at within one + // second) lands at a different row on two workspaces seeded seconds + // apart, so the limited rows are not compared across sides. Instead each + // side's limited rows must be, in order, a prefix of that SAME side's + // PrefixOf listing, both sides must return as many rows, and the two + // PrefixOf listings must hold the same ids. + PrefixOf []string `yaml:"prefix_of"` + // IgnoreFields are extra JSON keys dropped before comparing. + IgnoreFields []string `yaml:"ignore_fields"` + // ExpectExit is the exit code both sides must produce (default 0). An + // allowlisted shape must state it: the embedded run is held to it even + // though the served run is only held to the allowlisted refusal. + ExpectExit *int `yaml:"expect_exit"` + // ExpectStderr, when set, must match both sides' stderr (only the + // embedded side's on an allowlisted shape). + ExpectStderr string `yaml:"expect_stderr"` + // Verify are reads run on both sides after the shape and compared as json: + // how a write is checked for having done the same thing on both backends. + Verify [][]string `yaml:"verify"` + // Requests, when set, is exactly how many requests the served run of Args + // makes through the reference proxy (not its setup or verify reads). Each + // is a sequential round trip, so the count is the shape's latency floor + // over a gateway: a change that adds one fails here, and one that saves + // one updates the pin. + Requests *int `yaml:"requests"` + // Pending marks a known failure and names the slice that fixes it. + Pending *pending `yaml:"pending"` +} + +// wantExit is the exit code the embedded run must produce. +func (s shape) wantExit() int { + if s.ExpectExit == nil { + return 0 + } + return *s.ExpectExit +} + +type pending struct { + Slice string `yaml:"slice"` + Reason string `yaml:"reason"` +} + +// allowEntry is testdata/allowlist.yaml: a shape that is EXPECTED to be +// refused over http, permanently, for a stated reason. The served run must +// fail and match Refusal; if it ever succeeds the entry is stale and fails. +// The embedded run is still held to the shape's expect_exit and +// expect_stderr, and nothing else of the shape is checked. +type allowEntry struct { + ID string `yaml:"id"` + Reason string `yaml:"reason"` + Refusal string `yaml:"refusal"` +} + +// refusalMarkers are the texts a refusal of an operation over http carries: +// issueops.ErrUnsupported, encode.RefusedError, the client's capability +// preflight (wire.CapabilityError, which never reaches the proxy), the +// server's loopback-only unlimited-read 400, an unrouted 404, and a strict +// decoder's unknown member. +var refusalMarkers = regexp.MustCompile(`(?i)not supported by the|not expressible on the v0 wire|loopback-only|capability "[^"]+" not advertised|does not advertise capability|no such route on this server|unknown_parameter|unknown query parameter|json: unknown field`) + +// volatileKey names JSON members that legitimately differ between two +// workspaces fed the same commands: timestamps and revision tokens. +var volatileKey = regexp.MustCompile(`(^|_)at$|^revision$|^row_version$|^expected_revision$|^current_revision$`) + +// callerTimeKey names the timestamps a shape's own arguments set (bd create +// --defer, --due). They are compared as given, neither dropped as volatile +// nor scrubbed to , so a client that sends the wrong one fails; a shape +// must give them as absolute dates, since a relative one resolves against +// each side's own clock. +var callerTimeKey = map[string]bool{"defer_until": true, "due_at": true} + +var timestampText = regexp.MustCompile(`\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?`) + +func loadCorpus(t *testing.T) (*corpusFile, map[string]allowEntry) { + t.Helper() + raw, err := os.ReadFile("testdata/corpus.yaml") + if err != nil { + t.Fatalf("read corpus: %v", err) + } + var c corpusFile + dec := yaml.NewDecoder(strings.NewReader(string(raw))) + dec.KnownFields(true) + if err := dec.Decode(&c); err != nil { + t.Fatalf("parse testdata/corpus.yaml: %v", err) + } + rawAllow, err := os.ReadFile("testdata/allowlist.yaml") + if err != nil { + t.Fatalf("read allowlist: %v", err) + } + var entries []allowEntry + dec = yaml.NewDecoder(strings.NewReader(string(rawAllow))) + dec.KnownFields(true) + if err := dec.Decode(&entries); err != nil { + t.Fatalf("parse testdata/allowlist.yaml: %v", err) + } + allow := map[string]allowEntry{} + for _, e := range entries { + if e.ID == "" || strings.TrimSpace(e.Reason) == "" || e.Refusal == "" { + t.Fatalf("allowlist entry %+v needs id, reason and refusal", e) + } + allow[e.ID] = e + } + return &c, allow +} + +// TestCorpusFileIsWellFormed runs without the embedded engine: it keeps the +// data honest (unique ids, a source and a slice for every pending mark, no +// allowlist entry for a shape that does not exist, no shape both pending and +// allowlisted, an allowlisted shape states its embedded exit code and +// carries no check that the allowlist would skip, every expect_stderr and +// refusal compiles, and the reference profile loads). +func TestCorpusFileIsWellFormed(t *testing.T) { + c, allow := loadCorpus(t) + seen := map[string]bool{} + for _, s := range c.Shapes { + if s.ID == "" || len(s.Args) == 0 { + t.Errorf("shape %+v needs an id and args", s) + continue + } + if seen[s.ID] { + t.Errorf("duplicate shape id %q", s.ID) + } + seen[s.ID] = true + if strings.TrimSpace(s.Source) == "" { + t.Errorf("shape %s names no source", s.ID) + } + if s.Pending != nil && (s.Pending.Slice == "" || strings.TrimSpace(s.Pending.Reason) == "") { + t.Errorf("shape %s is pending without a slice and a reason", s.ID) + } + if _, ok := allow[s.ID]; ok { + if s.Pending != nil { + t.Errorf("shape %s is both pending and allowlisted; pick one", s.ID) + } + if s.ExpectExit == nil { + t.Errorf("shape %s is allowlisted without expect_exit; state the exit code the embedded run must produce", s.ID) + } + if modeOf(s) != "exit" || len(s.Verify) > 0 { + t.Errorf("shape %s is allowlisted, so only its exit code and stderr are checked; give it compare: exit and no verify", s.ID) + } + if s.Requests != nil { + t.Errorf("shape %s is allowlisted, so its request count is not checked; drop requests", s.ID) + } + } + switch s.Compare { + case "", "json", "ids", "count", "text", "exit": + default: + t.Errorf("shape %s: unknown compare mode %q", s.ID, s.Compare) + } + if len(s.PrefixOf) > 0 && s.Compare != "ids" { + t.Errorf("shape %s: prefix_of needs compare: ids", s.ID) + } + if _, err := regexp.Compile(s.ExpectStderr); err != nil { + t.Errorf("shape %s: expect_stderr: %v", s.ID, err) + } + if s.Requests != nil && *s.Requests < 0 { + t.Errorf("shape %s: requests %d is negative", s.ID, *s.Requests) + } + } + for id, entry := range allow { + if !seen[id] { + t.Errorf("allowlist names %q, which is not a corpus shape", id) + } + if _, err := regexp.Compile(entry.Refusal); err != nil { + t.Errorf("allowlist entry %s: refusal: %v", id, err) + } + } + for _, a := range c.Files { + if (a.Content == "") == (a.Bulk == nil) { + t.Errorf("asset %s needs exactly one of content and bulk", a.Name) + } + } + loadReferenceProfile(t) +} + +// side is one workspace the corpus runs in. +type side struct { + name string + dir string + files string + env []string +} + +type outcome struct { + id, status, detail string + requests int64 +} + +// corpusParts is how many parts the shapes are dealt across. Each part is a +// top-level test of its own (TestServedCorpusPart1..N, servedCorpusParts) +// that starts its own server and seeds its own pair of workspaces, so the +// embedded lane runs each part in a Bazel shard of its own +// (served_pinned_shards.txt pins part k to shard k). The parts can be split +// because no shape depends on another's effects: every comparison is the +// served side against the embedded side after the same commands, and each +// part keeps corpus order, so its reads still run on the bare seed before +// any of its writes (see testdata/corpus.yaml's header). +// +// Four parts, from the embedded lane's measured part times (PR #7538): each +// part's server start and concurrent seed take ~62-76s and the 127 shapes +// ~242s together, so four parts ran 114-146s each and three ran 170-180s. +// Three would save one setup (~75 test-seconds a run), but the longest part +// is the embedded lane's served long pole, on the gate's critical path +// (forks' above all), so the ~34s it saves is worth more. +const corpusParts = 4 + +// servedCorpusParts are the parts' tests, one per part, in part order. +var servedCorpusParts = []func(*testing.T){ + TestServedCorpusPart1, TestServedCorpusPart2, TestServedCorpusPart3, TestServedCorpusPart4, +} + +func TestServedCorpusPart1(t *testing.T) { testServedCorpus(t, 1) } +func TestServedCorpusPart2(t *testing.T) { testServedCorpus(t, 2) } +func TestServedCorpusPart3(t *testing.T) { testServedCorpus(t, 3) } +func TestServedCorpusPart4(t *testing.T) { testServedCorpus(t, 4) } + +// corpusPartNameErr fails a part test whose name is not its part's: a +// TestServedCorpusPart3 that ran part 2 would run part 2's shapes twice and +// silently drop its own. A part outside 1..corpusParts (a stray +// TestServedCorpusPart5 left after the parts shrink) would run no shapes. +func corpusPartNameErr(name string, part int) error { + if part < 1 || part > corpusParts { + return fmt.Errorf("%s runs corpus part %d; there are parts 1..%d (corpusParts)", name, part, corpusParts) + } + if want := fmt.Sprintf("TestServedCorpusPart%d", part); name != want { + return fmt.Errorf("%s runs corpus part %d; only %s may (fix its testServedCorpus call)", name, part, want) + } + return nil +} + +// corpusPart returns the shapes part (1..corpusParts) runs. +func corpusPart(shapes []shape, part int) []shape { + return corpusPartOf(shapes, part, corpusParts) +} + +// corpusPartOf deals shapes round robin, in corpus order, across parts parts +// and returns part's (1-based) share: shapes part-1, part-1+parts, and so on. +// Round robin keeps each part a mix of the corpus's reads and writes in +// their original order. +func corpusPartOf(shapes []shape, part, parts int) []shape { + var out []shape + for i := part - 1; i < len(shapes); i += parts { + out = append(out, shapes[i]) + } + return out +} + +// testServedCorpus is the suite, for one part of the corpus. Each shape is a +// subtest; a pending shape is still RUN and then skipped with what it did, so +// a slice that fixes it sees the subtest fail with "now passes; remove the +// pending mark". BEADS_CORPUS_SKIP_PENDING=1 skips pending shapes without +// running them. BEADS_CORPUS_REPORT= writes a JSON summary of every +// part this process has run. +func testServedCorpus(t *testing.T, part int) { + // First, before the engine gate: a part test wired to the wrong part + // fails in every lane, not only where the corpus runs. + if err := corpusPartNameErr(t.Name(), part); err != nil { + t.Fatal(err) + } + skipUnlessEmbeddedDolt(t) + c, allow := loadCorpus(t) + shapes := corpusPart(c.Shapes, part) + profile := loadReferenceProfile(t) + bin := buildBD(t) + + common := []string{ + "BEADS_ACTOR=worker", + "CLAUDE_SESSION_ID=corpus-session-s23", + "BD_BACKUP_ENABLED=false", + "BD_EXPORT_AUTO=false", + } + + // The embedded side needs no server: init and seed it on a goroutine + // while this one starts the server and seeds the served side. Each side + // has its own directories, env and bd processes (prepareSide), and each + // still runs the seed in order, so the seeded data is what it was when + // the two sides were seeded command by command in turn. The deferred + // cancel and Wait run on every exit, a t.Fatal included, so the goroutine + // never outlives the test or its TempDirs. + setupStart := time.Now() + ctx, cancel := context.WithCancel(context.Background()) + var seeding sync.WaitGroup + defer seeding.Wait() + defer cancel() + local := &side{name: "embedded", dir: t.TempDir(), files: t.TempDir(), env: common} + var localErr error + seeding.Add(1) + go func() { + defer seeding.Done() + localErr = prepareSide(ctx, t, bin, c, local, + []string{"init", "-p", corpusPrefix, "--non-interactive", "--skip-hooks", "--skip-agents", "-q"}) + if localErr != nil { + cancel() + } + }() + + serverAddr := startCorpusServer(t) + proxy := newReferenceProxy(t, profile, serverAddr) + proxyAddr := startProxy(t, proxy) + served := &side{name: "served", dir: t.TempDir(), files: t.TempDir(), + env: append([]string{"BEADS_HTTP_TOKEN=" + proxyAddr + "=" + corpusToken}, common...)} + servedErr := prepareSide(ctx, t, bin, c, served, + []string{"connect", "http://" + proxyAddr, "--expect-project-id", corpusProjectID, "--json"}) + if servedErr != nil { + cancel() + } + seeding.Wait() + // The side that failed first is the one to report; the other may only + // have seen the cancel. + for _, err := range []error{servedErr, localErr} { + if err != nil && !errors.Is(err, context.Canceled) { + t.Fatal(err) + } + } + t.Logf("part %d setup (server start and both sides seeded concurrently): %s", part, time.Since(setupStart).Round(100*time.Millisecond)) + proxy.takeRefusals() + + skipPending := os.Getenv("BEADS_CORPUS_SKIP_PENDING") == "1" + var outcomes []outcome + for _, s := range shapes { + s := s + t.Run(s.ID, func(t *testing.T) { + o := outcome{id: s.ID} + defer func() { outcomes = append(outcomes, o) }() + if s.Pending != nil && skipPending { + o.status = "pending:" + s.Pending.Slice + t.Skipf("pending %s: %s", s.Pending.Slice, s.Pending.Reason) + } + before := proxy.requests.Load() + failures := runShape(t, bin, s, served, local, allow, proxy) + o.requests = proxy.requests.Load() - before + entry, allowed := allow[s.ID] + switch { + case hasCorpusBug(failures): + // The embedded side itself disagrees with the corpus: no pending + // mark or allowlist entry may hide that, or a pending shape that + // can never pass would sit in the corpus forever. + o.status = "FAIL(corpus)" + o.detail = failures[0] + for _, f := range failures { + t.Error(f) + } + case s.Pending != nil && len(failures) == 0: + o.status = "FAIL(pending-now-passes)" + t.Errorf("shape is marked pending %s but now passes on the reference profile; remove the pending mark from testdata/corpus.yaml", s.Pending.Slice) + case s.Pending != nil: + o.status = "pending:" + s.Pending.Slice + o.detail = failures[0] + t.Skipf("pending %s: %s\nobserved:\n%s", s.Pending.Slice, s.Pending.Reason, strings.Join(failures, "\n")) + case len(failures) > 0: + o.status = "FAIL" + o.detail = failures[0] + for _, f := range failures { + t.Error(f) + } + case allowed: + o.status = "allowed" + o.detail = entry.Reason + default: + o.status = "pass" + } + }) + } + + summarize(t, part, len(c.Shapes), outcomes) +} + +// runShape runs one shape on both sides and returns every way the served run +// fell short. It never calls t.Error itself, so the caller can turn a pending +// shape's failures into a skip. +func runShape(t *testing.T, bin string, s shape, served, local *side, allow map[string]allowEntry, proxy *referenceProxy) []string { + t.Helper() + var fails []string + failf := func(format string, a ...any) { fails = append(fails, fmt.Sprintf(format, a...)) } + wantStderr, err := regexp.Compile(s.ExpectStderr) + if err != nil { + failf("CORPUS BUG: expect_stderr %q: %v", s.ExpectStderr, err) + return fails + } + + for _, args := range s.Setup { + for _, sd := range []*side{served, local} { + if r := runBD(t, bin, sd.dir, sd.env, "", expand(context.Background(), t, bin, sd, args)...); r.code != 0 { + failf("setup %v failed on %s: %s", args, sd.name, r) + return fails + } + } + } + proxy.takeRefusals() + args := expand(context.Background(), t, bin, served, s.Args) + before := proxy.requests.Load() + sr := runBD(t, bin, served.dir, served.env, s.Stdin, args...) + servedRequests := proxy.requests.Load() - before + wireRefusals := proxy.takeRefusals() + lr := runBD(t, bin, local.dir, local.env, s.Stdin, expand(context.Background(), t, bin, local, s.Args)...) + t.Logf("bd %s\nserved: %s\nembedded: exit=%d", strings.Join(s.Args, " "), sr, lr.code) + if len(wireRefusals) > 0 { + t.Logf("reference-profile refusals on the wire: %v", wireRefusals) + } + + // The embedded run is the oracle for every shape, an allowlisted one + // included: when it no longer does what the shape says, the shape is + // wrong or bd changed, whatever the served run did. + if lr.code != s.wantExit() { + failf("CORPUS BUG: the embedded run exited %d, want %d; the shape itself is wrong or bd changed: %s", lr.code, s.wantExit(), lr) + return fails + } + if s.ExpectStderr != "" && !wantStderr.MatchString(lr.stderr) { + failf("CORPUS BUG: embedded stderr does not match %q: %s", s.ExpectStderr, lr.stderr) + return fails + } + + if entry, ok := allow[s.ID]; ok { + re, err := regexp.Compile(entry.Refusal) + if err != nil { + failf("allowlist refusal regexp for %s: %v", s.ID, err) + return fails + } + if sr.code == 0 { + failf("allowlisted (%s) but the served run SUCCEEDED; drop it from testdata/allowlist.yaml and give it a comparison", entry.Reason) + } else if !re.MatchString(sr.stderr + sr.stdout) { + failf("allowlisted refusal did not match %q (a different failure than the one allowed): %s", entry.Refusal, sr) + } + return fails + } + + if m := refusalMarkers.FindString(sr.stderr + sr.stdout); m != "" { + failf("served run carries a refusal (%q): %s", m, sr) + } else if len(wireRefusals) > 0 && sr.code != 0 { + failf("served run failed on a reference-profile refusal %v: %s", wireRefusals, sr) + } + if sr.code != lr.code { + failf("exit code: served %d, embedded %d: %s", sr.code, lr.code, sr) + } + if s.ExpectStderr != "" && !wantStderr.MatchString(sr.stderr) { + failf("served stderr does not match %q (embedded does): %s", s.ExpectStderr, sr) + } + if s.Requests != nil && servedRequests != int64(*s.Requests) { + failf("the served run made %d requests, want exactly %d (requests); a change that saves one updates the pin", servedRequests, *s.Requests) + } + if len(fails) > 0 { + return fails + } + if len(s.PrefixOf) > 0 { + vs := runBD(t, bin, served.dir, served.env, "", expand(context.Background(), t, bin, served, s.PrefixOf)...) + vl := runBD(t, bin, local.dir, local.env, "", expand(context.Background(), t, bin, local, s.PrefixOf)...) + if vs.code != 0 || vl.code != 0 { + failf("prefix_of %v: exit served %d, embedded %d: served %s", s.PrefixOf, vs.code, vl.code, vs) + } else if d := comparePrefix(sr.stdout, lr.stdout, vs.stdout, vl.stdout); d != "" { + failf("output parity (ids, prefix_of): %s", d) + } + } else if d := compareOutputs(s, sr.stdout, lr.stdout); d != "" { + failf("output parity (%s): %s", modeOf(s), d) + } + for _, args := range s.Verify { + vs := runBD(t, bin, served.dir, served.env, "", expand(context.Background(), t, bin, served, args)...) + vl := runBD(t, bin, local.dir, local.env, "", expand(context.Background(), t, bin, local, args)...) + if vs.code != vl.code { + failf("verify %v: exit served %d, embedded %d: served %s", args, vs.code, vl.code, vs) + continue + } + if vl.code != 0 { + continue // both refused the read (e.g. a deleted id): equal is the check + } + if d := compareJSON(vs.stdout, vl.stdout, s.IgnoreFields, false); d != "" { + failf("verify %v diverged after the write: %s", args, d) + } + } + return fails +} + +func hasCorpusBug(failures []string) bool { + for _, f := range failures { + if strings.HasPrefix(f, "CORPUS BUG") { + return true + } + } + return false +} + +func modeOf(s shape) string { + if s.Compare == "" { + return "json" + } + return s.Compare +} + +func compareOutputs(s shape, served, local string) string { + switch modeOf(s) { + case "exit": + return "" + case "text": + a, b := scrubText(served), scrubText(local) + if a != b { + return fmt.Sprintf("text differs\nserved:\n%s\nembedded:\n%s", clip(a, 3000), clip(b, 3000)) + } + return "" + case "count": + a, errA := topLevelLen(served) + b, errB := topLevelLen(local) + if errA != nil || errB != nil { + return fmt.Sprintf("count: served err=%v embedded err=%v\nserved:\n%s", errA, errB, clip(served, 2000)) + } + if a != b { + return fmt.Sprintf("row count: served %d, embedded %d", a, b) + } + return "" + case "ids": + a, errA := idList(served, s.Ordered) + b, errB := idList(local, s.Ordered) + if errA != nil || errB != nil { + return fmt.Sprintf("ids: served err=%v embedded err=%v\nserved:\n%s", errA, errB, clip(served, 2000)) + } + if !reflect.DeepEqual(a, b) { + return fmt.Sprintf("ids differ\nserved (%d): %v\nembedded (%d): %v", len(a), a, len(b), b) + } + return "" + default: + return compareJSON(served, local, s.IgnoreFields, s.Ordered) + } +} + +// comparePrefix holds a limited listing to its unlimited form on each side: +// see shape.PrefixOf. +func comparePrefix(served, local, servedAll, localAll string) string { + lists := make([][]string, 4) + for i, out := range []string{served, local, servedAll, localAll} { + ids, err := idList(out, true) + if err != nil { + return fmt.Sprintf("listing %d: %v\n%s", i, err, clip(out, 2000)) + } + lists[i] = ids + } + s, l, sAll, lAll := lists[0], lists[1], lists[2], lists[3] + if len(s) != len(l) { + return fmt.Sprintf("row count: served %d, embedded %d", len(s), len(l)) + } + for _, c := range []struct { + name string + rows, all []string + }{{"served", s, sAll}, {"embedded", l, lAll}} { + if len(c.rows) > len(c.all) || !reflect.DeepEqual(c.rows, c.all[:len(c.rows)]) { + return fmt.Sprintf("%s limited rows are not a prefix of its own unlimited listing\nlimited: %v\nunlimited: %v", c.name, c.rows, c.all) + } + } + sSet := append([]string(nil), sAll...) + lSet := append([]string(nil), lAll...) + sort.Strings(sSet) + sort.Strings(lSet) + if !reflect.DeepEqual(sSet, lSet) { + return fmt.Sprintf("unlimited ids differ\nserved (%d): %v\nembedded (%d): %v", len(sSet), sSet, len(lSet), lSet) + } + return "" +} + +func scrubText(s string) string { + return strings.TrimSpace(timestampText.ReplaceAllString(s, "")) +} + +func decode(s string) (any, error) { + var v any + if err := json.Unmarshal([]byte(strings.TrimSpace(s)), &v); err != nil { + return nil, fmt.Errorf("not JSON: %w", err) + } + return v, nil +} + +// rows finds the row array in a bd --json payload: the payload itself, or the +// first array member of an envelope object. +func rows(v any) ([]any, bool) { + switch x := v.(type) { + case []any: + return x, true + case map[string]any: + for _, k := range []string{"issues", "data", "items", "results"} { + if arr, ok := x[k].([]any); ok { + return arr, true + } + } + } + return nil, false +} + +func topLevelLen(s string) (int, error) { + v, err := decode(s) + if err != nil { + return 0, err + } + arr, ok := rows(v) + if !ok { + return 0, fmt.Errorf("no row array in output") + } + return len(arr), nil +} + +func idList(s string, ordered bool) ([]string, error) { + v, err := decode(s) + if err != nil { + return nil, err + } + arr, ok := rows(v) + if !ok { + return nil, fmt.Errorf("no row array in output") + } + out := []string{} + for _, r := range arr { + if m, ok := r.(map[string]any); ok { + if id, ok := m["id"].(string); ok { + out = append(out, id) + } + } + } + if !ordered { + sort.Strings(out) + } + return out, nil +} + +func compareJSON(served, local string, ignore []string, ordered bool) string { + a, errA := decode(served) + b, errB := decode(local) + if errA != nil || errB != nil { + return fmt.Sprintf("served err=%v embedded err=%v\nserved:\n%s\nembedded:\n%s", errA, errB, clip(served, 2000), clip(local, 2000)) + } + drop := map[string]bool{} + for _, k := range ignore { + drop[k] = true + } + a, b = normalize(a, drop, ordered), normalize(b, drop, ordered) + if path, x, y, same := firstDiff("$", a, b); !same { + return fmt.Sprintf("first difference at %s: served=%s embedded=%s", path, brief(x), brief(y)) + } + return "" +} + +func normalize(v any, drop map[string]bool, ordered bool) any { + switch x := v.(type) { + case map[string]any: + out := make(map[string]any, len(x)) + for k, val := range x { + if drop[k] { + continue + } + if callerTimeKey[k] { + out[k] = val + continue + } + if volatileKey.MatchString(k) { + continue + } + out[k] = normalize(val, drop, ordered) + } + return out + case []any: + out := make([]any, len(x)) + for i, e := range x { + out[i] = normalize(e, drop, ordered) + } + if !ordered { + sort.SliceStable(out, func(i, j int) bool { return sortKey(out[i]) < sortKey(out[j]) }) + } + return out + case string: + return timestampText.ReplaceAllString(x, "") + default: + return v + } +} + +func sortKey(v any) string { + if m, ok := v.(map[string]any); ok { + for _, k := range []string{"id", "issue_id", "key"} { + if s, ok := m[k].(string); ok { + return k + "=" + s + } + } + if inner, ok := m["issue"].(map[string]any); ok { + if s, ok := inner["id"].(string); ok { + return "issue.id=" + s + } + } + } + raw, _ := json.Marshal(v) + return string(raw) +} + +func firstDiff(path string, a, b any) (string, any, any, bool) { + switch x := a.(type) { + case map[string]any: + y, ok := b.(map[string]any) + if !ok { + return path, a, b, false + } + keys := map[string]bool{} + for k := range x { + keys[k] = true + } + for k := range y { + keys[k] = true + } + sorted := make([]string, 0, len(keys)) + for k := range keys { + sorted = append(sorted, k) + } + sort.Strings(sorted) + for _, k := range sorted { + xv, xok := x[k] + yv, yok := y[k] + if !xok || !yok { + return path + "." + k, xv, yv, false + } + if p, l, r, same := firstDiff(path+"."+k, xv, yv); !same { + return p, l, r, false + } + } + return "", nil, nil, true + case []any: + y, ok := b.([]any) + if !ok { + return path, a, b, false + } + if len(x) != len(y) { + return path + ".length", len(x), len(y), false + } + for i := range x { + if p, l, r, same := firstDiff(path+"["+strconv.Itoa(i)+"]", x[i], y[i]); !same { + return p, l, r, false + } + } + return "", nil, nil, true + default: + if reflect.DeepEqual(a, b) { + return "", nil, nil, true + } + return path, a, b, false + } +} + +func brief(v any) string { + if v == nil { + return "" + } + raw, _ := json.Marshal(v) + return clip(string(raw), 400) +} + +var placeholder = regexp.MustCompile(`\{(file|rev):([^}]+)\}`) + +// expand substitutes {file:NAME} and {rev:ID} in args for side sd. It never +// fails t (a {rev:} it cannot read becomes "0"), so prepareSide may call it +// off the test's goroutine; its {rev:} lookup runs under ctx, so a cancelled +// prepareSide starts no further bd there either. +func expand(ctx context.Context, t *testing.T, bin string, sd *side, args []string) []string { + t.Helper() + out := make([]string, len(args)) + for i, a := range args { + out[i] = placeholder.ReplaceAllStringFunc(a, func(m string) string { + parts := placeholder.FindStringSubmatch(m) + switch parts[1] { + case "file": + return filepath.Join(sd.files, parts[2]) + default: + r, err := execBD(ctx, bin, sd.dir, sd.env, "", "show", parts[2], "--json") + if err != nil { + t.Logf("{rev:%s} on %s: %v", parts[2], sd.name, err) + return "0" + } + if r.code != 0 { + t.Logf("{rev:%s} on %s: show failed: %s", parts[2], sd.name, r) + return "0" + } + v, err := decode(r.stdout) + if err != nil { + return "0" + } + if arr, ok := rows(v); ok && len(arr) > 0 { + v = arr[0] + } + if m, ok := v.(map[string]any); ok { + if rev, ok := m["revision"].(string); ok { + return rev + } + } + return "0" + } + }) + } + return out +} + +// prepareSide attaches sd to its store with bd attach (connect or init), +// writes the corpus's asset files into sd.files and runs the seed on sd, in +// order. It touches only sd's own directories and bd processes and returns a +// failure as an error instead of failing t, so testServedCorpus runs it for +// the two sides at once; it stops before its next bd once ctx is done. +func prepareSide(ctx context.Context, t *testing.T, bin string, c *corpusFile, sd *side, attach []string) error { + t.Helper() + r, err := execBD(ctx, bin, sd.dir, sd.env, "", attach...) + if err != nil { + return err + } + if r.code != 0 { + return fmt.Errorf("bd %s on %s: %s", strings.Join(attach, " "), sd.name, r) + } + if err := writeAssets(c.Files, sd.files); err != nil { + return fmt.Errorf("%s: %w", sd.name, err) + } + for _, args := range c.Seed { + if err := ctx.Err(); err != nil { + return err + } + r, err := execBD(ctx, bin, sd.dir, sd.env, "", expand(ctx, t, bin, sd, args)...) + if err != nil { + return err + } + if r.code != 0 { + return fmt.Errorf("seed %v on %s failed; the seed must use shapes that work on the reference profile: %s", args, sd.name, r) + } + } + return nil +} + +func writeAssets(assets []corpusAsset, dir string) error { + for _, a := range assets { + content := a.Content + if a.Bulk != nil { + content = bulkPlan(*a.Bulk) + } + if err := os.WriteFile(filepath.Join(dir, a.Name), []byte(content), 0o600); err != nil { + return fmt.Errorf("write asset %s: %w", a.Name, err) + } + } + return nil +} + +func bulkPlan(b bulkGraph) string { + type node struct { + Key string `json:"key"` + ID string `json:"id"` + Title string `json:"title"` + Type string `json:"type"` + Priority int `json:"priority"` + Ephemeral bool `json:"ephemeral,omitempty"` + Metadata map[string]string `json:"metadata,omitempty"` + } + plan := struct { + CommitMessage string `json:"commit_message"` + Nodes []node `json:"nodes"` + }{CommitMessage: "corpus bulk " + b.IDPrefix} + for i := 1; i <= b.Count; i++ { + id := fmt.Sprintf("%s-%03d", b.IDPrefix, i) + plan.Nodes = append(plan.Nodes, node{Key: id, ID: id, Title: "bulk " + id, Type: "task", + Priority: b.Priority, Ephemeral: b.Ephemeral, Metadata: b.Metadata}) + } + raw, _ := json.MarshalIndent(plan, "", " ") + return string(raw) +} + +// reported is every outcome of every part this process has run, in the order +// the parts ran, for BEADS_CORPUS_REPORT. +var reported []outcome + +func summarize(t *testing.T, part, total int, outcomes []outcome) { + t.Helper() + counts := map[string]int{} + var lines []string + for _, o := range outcomes { + key := o.status + if strings.HasPrefix(key, "pending:") { + key = "pending" + } + counts[key]++ + lines = append(lines, fmt.Sprintf("%-26s %-48s req=%-3d %s", o.status, o.id, o.requests, firstLine(o.detail))) + } + t.Logf("corpus summary, part %d of %d (%d of %d shapes): %v\n%s", part, corpusParts, len(outcomes), total, counts, strings.Join(lines, "\n")) + reported = append(reported, outcomes...) + if path := os.Getenv("BEADS_CORPUS_REPORT"); path != "" { + type row struct { + ID string `json:"id"` + Status string `json:"status"` + Requests int64 `json:"requests"` + Detail string `json:"detail,omitempty"` + } + var out []row + for _, o := range reported { + out = append(out, row{o.id, o.status, o.requests, o.detail}) + } + raw, _ := json.MarshalIndent(out, "", " ") + if err := os.WriteFile(path, raw, 0o600); err != nil { + t.Errorf("write BEADS_CORPUS_REPORT: %v", err) + } + } +} + +func firstLine(s string) string { + s = strings.TrimSpace(s) + if i := strings.IndexByte(s, '\n'); i >= 0 { + s = s[:i] + } + return clip(s, 160) +} diff --git a/backend/http/corpus/gate_check_served_test.go b/backend/http/corpus/gate_check_served_test.go new file mode 100644 index 000000000..60d9f82c0 --- /dev/null +++ b/backend/http/corpus/gate_check_served_test.go @@ -0,0 +1,355 @@ +//go:build cgo + +package corpus_test + +import ( + "context" + "encoding/json" + "net/http" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/steveyegge/beads/internal/httpapi" + "github.com/steveyegge/beads/internal/storage/embeddeddolt" + "github.com/steveyegge/beads/internal/types" +) + +// gateCheckRequestLog records every request the reference proxy forwards. +type gateCheckRequestLog struct { + mu sync.Mutex + seen []string + next http.Handler +} + +func (l *gateCheckRequestLog) ServeHTTP(w http.ResponseWriter, r *http.Request) { + l.mu.Lock() + l.seen = append(l.seen, r.Method+" "+r.URL.Path) + l.mu.Unlock() + l.next.ServeHTTP(w, r) +} + +func (l *gateCheckRequestLog) take() []string { + l.mu.Lock() + defer l.mu.Unlock() + out := l.seen + l.seen = nil + return out +} + +func gateCheckWrites(reqs []string) []string { + var writes []string + for _, r := range reqs { + if !strings.HasPrefix(r, http.MethodGet+" ") { + writes = append(writes, r) + } + } + return writes +} + +// TestServedGateCheckOverAwaitTypedGates runs `bd gate check` over HTTP, through +// the reference proxy, against REAL await-typed gates, on a server that +// advertises neither gate token (issues.create.gates, issues.update.gates; the +// profile is masked here, so this holds whatever reference_server.json +// advertises). No create through it carries await_*: the gates are seeded +// straight into the served store before it listens, and every outcome is read +// back from that store: +// +// - --dry-run writes nothing; +// - an expired timer closes, a pending one stays open; +// - a bead gate whose target is open records its sighting (issues.update), +// and one whose target is closed closes; +// - a merged gh:pr gate closes, a closed one escalates and stays open; +// - a gh:run gate with a workflow-name hint discovers its run but cannot +// persist await_id through a server without issues.update.gates: the +// client refuses the patch before the dial, that gate's error names the +// missing token and the server, not a Go method, and await_id is +// untouched; +// - a persisted proto's gates are templates: listed, but no sweep evaluates +// or writes them, and they take no row of --limit (they sort first here). +// +// The corpus.yaml shapes prove the listing only (their gates have no +// await_type); this is the test that proves what the sweep does to the gates. +func TestServedGateCheckOverAwaitTypedGates(t *testing.T) { + skipUnlessEmbeddedDolt(t) + bin := buildBD(t) + ctx := context.Background() + + store, err := embeddeddolt.Open(ctx, t.TempDir(), corpusDatabase, "main") + if err != nil { + t.Fatalf("open the served store: %v", err) + } + t.Cleanup(func() { _ = store.Close() }) + if err := store.SetConfig(ctx, "issue_prefix", corpusPrefix); err != nil { + t.Fatalf("set the issue prefix: %v", err) + } + // The templates keep P0 and every other row gets P2, so the store's default + // order puts the template gates ahead of every live one. + seed := func(i *types.Issue) { + t.Helper() + i.Status = types.StatusOpen + i.Title = i.ID + if !i.IsTemplate { + i.Priority = 2 + } + if err := store.CreateIssue(ctx, i, "seed"); err != nil { + t.Fatalf("seed %s: %v", i.ID, err) + } + } + seed(&types.Issue{ID: "e2e-tgt-open", IssueType: "task"}) + seed(&types.Issue{ID: "e2e-tgt-closed", IssueType: "task"}) + if err := store.CloseIssue(ctx, "e2e-tgt-closed", "done", "seed", ""); err != nil { + t.Fatalf("close e2e-tgt-closed: %v", err) + } + seed(&types.Issue{ID: "e2e-g-timer", IssueType: "gate", AwaitType: "timer", Timeout: time.Millisecond}) + seed(&types.Issue{ID: "e2e-g-timer-pending", IssueType: "gate", AwaitType: "timer", Timeout: 100 * time.Hour}) + seed(&types.Issue{ID: "e2e-g-bead-open", IssueType: "gate", AwaitType: "bead", AwaitID: "e2e-tgt-open"}) + seed(&types.Issue{ID: "e2e-g-bead-closed", IssueType: "gate", AwaitType: "bead", AwaitID: "e2e-tgt-closed"}) + seed(&types.Issue{ID: "e2e-g-pr-merged", IssueType: "gate", AwaitType: "gh:pr", AwaitID: "11"}) + seed(&types.Issue{ID: "e2e-g-pr-closed", IssueType: "gate", AwaitType: "gh:pr", AwaitID: "12"}) + seed(&types.Issue{ID: "e2e-g-run-hint", IssueType: "gate", AwaitType: "gh:run", AwaitID: "ci-wf"}) + seed(&types.Issue{ID: "e2e-tpl-timer", IssueType: "gate", AwaitType: "timer", Timeout: time.Millisecond, IsTemplate: true}) + seed(&types.Issue{ID: "e2e-tpl-bead", IssueType: "gate", AwaitType: "bead", AwaitID: "e2e-tgt-open", IsTemplate: true}) + seed(&types.Issue{ID: "e2e-tpl-run", IssueType: "gate", AwaitType: "gh:run", AwaitID: "ci-wf", IsTemplate: true}) + + tokenFile := filepath.Join(t.TempDir(), "tokens") + if err := os.WriteFile(tokenFile, []byte(corpusToken+"\n"), 0o600); err != nil { + t.Fatalf("write the token file: %v", err) + } + auth, err := httpapi.NewTokenFileAuth(tokenFile) + if err != nil { + t.Fatalf("load the token file: %v", err) + } + cfg := corpusServeConfig(t, store) + cfg.AllowNonLoopback = true + cfg.Auth = auth + srv, err := httpapi.Listen(cfg) + if err != nil { + t.Fatalf("bind the in-process server: %v", err) + } + serveCtx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { defer close(done); _ = srv.Serve(serveCtx) }() + t.Cleanup(func() { + cancel() + select { + case <-done: + case <-time.After(30 * time.Second): + t.Error("the in-process server did not shut down") + } + }) + + // The gh:run case pins a server that cannot take an await_id patch, so the + // profile is held without issues.update.gates whatever + // reference_server.json advertises: upgrading the reference profile must + // not turn this case into a different test. + profile := loadReferenceProfile(t) + profile.Capabilities = slices.DeleteFunc(profile.Capabilities, func(c string) bool { return c == "issues.update.gates" }) + proxy := newReferenceProxy(t, profile, srv.Addr()) + reqs := &gateCheckRequestLog{next: proxy} + proxyAddr := startProxy(t, reqs) + + // gh and gt are fakes on PATH: gh answers the run discovery and the two PR + // states, gt records each escalation. + binDir := t.TempDir() + gh := `#!/bin/sh +case "$1 $2" in +"run list") echo '[{"databaseId":4242,"name":"ci-wf","status":"completed","conclusion":"success","createdAt":"2026-10-15T00:00:00Z","workflowName":"ci-wf"}]' ;; +"run view") echo '{"status":"completed","conclusion":"success","name":"ci-wf"}' ;; +"pr view") if [ "$3" = "11" ]; then echo '{"state":"MERGED","title":"m"}'; else echo '{"state":"CLOSED","title":"c"}'; fi ;; +*) echo "unexpected gh $*" >&2; exit 3 ;; +esac +` + if err := os.WriteFile(filepath.Join(binDir, "gh"), []byte(gh), 0o755); err != nil { + t.Fatalf("write fake gh: %v", err) + } + if err := os.WriteFile(filepath.Join(binDir, "gt"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil { + t.Fatalf("write fake gt: %v", err) + } + + dir := t.TempDir() + env := []string{ + "BEADS_HTTP_TOKEN=" + proxyAddr + "=" + corpusToken, + "BEADS_ACTOR=worker", + "BD_BACKUP_ENABLED=false", + "BD_EXPORT_AUTO=false", + "PATH=" + binDir + string(os.PathListSeparator) + os.Getenv("PATH"), + } + if r := runBD(t, bin, dir, env, "", "connect", "http://"+proxyAddr, "--expect-project-id", corpusProjectID, "--json"); r.code != 0 { + t.Fatalf("bd connect: %s", r) + } + reqs.take() + time.Sleep(50 * time.Millisecond) // the 1ms timer is expired by now + + get := func(id string) *types.Issue { + t.Helper() + issue, err := store.GetIssue(ctx, id) + if err != nil { + t.Fatalf("read %s back: %v", id, err) + } + return issue + } + wantStatus := func(id string, want types.Status) { + t.Helper() + if got := get(id).Status; got != want { + t.Errorf("%s status = %s, want %s", id, got, want) + } + } + seenOf := func(id string) string { + t.Helper() + var meta map[string]json.RawMessage + raw := get(id).Metadata + if len(raw) == 0 { + return "" + } + if err := json.Unmarshal(raw, &meta); err != nil { + t.Fatalf("%s metadata %s: %v", id, raw, err) + } + var seen string + _ = json.Unmarshal(meta["await_seen"], &seen) + return seen + } + allGates := []string{"e2e-g-timer", "e2e-g-timer-pending", "e2e-g-bead-open", "e2e-g-bead-closed", "e2e-g-pr-merged", "e2e-g-pr-closed", "e2e-g-run-hint"} + + t.Run("dry-run writes nothing", func(t *testing.T) { + r := runBD(t, bin, dir, env, "", "gate", "check", "--dry-run") + if r.code != 0 { + t.Fatalf("bd gate check --dry-run: %s", r) + } + if w := gateCheckWrites(reqs.take()); len(w) != 0 { + t.Fatalf("--dry-run sent writes %v\n%s", w, r) + } + for _, id := range allGates { + wantStatus(id, types.StatusOpen) + } + if seen := seenOf("e2e-g-bead-open"); seen != "" { + t.Errorf("--dry-run recorded a sighting %q", seen) + } + if got := get("e2e-g-run-hint").AwaitID; got != "ci-wf" { + t.Errorf("--dry-run persisted await_id %q", got) + } + }) + + t.Run("limit counts only live gates", func(t *testing.T) { + // bd gate list still lists templates, so its first three rows show the + // order the sweep's own listing would be cut from. + r := runBD(t, bin, dir, env, "", "gate", "list", "--limit", "3", "--json") + var listed []types.Issue + if start := strings.Index(r.stdout, "["); r.code != 0 || start < 0 || json.Unmarshal([]byte(r.stdout[start:]), &listed) != nil { + t.Fatalf("bd gate list --limit 3 --json: %s", r) + } + var ids []string + for _, g := range listed { + if strings.HasPrefix(g.ID, "e2e-tpl-") { + ids = append(ids, g.ID) + } + } + if len(listed) != 3 || len(ids) != 3 { + t.Fatalf("bd gate list --limit 3 listed %d gates, %d of them templates (%v), want the three template gates first", len(listed), len(ids), ids) + } + reqs.take() + + r = runBD(t, bin, dir, env, "", "gate", "check", "--dry-run", "--limit", "3") + if r.code != 0 { + t.Fatalf("bd gate check --dry-run --limit 3: %s", r) + } + if w := gateCheckWrites(reqs.take()); len(w) != 0 { + t.Fatalf("--dry-run sent writes %v\n%s", w, r) + } + if !strings.Contains(r.stdout, "Checked 3 gates") { + t.Errorf("--limit 3 behind three template gates must still check three live gates:\n%s", r) + } + if strings.Contains(r.stdout+r.stderr, "e2e-tpl-") { + t.Errorf("a template gate was checked:\n%s", r) + } + }) + + t.Run("timer sweep closes the expired timer", func(t *testing.T) { + r := runBD(t, bin, dir, env, "", "gate", "check", "--type=timer", "--escalate") + if r.code != 0 { + t.Fatalf("bd gate check --type=timer --escalate: %s", r) + } + reqs.take() + wantStatus("e2e-g-timer", types.StatusClosed) + wantStatus("e2e-g-timer-pending", types.StatusOpen) + wantStatus("e2e-tpl-timer", types.StatusOpen) + }) + + t.Run("bead sweep records the sighting and closes the done gate", func(t *testing.T) { + r := runBD(t, bin, dir, env, "", "gate", "check", "--type=bead") + if r.code != 0 { + t.Fatalf("bd gate check --type=bead: %s", r) + } + writes := gateCheckWrites(reqs.take()) + sighted := false + for _, w := range writes { + if strings.Contains(w, "e2e-g-bead-open") { + sighted = true + } + if strings.Contains(w, "e2e-tpl-bead") { + t.Errorf("the sweep wrote to the template gate: %s", w) + } + } + if !sighted { + t.Errorf("no write to e2e-g-bead-open reached the server; writes: %v\n%s", writes, r) + } + if seen := seenOf("e2e-g-bead-open"); seen != "e2e-tgt-open" { + t.Errorf("e2e-g-bead-open await_seen = %q, want e2e-tgt-open\n%s", seen, r) + } + if seen := seenOf("e2e-tpl-bead"); seen != "" { + t.Errorf("e2e-tpl-bead recorded a sighting %q; a template gate is never checked", seen) + } + wantStatus("e2e-g-bead-open", types.StatusOpen) + wantStatus("e2e-g-bead-closed", types.StatusClosed) + }) + + t.Run("gh:pr sweep closes the merged PR gate", func(t *testing.T) { + r := runBD(t, bin, dir, env, "", "gate", "check", "--type=gh:pr", "--escalate") + if r.code != 0 { + t.Fatalf("bd gate check --type=gh:pr --escalate: %s", r) + } + reqs.take() + wantStatus("e2e-g-pr-merged", types.StatusClosed) + wantStatus("e2e-g-pr-closed", types.StatusOpen) + if !strings.Contains(r.stdout, "e2e-g-pr-closed: ESCALATE") { + t.Errorf("closed PR gate was not escalated:\n%s", r) + } + }) + + t.Run("gh:run await_id persist refuses by the missing token", func(t *testing.T) { + r := runBD(t, bin, dir, env, "", "gate", "check", "--type=gh:run") + if r.code == 0 { + t.Fatalf("bd gate check --type=gh:run succeeded; the reference server does not advertise issues.update.gates: %s", r) + } + if w := gateCheckWrites(reqs.take()); len(w) != 0 { + t.Errorf("the refused await_id persist sent writes %v", w) + } + if !strings.Contains(r.stderr, "e2e-g-run-hint") || !strings.Contains(r.stderr, `does not advertise capability "issues.update.gates"`) { + t.Errorf("gh:run error does not name the gate and the missing issues.update.gates token:\n%s", r) + } + if !strings.Contains(r.stderr, "bd serve at http://"+proxyAddr) { + t.Errorf("gh:run error does not name the server it reached:\n%s", r) + } + if strings.Contains(r.stderr, "e2e-tpl-run") { + t.Errorf("the template gh:run gate was checked:\n%s", r) + } + // The capability refusal names the wire operation (updateIssue) that + // needs the token; the role and store methods stay out of it. + for _, leak := range []string{"UpdateIssue", "Lifecycle.Update"} { + if strings.Contains(r.stderr, leak) { + t.Errorf("gh:run error leaks %q:\n%s", leak, r) + } + } + if got := get("e2e-g-run-hint").AwaitID; got != "ci-wf" { + t.Errorf("e2e-g-run-hint await_id = %q, want ci-wf untouched", got) + } + wantStatus("e2e-g-run-hint", types.StatusOpen) + if got := get("e2e-tpl-run").AwaitID; got != "ci-wf" { + t.Errorf("e2e-tpl-run await_id = %q, want ci-wf untouched", got) + } + }) +} diff --git a/backend/http/corpus/harness_test.go b/backend/http/corpus/harness_test.go new file mode 100644 index 000000000..d2a2c4d02 --- /dev/null +++ b/backend/http/corpus/harness_test.go @@ -0,0 +1,333 @@ +//go:build cgo + +package corpus_test + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" + + "github.com/steveyegge/beads/internal/httpapi" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/storage/embeddeddolt" + "github.com/steveyegge/beads/internal/testutil/bazeltest" +) + +const ( + corpusProjectID = "proj-corpus-s23" + corpusDatabase = "corpus" + corpusPrefix = "e2e" + // corpusToken is the bearer the in-process server accepts. The reference + // deployment authenticates every request, so the suite does too. + // #nosec G101 -- a throwaway test credential for an httptest-scoped server. + corpusToken = "corpus-s23-test-token" + // bdTimeout bounds one bd subprocess so a hung shape fails rather than + // stalling the whole suite. + bdTimeout = 90 * time.Second +) + +// startCorpusServer binds the in-process server the way the reference +// deployment is bound: AllowNonLoopback with a bearer token file. The socket is +// still 127.0.0.1 (this suite never leaves the host), but every behavior the +// server keys off its bind mode — the loopback-only refusal of an unlimited +// read above all — is the non-loopback one, because that is decided by +// Config.AllowNonLoopback and not by the address. +func startCorpusServer(t *testing.T) string { + t.Helper() + beadsDir := t.TempDir() + ctx := context.Background() + store, err := embeddeddolt.Open(ctx, beadsDir, corpusDatabase, "main") + if err != nil { + t.Fatalf("open the served store: %v", err) + } + t.Cleanup(func() { _ = store.Close() }) + if err := store.SetConfig(ctx, "issue_prefix", corpusPrefix); err != nil { + t.Fatalf("set the issue prefix: %v", err) + } + + tokenFile := filepath.Join(t.TempDir(), "tokens") + if err := os.WriteFile(tokenFile, []byte(corpusToken+"\n"), 0o600); err != nil { + t.Fatalf("write the token file: %v", err) + } + auth, err := httpapi.NewTokenFileAuth(tokenFile) + if err != nil { + t.Fatalf("load the token file: %v", err) + } + + cfg := corpusServeConfig(t, store) + cfg.AllowNonLoopback = true + cfg.Auth = auth + srv, err := httpapi.Listen(cfg) + if err != nil { + t.Fatalf("bind the in-process server: %v", err) + } + serveCtx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { defer close(done); _ = srv.Serve(serveCtx) }() + t.Cleanup(func() { + cancel() + select { + case <-done: + case <-time.After(30 * time.Second): + t.Error("the in-process server did not shut down") + } + }) + return srv.Addr() +} + +// startProxy serves h on an ephemeral loopback port. +func startProxy(t *testing.T, h http.Handler) string { + t.Helper() + srv := &http.Server{Handler: h, ReadHeaderTimeout: 10 * time.Second} + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen for the reference proxy: %v", err) + } + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { _ = srv.Close() }) + return ln.Addr().String() +} + +// corpusServeConfig takes every role off the store, as bd serve does. It +// mirrors backend/http's e2eServeConfig (a sibling test package, so it cannot +// be imported). +func corpusServeConfig(t *testing.T, s storage.DoltStorage) httpapi.Config { + t.Helper() + cfg := httpapi.Config{ + Addr: "127.0.0.1:0", + Stdout: io.Discard, + Stderr: io.Discard, + Workspace: domain.ContextInfo{ProjectID: corpusProjectID, Database: corpusDatabase}, + } + var err error + must := func(name string) { + t.Helper() + if err != nil { + t.Fatalf("%s(): %v", name, err) + } + } + cfg.Reader, err = s.IssueReader() + must("IssueReader") + cfg.Claimer, err = s.IssueClaimer() + must("IssueClaimer") + cfg.ReadyClaimer, err = s.ReadyClaimer() + must("ReadyClaimer") + cfg.Releaser, err = s.Releaser() + must("Releaser") + cfg.Lifecycle, err = s.IssueLifecycle() + must("IssueLifecycle") + cfg.Settings, err = s.WorkspaceConfig() + must("WorkspaceConfig") + cfg.Stats, err = s.StatsReporter() + must("StatsReporter") + cfg.CycleDetector, err = s.CycleDetector() + must("CycleDetector") + cfg.EdgeReader, err = s.EdgeReader() + must("EdgeReader") + cfg.GraphCounter, err = s.GraphCounter() + must("GraphCounter") + cfg.BatchGetter, err = s.BatchGetter() + must("BatchGetter") + cfg.LeaseReclaimer, err = s.LeaseReclaimer() + must("LeaseReclaimer") + cfg.Heartbeater, err = s.Heartbeater() + must("Heartbeater") + cfg.BlockedLister, err = s.BlockedLister() + must("BlockedLister") + cfg.Relations, err = s.IssueRelations() + must("IssueRelations") + cfg.Commenter, err = s.Commenter() + must("Commenter") + cfg.BlockingAnnotator, err = s.BlockingAnnotator() + must("BlockingAnnotator") + cfg.TreeWalker, err = s.TreeWalker() + must("TreeWalker") + cfg.ReadyCounter, err = s.ReadyCounter() + must("ReadyCounter") + cfg.Counter, err = s.Counter() + must("Counter") + cfg.Querier, err = s.Querier() + must("Querier") + cfg.Sweeper, err = s.Sweeper() + must("Sweeper") + cfg.Deleter, err = s.Deleter() + must("Deleter") + cfg.BatchCreator, err = s.BatchCreator() + must("BatchCreator") + cfg.BatchCloser, err = s.BatchCloser() + must("BatchCloser") + cfg.DependencyEditor, err = s.DependencyEditor() + must("DependencyEditor") + cfg.MetadataCAS, err = s.MetadataCAS() + must("MetadataCAS") + cfg.BatchApplier, err = s.BatchApplier() + must("BatchApplier") + cfg.Memories, err = s.Memories() + must("Memories") + return cfg +} + +// This file is the corpus tier's cgo half; see TestCorpusTierIsLinkedWhenRequired. +func init() { corpusTierLinked = true } + +// skipUnlessEmbeddedDolt is the served tier's gate, as in backend/http. +func skipUnlessEmbeddedDolt(t *testing.T) { + t.Helper() + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") == "1" { + return + } + if os.Getenv("BEADS_HTTP_TEST_REQUIRED") == "1" { + t.Fatal("BEADS_HTTP_TEST_REQUIRED=1 but BEADS_TEST_EMBEDDED_DOLT is not 1; the http corpus tier is not enforced") + } + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run the http command-corpus tier") +} + +type bdResult struct { + stdout, stderr string + code int +} + +func (r bdResult) String() string { + return fmt.Sprintf("exit=%d\nstdout:\n%s\nstderr:\n%s", r.code, clip(r.stdout, 4000), clip(r.stderr, 4000)) +} + +func clip(s string, n int) string { + if len(s) <= n { + return s + } + return s[:n] + fmt.Sprintf("\n... (%d more bytes)", len(s)-n) +} + +// runBD runs the built bd binary in dir with a hermetic environment. +func runBD(t *testing.T, bin, dir string, env []string, stdin string, args ...string) bdResult { + t.Helper() + r, err := execBD(context.Background(), bin, dir, env, stdin, args...) + if err != nil { + t.Fatal(err) + } + return r +} + +// execBD is runBD without the testing.T: it returns an error, rather than +// failing a test, when bd could not be run at all or ctx was cancelled, so it +// is safe on a goroutine that is not the test's. A bd that runs and fails is +// a bdResult with its exit code, as in runBD. +func execBD(ctx context.Context, bin, dir string, env []string, stdin string, args ...string) (bdResult, error) { + if err := ctx.Err(); err != nil { + return bdResult{}, err + } + ctx, cancel := context.WithTimeout(ctx, bdTimeout) + defer cancel() + cmd := exec.CommandContext(ctx, bin, args...) + cmd.Dir = dir + cmd.Env = minimalBDEnv(dir, env...) + if stdin != "" { + cmd.Stdin = strings.NewReader(stdin) + } + var o, e strings.Builder + cmd.Stdout, cmd.Stderr = &o, &e + err := cmd.Run() + code := 0 + if err != nil { + var ee *exec.ExitError + switch { + case errors.Is(ctx.Err(), context.DeadlineExceeded): + code = -1 + e.WriteString(fmt.Sprintf("\n[corpus harness] bd timed out after %s", bdTimeout)) + case ctx.Err() != nil: + return bdResult{}, fmt.Errorf("bd %s: %w", strings.Join(args, " "), ctx.Err()) + case errors.As(err, &ee): + code = ee.ExitCode() + default: + return bdResult{}, fmt.Errorf("running bd %s: %v", strings.Join(args, " "), err) + } + } + return bdResult{stdout: o.String(), stderr: e.String(), code: code}, nil +} + +// minimalBDEnv is backend/http's hermetic bd environment: PATH and the few +// variables a Go binary needs, HOME repointed at dir, nothing BEADS_* carried +// over from the invoking shell. extra is applied last. +func minimalBDEnv(dir string, extra ...string) []string { + env := []string{ + "HOME=" + dir, + "BD_DISABLE_METRICS=1", + "BD_DISABLE_EVENT_FLUSH=1", + } + for _, key := range []string{"PATH", "TMPDIR", "SYSTEMROOT", "WINDIR"} { + if v, ok := os.LookupEnv(key); ok { + env = append(env, key+"="+v) + } + } + return append(env, extra...) +} + +var ( + buildBDOnce sync.Once + bdBinPath string + bdBuildErr error + bdBinOwnBuild bool +) + +// buildBD builds bd from this tree once per test process (or takes Bazel's +// prebuilt binary). TestMain deletes the build. +func buildBD(t *testing.T) string { + t.Helper() + buildBDOnce.Do(func() { + if bazeltest.IsBazel() { + bdBinPath, bdBuildErr = bazeltest.PrebuiltBD() + return + } + if prebuilt, err := bazeltest.PrebuiltBD(); err != nil || prebuilt != "" { + bdBinPath, bdBuildErr = prebuilt, err + return + } + dir, err := os.MkdirTemp(os.Getenv("TMPDIR"), "bd-corpus") + if err != nil { + bdBuildErr = fmt.Errorf("mkdir temp for bd binary: %w", err) + return + } + bin := filepath.Join(dir, "bd-corpus") + cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", bin, "./cmd/bd") + cmd.Dir = repoRoot() + if out, err := cmd.CombinedOutput(); err != nil { + bdBuildErr = fmt.Errorf("build bd: %w\n%s", err, out) + _ = os.RemoveAll(dir) + return + } + bdBinPath = bin + bdBinOwnBuild = true + }) + if bdBuildErr != nil { + t.Fatal(bdBuildErr) + } + if bdBinPath == "" { + t.Fatal("no bd binary: Bazel did not provide one") + } + return bdBinPath +} + +func TestMain(m *testing.M) { + code := m.Run() + if bdBinOwnBuild && bdBinPath != "" { + _ = os.RemoveAll(filepath.Dir(bdBinPath)) + } + os.Exit(code) +} + +func repoRoot() string { + _, file, _, _ := runtime.Caller(0) // /backend/http/corpus/harness_test.go + return filepath.Dir(filepath.Dir(filepath.Dir(filepath.Dir(file)))) +} diff --git a/backend/http/corpus/reference_proxy_test.go b/backend/http/corpus/reference_proxy_test.go new file mode 100644 index 000000000..0142b1ad4 --- /dev/null +++ b/backend/http/corpus/reference_proxy_test.go @@ -0,0 +1,279 @@ +//go:build cgo + +package corpus_test + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "maps" + "net/http" + "net/http/httputil" + "net/url" + "os" + "regexp" + "slices" + "sort" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/steveyegge/beads/internal/httpapi" + "github.com/steveyegge/beads/internal/httpapi/apigen" +) + +// referenceProfile is testdata/reference_server.json: the wire surface of the +// deployed server the corpus must work against. See README.md. +type referenceProfile struct { + Capabilities []string `json:"capabilities"` + ContextMembers []string `json:"context_members"` + Operations []referenceOperation `json:"operations"` +} + +type referenceOperation struct { + Method string `json:"method"` + Path string `json:"path"` + OperationID string `json:"operation_id"` + Query []string `json:"query"` + Body []string `json:"body"` + + pattern *regexp.Regexp + query map[string]bool + body map[string]bool +} + +func loadReferenceProfile(t *testing.T) *referenceProfile { + t.Helper() + raw, err := os.ReadFile("testdata/reference_server.json") + if err != nil { + t.Fatalf("read the reference server profile: %v", err) + } + var p referenceProfile + if err := json.Unmarshal(raw, &p); err != nil { + t.Fatalf("parse testdata/reference_server.json: %v", err) + } + if len(p.Capabilities) == 0 || len(p.Operations) == 0 || len(p.ContextMembers) == 0 { + t.Fatal("testdata/reference_server.json is missing capabilities, operations or context_members") + } + for i := range p.Operations { + op := &p.Operations[i] + pattern, err := templatePattern(op.Path) + if err != nil { + t.Fatalf("testdata/reference_server.json: operation %s path %q: %v", op.OperationID, op.Path, err) + } + op.pattern = pattern + op.query = setOf(op.Query) + op.body = setOf(op.Body) + } + return &p +} + +// templatePattern turns an OpenAPI path template into an anchored regexp. A +// path parameter never spans a "/" or a ":" (AIP-136 custom methods hang off +// the last segment as {id}:verb, and no issue id, config key or memory key +// carries a raw colon), so /issues/{id} does not swallow /issues/{id}:claim. +// A "{" with no "}" is an error: the profile is edited by hand, and without the +// check the loop would never advance past it. +func templatePattern(tmpl string) (*regexp.Regexp, error) { + var b strings.Builder + b.WriteString("^") + for { + open := strings.IndexByte(tmpl, '{') + if open < 0 { + b.WriteString(regexp.QuoteMeta(tmpl)) + break + } + closeAt := strings.IndexByte(tmpl[open:], '}') + if closeAt < 0 { + return nil, fmt.Errorf("unclosed { in %q", tmpl[open:]) + } + b.WriteString(regexp.QuoteMeta(tmpl[:open])) + b.WriteString(`[^/:]+`) + tmpl = tmpl[open+closeAt+1:] + } + b.WriteString("$") + return regexp.Compile(b.String()) +} + +func setOf(xs []string) map[string]bool { + m := make(map[string]bool, len(xs)) + for _, x := range xs { + m[x] = true + } + return m +} + +// referenceProxy fronts the in-process server and makes it answer the way the +// reference server answers, at the wire level, for everything this suite can +// see from a client: +// +// - GET /v0/beads/context publishes only the reference ContextResponse +// members (so no wire_revision: the reference server predates it) and +// exactly the reference capability set, whatever this build advertises; +// - a request for an operation the reference document does not publish gets +// the server's own unrouted 404 problem; +// - a query parameter or top-level JSON request member the reference +// operation does not declare gets the server's own 400 unknown_parameter +// problem naming it — which is how the real reference server answers, +// since its decoder is strict. +// +// Responses are otherwise passed through untouched. That is deliberately +// generous in one direction (a response member the reference server would not +// send still reaches the client) and is the residual fidelity gap README.md +// records. +type referenceProxy struct { + profile *referenceProfile + upstream *url.URL + rp *httputil.ReverseProxy + + requests atomic.Int64 + + mu sync.Mutex + refused []string // "METHOD path: why", for the per-shape log +} + +func newReferenceProxy(t *testing.T, profile *referenceProfile, upstreamAddr string) *referenceProxy { + t.Helper() + u, err := url.Parse("http://" + upstreamAddr) + if err != nil { + t.Fatalf("parse upstream address: %v", err) + } + p := &referenceProxy{profile: profile, upstream: u} + p.rp = &httputil.ReverseProxy{ + Rewrite: func(r *httputil.ProxyRequest) { + r.SetURL(u) // also rewrites Host, so the server's Host gate sees its own bind + }, + FlushInterval: -1, // events:watch streams + } + return p +} + +func (p *referenceProxy) takeRefusals() []string { + p.mu.Lock() + defer p.mu.Unlock() + out := p.refused + p.refused = nil + return out +} + +func (p *referenceProxy) noteRefusal(r *http.Request, why string) { + p.mu.Lock() + defer p.mu.Unlock() + p.refused = append(p.refused, fmt.Sprintf("%s %s: %s", r.Method, r.URL.Path, why)) +} + +func (p *referenceProxy) match(r *http.Request) *referenceOperation { + path := r.URL.EscapedPath() + var best *referenceOperation + for i := range p.profile.Operations { + op := &p.profile.Operations[i] + if op.Method != r.Method || !op.pattern.MatchString(path) { + continue + } + // Prefer the most literal template when two match (none do today). + if best == nil || len(op.Path) > len(best.Path) { + best = op + } + } + return best +} + +func (p *referenceProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { + p.requests.Add(1) + if r.Method == http.MethodGet && r.URL.Path == "/v0/beads/context" { + p.serveContext(w, r) + return + } + op := p.match(r) + if op == nil { + p.noteRefusal(r, "operation not published by the reference server") + detail := "no such route on this server" + httpapi.Write(w, httpapi.Result{Problem: apigen.Problem{ + Status: http.StatusNotFound, + Title: http.StatusText(http.StatusNotFound), + Code: string(httpapi.CodeNotFound), + Detail: &detail, + }}) + return + } + if offender := firstUnknown(slices.Collect(maps.Keys(r.URL.Query())), op.query); offender != "" { + p.noteRefusal(r, "query parameter "+offender+" unknown to "+op.OperationID) + httpapi.Write(w, httpapi.InvalidArgument(offender, httpapi.ReasonUnknownParameter, + "unknown query parameter "+offender)) + return + } + if r.Body != nil && r.Body != http.NoBody { + raw, err := io.ReadAll(r.Body) + _ = r.Body.Close() + if err != nil { + http.Error(w, "reference proxy: read body: "+err.Error(), http.StatusBadGateway) + return + } + r.Body = io.NopCloser(bytes.NewReader(raw)) + r.ContentLength = int64(len(raw)) + var members map[string]json.RawMessage + if len(bytes.TrimSpace(raw)) > 0 && json.Unmarshal(raw, &members) == nil { + if offender := firstUnknown(slices.Collect(maps.Keys(members)), op.body); offender != "" { + p.noteRefusal(r, "request member "+offender+" unknown to "+op.OperationID) + httpapi.Write(w, httpapi.InvalidArgument(offender, httpapi.ReasonUnknownParameter, + "json: unknown field \""+offender+"\"")) + return + } + } + } + p.rp.ServeHTTP(w, r) +} + +// firstUnknown names the smallest key not in known, the same deterministic +// choice the server makes, or "" when every key is known. +func firstUnknown(keys []string, known map[string]bool) string { + sort.Strings(keys) + for _, k := range keys { + if !known[k] { + return k + } + } + return "" +} + +func (p *referenceProxy) serveContext(w http.ResponseWriter, r *http.Request) { + out := r.Clone(r.Context()) + out.URL.Scheme, out.URL.Host, out.Host = p.upstream.Scheme, p.upstream.Host, p.upstream.Host + out.RequestURI = "" + resp, err := http.DefaultTransport.RoundTrip(out) + if err != nil { + http.Error(w, "reference proxy: "+err.Error(), http.StatusBadGateway) + return + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + http.Error(w, "reference proxy: "+err.Error(), http.StatusBadGateway) + return + } + if resp.StatusCode != http.StatusOK { + maps.Copy(w.Header(), resp.Header) + w.WriteHeader(resp.StatusCode) + _, _ = w.Write(raw) + return + } + var body map[string]json.RawMessage + if err := json.Unmarshal(raw, &body); err != nil { + http.Error(w, "reference proxy: decode context: "+err.Error(), http.StatusBadGateway) + return + } + keep := setOf(p.profile.ContextMembers) + for k := range body { + if !keep[k] { + delete(body, k) + } + } + caps, _ := json.Marshal(p.profile.Capabilities) + body["capabilities"] = caps + masked, _ := json.Marshal(body) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(masked) +} diff --git a/backend/http/corpus/required_corpus_tier_test.go b/backend/http/corpus/required_corpus_tier_test.go new file mode 100644 index 000000000..055afeb79 --- /dev/null +++ b/backend/http/corpus/required_corpus_tier_test.go @@ -0,0 +1,23 @@ +package corpus_test + +import ( + "os" + "testing" +) + +// corpusTierLinked reports whether this test binary links the corpus tier. +// harness_test.go, which builds only under cgo like every other file in this +// package, sets it from its init. +var corpusTierLinked bool + +// TestCorpusTierIsLinkedWhenRequired is the one corpus check that builds +// without cgo. skipUnlessEmbeddedDolt turns a missing BEADS_TEST_EMBEDDED_DOLT +// into a failure under BEADS_HTTP_TEST_REQUIRED=1, but it lives in a cgo file: +// with cgo off the go tool drops every other file in this package, so no +// corpus test exists to fail, and a required run would pass having run nothing. +func TestCorpusTierIsLinkedWhenRequired(t *testing.T) { + if os.Getenv("BEADS_HTTP_TEST_REQUIRED") == "1" && !corpusTierLinked { + t.Fatal("BEADS_HTTP_TEST_REQUIRED=1 but this test binary was built without cgo, which drops " + + "the http command corpus (every other file in this package); build it with CGO_ENABLED=1") + } +} diff --git a/backend/http/corpus/served_pinned_shards.txt b/backend/http/corpus/served_pinned_shards.txt new file mode 100644 index 000000000..6fc0f44d9 --- /dev/null +++ b/backend/http/corpus/served_pinned_shards.txt @@ -0,0 +1,12 @@ +# Pinned shards for tools/bazel/go_test_pinned_shard.sh. Not pin_shards.py's: +# each corpus part (corpus_test.go's corpusParts; TestServedCorpusPart1..N) +# runs alone in the shard of its number, on its own server and seed, and the +# binary's round-robin runs the package's other (engine-free) tests in the +# one shard left over. Change corpusParts, this file and the target's +# shard_count together (scripts TestCorpusPartsArePinnedOnePerShard). +# +# +1 TestServedCorpusPart1 +2 TestServedCorpusPart2 +3 TestServedCorpusPart3 +4 TestServedCorpusPart4 diff --git a/backend/http/corpus/testdata/allowlist.yaml b/backend/http/corpus/testdata/allowlist.yaml new file mode 100644 index 000000000..090577cc9 --- /dev/null +++ b/backend/http/corpus/testdata/allowlist.yaml @@ -0,0 +1,29 @@ +# Shapes that are EXPECTED to be refused on a served workspace, permanently. +# The served run must fail and its output must match `refusal`; if it ever +# succeeds, the entry is stale and the suite fails until it is removed. The +# embedded run is still held to the shape's expect_exit, which an allowlisted +# shape must state, and to its expect_stderr: a shape that stops doing what it +# says on the embedded backend fails as a corpus bug, not as allowed. +# A gap some slice will close is NOT listed here: it is a `pending` mark on the +# shape in corpus.yaml instead. + +- id: gc-sql-ready-projection + reason: >- + bd sql needs a Dolt sql-server workspace: the embedded backend refuses it + too (the shape's expect_exit and expect_stderr pin that), and an http + workspace refuses it with the same "embedded mode" text. gc must not issue + it against a remote workspace (DESIGN B3 #10 and B6: gc reads the ready + projection through roles there). + refusal: "'bd sql' is not yet supported" +- id: gc-sql-release-fallback + reason: >- + bd sql needs a Dolt sql-server workspace and the embedded backend refuses + it too; gc's ReleaseIfCurrent fallback must take the conditional update + path on a remote workspace (DESIGN B3 #10). + refusal: "'bd sql' is not yet supported" +- id: mc-meta-set + reason: >- + `bd meta set` is not an OSS bd command (pack scripts written against an + older pinned CLI); it fails on the embedded backend too. The packs should + use `bd update --set-metadata`, which the corpus covers. + refusal: 'unknown command "meta"' diff --git a/backend/http/corpus/testdata/corpus.yaml b/backend/http/corpus/testdata/corpus.yaml new file mode 100644 index 000000000..925d1db64 --- /dev/null +++ b/backend/http/corpus/testdata/corpus.yaml @@ -0,0 +1,882 @@ +# Served command corpus (slice S23): every distinct bd command shape the +# orchestrator (gc) and its packs/formulas issue against a work store. +# +# Sources: +# gc: gascity origin/main internal/beads/bdstore*.go, internal/config/workquery.go, +# cmd/gc (BdStore subprocess shapes, work_query/scale_check/on_boot/on_death +# shell, hook claim, agent-script actions, doctor/preflight probes). +# mc: pack, formula, prompt and script invocations counted across the +# maintainer packs (flag sets, not values; values here are representative). +# +# Each shape runs on a served workspace (bd connect to an in-process bd serve, +# non-loopback bind mode, bearer auth, masked to testdata/reference_server.json) +# and on an embedded workspace, with BEADS_ACTOR=worker and CLAUDE_SESSION_ID set +# on both. See README.md for the fields. Reads come first; writes after them +# each own their target ids (e2e-t-*), so write order never changes a read. +# The shapes are dealt round robin, in this order, across the suite's parts, +# and each part seeds its own workspaces: a shape may rely on the seed and its +# own setup, never on another shape having run. +# +# pending: {slice, reason} marks a known failure. The shape still runs; when it +# passes the subtest FAILS until the mark is removed. That is how a slice proves +# itself. Permanent refusals live in allowlist.yaml instead. + +files: + - name: seed-core.json + content: | + {"commit_message": "corpus seed", "nodes": [ + {"key": "r1", "id": "e2e-r1", "title": "Routed open task", "type": "task", "priority": 1, "labels": ["lane:a"], "metadata": {"gc.routed_to": "pool-a"}}, + {"key": "r2", "id": "e2e-r2", "title": "Held routed task", "type": "task", "labels": ["hold:mayor"], "metadata": {"gc.routed_to": "pool-a"}}, + {"key": "r3", "id": "e2e-r3", "title": "Routed epic", "type": "epic", "metadata": {"gc.routed_to": "pool-a"}}, + {"key": "wf1", "id": "e2e-wf1", "title": "Workflow root", "type": "task", "metadata": {"gc.run_target": "pool-a", "gc.kind": "workflow"}}, + {"key": "a1", "id": "e2e-a1", "title": "Alice bug", "type": "bug", "assignee": "alice"}, + {"key": "ip1", "id": "e2e-ip1", "title": "Worker in progress", "type": "task", "priority": 0, "assignee": "worker", "metadata": {"gc.routed_to": "pool-a"}}, + {"key": "wr", "id": "e2e-wr", "title": "Worker ready task", "type": "task", "assignee": "worker"}, + {"key": "ipna", "id": "e2e-ipna", "title": "Orphaned in progress", "type": "task", "metadata": {"gc.routed_to": "pool-a"}}, + {"key": "ipnb", "id": "e2e-ipnb", "title": "Orphaned workflow", "type": "task", "metadata": {"gc.run_target": "pool-a", "gc.kind": "workflow"}}, + {"key": "blk", "id": "e2e-blk", "title": "Blocked by r1", "type": "task", "deps": [{"target": "r1"}]}, + {"key": "done", "id": "e2e-done", "title": "Closed task", "type": "task"}, + {"key": "ext", "id": "e2e-ext", "title": "GitHub source", "type": "task", "external_ref": "gh-123", "metadata": {"gc.kind": "github_source", "gc.github.kind": "issue", "gc.github.repo": "o/r"}}, + {"key": "ep", "id": "e2e-ep", "title": "Epic", "type": "epic"}, + {"key": "ep.1", "id": "e2e-ep.1", "title": "Epic child one", "type": "task", "parent_key": "ep"}, + {"key": "ep.2", "id": "e2e-ep.2", "title": "Epic child two", "type": "task", "parent_key": "ep"}, + {"key": "mol", "id": "e2e-mol", "title": "Molecule root", "type": "epic"}, + {"key": "mol.1", "id": "e2e-mol.1", "title": "step one", "type": "task", "assignee": "worker", "parent_key": "mol"}, + {"key": "mol.2", "id": "e2e-mol.2", "title": "step two", "type": "task", "parent_key": "mol", "deps": [{"target": "mol.1"}], "metadata": {"gc.root_bead_id": "e2e-mol", "gc.routed_to": "pool-a"}}, + {"key": "mol.3", "id": "e2e-mol.3", "title": "step three", "type": "task", "parent_key": "mol"}, + {"key": "mac", "id": "e2e-mac", "title": "Auto-close molecule", "type": "epic"}, + {"key": "mac.1", "id": "e2e-mac.1", "title": "done step", "type": "task", "parent_key": "mac"}, + {"key": "mac.2", "id": "e2e-mac.2", "title": "last step", "type": "task", "assignee": "worker", "parent_key": "mac"}, + {"key": "wisp-1", "id": "e2e-wisp-1", "title": "Wisp wisp-1", "type": "task", "ephemeral": true, "metadata": {"gc.routed_to": "pool-a"}, "labels": ["lane:w"]}, + {"key": "wisp-2", "id": "e2e-wisp-2", "title": "Wisp wisp-2", "type": "task", "ephemeral": true, "assignee": "worker", "labels": ["lane:w"]}, + {"key": "wisp-wr", "id": "e2e-wisp-wr", "title": "Wisp worker ready", "type": "task", "ephemeral": true, "priority": 1, "assignee": "worker"}, + {"key": "wisp-c", "id": "e2e-wisp-c", "title": "Wisp wisp-c", "type": "task", "ephemeral": true}, + {"key": "wisp-p", "id": "e2e-wisp-p", "title": "Wisp wisp-p", "type": "task", "ephemeral": true}, + {"key": "wisp-m", "id": "e2e-wisp-m", "title": "Wisp molecule", "type": "epic", "ephemeral": true}, + {"key": "wisp-m.1", "id": "e2e-wisp-m.1", "title": "wisp step", "type": "task", "ephemeral": true, "parent_key": "wisp-m"}, + {"key": "gate-o", "id": "e2e-gate-o", "title": "Open gate", "type": "gate"}, + {"key": "gate-c", "id": "e2e-gate-c", "title": "Closed gate", "type": "gate"}, + {"key": "wisp-gate", "id": "e2e-wisp-gate", "title": "Wisp gate", "type": "gate", "ephemeral": true}, + {"key": "t-upd", "id": "e2e-t-upd", "title": "target upd", "type": "task", "labels": ["lane:z"]}, + {"key": "t-upd2", "id": "e2e-t-upd2", "title": "target upd2", "type": "task"}, + {"key": "t-m1", "id": "e2e-t-m1", "title": "target m1", "type": "task"}, + {"key": "t-m2", "id": "e2e-t-m2", "title": "target m2", "type": "task"}, + {"key": "t-claim", "id": "e2e-t-claim", "title": "target claim", "type": "task"}, + {"key": "t-claim2", "id": "e2e-t-claim2", "title": "target claim2", "type": "task"}, + {"key": "t-rev", "id": "e2e-t-rev", "title": "target rev", "type": "task"}, + {"key": "t-rev2", "id": "e2e-t-rev2", "title": "target rev2", "type": "task"}, + {"key": "t-sling", "id": "e2e-t-sling", "title": "target sling", "type": "task"}, + {"key": "t-as", "id": "e2e-t-as", "title": "target as", "type": "task"}, + {"key": "t-ms", "id": "e2e-t-ms", "title": "target ms", "type": "task"}, + {"key": "t-msc", "id": "e2e-t-msc", "title": "target msc", "type": "task"}, + {"key": "t-um", "id": "e2e-t-um", "title": "target um", "type": "task", "metadata": {"k": "v"}}, + {"key": "t-notes", "id": "e2e-t-notes", "title": "target notes", "type": "task"}, + {"key": "t-er", "id": "e2e-t-er", "title": "target er", "type": "task"}, + {"key": "t-md", "id": "e2e-t-md", "title": "target md", "type": "task"}, + {"key": "t-asg", "id": "e2e-t-asg", "title": "target asg", "type": "task"}, + {"key": "t-dac", "id": "e2e-t-dac", "title": "target dac", "type": "task"}, + {"key": "t-c1", "id": "e2e-t-c1", "title": "target c1", "type": "task"}, + {"key": "t-c2", "id": "e2e-t-c2", "title": "target c2", "type": "task"}, + {"key": "t-c3", "id": "e2e-t-c3", "title": "target c3", "type": "task"}, + {"key": "t-c4", "id": "e2e-t-c4", "title": "target c4", "type": "task"}, + {"key": "t-c5", "id": "e2e-t-c5", "title": "target c5", "type": "task"}, + {"key": "t-d1", "id": "e2e-t-d1", "title": "target d1", "type": "task"}, + {"key": "t-d2", "id": "e2e-t-d2", "title": "target d2", "type": "task"}, + {"key": "t-d3", "id": "e2e-t-d3", "title": "target d3", "type": "task"}, + {"key": "t-d4", "id": "e2e-t-d4", "title": "target d4", "type": "task"}, + {"key": "t-df1", "id": "e2e-t-df1", "title": "target df1", "type": "task"}, + {"key": "t-df2", "id": "e2e-t-df2", "title": "target df2", "type": "task"}, + {"key": "t-da", "id": "e2e-t-da", "title": "target da", "type": "task"}, + {"key": "t-db", "id": "e2e-t-db", "title": "target db", "type": "task"}, + {"key": "t-l", "id": "e2e-t-l", "title": "target l", "type": "task"}, + {"key": "t-as2", "id": "e2e-t-as2", "title": "target as2", "type": "task"}, + {"key": "t-cm", "id": "e2e-t-cm", "title": "target cm", "type": "task"}, + {"key": "t-rel", "id": "e2e-t-rel", "title": "target rel", "type": "task", "assignee": "worker"}, + {"key": "t-xfer", "id": "e2e-t-xfer", "title": "target xfer", "type": "task", "assignee": "worker"}, + {"key": "t-ifa", "id": "e2e-t-ifa", "title": "target ifa", "type": "task", "assignee": "worker", "metadata": {"seeded": "keep"}}, + {"key": "t-death", "id": "e2e-t-death", "title": "target death", "type": "task", "assignee": "worker"}, + {"key": "t-rc", "id": "e2e-t-rc", "title": "target rc", "type": "task", "assignee": "worker"}, + {"key": "t-hb", "id": "e2e-t-hb", "title": "target hb", "type": "task"}, + {"key": "t-hb2", "id": "e2e-t-hb2", "title": "target hb2", "type": "task"}, + {"key": "t-hb3", "id": "e2e-t-hb3", "title": "target hb3", "type": "task"}, + {"key": "t-boot", "id": "e2e-t-boot", "title": "target boot", "type": "task"}, + {"key": "t-ro", "id": "e2e-t-ro", "title": "target reopen", "type": "task"}, + {"key": "t-dr", "id": "e2e-t-dr", "title": "target dep remove", "type": "task", "deps": [{"target": "t-db"}]}, + {"key": "t-dc", "id": "e2e-t-dc", "title": "cascade root", "type": "epic"}, + {"key": "t-dc.1", "id": "e2e-t-dc.1", "title": "cascade child", "type": "task", "parent_key": "t-dc"}, + {"key": "t-gcr", "id": "e2e-t-gcr", "title": "target gate create", "type": "task"}, + {"key": "t-gct", "id": "e2e-t-gct", "title": "target gate check", "type": "task"}, + {"key": "t-gw", "id": "e2e-t-gw", "title": "target gate waiter", "type": "gate"}, + {"key": "t-gaw", "id": "e2e-t-gaw", "title": "target gate await id", "type": "gate"} + ]} + - name: bulk-ready-a.json + bulk: {id_prefix: e2e-bra, count: 60, priority: 3, metadata: {gc.routed_to: pool-a}} + - name: bulk-ready-b.json + bulk: {id_prefix: e2e-brb, count: 60, priority: 3, metadata: {gc.routed_to: pool-a}} + - name: bulk-wisp-a.json + bulk: {id_prefix: e2e-wisp-bwa, count: 55, priority: 3, ephemeral: true, metadata: {gc.routed_to: pool-a}} + - name: bulk-wisp-b.json + bulk: {id_prefix: e2e-wisp-bwb, count: 55, priority: 3, ephemeral: true, metadata: {gc.routed_to: pool-a}} + - name: graph-small.json + content: | + {"commit_message": "gc graph apply", "nodes": [ + {"key": "root", "id": "e2e-g-root", "title": "graph root", "type": "epic", "metadata": {"gc.kind": "workflow"}}, + {"key": "s1", "id": "e2e-g-s1", "title": "graph step 1", "type": "task", "parent_key": "root", "assignee": "worker", "labels": ["lane:g"], "metadata": {"gc.routed_to": "pool-a"}}, + {"key": "s2", "id": "e2e-g-s2", "title": "graph step 2", "type": "task", "parent_key": "root"} + ], "edges": [{"from_key": "s2", "to_key": "s1", "type": "blocks"}]} + - name: graph-eph.json + content: | + {"nodes": [ + {"key": "root", "id": "e2e-wisp-g-root", "title": "wisp graph root", "type": "epic"}, + {"key": "s1", "id": "e2e-wisp-g-s1", "title": "wisp graph step", "type": "task", "parent_key": "root"} + ]} + - name: delete-list.txt + content: | + e2e-t-df1 + e2e-t-df2 + +seed: + - [create, --graph, "{file:seed-core.json}", --json] + - [create, --graph, "{file:bulk-ready-a.json}", --json] + - [create, --graph, "{file:bulk-ready-b.json}", --json] + - [create, --graph, "{file:bulk-wisp-a.json}", --json] + - [create, --graph, "{file:bulk-wisp-b.json}", --json] + # Graph plans carry no status: a node created in_progress or closed stamps + # started_at/closed_at, which batchApply's create vocabulary cannot carry + # (gc's own plans never set a status). Lifecycle goes through update/close. + - [update, e2e-ip1, e2e-ipna, e2e-ipnb, e2e-mol.1, e2e-mac.2, e2e-t-rel, e2e-t-xfer, e2e-t-ifa, e2e-t-death, e2e-t-rc, e2e-t-boot, --status, in_progress] + - [update, e2e-wisp-2, --status, in_progress] + - [close, --force, e2e-done, e2e-ep.2, e2e-mol.3, e2e-mac.1, e2e-t-ro, e2e-gate-c] + - [comments, add, e2e-r1, "seed comment"] + +shapes: + # ---------------------------------------------------------------- show + # requests pins each show's round trips (mc-5dkzp): resolving the id, + # fetching the row and reading it for output are one request per id, which + # the per-command read memo answers once. + - id: gc-show-json + source: gc bdstore.go BdStore.Get (show --json ); counts must not read 0 + args: [show, --json, e2e-blk] + requests: 1 + - id: gc-show-json-batch + source: gc bdstore_exact_batch.go GetExactBatch + args: [show, --json, e2e-r1, e2e-a1, e2e-blk, e2e-mol] + requests: 4 + - id: gc-show-json-wisp + source: gc workquery.go blocked_by enrichment; wisps live in the ready tier + args: [show, e2e-wisp-1, --json] + requests: 1 + - id: gc-show-id-flag + source: gc cmd_bd_show_watch.go bdWatchRunner (show --json --id=) + args: [show, --json, --id=e2e-r1] + requests: 1 + # The worker holds eight in-progress issues; e2e-ip1 is the only P0 among + # them, so "first in the store's default order" (priority first) names it on + # both sides. Among equal priorities the order rests on created_at, and a + # seed that straddles a second boundary on one side only picked another issue. + - id: gc-show-current + source: gc cmd_bd_show_watch.go bdWatchRunner (show --current --json) + args: [show, --current, --json] + requests: 3 + - id: gc-show-missing + source: gc BdStore.Get not-found classification (routing fallbacks) + args: [show, --json, e2e-nonexistent] + expect_exit: 1 + expect_stderr: "(?i)not found" + compare: exit + requests: 1 + # Text show reads the row, then its dependents and its comments: three + # different URLs the memo cannot collapse. + - id: mc-show-text + source: mc prompts (bd show , ~80) + args: [show, e2e-r1] + compare: text + requests: 3 + + # ---------------------------------------------------------------- ready + # e2e-wr and e2e-wisp-wr are the only open rows assigned to the worker when + # these shapes run, so the assignee shapes compare real rows: a client that + # sends the wrong assignee or drops --include-ephemeral returns a different + # list. The wisp is P1 and the task P2, so --limit=1 picks the wisp on both + # sides by priority alone. + - id: gc-ready-unlimited + source: gc bdstore.go bdReadyArgs (BdStore.Ready, ready --json --limit 0) + args: [ready, --json, --limit, "0"] + compare: ids + - id: gc-ready-ephemeral-assignee-unlimited + source: gc bdstore.go bdReadyArgs with --include-ephemeral --assignee + args: [ready, --json, --include-ephemeral, --assignee, worker, --limit, "0"] + compare: ids + - id: gc-ready-pool-demand + source: gc workquery.go bdReadyPoolDemandShell (scale_check, --limit=20) + args: [ready, --metadata-field, gc.routed_to=pool-a, --unassigned, --exclude-type=epic, --exclude-label, "hold:mayor", --exclude-label, "hold:external", --json, --limit=20] + compare: ids + - id: gc-ready-pool-demand-unlimited + source: gc workquery.go bdReadyPoolDemandShell (work_query, --include-ephemeral --limit 0) + args: [ready, --include-ephemeral, --metadata-field, gc.routed_to=pool-a, --unassigned, --exclude-type=epic, --exclude-label, "hold:mayor", --exclude-label, "hold:external", --json, --limit, "0"] + compare: ids + - id: gc-ready-workflow-migration + source: gc workquery.go bdReadyPoolDemandMigrationShell (--sort oldest --limit 0) + args: [ready, --include-ephemeral, --metadata-field, gc.run_target=pool-a, --metadata-field, gc.kind=workflow, --unassigned, --exclude-type=epic, --exclude-label, "hold:mayor", --exclude-label, "hold:external", --json, --sort, oldest, --limit, "0"] + compare: ids + - id: gc-ready-graph-anchor + source: gc workquery.go assignedGraphWorkflowAnchorReadyFunctionScript + args: [ready, --include-ephemeral, --metadata-field, gc.root_bead_id=e2e-mol, --metadata-field, gc.routed_to=pool-a, --exclude-type=epic, --exclude-label, "hold:mayor", --exclude-label, "hold:external", --json, --sort, oldest, --limit=20] + compare: ids + - id: gc-ready-assigned-tier + source: gc workquery.go assignedReadyTierCommand (--assignee= --limit=1) + args: [ready, --include-ephemeral, --assignee=worker, --json, --limit=1] + compare: ids + - id: gc-ready-probe + source: gc examples/bd gc-beads-bd.sh (bare bd ready probe) + args: [ready] + compare: exit + - id: mc-ready-json + source: mc scripts/prompts (bd ready --json, ~36) + args: [ready, --json] + compare: ids + - id: mc-ready-mol + source: mc skills/pr-review (bd ready --mol ) + args: [ready, --mol, e2e-mol, --json] + - id: mc-ready-parent + source: mc skills/pr-review (bd ready --parent ) + args: [ready, --parent, e2e-ep, --json] + compare: ids + + # ---------------------------------------------------------------- list + - id: gc-list-full-filters + source: gc bdstore.go listViaBDList (List/ListByLabel/ListByMetadata) + args: [list, --json, --label=lane:a, --status=open, --type=task, --include-infra, --include-gates, --limit, "0", --metadata-field, gc.routed_to=pool-a] + - id: gc-list-ping + source: gc bdstore.go BdStore.Ping (list --json --limit 0) + args: [list, --json, --limit, "0"] + compare: ids + - id: gc-list-limit1 + source: gc doctor_gate_sandbox.go / doctor_store_preflight.go + args: [list, --json, --limit, "1"] + compare: count + - id: gc-list-readonly + source: gc doctor_v2_session_migration.go readOnlyBdRunner + args: [--readonly, list, --json, --limit, "1"] + compare: count + - id: gc-list-assignee-status + source: gc bdstore.go listViaBDList (ListByAssignee) + args: [list, --json, --assignee=worker, --status=in_progress, --include-infra, --include-gates, --limit, "0"] + - id: gc-list-all-created-before + source: gc bdstore.go listViaBDList (--all --created-before --include-templates --skip-labels) + args: [list, --json, --all, --created-before, "2100-01-01T00:00:00Z", --include-infra, --include-gates, --include-templates, --limit, "0", --skip-labels] + compare: ids + - id: gc-list-children + source: gc bdstore.go listViaBDList (Children, --parent) + args: [list, --json, --include-infra, --include-gates, --limit, "0", --parent, e2e-ep, --all] + - id: gc-list-in-progress-tier + source: gc workquery.go assignedInProgressTierCommandWithLimit + args: [list, --status, in_progress, --assignee=worker, --json, --limit=20] + - id: gc-list-on-death + source: gc workquery.go EffectiveOnDeath + args: [list, --assignee=worker, --status=in_progress, --json] + - id: gc-list-on-boot + source: gc workquery.go on_boot recovery (--no-assignee) + args: [list, --metadata-field, gc.routed_to=pool-a, --status=in_progress, --no-assignee, --json] + pending: {slice: "SRV-1", reason: "S15b sends --no-assignee as listIssues no_assignee behind issues.list.noAssignee, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_ListScopeFiltersOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: gc-list-on-boot-workflow + source: gc workquery.go on_boot recovery, workflow lane + args: [list, --metadata-field, gc.run_target=pool-a, --metadata-field, gc.kind=workflow, --status=in_progress, --no-assignee, --json] + pending: {slice: "SRV-1", reason: "S15b sends --no-assignee as listIssues no_assignee behind issues.list.noAssignee, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_ListScopeFiltersOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: mc-list-meta-status + source: mc assets snapshot.md (list --json --limit --metadata-field --status) + args: [list, --json, --limit, "50", --metadata-field, gc.routed_to=pool-a, --status, open] + compare: ids + # More than 50 rows match, most at one priority: --limit 50 cuts a tie set + # whose created_at order differs between the two seeds, so each side's 50 + # rows are held to its own unlimited listing instead. + prefix_of: [list, --json, --limit, "0", --metadata-field, gc.routed_to=pool-a, --status, open] + - id: mc-list-github-source + source: mc github-intake (list --all --json --limit --metadata-field x3) + args: [list, --metadata-field, gc.kind=github_source, --metadata-field, gc.github.kind=issue, --metadata-field, gc.github.repo=o/r, --all, --json, --limit, "0"] + - id: mc-list-all-type + source: mc normalized_candidate_graph.py (list --all --type) + args: [list, --all, --type, epic, --json, --limit, "50"] + - id: mc-list-include-gates-infra-label + source: mc mol-normalized-issue-pr-v1 (list --all --include-gates --include-infra --json --label --limit) + args: [list, --all, --include-gates, --include-infra, --json, --label, "lane:a", --limit, "0"] + - id: mc-list-title + source: mc mol-normalized-issue-pr-v1 (list --all --include-infra --json --limit --title) + args: [list, --all, --include-infra, --json, --limit, "10", --title, "Routed open task"] + pending: {slice: "SRV-1", reason: "S15b sends --title as listIssues title behind issues.list.title, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_ListScopeFiltersOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: mc-list-id + source: mc skills/pr-review (list --all --id --json --limit) + args: [list, --all, --id, "e2e-r1,e2e-a1", --json, --limit, "0"] + pending: {slice: "SRV-1", reason: "S15b sends --id as listIssues id behind issues.list.ids, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_ListScopeFiltersOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: gc-polecat-title-contains + source: gascity core formulas/mol-polecat-base.toml (list --title-contains --status a,b,c --json) + args: [list, --title-contains, "Routed", --status, "open,in_progress,blocked", --json] + pending: {slice: "SRV-1", reason: "--title-contains folds onto listIssues title behind issues.list.title, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_ListScopeFiltersOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: gc-polecat-title-contains-closed-after + source: gascity core formulas/mol-polecat-base.toml (pre-flight 3d, list --title-contains --status closed --closed-after DATE --json) + args: [list, --title-contains, "closed task", --status, closed, --closed-after, "2000-01-01", --json] + pending: {slice: "SRV-1", reason: "needs issues.list.title (--title-contains folds onto listIssues title) and issues.list.filters (closed_after), which the reference server does not advertise, so the client refuses before dialing; remove the mark when reference_server.json is upgraded"} + - id: gc-polecat-closed-after + source: gascity core formulas/mol-polecat-base.toml:267 (list --title-contains --status closed --closed-after --json) + args: [list, --title-contains, "task", --status, closed, --closed-after, "2000-01-01", --json] + compare: ids + pending: {slice: "SRV-1", reason: "needs issues.list.title (--title-contains folds onto listIssues title) and issues.list.filters (closed_after), which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_ListFilterParityOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: wf-session-cleanup + source: an order cleanup script's closed-session sweep (list --all --include-infra --include-gates --status closed --label --closed-before --updated-before) + args: [list, --json, --all, --include-infra, --include-gates, --status, closed, --label, "lane:a", --closed-before, "2100-01-01T00:00:00Z", --updated-before, "2100-01-01T00:00:00Z", --limit, "0"] + compare: ids + pending: {slice: "SRV-1", reason: "needs issues.list.filters, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_ListFilterParityOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: list-filter-priority-range + source: bd list --priority-min/--priority-max (listing filter parity) + args: [list, --json, --priority-min, "1", --priority-max, "3", --limit, "0"] + compare: ids + pending: {slice: "SRV-1", reason: "needs issues.list.filters, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_ListFilterParityOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: list-filter-exclude-type-no-parent + source: bd list --exclude-type --no-parent (listing filter parity) + args: [list, --json, --exclude-type, epic, --no-parent, --limit, "0"] + compare: ids + pending: {slice: "SRV-1", reason: "needs issues.list.filters, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_ListFilterParityOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: list-filter-updated-after + source: bd list --updated-after (listing filter parity) + args: [list, --json, --updated-after, "2000-01-01", --limit, "0"] + compare: ids + pending: {slice: "SRV-1", reason: "needs issues.list.filters, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_ListFilterParityOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: mc-list-assignee-status + source: mc review summaries (list --assignee --json --limit --status) + args: [list, --assignee, alice, --json, --limit, "10", --status, open] + - id: mc-list-label-text + source: mc normalized_child_launch.py (list --label) + args: [list, --label, "lane:a"] + compare: text + - id: mc-list-plain + source: mc scripts (bare bd list) + args: [list] + compare: exit + - id: mc-children + source: mc prompts (bd children ) + args: [children, e2e-ep, --json] + + # ---------------------------------------------------------------- query / count / search + - id: gc-query-wisps + source: gc bdstore.go listEphemeral (query --json "ephemeral=true AND ..." --limit N) + args: [query, --json, "ephemeral=true AND label=lane:w", --limit, "50"] + - id: gc-query-wisps-all + source: gc bdstore.go listEphemeral with IncludeClosed (--all) + args: [query, --json, "ephemeral=true AND status=in_progress", --all, --limit, "50"] + - id: gc-query-wisp-by-id + source: gc bdstore.go getEphemeralByID + args: [query, --json, "ephemeral=true AND id=e2e-wisp-1", --all, --limit, "1"] + - id: gc-query-wisps-unlimited + source: gc workquery.go bdQueryEphemeralStatusShell (--limit=0, wisp tier) + args: [query, --json, "ephemeral=true AND status=open", --limit=0] + compare: ids + - id: mc-query + source: mc pr_merge.py (bd query) + args: [query, --json, "status=open AND priority<=1", --limit, "50"] + - id: gc-count + source: gc native CountIssues fallback (count without scope) + args: [count, --json] + - id: gc-count-status + source: gc count with a status filter + args: [count, --json, --status, open] + - id: mc-search + source: mc mol-bug-report-flow-v2 (bd search) + args: [search, "Routed", --json] + compare: ids + pending: {slice: "S6c+SRV-1", reason: "S26 sends bd search as listIssues q behind issues.list.search, which the reference server does not advertise, so the client refuses before dialing; remove the mark when reference_server.json is upgraded"} + - id: mc-status + source: mc normalized_child_launch.py (bd status) + args: [status, --json] + + # ---------------------------------------------------------------- deps / graph reads + - id: gc-dep-list + source: gc bdstore.go DepList + args: [dep, list, e2e-blk, --json] + - id: gc-dep-list-up + source: gc bdstore.go DepList (--direction=up) + args: [dep, list, e2e-r1, --json, --direction=up] + - id: gc-dep-list-batch + source: gc bdstore.go DepListBatch + args: [dep, list, e2e-blk, e2e-mol.2, --json] + - id: mc-dep-tree + source: mc pr_review.py city_dep_subtree (dep tree --json) + args: [dep, tree, e2e-mol, --json] + - id: gc-blocked + source: gc bdstore_ready_projection.go fetchReadyProjectionViaBlocked + args: [blocked, --json] + pending: {slice: "SRV-1", reason: "bd blocked dials listBlockedIssues behind blocked.list, which the reference server does not advertise, so the client refuses at its capability preflight (pinned passing against the current server by backend/http TestE2E_BlockedOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: gc-blocked-flags + source: gc bdstore_ready_projection.go readiness door (bd blocked --flags --json, ids on stdin) + args: [blocked, --flags, --json] + stdin: "e2e-mol\ne2e-mol.1\ne2e-mol.2\ne2e-no-such-row\n" + compare: json + pending: {slice: "SRV-1", reason: "bd blocked --flags reads listBlockingAnnotations is_blocked behind dependencies.blocking.isBlocked, which the reference server does not advertise, so the client refuses at its capability preflight (pinned passing against the current server by backend/http TestE2E_BlockedFlagsOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: gc-blocked-flags-raw + source: gc bdstore_ready_projection.go readiness door (the stored is_blocked column, bd blocked --flags --raw --json, ids on stdin) + args: [blocked, --flags, --raw, --json] + stdin: "e2e-mol\ne2e-mol.1\ne2e-mol.2\ne2e-no-such-row\n" + compare: json + pending: {slice: "SRV-1", reason: "bd blocked --flags reads listBlockingAnnotations is_blocked behind dependencies.blocking.isBlocked, which the reference server does not advertise, so the client refuses at its capability preflight (pinned passing against the current server by backend/http TestE2E_BlockedFlagsOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: gc-blocked-parent + source: bd blocked --parent (the molecule-scoped blocked listing) + args: [blocked, --json, --parent, e2e-mol] + pending: {slice: "SRV-1", reason: "bd blocked dials listBlockedIssues behind blocked.list, which the reference server does not advertise, so the client refuses at its capability preflight (pinned passing against the current server by backend/http TestE2E_BlockedOverHTTP); remove the mark when reference_server.json is upgraded"} + + # ---------------------------------------------------------------- molecules + - id: mc-mol-current + source: mc worker prompts (bd mol current, ~38; inferred from in_progress work) + args: [mol, current, --json] + - id: mc-mol-current-text + source: mc gc-role-worker template (bd mol current, text) + args: [mol, current] + compare: text + - id: mc-mol-current-id + source: mc prompts (bd mol current ) + args: [mol, current, e2e-mol, --json] + - id: mc-mol-progress + source: mc prompts (bd mol progress ) + args: [mol, progress, e2e-mol, --json] + + # ---------------------------------------------------------------- config / probes / local + - id: gc-config-get-types + source: gc beads_provider_lifecycle.go / checks_custom_types.go (config get --json types.custom) + args: [config, get, --json, types.custom] + - id: gc-config-get-prefix + source: gc gc-beads-bd.sh (config get issue_prefix) + args: [config, get, issue_prefix] + compare: text + - id: gc-types + source: gc checks_custom_types.go (types --json) + args: [types, --json] + - id: gc-context + source: gc beads_preflight_checker.go (context --json); never touches the store + args: [context, --json] + compare: exit + - id: gc-version + source: gc bdstore_blocked_repair.go BDVersion + args: [version] + compare: exit + - id: gc-ping + source: gc cmd_beads_city_migrate_proxied.go / dashboard (ping --json) + args: [ping, --json] + compare: exit + - id: mc-prime + source: mc formulas (bd prime) + args: [prime] + compare: exit + - id: gc-sql-ready-projection + source: gc bdstore_ready_projection.go fetchReadyProjection + args: [sql, "select id,is_blocked from issues where status <> 'closed' union all select id,is_blocked from wisps where status <> 'closed'", --json] + expect_exit: 1 + expect_stderr: "'bd sql' is not yet supported" + compare: exit + - id: gc-sql-release-fallback + source: gc bdstore.go ReleaseIfCurrent fallback (sql UPDATE) + args: [sql, --json, "UPDATE issues SET status='open', assignee='' WHERE id='e2e-t-rel' AND status='in_progress' AND assignee='worker'"] + expect_exit: 1 + expect_stderr: "'bd sql' is not yet supported" + compare: exit + - id: gc-purge-dry-run + source: gc bdstore.go Purge (purge --json --dry-run) + args: [purge, --json, --dry-run] + compare: exit + pending: {slice: "SRV-1", reason: "purge needs the sweep tokens the reference server does not advertise (B3 #13); remove the mark when reference_server.json is upgraded"} + - id: gc-recompute-blocked + source: gc bdstore_blocked_repair.go RecomputeBlocked + args: [recompute-blocked, --json] + compare: exit + - id: gc-backup-status + source: gc checks_proxied_backup_coverage.go (backup status --json) + args: [backup, status, --json] + compare: exit + # The seed holds an open gate, a closed gate and an ephemeral gate, so the + # open listing and the --all listing answer different, non-empty sets. + - id: mc-gate-list + source: gc core pack order renudge-stale-human-gates.sh (gc bd gate list --limit 0 --json) + args: [gate, list, --limit, "0", --json] + - id: mc-gate-list-all + source: core pack orders (gate list --all) + args: [gate, list, --all, --json] + # gate check lists the open gates through the same ListGates entry. No + # seeded gate carries an await type (the seed graph carries no gate members; + # mc-gate-check-timer-resolves below creates a real timer gate), so the + # typed sweeps find nothing of their type and the untyped one lists the open + # gates and evaluates none: the listing is what these shapes prove served, + # and nothing resolves, escalates (no gt exec) or writes. + - id: mc-gate-check-timer + source: gc core pack gate-sweep.sh (bd gate check --type=timer --escalate) + args: [gate, check, --type=timer, --escalate] + compare: text + - id: mc-gate-check-gh + source: gc core pack gate-sweep.sh (bd gate check --type=gh --escalate) + args: [gate, check, --type=gh, --escalate] + compare: text + - id: gate-check-all + source: bd gate check (every open gate) + args: [gate, check] + compare: text + + - id: gc-export-all + source: gc core pack reaper (gc bd export --all -o F) + args: [export, --all, -o, "{file:export.jsonl}"] + compare: exit + + # ================================================================ writes + # ---------------------------------------------------------------- create + - id: gc-create-full + source: gc bdstore.go CreateWithStorage (every optional flag but --parent) + args: [create, --json, "gc created", -t, task, --id, e2e-n1, --priority, "1", --description, "made by gc", --assignee, worker, --deps, e2e-r1, --labels, "lane:n,x", --metadata, '{"gc.routed_to":"pool-a"}'] + compare: exit + verify: [[show, --json, e2e-n1]] + - id: gc-create-parent + source: gc bdstore.go CreateWithStorage (--parent, server-minted child id) + args: [create, --json, "gc child", -t, task, --parent, e2e-ep] + compare: exit + verify: [[show, --json, e2e-ep.3]] + - id: gc-create-ephemeral + source: gc bdstore.go CreateWithStorage (--ephemeral) + args: [create, --json, "gc wisp", -t, task, --id, e2e-wisp-n2, --ephemeral, --metadata, '{"gc.routed_to":"pool-a"}'] + compare: exit + verify: [[show, --json, e2e-wisp-n2]] + - id: gc-create-no-history + source: gc bdstore.go CreateWithStorage (--no-history, agent beads) + args: [create, --json, "gc agent bead", -t, task, --id, e2e-n3, --no-history] + compare: exit + verify: [[show, --json, e2e-n3]] + - id: gc-create-defer + source: gc bdstore.go CreateWithStorage (--defer RFC3339) + args: [create, --json, "gc deferred", -t, task, --id, e2e-n4, --defer, "2100-01-01T00:00:00Z"] + compare: exit + verify: [[show, --json, e2e-n4]] + - id: mc-create-external-ref + source: mc snapshot.md (create --external-ref --labels --metadata --type) + args: [create, "triaged issue", --external-ref, gh-999, --labels, "triage", --metadata, '{"gc.kind":"github_source"}', --type, task, --id, e2e-n5, --json] + compare: exit + verify: [[show, --json, e2e-n5]] + - id: mc-create-text + source: mc prompts (bd create, text output) + args: [create, "plain create", --type, task, --id, e2e-n6] + compare: exit + verify: [[show, --json, e2e-n6]] + - id: gc-create-graph + source: gc bdstore_graph_apply.go ApplyGraphPlanWithStorage + args: [create, --graph, "{file:graph-small.json}", --json] + verify: [[show, --json, e2e-g-root, e2e-g-s1, e2e-g-s2]] + - id: gc-create-graph-ephemeral + source: gc bdstore_graph_apply.go (--ephemeral by storage class) + args: [create, --graph, "{file:graph-eph.json}", --json, --ephemeral] + verify: [[show, --json, e2e-wisp-g-root, e2e-wisp-g-s1]] + + # ---------------------------------------------------------------- update + - id: gc-update-fields + source: gc bdstore.go bdUpdateArgs (Update) + args: [update, --json, e2e-t-upd, --title, "updated", --status, in_progress, --type, bug, --priority, "1", --description, "new", --assignee, bob, --set-metadata, a=1, --set-metadata, b=2, --add-label, x, --remove-label, "lane:z"] + compare: exit + verify: [[show, --json, e2e-t-upd]] + - id: gc-update-parent + source: gc bdstore.go bdUpdateArgs (--parent) + args: [update, --json, e2e-t-upd2, --parent, e2e-ep] + compare: exit + verify: [[show, --json, e2e-t-upd2]] + - id: gc-update-many + source: gc bdstore.go UpdateAll / setMetadataBatchAll + args: [update, --json, e2e-t-m1, e2e-t-m2, --set-metadata, gc.batch=1, --priority, "3"] + compare: exit + verify: [[show, --json, e2e-t-m1, e2e-t-m2]] + - id: gc-update-claim + source: gc bdstore.go BdStore.Claim and gc hook --claim (update --claim --json) + args: [update, e2e-t-claim, --claim, --json] + compare: exit + verify: [[show, --json, e2e-t-claim]] + - id: gc-update-claim-actor + source: gc cmd_agent_script.go bd_claim (update --claim --actor X) + args: [update, e2e-t-claim2, --claim, --actor, alice] + compare: exit + verify: [[show, --json, e2e-t-claim2]] + - id: gc-update-claim-wisp + source: gc ready queues include ephemeral work; claiming a wisp + args: [update, e2e-wisp-c, --claim, --json] + compare: exit + verify: [[show, --json, e2e-wisp-c]] + pending: {slice: "SRV-1", reason: "the reference server lacks UpdateIssueRequest.claim, and the claimIssue fallback excludes wisps (B3 #6); remove the mark when reference_server.json is upgraded"} + - id: gc-update-if-revision + source: gc bdstore_conditional.go UpdateIfMatch / CompareAndSetMetadataKey + args: [update, e2e-t-rev, --set-metadata, k=v, --if-revision, "{rev:e2e-t-rev}"] + compare: exit + verify: [[show, --json, e2e-t-rev]] + - id: gc-update-if-revision-stale + source: gc bdstore_conditional.go UpdateIfMatch mismatch (exit 13) + args: [update, e2e-t-rev2, --set-metadata, k=v, --if-revision, "1"] + expect_exit: 13 + compare: exit + verify: [[show, --json, e2e-t-rev2]] + - id: gc-update-release-if-current + source: gc bdstore_conditional_release.go releaseIfCurrentViaBdVerb + args: [update, e2e-t-rel, --if-assignee, worker, --if-status, in_progress, --status, open, --assignee, ""] + compare: exit + verify: [[show, --json, e2e-t-rel]] + - id: gc-update-transfer-if-current + source: gc bdstore_conditional_release.go TransferIfCurrent + args: [update, e2e-t-xfer, --if-assignee, worker, --if-status, in_progress, --assignee, alice] + compare: exit + verify: [[show, --json, e2e-t-xfer]] + - id: gc-update-if-assignment + source: gc bdstore_conditional.go UpdateIfAssignment + args: [update, --json, e2e-t-ifa, --set-metadata, k=v, --if-status, in_progress, --if-assignee, worker] + compare: exit + verify: [[show, --json, e2e-t-ifa]] + # e2e-t-ifa is seeded with metadata seeded=keep, so each refused (exit 13) + # update's verify still holds that the refusal left existing metadata + # alone, in whichever corpus part runs it (the parts seed separately, so + # the k=v written by gc-update-if-assignment may not be there). + - id: gc-update-if-assignment-assignee-stale + source: gc bdstore_conditional.go UpdateIfAssignment mismatch (exit 13) + args: [update, --json, e2e-t-ifa, --set-metadata, probe=a, --if-status, in_progress, --if-assignee, nobody] + expect_exit: 13 + compare: exit + verify: [[show, --json, e2e-t-ifa]] + - id: gc-update-if-assignment-status-stale + source: gc bdstore_conditional.go UpdateIfAssignment mismatch (exit 13) + args: [update, --json, e2e-t-ifa, --set-metadata, probe=s, --if-status, open, --if-assignee, worker] + expect_exit: 13 + compare: exit + verify: [[show, --json, e2e-t-ifa]] + - id: gc-update-on-death + source: gc workquery.go on_death (update --assignee "" --status open --set-metadata) + args: [update, e2e-t-death, --assignee, "", --status, open, --set-metadata, gc.run_target=pool-a] + compare: exit + verify: [[show, --json, e2e-t-death]] + - id: gc-update-on-boot + source: gc workquery.go on_boot (update --status open) + args: [update, e2e-t-boot, --status, open] + compare: exit + verify: [[show, --json, e2e-t-boot]] + - id: gc-update-sling + source: gc workquery.go DefaultSlingQuery (update --set-metadata gc.routed_to=) + args: [update, e2e-t-sling, --set-metadata, gc.routed_to=pool-b] + compare: exit + verify: [[show, --json, e2e-t-sling]] + - id: gc-update-agent-script + source: gc cmd_agent_script.go bd_update (--assignee --status --append-notes --set-metadata) + args: [update, e2e-t-as, --assignee, worker, --status, in_progress, --append-notes, "agent note", --set-metadata, k=v] + compare: exit + verify: [[show, --json, e2e-t-as]] + - id: gc-update-dolt-auto-commit-off + source: gc bdstore.go bdTransientWriteArgs (--dolt-auto-commit off prefix) + args: [--dolt-auto-commit, "off", update, --json, e2e-t-dac, --set-metadata, k=v] + compare: exit + verify: [[show, --json, e2e-t-dac]] + - id: mc-update-meta-status + source: mc prompts (update --set-metadata --status, ~151) + args: [update, e2e-t-ms, --set-metadata, review.verdict=iterate, --status, in_progress] + compare: exit + verify: [[show, --json, e2e-t-ms]] + - id: mc-update-meta-status-closed + source: mc prompts (update --set-metadata --status closed, under Claude Code) + args: [update, e2e-t-msc, --set-metadata, review.verdict=done, --status, closed] + compare: exit + verify: [[show, --json, e2e-t-msc]] + pending: {slice: "S6d", reason: "a silent data difference, not a refusal: the update succeeds on both sides under CLAUDE_SESSION_ID, but the served update records no closed_by_session (an http update patch cannot carry one, so the CLI drops it without a word; bd close does carry it) where embedded records the session, so the verify show differs (B3 #7)"} + - id: mc-update-unset-metadata + source: mc adopt-pr-operator (update --unset-metadata) + args: [update, e2e-t-um, --unset-metadata, k] + compare: exit + verify: [[show, --json, e2e-t-um]] + - id: mc-update-notes + source: mc github fix-issue formula (update --notes) + args: [update, e2e-t-notes, --notes, "notes text"] + compare: exit + verify: [[show, --json, e2e-t-notes]] + - id: mc-update-external-ref-metadata + source: mc snapshot.md (update --external-ref --metadata) + args: [update, e2e-t-er, --external-ref, gh-1, --metadata, '{"gc.kind":"github_source"}'] + compare: exit + verify: [[show, --json, e2e-t-er]] + - id: mc-update-metadata + source: mc build-base prepare.md (update --metadata) + args: [update, e2e-t-md, --metadata, '{"x":"1"}'] + compare: exit + verify: [[show, --json, e2e-t-md]] + - id: mc-update-assignee + source: mc review reports (update --assignee) + args: [update, e2e-t-asg, --assignee, bob] + compare: exit + verify: [[show, --json, e2e-t-asg]] + + # ---------------------------------------------------------------- close / reopen + - id: gc-close-force-reason-many + source: gc bdstore.go bdCloseArgs (CloseAll/CloseAllWithReason) + args: [close, --force, --json, --reason, done, e2e-t-c1, e2e-t-c2] + compare: exit + verify: [[show, --json, e2e-t-c1, e2e-t-c2]] + - id: gc-close-if-revision + source: gc bdstore_conditional.go CloseIfMatch + args: [close, --force, --json, e2e-t-c3, --if-revision, "{rev:e2e-t-c3}"] + compare: exit + verify: [[show, --json, e2e-t-c3]] + - id: mc-close-text + source: mc formulas (bd close ) + args: [close, e2e-t-c4] + compare: exit + verify: [[show, --json, e2e-t-c4]] + - id: mc-close-reason + source: mc build-basic-review (bd close --reason) + args: [close, e2e-t-c5, --reason, "review applied"] + compare: exit + verify: [[show, --json, e2e-t-c5]] + - id: gc-close-last-step-autocloses-molecule + source: gc/mc molecule lifecycle (closing the last open step closes the root) + args: [close, --force, --json, e2e-mac.2] + compare: exit + verify: [[show, --json, e2e-mac]] + - id: gc-reopen + source: gc bdstore.go Reopen + args: [reopen, --json, e2e-t-ro] + compare: exit + verify: [[show, --json, e2e-t-ro]] + + # ---------------------------------------------------------------- delete / reclaim / promote / burn + - id: gc-delete + source: gc bdstore.go Delete + args: [delete, --force, --json, e2e-t-d1] + compare: exit + verify: [[show, --json, e2e-t-d1]] + - id: gc-delete-if-revision + source: gc bdstore_conditional.go DeleteIfMatch + args: [delete, --force, --json, e2e-t-d2, --if-revision, "{rev:e2e-t-d2}"] + compare: exit + verify: [[show, --json, e2e-t-d2]] + - id: gc-delete-batch + source: gc bdstore.go DeleteBatch (no --json) + args: [delete, e2e-t-d3, e2e-t-d4, --force] + compare: exit + verify: [[show, --json, e2e-t-d3]] + - id: gc-delete-cascade + source: gc cmd_convoy_dispatch.go deleteWorkflowMatches + args: [delete, e2e-t-dc, --cascade, --force] + compare: exit + verify: [[show, --json, e2e-t-dc.1]] + - id: mc-delete-from-file + source: mc session_cleanup.py / core reaper (delete --from-file) + args: [delete, --from-file, "{file:delete-list.txt}", --force] + compare: exit + verify: [[show, --json, e2e-t-df1]] + - id: gc-reclaim + source: gc bdstore.go ReclaimStale (reclaim --id --json) + args: [reclaim, --id, e2e-t-rc, --json] + compare: exit + verify: [[show, --json, e2e-t-rc]] + pending: {slice: "SRV-1", reason: "the reference server does not advertise issues.reclaim (B3 #12), so the client refuses at its capability preflight"} + - id: gc-heartbeat + source: gc formulas/mol-do-work.toml:47 (gc bd heartbeat -> bd heartbeat) + setup: [[update, e2e-t-hb, --claim]] + args: [heartbeat, e2e-t-hb, --json] + verify: [[show, --json, e2e-t-hb]] + pending: {slice: "reference-server-heartbeat", reason: "the reference server does not advertise issues.heartbeat, so the client refuses at its capability preflight; pinned passing by backend/http TestE2E_HeartbeatOverHTTP; remove the mark when reference_server.json is upgraded"} + - id: gc-heartbeat-non-holder + source: gc formulas/mol-do-work.toml:47 (a worker heartbeating a bead another actor holds) + setup: [[update, e2e-t-hb2, --claim, --actor, alice]] + args: [heartbeat, e2e-t-hb2] + expect_exit: 1 + expect_stderr: "(?i)claimed by|alice" + compare: exit + pending: {slice: "reference-server-heartbeat", reason: "the reference server does not advertise issues.heartbeat, so the client refuses at its capability preflight; pinned passing by backend/http TestE2E_HeartbeatOverHTTP; remove the mark when reference_server.json is upgraded"} + - id: gc-heartbeat-closed + source: gc formulas/mol-do-work.toml:47 (a worker heartbeating a bead that was closed under it) + setup: [[update, e2e-t-hb3, --claim], [close, e2e-t-hb3]] + args: [heartbeat, e2e-t-hb3] + expect_exit: 1 + expect_stderr: "(?i)status closed|is closed" + compare: exit + pending: {slice: "reference-server-heartbeat", reason: "the reference server does not advertise issues.heartbeat, so the client refuses at its capability preflight; pinned passing by backend/http TestE2E_HeartbeatOverHTTP; remove the mark when reference_server.json is upgraded"} + - id: gc-heartbeat-wisp + source: gc formulas/mol-do-work.toml:47 (a heartbeat on a wisp, which is never leased) + args: [heartbeat, e2e-wisp-2] + expect_exit: 1 + expect_stderr: "(?i)ephemeral" + compare: exit + pending: {slice: "reference-server-heartbeat", reason: "the reference server does not advertise issues.heartbeat, so the client refuses at its capability preflight; pinned passing by backend/http TestE2E_HeartbeatOverHTTP; remove the mark when reference_server.json is upgraded"} + - id: mc-promote + source: mc mol-normalized-issue-pr-v1 (promote --reason) + args: [promote, e2e-wisp-p, --reason, "keep it"] + compare: exit + pending: {slice: "SRV-1", reason: "the reference server does not advertise issues.update.persistence, so the client refuses at its capability preflight"} + - id: mc-mol-burn + source: mc review fixtures (mol burn --force) + args: [mol, burn, e2e-wisp-m, --force] + compare: exit + verify: [[show, --json, e2e-wisp-m.1]] + pending: {slice: "S17", reason: "mol burn needs RunInTransaction (B3 #14)"} + + # ---------------------------------------------------------------- deps / comments / labels / config writes + - id: gc-dep-add + source: gc bdstore.go DepAdd + args: [dep, add, e2e-t-da, e2e-t-db, --type, blocks] + compare: exit + verify: [[dep, list, e2e-t-da, --json]] + - id: gc-dep-remove + source: gc bdstore.go DepRemove + args: [dep, remove, e2e-t-dr, e2e-t-db] + compare: exit + verify: [[dep, list, e2e-t-dr, --json]] + - id: mc-comment + source: mc bug_hunt.py (bd comment ) + args: [comment, e2e-t-cm, "a comment"] + compare: exit + verify: [[comments, e2e-t-cm, --json]] + ignore_fields: [id] # comment ids are minted per workspace + - id: mc-comments-list + source: mc prompts (bd comments ) + args: [comments, e2e-r1, --json] + ignore_fields: [id] # comment ids are minted per workspace + - id: mc-label-add + source: mc prompts (bd label add) + args: [label, add, e2e-t-l, "lane:q"] + compare: exit + verify: [[show, --json, e2e-t-l]] + - id: mc-assign + source: mc prompts (bd assign) + args: [assign, e2e-t-as2, alice] + compare: exit + verify: [[show, --json, e2e-t-as2]] + - id: gc-config-set-types + source: gc beads_provider_lifecycle.go (config set types.custom a,b) + args: [config, set, types.custom, "corpus-a,corpus-b"] + compare: exit + verify: [[config, get, --json, types.custom]] + - id: mc-meta-set + source: mc adopt-pr-review checks (bd meta set k=v) + args: [meta, set, e2e-r1, review.verdict=done] + expect_exit: 1 + expect_stderr: 'unknown command "meta"' + compare: exit + # ---------------------------------------------------------------- gates + # The gate writes: create (one createIssue carrying the gate members and the + # blocks edge), a real timer gate resolving under gate check, add-waiter (a + # guarded waiters patch) and update --await-id. A --timeout=1ns timer is + # expired by the time gate check runs, so the resolution is deterministic. + - id: mc-gate-create-timer + source: core formulas / gate-sweep (bd gate create --type=timer --timeout --blocks) + args: [gate, create, --type=timer, --timeout=1ns, --blocks, e2e-t-gcr, --json] + ignore_fields: [id] # each side mints its own gate id + pending: {slice: "SRV-1", reason: "bd gate create sends the gate members on createIssue behind issues.create.gates, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_GatesOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: mc-gate-check-timer-resolves + source: core gate-sweep.sh (gate check --type=timer --escalate) over a real timer gate + setup: [[gate, create, --type=timer, --timeout=1ns, --blocks, e2e-t-gct]] + args: [gate, check, --type=timer, --escalate] + compare: exit + verify: [[ready, --json, --limit, "0"]] # e2e-t-gct is ready on both sides + ignore_fields: [depends_on_id] # its (closed) gate's id is minted per workspace + pending: {slice: "SRV-1", reason: "the setup bd gate create sends the gate members on createIssue behind issues.create.gates, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_GatesOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: mc-gate-add-waiter + source: bd done --phase-complete (gate add-waiter) + args: [gate, add-waiter, e2e-t-gw, "rig/workers/a"] + compare: text + verify: [[show, --json, e2e-t-gw]] + pending: {slice: "SRV-1", reason: "bd gate add-waiter sends waiters on updateIssue behind issues.update.gates, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_GatesOverHTTP); remove the mark when reference_server.json is upgraded"} + - id: mc-update-await-id + source: gate discover / gate check gh:run persist (update --await-id) + args: [update, e2e-t-gaw, --await-id, "12345", --json] + compare: exit + verify: [[show, --json, e2e-t-gaw]] + pending: {slice: "SRV-1", reason: "bd update --await-id sends await_id on updateIssue behind issues.update.gates, which the reference server does not advertise, so the client refuses before dialing (pinned passing against the current server by backend/http TestE2E_GatesOverHTTP); remove the mark when reference_server.json is upgraded"} diff --git a/backend/http/corpus/testdata/reference_server.json b/backend/http/corpus/testdata/reference_server.json new file mode 100644 index 000000000..7bdf6d0d0 --- /dev/null +++ b/backend/http/corpus/testdata/reference_server.json @@ -0,0 +1,595 @@ +{ + "comment": [ + "The reference server profile the corpus suite masks the in-process server to.", + "It is the wire surface of a deployed bd 1.3.0 `bd serve` that predates wire_revision:", + "capabilities is that server's advertised ContextResponse.capabilities (read off a live GET /v0/beads/context),", + "context_members is its ContextResponse property set, and operations are the method, path template,", + "query parameter names and top-level JSON request members of its published OpenAPI document (MIT).", + "Regenerate by hand when the reference deployment is upgraded; see README.md." + ], + "capabilities": [ + "config.get", + "config.list", + "config.set", + "config.unset", + "dependencies.add", + "dependencies.blocking", + "dependencies.count", + "dependencies.cycles", + "dependencies.list", + "dependencies.remove", + "dependencies.tree", + "events.list", + "events.watch", + "issues.addComment", + "issues.batchApply", + "issues.batchClose", + "issues.batchCreate", + "issues.casMetadata", + "issues.claim", + "issues.claimNext", + "issues.close", + "issues.count", + "issues.create", + "issues.delete", + "issues.get", + "issues.list", + "issues.list.sort", + "issues.query", + "issues.related", + "issues.release", + "issues.reopen", + "issues.sweep", + "issues.update", + "memories.forget", + "memories.get", + "memories.list", + "memories.remember", + "policy.external_dependencies", + "project.enforce", + "ready.count", + "ready.list", + "stats.get" + ], + "context_members": [ + "api_version", + "backend", + "bd_version", + "beads_dir", + "capabilities", + "database", + "dolt_mode", + "project_id", + "repo_root", + "schema_version" + ], + "operations": [ + { + "method": "GET", + "path": "/healthz", + "operation_id": "health", + "query": [], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/config", + "operation_id": "listSettings", + "query": [], + "body": [] + }, + { + "method": "DELETE", + "path": "/v0/beads/config/{key}", + "operation_id": "unsetSetting", + "query": [], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/config/{key}", + "operation_id": "getSetting", + "query": [], + "body": [] + }, + { + "method": "PUT", + "path": "/v0/beads/config/{key}", + "operation_id": "setSetting", + "query": [], + "body": [ + "value" + ] + }, + { + "method": "GET", + "path": "/v0/beads/context", + "operation_id": "getContext", + "query": [], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/dependencies", + "operation_id": "listDependencies", + "query": [ + "issue_id", + "type" + ], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/dependencies/blocking", + "operation_id": "listBlockingAnnotations", + "query": [ + "issue_id" + ], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/dependencies/cycles", + "operation_id": "listDependencyCycles", + "query": [], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/dependencies/tree", + "operation_id": "getDependencyTree", + "query": [ + "direction", + "max_depth", + "root_id", + "status" + ], + "body": [] + }, + { + "method": "POST", + "path": "/v0/beads/dependencies:add", + "operation_id": "addDependencies", + "query": [], + "body": [ + "actor", + "edges" + ] + }, + { + "method": "GET", + "path": "/v0/beads/dependencies:count", + "operation_id": "countDependencyEdges", + "query": [ + "direction", + "issue_id", + "status", + "type" + ], + "body": [] + }, + { + "method": "POST", + "path": "/v0/beads/dependencies:remove", + "operation_id": "removeDependency", + "query": [], + "body": [ + "actor", + "depends_on_id", + "issue_id" + ] + }, + { + "method": "GET", + "path": "/v0/beads/events", + "operation_id": "listEvents", + "query": [ + "limit", + "since" + ], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/events:watch", + "operation_id": "watchEvents", + "query": [ + "since" + ], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/issues", + "operation_id": "listIssues", + "query": [ + "all", + "assignee", + "brief", + "created_after", + "created_before", + "cursor", + "exclude_label", + "has_metadata_key", + "include_ephemeral", + "include_gates", + "include_infra", + "include_templates", + "label", + "label_any", + "limit", + "metadata_field", + "parent", + "reverse", + "sort", + "status", + "type" + ], + "body": [] + }, + { + "method": "POST", + "path": "/v0/beads/issues", + "operation_id": "createIssue", + "query": [], + "body": [ + "acceptance_criteria", + "actor", + "assignee", + "defer_until", + "dependencies", + "description", + "design", + "due_at", + "ephemeral", + "estimated_minutes", + "external_ref", + "force_id_prefix", + "id", + "inherit_labels_from_parent", + "issue_type", + "labels", + "metadata", + "no_history", + "notes", + "owner", + "parent_id", + "priority", + "sender", + "status", + "title", + "waits_for" + ] + }, + { + "method": "GET", + "path": "/v0/beads/issues/{id}", + "operation_id": "getIssue", + "query": [ + "brief_deps", + "include_comments", + "include_dependents" + ], + "body": [] + }, + { + "method": "PATCH", + "path": "/v0/beads/issues/{id}", + "operation_id": "updateIssue", + "query": [], + "body": [ + "actor", + "expected_assignee", + "expected_status", + "expected_version", + "force_assignee_transfer", + "force_close_policy", + "patch" + ] + }, + { + "method": "POST", + "path": "/v0/beads/issues/{id}/comments", + "operation_id": "addComment", + "query": [], + "body": [ + "author", + "text" + ] + }, + { + "method": "GET", + "path": "/v0/beads/issues/{id}/related", + "operation_id": "listRelatedIssues", + "query": [ + "direction", + "type" + ], + "body": [] + }, + { + "method": "POST", + "path": "/v0/beads/issues/{id}:casMetadata", + "operation_id": "compareAndSetMetadata", + "query": [], + "body": [ + "actor", + "expected", + "key", + "value" + ] + }, + { + "method": "POST", + "path": "/v0/beads/issues/{id}:claim", + "operation_id": "claimIssue", + "query": [], + "body": [ + "actor" + ] + }, + { + "method": "POST", + "path": "/v0/beads/issues/{id}:close", + "operation_id": "closeIssue", + "query": [], + "body": [ + "actor", + "expected_version", + "force", + "reason", + "session" + ] + }, + { + "method": "POST", + "path": "/v0/beads/issues/{id}:release", + "operation_id": "releaseIssue", + "query": [], + "body": [ + "actor", + "expected_assignee", + "force" + ] + }, + { + "method": "POST", + "path": "/v0/beads/issues/{id}:reopen", + "operation_id": "reopenIssue", + "query": [], + "body": [ + "actor", + "expected_version", + "reason" + ] + }, + { + "method": "POST", + "path": "/v0/beads/issues:batchApply", + "operation_id": "applyBatch", + "query": [], + "body": [ + "actor", + "force_id_prefix", + "items", + "provenance", + "skip_per_edge_cycle_check" + ] + }, + { + "method": "POST", + "path": "/v0/beads/issues:batchClose", + "operation_id": "batchCloseIssues", + "query": [], + "body": [ + "actor", + "claim_next", + "force", + "items", + "session" + ] + }, + { + "method": "POST", + "path": "/v0/beads/issues:batchCreate", + "operation_id": "batchCreateIssues", + "query": [], + "body": [ + "actor", + "items" + ] + }, + { + "method": "POST", + "path": "/v0/beads/issues:claimNext", + "operation_id": "claimNextIssue", + "query": [ + "assignee", + "exclude_label", + "exclude_type", + "has_metadata_key", + "include_deferred", + "include_ephemeral", + "label", + "label_any", + "label_pattern", + "label_regex", + "metadata_field", + "parent", + "priority", + "sort", + "type", + "unassigned" + ], + "body": [ + "actor" + ] + }, + { + "method": "GET", + "path": "/v0/beads/issues:count", + "operation_id": "countIssues", + "query": [ + "assignee", + "closed_after", + "closed_before", + "created_after", + "created_before", + "desc_contains", + "empty_description", + "group_by", + "id", + "include_infra", + "label", + "label_any", + "metadata_field", + "no_assignee", + "no_labels", + "notes_contains", + "priority", + "priority_max", + "priority_min", + "status", + "title", + "title_contains", + "type", + "updated_after", + "updated_before" + ], + "body": [] + }, + { + "method": "POST", + "path": "/v0/beads/issues:delete", + "operation_id": "deleteIssues", + "query": [], + "body": [ + "actor", + "cascade", + "dry_run", + "expected_version", + "force", + "ids" + ] + }, + { + "method": "GET", + "path": "/v0/beads/issues:query", + "operation_id": "queryIssues", + "query": [ + "all", + "limit", + "q", + "reverse", + "sort" + ], + "body": [] + }, + { + "method": "POST", + "path": "/v0/beads/issues:sweep", + "operation_id": "sweepIssues", + "query": [], + "body": [ + "actor", + "closed_before", + "dry_run", + "pattern", + "protect_referenced", + "tier" + ] + }, + { + "method": "GET", + "path": "/v0/beads/memories", + "operation_id": "listMemories", + "query": [ + "search" + ], + "body": [] + }, + { + "method": "POST", + "path": "/v0/beads/memories", + "operation_id": "rememberMemory", + "query": [], + "body": [ + "content", + "key" + ] + }, + { + "method": "DELETE", + "path": "/v0/beads/memories/{key}", + "operation_id": "forgetMemory", + "query": [], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/memories/{key}", + "operation_id": "getMemory", + "query": [], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/ready", + "operation_id": "listReadyWork", + "query": [ + "assignee", + "brief", + "exclude_label", + "exclude_type", + "has_metadata_key", + "include_deferred", + "include_ephemeral", + "label", + "label_any", + "label_pattern", + "label_regex", + "limit", + "metadata_field", + "parent", + "priority", + "sort", + "type", + "unassigned" + ], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/ready:count", + "operation_id": "countReadyWork", + "query": [ + "assignee", + "exclude_label", + "exclude_type", + "has_metadata_key", + "include_deferred", + "include_ephemeral", + "label", + "label_any", + "label_pattern", + "label_regex", + "metadata_field", + "parent", + "priority", + "type", + "unassigned" + ], + "body": [] + }, + { + "method": "GET", + "path": "/v0/beads/stats", + "operation_id": "getStats", + "query": [ + "assignee", + "skip_blocked" + ], + "body": [] + } + ] +} \ No newline at end of file diff --git a/backend/http/credential.go b/backend/http/credential.go new file mode 100644 index 000000000..3290fd3b7 --- /dev/null +++ b/backend/http/credential.go @@ -0,0 +1,66 @@ +package bdhttp + +import ( + "net/url" + + "github.com/steveyegge/beads/internal/httpclient" +) + +// CredentialProvider authorizes outbound requests to a bd serve. +// +// An implementation must be safe for concurrent use, must never log or +// persist a secret, and must FAIL CLOSED: a configured source that errors +// aborts the request rather than silently downgrading to an unauthenticated +// one. +// +// Authorize is called once per request, not once per attempt: a read whose +// first attempt stalls or has its connection reset is resent once with the +// same headers, up to the client's overall timeout later. A provider whose +// credentials are single-use or short-lived should expect that resend to draw +// a 401, which reaches Refresh like any other. +type CredentialProvider = httpclient.CredentialProvider + +const ( + // TokenEnv carries the bearer token itself, the highest rung of the + // built-in ladder. + // #nosec G101 -- the NAME of an environment variable, not a credential. + TokenEnv = httpclient.TokenEnv + // TokenCommandEnv names a helper that prints a token, either bare or in + // the kubectl ExecCredential envelope {"token","expirationTimestamp"}. + // #nosec G101 -- the NAME of an environment variable, not a credential. + TokenCommandEnv = httpclient.TokenCommandEnv +) + +// BearerProvider is the built-in credential ladder: TokenEnv, then +// TokenCommandEnv, then the credentials file's [host:port] section, then no +// credential at all (the tip OSS server's loopback-trust posture, a +// legitimate answer and not a failure). +type BearerProvider = httpclient.BearerProvider + +// NewBearerProvider builds the built-in ladder for a server. Open and +// Handshake already dial with it; it is exported so an embedder that wants to +// WRAP the default (decorate it for one target, delegate to it for the rest) +// does not have to reimplement it. +func NewBearerProvider(base *url.URL) *BearerProvider { + return httpclient.NewBearerProvider(base) +} + +// ProvidedCredential adapts a CredentialProvider into the opaque +// backends.Credential marker interface, so it can be carried through +// beads.OpenOptions / beads.OpenBestAvailableWith (and, directly, through +// backends.OpenOptions) to the registered "http" backend's OpenWith hook +// Register installs. +// +// A multi-tenant embedder (for example gc, Gas City: one process serving many +// workspaces, called "cities") that wants a distinct credential per workspace +// wraps that workspace's own provider in a ProvidedCredential when it opens +// through the registry (the direct door takes the provider itself, as +// Options.Credential): the registered dialer Register installs is +// process-wide and cannot hold one credential per tenant, but the per-open +// OpenWith seam can, and this is the opaque wrapper type that seam +// recognizes. Either way the supplied provider is the ONLY credential the +// open uses, and no ambient credential, CA or plaintext grant is read; see the +// package doc's "Credentials" section. See httpclient.ResolveCredential and +// backends.OpenOptions.Credential's own doc comment for the single-tenant +// ambient-ladder default this exists to opt out of. +type ProvidedCredential = httpclient.ProvidedCredential diff --git a/backend/http/e2e_blocked_flags_test.go b/backend/http/e2e_blocked_flags_test.go new file mode 100644 index 000000000..1943bd676 --- /dev/null +++ b/backend/http/e2e_blocked_flags_test.go @@ -0,0 +1,287 @@ +//go:build cgo + +package bdhttp_test + +import ( + "context" + "encoding/json" + "errors" + "os/exec" + "reflect" + "sort" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/storage/issueops" +) + +// runBDStdin is runBD with stdin. +func runBDStdin(t *testing.T, f *remoteRolesFixture, stdin string, args ...string) bdResult { + t.Helper() + cmd := exec.Command(f.bin, args...) + cmd.Dir = f.dir + cmd.Env = minimalBDEnv(f.dir) + cmd.Stdin = strings.NewReader(stdin) + var o, e strings.Builder + cmd.Stdout, cmd.Stderr = &o, &e + err := cmd.Run() + code := 0 + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + code = exitErr.ExitCode() + } else if err != nil { + t.Fatalf("run bd %v: %v", args, err) + } + return bdResult{stdout: o.String(), stderr: e.String(), code: code} +} + +type blockedFlagRow struct { + ID string `json:"id"` + IsBlocked bool `json:"is_blocked"` +} + +func parseBlockedFlags(t *testing.T, out string) []blockedFlagRow { + t.Helper() + var rows []blockedFlagRow + if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &rows); err != nil { + t.Fatalf("parse bd blocked --flags --json: %v\n%s", err, out) + } + if rows == nil { + t.Fatalf("bd blocked --flags --json printed null, want an array: %s", out) + } + return rows +} + +// flagStdin is every id the fixture created, in title order, plus an id that +// names no row, a blank line and a repeat: the omitted, ignored and collapsed +// cases. +func flagStdin(f *remoteRolesFixture) string { + titles := make([]string, 0, len(f.ids)) + for title := range f.ids { + titles = append(titles, title) + } + sort.Strings(titles) + var b strings.Builder + for _, title := range titles { + b.WriteString(f.ids[title] + "\n") + } + b.WriteString("\n " + f.ids[titles[0]] + " \ne2e-no-such-row\n") + return b.String() +} + +// TestE2E_BlockedFlagsOverHTTP runs `bd blocked --flags --json` (the blocked +// flag per id read from stdin, the readiness column gc projects) through the +// real `bd` binary against an in-process `bd serve` and against a local +// embedded workspace holding the same graph, and requires the same JSON once +// each generated id is mapped to its title. Over HTTP the read is +// listBlockingAnnotations with is_blocked; an older server's handshake is +// refused before the dial, naming dependencies.blocking.isBlocked. +// +// It also pins that this is the FLAG and not the listing: a row whose stored +// flag is set with no nameable blocker reads true here and is absent from +// `bd blocked --json`. +func TestE2E_BlockedFlagsOverHTTP(t *testing.T) { + skipUnlessEmbeddedDolt(t) + bin := buildBD(t) + + seed := func(f *remoteRolesFixture) { + f.seed() + blocker := f.create("blocker", "-t", "task") + gp := f.create("gate-parent", "-t", "epic") + kid := f.create("gate-kid", "-t", "task") + f.mustRun(nil, "dep", "add", kid, gp, "--type", "parent-child") + f.mustRun(nil, "dep", "add", gp, blocker) + } + + t.Run("served equals local", func(t *testing.T) { + addr := startE2EServer(t) + local := newEmbeddedFixture(t, bin) + seed(local) + served := newHTTPFixture(t, bin, addr) + seed(served) + + lr := runBDStdin(t, local, flagStdin(local), "blocked", "--flags", "--json") + sr := runBDStdin(t, served, flagStdin(served), "blocked", "--flags", "--json") + if lr.code != 0 || sr.code != 0 { + t.Fatalf("exit local=%d served=%d\nlocal: %s %s\nserved: %s %s", lr.code, sr.code, lr.stdout, lr.stderr, sr.stdout, sr.stderr) + } + normalize := func(f *remoteRolesFixture, rows []blockedFlagRow) []blockedFlagRow { + titleOf := map[string]string{} + for title, id := range f.ids { + titleOf[id] = title + } + out := make([]blockedFlagRow, 0, len(rows)) + for _, row := range rows { + if title, ok := titleOf[row.ID]; ok { + row.ID = title + } + out = append(out, row) + } + return out + } + want := normalize(local, parseBlockedFlags(t, lr.stdout)) + got := normalize(served, parseBlockedFlags(t, sr.stdout)) + if !reflect.DeepEqual(want, got) { + t.Errorf("served bd blocked --flags --json differs from the local command:\nlocal: %v\nserved: %v", want, got) + } + if len(want) != len(local.ids) { + t.Errorf("local answered %d rows for %d ids (the unknown id omitted, the repeat collapsed): %v", len(want), len(local.ids), want) + } + blocked := map[string]bool{} + for _, row := range got { + blocked[row.ID] = row.IsBlocked + } + for title, wantBlocked := range map[string]bool{ + "loner": true, "child-x": true, "gate-parent": true, "gate-kid": true, + "blocker": false, "child-b": false, "parent": false, + } { + if blocked[title] != wantBlocked { + t.Errorf("%s is_blocked = %v, want %v (rows %v)", title, blocked[title], wantBlocked, got) + } + } + // Byte-for-byte the same members in the same order. + if strings.Count(lr.stdout, "\n") != strings.Count(sr.stdout, "\n") { + t.Errorf("line counts differ:\nlocal:\n%s\nserved:\n%s", lr.stdout, sr.stdout) + } + // Nothing piped is an empty array. + if r := runBDStdin(t, served, "", "blocked", "--flags", "--json"); r.code != 0 || strings.TrimSpace(r.stdout) != "[]" { + t.Errorf("empty stdin: exit %d stdout %q, want [] and exit 0", r.code, r.stdout) + } + // The listing's filters are refused, not silently ignored. + if r := runBDStdin(t, served, "x\n", "blocked", "--flags", "--json", "--label", "a"); r.code != 1 { + t.Errorf("--flags --label exited %d, want 1: %s", r.code, r.stdout) + } + }) + + t.Run("the flag, not the listing", func(t *testing.T) { + addr, reference := startE2EServerWithStore(t, e2eProjectID, e2eDatabase) + served := newHTTPFixture(t, bin, addr) + stale := served.create("stale") + if err := reference.RunEventsMaintenanceTx(context.Background(), func(ctx context.Context, tx issueops.DBTX) error { + _, err := tx.ExecContext(ctx, "UPDATE issues SET is_blocked = 1 WHERE id = ?", stale) + return err + }); err != nil { + t.Fatalf("set the stale flag: %v", err) + } + rows := parseBlockedFlags(t, runBDStdin(t, served, stale+"\n", "blocked", "--flags", "--json").stdout) + if len(rows) != 1 || rows[0].ID != stale || !rows[0].IsBlocked { + t.Errorf("--flags for a stale-flagged row = %v, want [{%s true}]", rows, stale) + } + listing := served.mustRun(nil, "blocked", "--json").stdout + if strings.Contains(listing, stale) { + t.Errorf("bd blocked --json lists %s, which has no nameable blocker: %s", stale, listing) + } + }) + + t.Run("raw is the stored column", func(t *testing.T) { + addr, reference := startE2EServerWithStore(t, e2eProjectID, e2eDatabase) + local := newEmbeddedFixture(t, bin) + seed(local) + served := newHTTPFixture(t, bin, addr) + seed(served) + + flagsOf := func(f *remoteRolesFixture, stdin string, args ...string) map[string]bool { + t.Helper() + r := runBDStdin(t, f, stdin, append([]string{"blocked", "--flags", "--json"}, args...)...) + if r.code != 0 { + t.Fatalf("bd blocked --flags --json %v exited %d: %s %s", args, r.code, r.stdout, r.stderr) + } + titleOf := map[string]string{} + for title, id := range f.ids { + titleOf[id] = title + } + out := map[string]bool{} + for _, row := range parseBlockedFlags(t, r.stdout) { + key := row.ID + if title, ok := titleOf[row.ID]; ok { + key = title + } + out[key] = row.IsBlocked + } + return out + } + + localRaw := flagsOf(local, flagStdin(local), "--raw") + servedRaw := flagsOf(served, flagStdin(served), "--raw") + if !reflect.DeepEqual(localRaw, servedRaw) { + t.Errorf("served --raw differs from local --raw:\nlocal: %v\nserved: %v", localRaw, servedRaw) + } + lr := runBDStdin(t, local, flagStdin(local), "blocked", "--flags", "--json", "--raw") + sr := runBDStdin(t, served, flagStdin(served), "blocked", "--flags", "--json", "--raw") + if strings.Count(lr.stdout, "\n") != strings.Count(sr.stdout, "\n") { + t.Errorf("--raw line counts differ:\nlocal:\n%s\nserved:\n%s", lr.stdout, sr.stdout) + } + + // child-x is blocked ONLY by an unsatisfied external ref: the policy + // flag says blocked, the stored column does not. + decorated := flagsOf(served, flagStdin(served)) + if !decorated["child-x"] || servedRaw["child-x"] || localRaw["child-x"] { + t.Errorf("child-x (externally blocked only): --flags %v, --raw served %v local %v; want true, false, false", + decorated["child-x"], servedRaw["child-x"], localRaw["child-x"]) + } + // Locally blocked rows read the same either way. + for _, title := range []string{"loner", "gate-parent", "gate-kid", "blocker"} { + if decorated[title] != servedRaw[title] { + t.Errorf("%s: --flags %v, --raw %v; a local blocker is the column", title, decorated[title], servedRaw[title]) + } + } + + // A stale flag (set, no blocker) is the column, so both read true. + stale := served.create("stale") + if err := reference.RunEventsMaintenanceTx(context.Background(), func(ctx context.Context, tx issueops.DBTX) error { + _, err := tx.ExecContext(ctx, "UPDATE issues SET is_blocked = 1 WHERE id = ?", stale) + return err + }); err != nil { + t.Fatalf("set the stale flag: %v", err) + } + if got := flagsOf(served, stale+"\n", "--raw"); !got["stale"] { + t.Errorf("--raw for the stale-flagged row = %v, want true", got) + } + if got := flagsOf(served, stale+"\n"); !got["stale"] { + t.Errorf("--flags for the stale-flagged row = %v, want true", got) + } + + // --raw qualifies --flags only. + if r := runBDStdin(t, served, "", "blocked", "--json", "--raw"); r.code != 1 || !strings.Contains(r.stdout+r.stderr, "--raw") { + t.Errorf("bd blocked --raw without --flags: exit %d %s %s, want exit 1 naming --raw", r.code, r.stdout, r.stderr) + } + + // A server that applies the policy answers the decorated flag and the + // wire cannot ask it for the column: --raw is refused there, before + // the annotation read, rather than answered with the policy flag. + proxyAddr, counter := startMaskingProxy(t, addr, func(body map[string]any) { + caps, _ := body["capabilities"].([]any) + body["capabilities"] = append(caps, "policy.external_dependencies") + }) + enforced := newHTTPFixture(t, bin, proxyAddr) + counter.reset() + r := runBDStdin(t, enforced, served.ids["child-x"]+"\n", "blocked", "--flags", "--json", "--raw") + if r.code != 1 || !strings.Contains(r.stdout+r.stderr, "policy.external_dependencies") { + t.Errorf("--raw against a policy server: exit %d %s %s, want exit 1 naming the policy token", r.code, r.stdout, r.stderr) + } + for _, p := range counter.snapshot() { + if strings.Contains(p, "/v0/beads/dependencies/blocking") { + t.Errorf("a refused --raw dialed %s", p) + } + } + }) + + t.Run("older server mask", func(t *testing.T) { + addr := startE2EServer(t) + proxyAddr, counter := startMaskingProxy(t, addr, mcContextMask) + f := newHTTPFixture(t, bin, proxyAddr) + counter.reset() + r := runBDStdin(t, f, "e2e-anything\n", "blocked", "--flags", "--json") + if r.code != 1 { + t.Fatalf("bd blocked --flags against a server without the token exited %d, want 1: %s", r.code, r.stdout) + } + if !strings.Contains(r.stdout+r.stderr, "dependencies.blocking.isBlocked") { + t.Errorf("refusal does not name the missing capability: stdout=%s stderr=%s", r.stdout, r.stderr) + } + for _, p := range counter.snapshot() { + if strings.Contains(p, "/v0/beads/dependencies/blocking") { + t.Errorf("a refused bd blocked --flags dialed %s", p) + } + } + }) +} diff --git a/backend/http/e2e_blocked_test.go b/backend/http/e2e_blocked_test.go new file mode 100644 index 000000000..786379fba --- /dev/null +++ b/backend/http/e2e_blocked_test.go @@ -0,0 +1,229 @@ +//go:build cgo + +package bdhttp_test + +import ( + "encoding/json" + "reflect" + "slices" + "strings" + "testing" +) + +// TestE2E_BlockedOverHTTP runs `bd blocked --json` (the blocked door gc's +// readiness projection reads) through the real `bd` binary against an +// in-process `bd serve`, and against a local embedded workspace holding the +// same graph. +// +// Over HTTP the CLI takes the store's BlockedLister, which dials +// GET /v0/beads/blocked behind blocked.list. The two answers must be the same +// JSON once the values that cannot agree between two workspaces (each row's +// generated id, and its timestamps) are mapped out: the same rows, the same +// members, the same blockers (local, parent-attributed and external), in the +// same order. Against a server that does not advertise blocked.list (an older +// server's handshake) the client refuses before the dial, naming the token. +func TestE2E_BlockedOverHTTP(t *testing.T) { + skipUnlessEmbeddedDolt(t) + bin := buildBD(t) + addr := startE2EServer(t) + + seedBlocked := func(f *remoteRolesFixture) { + f.seed() + // A plain blocks edge, a blocked parent's child attributed to the + // parent, and a labelled blocked row for the filter arms. + blocker := f.create("blocker", "-t", "task", "-p", "1") + gp := f.create("gate-parent", "-t", "epic", "-p", "2") + // Its own priority: rows tied on priority and created_at fall to the + // id order, and ids are generated per workspace, so a tie would order + // the two workspaces differently. + kid := f.create("gate-kid", "-t", "task", "-p", "3") + tagged := f.create("tagged", "-t", "task", "-p", "1", "-l", "lane:a") + // Blocked by nothing but an unsatisfied external ref, as child-x is, + // and labelled: the decorator lists such rows itself, after the label + // query ran, so the filter arms must judge them too. + extTagged := f.create("ext-tagged", "-t", "task", "-p", "4", "-l", "lane:a") + f.mustRun(nil, "dep", "add", kid, gp, "--type", "parent-child") + f.mustRun(nil, "dep", "add", gp, blocker) + f.mustRun(nil, "dep", "add", tagged, blocker) + f.mustRun(nil, "dep", "add", extTagged, "external:other:cap") + } + + local := newEmbeddedFixture(t, bin) + seedBlocked(local) + served := newHTTPFixture(t, bin, addr) + seedBlocked(served) + + for _, args := range [][]string{ + {"blocked", "--json"}, + {"blocked", "--json", "--label", "lane:a"}, + {"blocked", "--json", "--label-any", "lane:a"}, + {"blocked", "--json", "--exclude-label", "lane:a"}, + {"blocked", "--json", "--parent", "{gate-parent}"}, + {"blocked", "--json", "--label", "no-such-label"}, + } { + t.Run(strings.Join(args[1:], " "), func(t *testing.T) { + want := local.mustRun(nil, local.expand(args)...).stdout + got := served.mustRun(nil, served.expand(args)...).stdout + if strings.TrimSpace(want) == "null" || strings.TrimSpace(got) == "null" { + t.Fatalf("bd blocked --json printed null: local=%s served=%s", want, got) + } + if w, g := normalizeBlocked(t, local, want), normalizeBlocked(t, served, got); !reflect.DeepEqual(w, g) { + t.Errorf("served bd blocked --json differs from the local command:\nlocal: %v\nserved: %v", w, g) + } + if w, g := blockedKeyOrder(t, want), blockedKeyOrder(t, got); !reflect.DeepEqual(w, g) { + t.Errorf("served member order %v differs from the local command's %v", g, w) + } + }) + } + + t.Run("names the external blocker", func(t *testing.T) { + got := normalizeBlocked(t, served, served.mustRun(nil, "blocked", "--json").stdout) + found := false + for _, row := range got { + if row["id"] == "child-x" { + found = reflect.DeepEqual(row["blocked_by"], []any{"external:other:cap"}) + } + } + if !found { + t.Errorf("served bd blocked --json does not list child-x blocked by its external ref: %v", got) + } + }) + + // The arms above compare the two answers, which agree just as well when + // both list a row the filter rules out. These pin which rows each filter + // leaves, the external-only ones (child-x unlabelled, ext-tagged + // labelled) among them. + for _, tc := range []struct { + args []string + want []string // the whole listing, when set + listed, ruled []string + }{ + {args: []string{"--label", "lane:a"}, want: []string{"ext-tagged", "tagged"}}, + {args: []string{"--label-any", "lane:a"}, want: []string{"ext-tagged", "tagged"}}, + {args: []string{"--label", "no-such-label"}, want: []string{}}, + {args: []string{"--exclude-label", "lane:a"}, listed: []string{"child-x"}, ruled: []string{"ext-tagged", "tagged"}}, + } { + t.Run("filters external-only rows "+strings.Join(tc.args, " "), func(t *testing.T) { + for _, f := range []struct { + name string + f *remoteRolesFixture + }{{"local", local}, {"served", served}} { + got := f.f.titlesOf(f.f.mustRun(nil, append([]string{"blocked", "--json"}, tc.args...)...).stdout) + if tc.want != nil && !slices.Equal(got, tc.want) { + t.Errorf("%s bd blocked %s listed %v, want %v", f.name, strings.Join(tc.args, " "), got, tc.want) + } + for _, title := range tc.listed { + if !slices.Contains(got, title) { + t.Errorf("%s bd blocked %s does not list %s: %v", f.name, strings.Join(tc.args, " "), title, got) + } + } + for _, title := range tc.ruled { + if slices.Contains(got, title) { + t.Errorf("%s bd blocked %s lists %s, which the filter rules out: %v", f.name, strings.Join(tc.args, " "), title, got) + } + } + } + }) + } + + t.Run("older server mask", func(t *testing.T) { + proxyAddr, counter := startMaskingProxy(t, addr, mcContextMask) + f := newHTTPFixture(t, bin, proxyAddr) + counter.reset() + r := f.run(nil, "blocked", "--json") + if r.code != 1 { + t.Fatalf("bd blocked against a server without blocked.list exited %d, want 1: %s", r.code, r.stdout) + } + if !strings.Contains(r.stdout+r.stderr, "blocked.list") { + t.Errorf("refusal does not name the missing capability: stdout=%s stderr=%s", r.stdout, r.stderr) + } + for _, p := range counter.snapshot() { + if strings.Contains(p, "/v0/beads/blocked") { + t.Errorf("a refused bd blocked dialed %s; the refusal must come before the dial", p) + } + } + }) +} + +// normalizeBlocked parses `bd blocked --json` and maps out what two +// workspaces cannot share: each id (and each blocker id) becomes the title the +// fixture created it under, and every timestamp member is blanked. +func normalizeBlocked(t *testing.T, f *remoteRolesFixture, out string) []map[string]any { + t.Helper() + var rows []map[string]any + if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &rows); err != nil { + t.Fatalf("parse bd blocked --json: %v\n%s", err, out) + } + titleOf := map[string]string{} + for title, id := range f.ids { + titleOf[id] = title + } + var walk func(key string, v any) any + walk = func(key string, v any) any { + switch v := v.(type) { + case map[string]any: + for k, inner := range v { + v[k] = walk(k, inner) + } + return v + case []any: + for i := range v { + v[i] = walk("", v[i]) + } + return v + case string: + if strings.HasSuffix(key, "_at") { + return " " + aliases: ["fart"] + short: "Bond two protos or molecules together" + hidden: false + runnable: true + long: + | Bond two protos or molecules to create a compound. + | + | The bond command is polymorphic - it handles different operand types: + | + | formula + formula → cook both, compound proto + | formula + proto → cook formula, compound proto + | formula + mol → cook formula, spawn and attach + | proto + proto → compound proto (reusable template) + | proto + mol → spawn proto, attach to molecule + | mol + proto → spawn proto, attach to molecule + | mol + mol → join into compound molecule + | + | Formula names (e.g., mol-polecat-arm) are cooked inline as ephemeral protos. + | This avoids needing pre-cooked proto beads in the database. + | + | Bond types: + | sequential (default) - B runs after A completes + | parallel - B runs alongside A + | conditional - B runs only if A fails + | + | With --ref, the spawned proto arm is nested inside the molecule operand + | rather than ordered against it - whichever side of the bond that is - so a + | sequential --ref arm carries no ordering: it is ready as soon as it is + | spawned. Ordering a nested arm against its own container is unsatisfiable + | in both directions (the arm waits for the molecule to close; the molecule + | cannot close while it holds an open arm). --ref is refused with --type + | conditional, which has no safe degradation - omit --ref to bond a + | conditional arm as a sibling. + | + | Phase control: + | By default, spawned protos follow the target's phase: + | - Attaching to mol (Ephemeral=false) → spawns as persistent (Ephemeral=false) + | - Attaching to ephemeral issue (Ephemeral=true) → spawns as ephemeral (Ephemeral=true) + | + | Override with: + | --pour Force spawn as liquid (persistent, Ephemeral=false) + | --ephemeral Force spawn as vapor (ephemeral, Ephemeral=true, excluded from Dolt sync via dolt_ignore) + | + | Dynamic bonding (Christmas Ornament pattern): + | Use --ref to specify a custom child reference with variable substitution. + | This creates IDs like "parent.child-ref" instead of random hashes. + | + | Example: + | bd mol bond mol-worker-arm bd-patrol --ref arm-{{worker_name}} --var worker_name=ace + | # Creates: bd-patrol.arm-ace (and children like bd-patrol.arm-ace.capture) + | + | Use cases: + | - Found important bug during patrol? Use --pour to persist it + | - Need ephemeral diagnostic on persistent feature? Use --ephemeral + | - Spawning per-worker arms on a patrol? Use --ref for readable IDs + | + | Examples: + | bd mol bond mol-feature mol-deploy # Compound proto + | bd mol bond mol-feature mol-deploy --type parallel # Run in parallel + | bd mol bond mol-feature bd-abc123 # Attach proto to molecule + | bd mol bond bd-abc123 bd-def456 # Join two molecules + | bd mol bond mol-critical-bug wisp-patrol --pour # Persist found bug + | bd mol bond mol-temp-check bd-feature --ephemeral # Ephemeral diagnostic + | bd mol bond mol-arm bd-patrol --ref arm-{{name}} --var name=ace # Dynamic child ID + flag --as type=string default="" usage="Custom title for compound proto (proto+proto only)" + flag --dry-run type=bool default="false" usage="Preview what would be created" + flag --ephemeral type=bool default="false" usage="Force spawn as vapor (ephemeral, Ephemeral=true)" + flag --pour type=bool default="false" usage="Force spawn as liquid (persistent, Ephemeral=false)" + flag --ref type=string default="" usage="Custom child reference with {{var}} substitution (e.g., arm-{{polecat_name}})" + flag --type type=string default="sequential" usage="Bond type: sequential, parallel, or conditional" + flag --var type=stringArray default="[]" usage="Variable substitution for spawned protos (key=value)" + +bd mol burn + use: "burn [molecule-id...]" + short: "Delete a molecule without creating a digest" + hidden: false + runnable: true + long: + | Burn a molecule, deleting it without creating a digest. + | + | Unlike squash (which creates a permanent digest before deletion), burn + | completely removes the molecule with no trace. Use this for: + | - Abandoned patrol cycles + | - Crashed or failed workflows + | - Test/debug molecules you don't want to preserve + | + | The burn operation differs based on molecule phase: + | - Wisp (ephemeral): Direct delete + | - Mol (persistent): Cascade delete (syncs to remotes) + | + | CAUTION: This is a destructive operation. The molecule's data will be + | permanently lost. If you want to preserve a summary, use 'bd mol squash'. + | + | Example: + | bd mol burn bd-abc123 # Delete molecule with no trace + | bd mol burn bd-abc123 --dry-run # Preview what would be deleted + | bd mol burn bd-abc123 --force # Skip confirmation + | bd mol burn bd-a1 bd-b2 bd-c3 # Batch delete multiple wisps + flag --dry-run type=bool default="false" usage="Preview what would be deleted" + flag --force type=bool default="false" usage="Skip confirmation prompt" + flag --yes -y type=bool default="false" hidden usage="Alias for --force (skip confirmation)" + +bd mol current + use: "current [molecule-id]" + short: "Show current position in molecule workflow" + hidden: false + runnable: true + long: + | Show where you are in a molecule workflow. + | + | If molecule-id is given, show status for that molecule. + | If not given, infer from in_progress issues assigned to current agent. + | + | The output shows all steps with status indicators: + | [done] - Step is complete (closed) + | [current] - Step is in_progress (you are here) + | [ready] - Step is ready to start (unblocked) + | [blocked] - Step is blocked by dependencies + | [pending] - Step is waiting + | + | For large molecules (>100 steps), a summary is shown instead. + | Use --limit or --range to view specific steps: + | bd mol current --limit 50 # Show first 50 steps + | bd mol current --range 100-150 # Show steps 100-150 + flag --for type=string default="" usage="Show molecules for a specific agent/assignee" + flag --limit type=int default="0" usage="Maximum number of steps to display (0 = auto, use 'all' threshold)" + flag --range type=string default="" usage="Display specific step range (e.g., '1-50', '100-150')" + +bd mol distill + use: "distill [formula-name]" + short: "Extract a formula from an existing epic" + hidden: false + runnable: true + long: + | Distill a molecule by extracting a reusable formula from an existing epic. + | + | This is the reverse of pour: instead of formula → molecule, it's molecule → formula. + | + | The distill command: + | 1. Loads the existing epic and all its children + | 2. Converts the structure to a .formula.json file + | 3. Replaces concrete values with {{variable}} placeholders (via --var flags) + | + | Use cases: + | - Team develops good workflow organically, wants to reuse it + | - Capture tribal knowledge as executable templates + | - Create starting point for similar future work + | + | Variable syntax (both work - we detect which side is the concrete value): + | --var branch=feature-auth Spawn-style: variable=value (recommended) + | --var feature-auth=branch Substitution-style: value=variable + | + | Output locations (first writable wins): + | 1. /formulas/ (project-level, default) + | 2. /.beads/formulas/ (repo-local formulas) + | 3. ~/.beads/formulas/ (user-level, if project not writable) + | + | Examples: + | bd mol distill bd-o5xe my-workflow + | bd mol distill bd-abc release-workflow --var feature_name=auth-refactor + flag --dry-run type=bool default="false" usage="Preview what would be created" + flag --output type=string default="" usage="Output directory for formula file" + flag --var type=stringArray default="[]" usage="Replace value with {{variable}} placeholder (variable=value)" + +bd mol last-activity + use: "last-activity " + short: "Show last activity timestamp for a molecule" + hidden: false + runnable: true + long: + | Show the most recent activity timestamp for a molecule. + | + | Returns the timestamp of the most recent change to any step in the molecule, + | making it easy to detect stale or stuck molecules. + | + | Activity sources: + | step_closed - A step was closed + | step_updated - A step was updated (claimed, edited, etc.) + | molecule_updated - The molecule root itself was updated + | + | Examples: + | bd mol last-activity hq-wisp-0laki + | bd mol last-activity hq-wisp-0laki --json + +bd mol pour + use: "pour " + short: "Instantiate a proto as a persistent mol (solid -> liquid)" + hidden: false + runnable: true + long: + | Pour a proto into a persistent mol - like pouring molten metal into a mold. + | + | This is the chemistry-inspired command for creating PERSISTENT work from templates. + | The resulting mol is stored as persistent beads in the issue database and + | syncs like any other bead (bd dolt push / pull). + | + | Phase transition: Proto (solid) -> pour -> Mol (liquid) + | + | WHEN TO USE POUR vs WISP: + | pour (liquid): Persistent work that needs audit trail + | - Feature implementations spanning multiple sessions + | - Work you may need to reference later + | - Anything worth preserving in git history + | + | wisp (vapor): Ephemeral work that auto-cleans up + | - Release workflows (one-time execution) + | - Operational loops and recurring cycles + | - Health checks and diagnostics + | - Any operational workflow without audit value + | + | TIP: Formulas can specify phase:"vapor" to recommend wisp usage. + | If you pour a vapor-phase formula, you'll get a warning. + | + | Examples: + | bd mol pour mol-feature --var name=auth # Persistent feature work + | bd mol pour mol-review --var pr=123 # Persistent code review + flag --assignee type=string default="" usage="Assign the root issue to this agent/user" + flag --attach type=stringSlice default="[]" usage="Proto to attach after spawning (repeatable)" + flag --attach-type type=string default="sequential" usage="Bond type for attachments: sequential, parallel, or conditional" + flag --dry-run type=bool default="false" usage="Preview what would be created" + flag --var type=stringArray default="[]" usage="Variable substitution (key=value); a name the proto cannot consume is an error" + +bd mol progress + use: "progress [molecule-id]" + short: "Show molecule progress summary" + hidden: false + runnable: true + long: + | Show efficient progress summary for a molecule. + | + | This command uses indexed queries to count progress without loading all steps, + | making it suitable for very large molecules (millions of steps). + | + | If no molecule-id is given, shows progress for any molecule you're working on. + | + | Output includes: + | - Progress: completed / total (percentage) + | - Current step: the in-progress step (if any) + | - Rate: steps/hour based on closure times + | - ETA: estimated time to completion + | + | Example: + | bd mol progress bd-hanoi-xyz + +bd mol ready + use: "ready --gated" + short: "Find molecules ready for gate-resume dispatch" + hidden: false + runnable: true + long: + | Find molecules where a gate has closed and the workflow is ready to resume. + | + | This command discovers molecules waiting at a gate step where: + | 1. The molecule has a gate bead that blocks a step + | 2. The gate bead is now closed (condition satisfied) + | 3. The blocked step is now ready to proceed + | 4. No agent currently has this molecule hooked + | + | This enables discovery-based resume without explicit waiter tracking. + | The patrol system uses this to find and dispatch gate-ready molecules. + | + | Examples: + | bd mol ready --gated # Find all gate-ready molecules + | bd mol ready --gated --json # JSON output for automation + flag --gated type=bool default="false" usage="Find molecules ready for gate-resume dispatch (always on for this subcommand)" + +bd mol seed + use: "seed " + short: "Verify formula accessibility" + hidden: false + runnable: true + long: + | Verify that a formula is accessible and can be cooked. + | + | The seed command checks formula search paths to ensure a formula exists + | and can be loaded. This is useful for verifying system health before + | attempting to spawn work from a formula. + | + | Formula search paths (checked in order): + | 1. /formulas/ (active project) + | 2. /.beads/formulas/ (repo-local formulas) + | 3. ~/.beads/formulas/ (user level) + | 4. $GT_ROOT/.beads/formulas/ (shared workspace root, if GT_ROOT set) + | + | Examples: + | bd mol seed mol-feature # Verify specific formula + | bd mol seed mol-review --var name=test # Verify with variable substitution + flag --var type=stringArray default="[]" usage="Variable substitution for condition filtering (key=value)" + +bd mol show + use: "show " + short: "Show molecule details" + hidden: false + runnable: true + long: + | Show molecule structure and details. + | + | A molecule's steps are the issues linked to its root by parent-child + | dependencies (bd create --parent, bd mol pour); an id that merely looks + | hierarchical, like bd-xyz.4, does not make an issue a step. + | + | The --parallel flag highlights parallelizable steps: + | - Steps with no blocking dependencies can run in parallel + | - Shows which steps are ready to start now + | - Identifies parallel groups (steps that can run concurrently) + | + | Example: + | bd mol show bd-patrol --parallel + flag --parallel -p type=bool default="false" usage="Show parallel step analysis" + +bd mol squash + use: "squash " + short: "Compress molecule execution into a digest" + hidden: false + runnable: true + long: + | Squash a molecule's ephemeral children into a single digest issue. + | + | This command collects all ephemeral child issues of a molecule (Ephemeral=true), + | generates a summary digest, and promotes the wisps to persistent by + | clearing their Wisp flag (or optionally deletes them). + | + | The squash operation: + | 1. Loads the molecule and all its children + | 2. Filters to only wisps (ephemeral issues with Ephemeral=true) + | 3. Generates a digest (summary of work done) + | 4. Creates a permanent digest issue (Ephemeral=false) + | 5. Clears Wisp flag on children (promotes to persistent) + | OR keeps them with --keep-children (default: delete) + | + | AGENT INTEGRATION: + | Use --summary to provide an AI-generated summary. This keeps bd as a pure + | tool - the calling agent (orchestrator worker, Claude Code, etc.) is responsible + | for generating intelligent summaries. Without --summary, a basic concatenation + | of child issue content is used. + | + | This is part of the wisp workflow: spawn creates wisps, + | execution happens, squash compresses the trace into an outcome (digest). + | + | Example: + | bd mol squash bd-abc123 # Squash and promote children + | bd mol squash bd-abc123 --dry-run # Preview what would be squashed + | bd mol squash bd-abc123 --keep-children # Keep wisps after digest + | bd mol squash bd-abc123 --summary "Agent-generated summary of work done" + flag --dry-run type=bool default="false" usage="Preview what would be squashed" + flag --keep-children type=bool default="false" usage="Don't delete ephemeral children after squash" + flag --summary type=string default="" usage="Agent-provided summary (bypasses auto-generation)" + +bd mol stale + use: "stale" + short: "Detect molecules with all children closed but root still open" + hidden: false + runnable: true + long: + | Detect molecules (epics with children) whose children are all closed + | with completing reasons, but the root is still open. + | + | A molecule is considered stale if: + | 1. Every child is closed with a completing reason (not duplicate/wontfix/superseded) + | 2. Root issue is still open + | 3. Not assigned to anyone (optional, use --unassigned) + | 4. Is blocking other work (optional, use --blocking) + | + | Review whether epic scope is actually finished before closing — child + | closure alone does not prove the epic's stated work is done (GH#5026). + | + | Examples: + | bd mol stale # List all stale molecules + | bd mol stale --json # Machine-readable output + | bd mol stale --blocking # Only show those blocking other work + | bd mol stale --unassigned # Only show unassigned molecules + | bd mol stale --all # Include molecules with 0 children + flag --all type=bool default="false" usage="Include molecules with 0 children" + flag --blocking type=bool default="false" usage="Only show molecules blocking other work" + flag --unassigned type=bool default="false" usage="Only show unassigned molecules" + +bd mol wisp + use: "wisp [proto-id]" + short: "Create or manage wisps (ephemeral molecules)" + hidden: false + runnable: true + long: + | Create or manage wisps - EPHEMERAL molecules for operational workflows. + | + | When called with a proto-id argument, creates a wisp from that proto. + | When called with a subcommand (list, gc), manages existing wisps. + | + | Wisps are issues with Ephemeral=true in the main database. They're stored + | locally but NOT synced via git. + | + | WHEN TO USE WISP vs POUR: + | wisp (vapor): Ephemeral work that auto-cleans up + | - Release workflows (one-time execution) + | - Operational loops and recurring cycles + | - Health checks and diagnostics + | - Any operational workflow without audit value + | + | pour (liquid): Persistent work that needs audit trail + | - Feature implementations spanning multiple sessions + | - Work you may need to reference later + | - Anything worth preserving in git history + | + | TIP: Formulas can specify phase:"vapor" to recommend wisp usage. + | If you use pour on a vapor-phase formula, you'll get a warning. + | + | The wisp lifecycle: + | 1. Create: bd mol wisp or bd create --ephemeral + | 2. Execute: Normal bd operations work on wisp issues + | 3. Squash: bd mol squash (clears Ephemeral flag, promotes to persistent) + | 4. Or burn: bd mol burn (deletes without creating digest) + | + | Examples: + | bd mol wisp beads-release --var version=1.0 # Release workflow + | bd mol wisp mol-my-workflow # Ephemeral operational cycle + | bd mol wisp list # List all wisps + | bd mol wisp gc # Garbage collect old wisps + | + | Subcommands: + | list List all wisps in current context + | gc Garbage collect orphaned wisps + flag --dry-run type=bool default="false" usage="Preview what would be created" + flag --root-only type=bool default="false" usage="Create only the root issue (no child step issues)" + flag --var type=stringArray default="[]" usage="Variable substitution (key=value); a name the proto cannot consume is an error" + +bd mol wisp create + use: "create " + short: "Instantiate a proto as a wisp (solid -> vapor)" + hidden: false + runnable: true + long: + | Create a wisp from a proto - sublimation from solid to vapor. + | + | This is the chemistry-inspired command for creating ephemeral work from templates. + | The resulting wisp is stored in the main database with Ephemeral=true and NOT synced via git. + | + | Phase transition: Proto (solid) -> Wisp (vapor) + | + | Use wisp for: + | - Operational loops and recurring cycles + | - Health checks and monitoring + | - One-shot orchestration runs + | - Routine operations with no audit value + | + | The wisp will: + | - Be stored in main database with Ephemeral=true flag + | - NOT be synced via git + | - Either evaporate (burn) or condense to digest (squash) + | + | Examples: + | bd mol wisp create mol-patrol # Ephemeral patrol cycle + | bd mol wisp create mol-health-check # One-time health check + | bd mol wisp create mol-diagnostics --var target=db # Diagnostic run + flag --dry-run type=bool default="false" usage="Preview what would be created" + flag --root-only type=bool default="false" usage="Create only the root issue (no child step issues)" + flag --var type=stringArray default="[]" usage="Variable substitution (key=value); a name the proto cannot consume is an error" + +bd mol wisp gc + use: "gc" + short: "Garbage collect old/abandoned wisps" + hidden: false + runnable: true + long: + | Garbage collect old or abandoned wisps from the database. + | + | A wisp is considered abandoned if: + | - It hasn't been updated in --age duration and is not closed + | - AND it is not live work: blocked steps (waiting on a dependency), pinned + | beads, and any step whose status category is wip (in_progress, blocked, + | hooked) or frozen (deferred, pinned) are never reclaimed by age, no matter + | how long they have been waiting (GH#4394). Custom statuses count by their + | configured category, so only plain open (active) and closed (done) steps + | are age-reclaimable. If the blocked set or the custom-status list cannot be + | read, the GC aborts rather than risk reclaiming live steps. + | + | Wisps that depend on an abandoned wisp are deleted with it, closed ones + | included even without --all, but only if they too haven't been updated in + | --age duration and are not live work. A dependent that is too young is + | spared and loses its edge to the deleted wisp: an open one is collected once + | it ages out, a closed one only by --all, --closed or 'bd purge'. + | + | Abandoned wisps are deleted without creating a digest. Use 'bd mol squash' + | if you want to preserve a summary before garbage collection. + | + | Use --closed to purge ALL closed wisps (regardless of age). This is the + | fastest way to reclaim space from accumulated wisp bloat. Safe by default: + | requires --force to actually delete. + | + | Note: This uses time-based cleanup, appropriate for ephemeral wisps. + | For graph-pressure staleness detection (blocking other work), see 'bd mol stale'. + | + | Examples: + | bd mol wisp gc # Clean abandoned wisps (default: 1h threshold) + | bd mol wisp gc --dry-run # Preview what would be cleaned + | bd mol wisp gc --age 24h # Custom age threshold + | bd mol wisp gc --all # Also clean closed wisps older than threshold + | bd mol wisp gc --closed # Preview closed wisp deletion + | bd mol wisp gc --closed --force # Delete all closed wisps + | bd mol wisp gc --closed --dry-run # Explicit dry-run (same as no --force) + | bd mol wisp gc --exclude-type agent,rig # Protect agent and rig wisps from GC + | bd mol wisp gc --closed --force --exclude-type mol # Delete closed wisps except mol type + flag --age type=string default="1h" usage="Age threshold for abandoned wisp detection" + flag --all type=bool default="false" usage="Also clean closed wisps older than threshold" + flag --closed type=bool default="false" usage="Delete all closed wisps (ignores --age threshold)" + flag --dry-run type=bool default="false" usage="Preview what would be cleaned" + flag --exclude-type type=stringSlice default="[]" usage="Exclude wisps of these types from GC (comma-separated, e.g., agent,rig)" + flag --force -f type=bool default="false" usage="Actually delete (default: preview only)" + +bd mol wisp list + use: "list" + short: "List all wisps in current context" + hidden: false + runnable: true + long: + | List all wisps (ephemeral molecules) in the current context. + | + | Wisps are issues with Ephemeral=true in the main database. They are stored + | locally but not synced via git. + | + | The list shows: + | - ID: Issue ID of the wisp + | - Title: Wisp title + | - Status: Current status (open, in_progress, closed) + | - Started: When the wisp was created + | - Updated: Last modification time + | + | Old wisp detection: + | - Old wisps haven't been updated in 24+ hours + | - Use 'bd mol wisp gc' to clean up old/abandoned wisps + | + | Examples: + | bd mol wisp list # List all wisps + | bd mol wisp list --json # JSON output for programmatic use + | bd mol wisp list --all # Include closed wisps + flag --all type=bool default="false" usage="Include closed wisps" + flag --type type=string default="" usage="Filter by issue type (e.g., agent, task, patrol)" + +bd note + use: "note [text...]" + short: "Append a note to an issue" + group: "issues" + hidden: false + runnable: true + long: + | Append a note to an issue's notes field. + | + | Shorthand for 'bd update --append-notes "text"'. + | + | Examples: + | bd note gt-abc "Fixed the flaky test" + | bd note gt-abc Fixed the flaky test + | echo "note from pipe" | bd note gt-abc --stdin + | bd note gt-abc --file notes.txt + | + | Note: "note" has NO subcommands — it only appends. + | To read notes on an issue, use: bd show + flag --file type=string default="" annotations={cobra_annotation_mutually_exclusive=["stdin file"]} usage="Read note text from file" + flag --stdin type=bool default="false" annotations={cobra_annotation_mutually_exclusive=["stdin file"]} usage="Read note text from stdin" + +bd notion + use: "notion" + short: "Notion integration commands" + hidden: false + runnable: false + long: + | Commands for syncing issues between beads and Notion. + +bd notion connect + use: "connect" + short: "Connect bd to an existing Notion database or data source" + hidden: false + runnable: true + flag --url type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Existing Notion database or data source URL" + +bd notion init + use: "init" + short: "Create a dedicated Beads database in Notion" + hidden: false + runnable: true + flag --parent type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Parent page ID" + flag --title type=string default="Beads Issues" usage="Database title" + +bd notion pull + use: "pull [refs...]" + short: "Pull specific items from Notion" + hidden: false + runnable: true + long: + | Pull one or more items from Notion. + | + | Accepts bead IDs or external references as positional arguments. + | Equivalent to: bd notion sync --pull --issues + flag --dry-run type=bool default="false" usage="Preview pull without making changes" + +bd notion push + use: "push [bead-ids...]" + short: "Push specific beads to Notion" + hidden: false + runnable: true + long: + | Push one or more beads issues to Notion. + | + | Accepts bead IDs as positional arguments. + | Equivalent to: bd notion sync --push --issues + flag --dry-run type=bool default="false" usage="Preview push without making changes" + +bd notion status + use: "status" + short: "Show Notion sync status" + hidden: false + runnable: true + +bd notion sync + use: "sync" + short: "Sync issues with Notion" + hidden: false + runnable: true + long: + | Synchronize issues between beads and Notion. + | + | By default this performs bidirectional sync. Use --pull or --push to limit direction. + flag --create-only type=bool default="false" usage="Only create missing remote pages, do not update existing ones" + flag --dry-run type=bool default="false" usage="Preview changes without making mutations" + flag --issues type=string default="" usage="Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent." + flag --parent type=string default="" usage="Limit push to this bead and its descendants (push only). Mutually exclusive with --issues." + flag --prefer-local type=bool default="false" usage="On conflict, keep the local beads version" + flag --prefer-notion type=bool default="false" usage="On conflict, use the Notion version" + flag --pull type=bool default="false" usage="Only pull issues from Notion" + flag --push type=bool default="false" usage="Only push issues to Notion" + flag --state type=string default="all" usage="Issue state to sync: open, closed, or all" + +bd onboard + use: "onboard" + short: "Display minimal snippet for agent instructions file" + group: "setup" + hidden: false + runnable: true + long: + | Display a minimal snippet to add to your agent instructions file for bd integration. + | + | By default, the agent instructions file is AGENTS.md. Use 'bd init --agents-file' + | to configure a different filename (e.g. BEADS.md). + | + | This outputs a small (~10 line) snippet that points to 'bd prime' for full + | workflow context. This is the same minimal profile that 'bd init' generates + | by default. This approach: + | + | • Keeps your agent file lean (doesn't bloat with instructions) + | • bd prime provides dynamic, always-current workflow details + | • Hooks auto-inject bd prime at session start + | + | For agents or environments that do not auto-inject hook output, use + | 'bd init --agents-profile=full' to embed the complete command reference. + +bd orphans + use: "orphans" + short: "Identify orphaned issues (referenced in commits but still open)" + hidden: false + runnable: true + long: + | Identify orphaned issues - issues that are referenced in commit messages but remain open or in_progress in the database. + | + | This helps identify work that has been implemented but not formally closed. + | + | Examples: + | bd orphans # Show orphaned issues + | bd orphans --json # Machine-readable output + | bd orphans --details # Show full commit information + | bd orphans --fix # Close orphaned issues with confirmation + | bd orphans --label theme:personal # Only orphans with this label + | bd orphans --label-any theme:personal,theme:ventures # Orphans with either label + flag --details type=bool default="false" usage="Show full commit information" + flag --fix -f type=bool default="false" usage="Close orphaned issues with confirmation" + flag --label -l type=stringSlice default="[]" usage="Filter by labels (AND: must have ALL). Can combine with --label-any" + flag --label-any type=stringSlice default="[]" usage="Filter by labels (OR: must have AT LEAST ONE). Can combine with --label" + +bd ping + use: "ping" + short: "Check database connectivity" + group: "maint" + hidden: false + runnable: true + long: + | Lightweight health check that confirms bd can reach its database. + | + | Steps: + | 1. Resolve the .beads workspace + | 2. Open the store (embedded or server) + | 3. Run a trivial query (one issue row; a remote backend reads its + | authenticated server context instead) + | 4. Report timing + | + | Exit 0 on success, exit 1 on failure. + | + | Examples: + | bd ping # Quick connectivity check + | bd ping --json # Structured output for automation + +bd preflight + use: "preflight" + short: "Show PR readiness checklist" + group: "maint" + hidden: false + runnable: true + long: + | Display a checklist of common pre-PR checks for contributors. + | + | This command helps catch common issues before pushing to CI: + | - Tests not run locally + | - Lint errors + | - Unformatted Go files + | - .beads/issues.jsonl pollution + | - Stale nix vendorHash + | - Version mismatches + | + | Examples: + | bd preflight # Show checklist + | bd preflight --check # Run checks automatically + | bd preflight --check --json # JSON output for programmatic use + | bd preflight --check --skip-lint # Explicitly skip lint check + | + flag --check type=bool default="false" usage="Run checks automatically" + flag --fix type=bool default="false" usage="Auto-fix issues where possible (vendorHash)" + flag --skip-lint type=bool default="false" usage="Skip lint check explicitly" + +bd prime + use: "prime" + short: "Output AI-optimized workflow context" + group: "setup" + hidden: false + runnable: true + long: + | Output essential Beads workflow context in AI-optimized markdown format. + | + | Automatically detects if MCP server is active and adapts output: + | - MCP mode: Brief workflow reminders (~50 tokens) + | - CLI mode: Full command reference (~1-2k tokens) + | + | Designed for Claude Code, Gemini CLI, and Codex SessionStart hooks to prevent + | agents from forgetting bd workflow after context compaction. + | + | Config options: + | - no-git-ops: When true, outputs stealth mode (no git commands in session close protocol). + | Set via: bd config set no-git-ops true + | Useful when you want to control when commits happen manually. + | - agent.profile: Explicit policy profile for git/commit authority wording + | (conservative | minimal | team-maintainer; default conservative). + | Set via: bd config set agent.profile team-maintainer + | Or per-session: BD_AGENT_PROFILE=team-maintainer (env var takes precedence). + | See docs/getting-started/ide-setup.md#policy-profiles for what each profile means. + | - prime.disabled: When true, bd prime prints nothing, as it does outside a + | workspace (an empty envelope under --hook-json), whatever its other flags. + | For sessions whose host briefs the agent itself but that inherit a + | project's bd prime hook, such as an orchestrator's agent sessions. + | Set per-session: BD_PRIME_DISABLED=true. Or: bd config set prime.disabled true + | + | Workflow customization: + | - Place a PRIME.md file to override the default workflow text. Checked in this + | order, once bd resolves a workspace (outside one, prime emits no content): + | (1) .beads/PRIME.md relative to the current directory (the -C target + | when -C is set); + | (2) PRIME.md in the .beads directory bd resolves for this workspace + | (honors $BEADS_DIR, which -C overrides; a redirected .beads is + | followed); + | (3) the global PRIME.md in bd's user config dir: + | ~/.config/beads/ on Linux ($XDG_CONFIG_HOME/beads/ if set), + | ~/Library/Application Support/beads/ on macOS, + | %AppData%\beads\ on Windows. + | - Persistent memories (from bd remember) are still appended so memory + | injection keeps working under a custom template. + | - Use --export to dump the default content for customization. + | - Use --memories-only for hook contexts that should inject only persistent memories; this returns only the memories section even when a custom PRIME.md is present. + | - Use --no-memories to omit the persistent memories section (useful when the memories section is large and would dominate a context budget). --memories-only takes precedence if both are set. + | + | Memory injection caps: + | Large memory sets can exceed what a session-start hook host will ingest, + | and hosts truncate silently. Cap what prime injects with --max-memories N + | and/or --max-memory-chars N (or the prime.max-memories / + | prime.max-memory-chars config keys; an explicit flag wins, and an explicit + | 0 forces unlimited). Caps apply at whole-memory boundaries, at least one + | memory is always emitted, and a banner ahead of the entries reports how + | many were elided and how to browse the rest with bd memories. + | --max-memory-chars caps the total bytes of the injected memory entries; + | the section header and elision banner are excluded from the budget. + flag --export type=bool default="false" usage="Output default content (ignores PRIME.md override)" + flag --full type=bool default="false" usage="Force full CLI output (ignore MCP detection)" + flag --hook-json type=bool default="false" usage="Wrap output in the SessionStart hook JSON envelope (Claude Code, Gemini CLI, Codex)" + flag --max-memories type=int default="0" usage="Cap injected persistent memories to N entries (0 = unlimited; falls back to the prime.max-memories config key)" + flag --max-memory-chars type=int default="0" usage="Cap the total bytes of injected memory entries, at whole-memory boundaries; section header and banner are not counted (0 = unlimited; falls back to the prime.max-memory-chars config key)" + flag --mcp type=bool default="false" usage="Force MCP mode (minimal output)" + flag --memories-only type=bool default="false" usage="Output only persistent memories for compact hook contexts" + flag --no-memories type=bool default="false" usage="Omit the persistent memories section (ignored when --memories-only is set, which wins)" + flag --stealth type=bool default="false" usage="Stealth mode (no git operations, flush only)" + +bd priority + use: "priority " + short: "Set the priority of an issue" + group: "issues" + hidden: false + runnable: true + long: + | Set the priority of an issue. + | + | Shorthand for 'bd update --priority '. + | + | Priority levels: + | 0 - Critical (security, data loss, broken builds) + | 1 - High (major features, important bugs) + | 2 - Medium (default) + | 3 - Low (polish, optimization) + | 4 - Backlog (future ideas) + | + | Examples: + | bd priority bd-123 0 # Critical + | bd priority bd-123 2 # Medium + +bd promote + use: "promote " + short: "Promote a wisp to a permanent bead" + group: "issues" + hidden: false + runnable: true + long: + | Promote a wisp (ephemeral issue) to a permanent bead. + | + | This copies the issue from the wisps table (dolt_ignored) to the permanent + | issues table (Dolt-versioned), preserving labels, dependencies, events, and + | comments. The original ID is preserved so all links keep working. + | + | A comment is added recording the promotion and optional reason. + | + | Examples: + | bd promote bd-wisp-abc123 + | bd promote bd-wisp-abc123 --reason "Worth tracking long-term" + flag --reason -r type=string default="" usage="Reason for promotion" + +bd provenance + use: "provenance" + short: "Append-only provenance event log" + group: "issues" + hidden: false + runnable: false + long: + | Record and read provenance events: typed bindings from an issue to an + | opaque external artifact (a git SHA, PR, work-id, transcript, or branch). + | + | The log is append-only — there is no update or delete. bd never interprets the + | actor or ref; only kind and ref-kind are structurally validated. Recording is + | idempotent on a deterministic id, so a producer firing twice is harmless. + +bd provenance by-ref + use: "by-ref " + short: "List provenance events bound to a ref" + hidden: false + runnable: true + +bd provenance log + use: "log " + short: "List provenance events for an issue" + hidden: false + runnable: true + flag --kind type=string default="" usage="filter by kind (optional)" + +bd provenance record + use: "record --issue --kind --source " + short: "Record a provenance event (idempotent)" + hidden: false + runnable: true + long: + | Record a provenance event. The event is appended idempotently: a + | deterministic id is computed from source:issue:kind:(ref or --at), so re-running + | the same record is a no-op. + | + | An event recorded without --ref requires --at so the id is caller-owned. + flag --actor type=string default="" usage="opaque actor identifier (optional)" + flag --at type=string default="" usage="event-time as RFC3339 (required for ref-less kinds)" + flag --issue type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="issue id (required)" + flag --kind type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="event kind: cut|claim|suspend|resume|handoff|commit|land|used (required)" + flag --payload type=string default="" usage="opaque payload, e.g. JSON (optional)" + flag --ref type=string default="" usage="opaque external reference, e.g. a SHA or PR url (optional)" + flag --ref-kind type=string default="" usage="ref kind: git-sha|pr|work-id|transcript|branch (optional)" + flag --source type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="producer of the event, e.g. git-hook, orchestrator (required)" + +bd prune + use: "prune" + short: "Delete old closed beads to reclaim space and shrink exports" + group: "maint" + hidden: false + runnable: true + long: + | Permanently delete closed non-ephemeral beads and their associated data. + | + | Use this to trim closed regular beads (tasks, features, bugs, chores, etc.) + | that are no longer useful. The common case is a long-lived repo where + | closed work has piled up and is bloating auto-export or slowing queries. + | + | Requires --older-than or --pattern. The flag is a safety gate — without + | it, a muscle-memory `--force` could wipe every closed bead in the repo. + | Use `--pattern '*'` if you really do want to sweep everything closed. + | + | Deletes: issues, dependencies, labels, events, and comments for matching beads. + | Skips: pinned beads (protected), open/in-progress beads, and ephemeral beads. + | + | Also skips closed beads whose ID appears in the description, notes, or + | comments of any open / in-progress bead. This protects ADR / decision / + | verification trails that downstream beads still cite. Use + | --ignore-references to override (e.g., when bulk-decommissioning a + | retired label across the rig). + | + | To delete closed ephemeral beads (wisps, transient molecules) use + | `bd purge` instead. + | + | For full Dolt storage reclaim after deleting many rows, follow with `bd flatten` + | so history can be collapsed and old chunks can be garbage-collected. + | + | EXAMPLES: + | bd prune --older-than 30d # Preview closed beads >30d old + | bd prune --older-than 30d --force # Delete them + | bd prune --older-than 90d --dry-run # Detailed preview with stats + | bd prune --pattern "*" --force # Delete all closed regular beads + | bd prune --pattern "gm-temp-*" --force # Scope to a pattern + flag --dry-run type=bool default="false" usage="Preview what would be pruned with stats" + flag --force -f type=bool default="false" usage="Actually prune (without this, shows preview)" + flag --ignore-references type=bool default="false" usage="Delete closed beads even when referenced by open beads (use with care; see --help for details)" + flag --older-than type=string default="" usage="Only prune beads closed more than N ago (e.g., 30d, 2w, 60, 36h)" + flag --pattern type=string default="" usage="Only prune beads matching ID glob pattern (e.g., 'gm-old-*')" + +bd purge + use: "purge" + short: "Delete closed ephemeral beads to reclaim space" + group: "maint" + hidden: false + runnable: true + long: + | Permanently delete closed ephemeral beads and their associated data. + | + | Closed ephemeral beads (wisps, transient molecules) accumulate rapidly and + | have no value once closed. This command removes them to reclaim storage. + | + | Deletes: issues, dependencies, labels, events, and comments for matching beads. + | Skips: pinned beads, and closed beads a live bead still depends on through a + | parent-child, tracks or blocks edge (a closed molecule root whose step is open, + | a closed bead a live convoy tracks). Live means any status that is not done. + | + | --wisps-plane selects by storage plane instead: every closed row stored in the + | wisps table, including --no-history beads, which the default ephemeral + | selection leaves to `bd prune`. It reaches durable-tier rows, so it requires + | --older-than or --pattern, like `bd prune`. + | + | --limit N caps one run at N beads, oldest-closed first, so a large backlog can + | be drained in bounded transactions; --json then reports "remaining" and + | "has_more". Loop while has_more is true. + | + | --older-than takes days (7, 7d), weeks (2w) or a duration with hour precision + | (36h, 168h, 90m). + | + | To delete closed non-ephemeral beads (regular tasks, features, bugs, etc.) + | use `bd prune` instead. + | + | For full Dolt storage reclaim after deleting many rows, follow with `bd flatten` + | so history can be collapsed and old chunks can be garbage-collected. + | + | EXAMPLES: + | bd purge # Preview what would be purged + | bd purge --force # Delete all closed ephemeral beads + | bd purge --older-than 7d --force # Only purge items closed 7+ days ago + | bd purge --pattern "*-wisp-*" # Only purge matching ID pattern + | bd purge --older-than 36h --force # Hour precision: closed 36+ hours ago + | bd purge --wisps-plane --older-than 168h --force + | # Every closed wisps-table row, incl. no-history + | bd purge --dry-run # Detailed preview with stats + flag --dry-run type=bool default="false" usage="Preview what would be purged with stats" + flag --force -f type=bool default="false" usage="Actually purge (without this, shows preview)" + flag --limit type=int default="0" usage="Purge at most N beads this run, oldest-closed first (0 = no limit); --json reports remaining/has_more" + flag --older-than type=string default="" usage="Only purge beads closed more than N ago (e.g., 7d, 2w, 30, 36h)" + flag --pattern type=string default="" usage="Only purge beads matching ID glob pattern (e.g., *-wisp-*)" + flag --wisps-plane type=bool default="false" usage="Select every closed row in the wisps table, including --no-history beads (requires --older-than or --pattern)" + +bd q + use: "q [title]" + short: "Quick capture: create issue and output only ID" + group: "issues" + hidden: false + runnable: true + long: + | Quick capture creates an issue and outputs only the issue ID. + | Designed for scripting and AI agent integration. + | + | Example: + | bd q "Fix login bug" # Outputs: bd-a1b2 + | ISSUE=$(bd q "New feature") # Capture ID in variable + | bd q "Task" | xargs bd show # Pipe to other commands + | bd q "Subtask" --parent=bd-a1b2 # Hierarchical child (outputs: bd-a1b2.1) + flag --labels -l type=stringSlice default="[]" usage="Labels" + flag --parent type=string default="" usage="Parent issue ID for hierarchical child (e.g., 'bd-a3f8e9')" + flag --priority -p type=string default="2" usage="Priority (0-4 or P0-P4)" + flag --type -t type=string default="task" usage="Issue type" + +bd query + use: "query [expression]" + short: "Query issues using a simple query language" + group: "issues" + hidden: false + runnable: true + long: + | Query issues using a simple query language that supports compound filters, + | boolean operators, and date-relative expressions. + | + | The query language enables complex filtering that would otherwise require + | multiple flags or piping through jq. + | + | Syntax: + | field=value Equality comparison + | field!=value Inequality comparison + | field>value Greater than + | field>=value Greater than or equal + | field1" + | bd query "status=open AND priority<=2 AND updated>7d" + | bd query "(status=open OR status=blocked) AND priority<2" + | bd query "type=bug AND label=urgent" + | bd query "NOT status=closed" + | bd query "assignee=none AND type=task" + | bd query "created>30d AND status!=closed" + | bd query "label=frontend OR label=backend" + | bd query "title=authentication AND priority=0" + flag --all -a type=bool default="false" usage="Include closed issues (default: exclude closed)" + flag --limit -n type=int default="50" usage="Limit results (default: 50, 0 = unlimited)" + flag --long type=bool default="false" usage="Show detailed multi-line output for each issue" + flag --offset type=int default="0" usage="Skip the first N matching results (0-based). Only supported under --proxied-server." + flag --parse-only type=bool default="false" usage="Only parse the query and show the AST (for debugging)" + flag --reverse -r type=bool default="false" usage="Invert the sort field's default direction (created/updated/closed default to newest-first, so --sort updated --reverse is oldest-first)" + flag --sort type=string default="" usage="Sort by field: priority, created, updated, closed, status, id, title, type, assignee" + +bd quickstart + use: "quickstart" + short: "Quick start guide for bd" + group: "setup" + hidden: false + runnable: true + long: + | Display a quick start guide showing common bd workflows and patterns. + +bd ready + use: "ready" + short: "Show ready work (open, no active blockers)" + hidden: false + runnable: true + long: + | Show ready work (open issues with no active blockers). + | + | Excludes in_progress, blocked, deferred, and hooked issues. This uses the + | GetReadyWork API which applies blocker-aware semantics to find truly claimable work. + | + | Note: 'bd list --ready' uses the same blocker-aware ready-work semantics. + | + | Use --mol to filter to a specific molecule's steps: + | bd ready --mol bd-patrol # Show ready steps within molecule + | + | Use --gated to find molecules ready for gate-resume dispatch: + | bd ready --gated # Find molecules where a gate closed + | + | Use --claim to atomically claim the first ready issue matching the filters: + | bd ready --claim --json + | + | This is useful for agents executing molecules to see which steps can run next. + flag --assignee -a type=string default="" usage="Filter by assignee" + flag --brief type=bool default="false" usage="Omit the free-form text (description, design, acceptance criteria, notes, payload, waiters) from each row. Filters that read those fields still select on them. An omitted field is indistinguishable from an empty one; fetch a whole issue with bd show. Requires --json, and cannot be combined with --claim, --gated, --mol or --explain." + flag --claim type=bool default="false" usage="Atomically claim the first ready issue matching the filters" + flag --exclude-label type=stringSlice default="[]" usage="Exclude issues that have ANY of these labels" + flag --exclude-type type=stringSlice default="[]" usage="Exclude issue types from results (comma-separated or repeatable, e.g., --exclude-type=convoy,epic)" + flag --explain type=bool default="false" usage="Show dependency-aware reasoning for why issues are ready or blocked" + flag --flat type=bool default="false" usage="Alias for --plain, spelled the way bd list spells it" + flag --gated type=bool default="false" usage="Find molecules ready for gate-resume dispatch" + flag --has-metadata-key type=string default="" usage="Filter issues that have this metadata key set" + flag --include-deferred type=bool default="false" usage="Include issues with future defer_until timestamps" + flag --include-ephemeral type=bool default="false" usage="Include ephemeral issues (wisps) in results" + flag --label -l type=stringSlice default="[]" usage="Filter by labels (AND: must have ALL). Can combine with --label-any" + flag --label-any type=stringSlice default="[]" usage="Filter by labels (OR: must have AT LEAST ONE). Can combine with --label" + flag --label-pattern type=string default="" usage="Filter by label glob pattern (e.g., 'tech-*' matches tech-debt, tech-legacy)" + flag --label-regex type=string default="" usage="Filter by label regex pattern (e.g., 'tech-(debt|legacy)')" + flag --limit -n type=int default="100" usage="Maximum issues to show (use 0 for unlimited)" + flag --max-rows type=int default="0" usage="Hard upper bound on rows fetched from storage. Returns a non-zero exit (code 2) and an error to stderr if exceeded. 0 disables (the default). Overrides BEADS_MAX_ROWS for this invocation. Useful in CI/agent rigs that want a circuit breaker against pathological queries. Not supported under --proxied-server: an explicit --max-rows or BEADS_MAX_ROWS cap errors out rather than silently going unenforced." + flag --metadata-field type=stringArray default="[]" usage="Filter by metadata field (key=value, repeatable)" + flag --mol type=string default="" usage="Filter to steps within a specific molecule" + flag --mol-type type=string default="" usage="Filter by molecule type: swarm, patrol, or work" + flag --offset type=int default="0" usage="Skip the first N matching results (0-based). Only supported under --proxied-server." + flag --parent type=string default="" usage="Filter to descendants of this bead/epic" + flag --plain type=bool default="false" usage="Display issues as a plain numbered list" + flag --pretty type=bool default="true" usage="Display issues in a tree format with status/priority symbols" + flag --priority -p type=int default="0" usage="Filter by priority" + flag --sort -s type=string default="priority" usage="Sort policy: priority (default), hybrid, oldest" + flag --type -t type=string default="" usage="Filter by issue type (task, bug, feature, epic, decision, merge-request). Aliases: mr→merge-request, feat→feature, mol→molecule, dec/adr→decision" + flag --unassigned -u type=bool default="false" usage="Show only unassigned issues" + +bd recall + use: "recall " + short: "Retrieve a specific memory" + group: "setup" + hidden: false + runnable: true + long: + | Retrieve the full content of a memory by its key. + | + | Examples: + | bd recall dolt-phantoms + | bd recall auth-jwt + +bd reclaim + use: "reclaim" + short: "Revert stale-lease in_progress issues back to ready (dead-worker recovery)" + group: "issues" + hidden: false + runnable: true + long: + | Revert in_progress issues whose lease has gone stale back to ready. + | + | When a worker claims an issue it takes a lease that expires after a TTL, kept + | alive by 'bd heartbeat'. A worker that dies stops heartbeating, so its lease + | expires and its issue would otherwise stay in_progress forever. reclaim is the + | reaper: it finds in_progress issues whose lease expired more than --older-than + | ago, clears the assignee, and sets them back to open so another worker can + | claim them. The previous owner's stale lease is recorded as a recovery event. + | + | --older-than is a grace window past lease expiry: only leases that expired at + | least this long ago are reclaimed, so a worker briefly paused (GC, clock skew) + | is not robbed of live work. Run it from a supervisor on a timer with a window + | of roughly 2× the claim TTL. + | + | By default reclaim covers every stale lease THIS replica granted. The scope + | filters below narrow it further, using the same label surface claiming is + | scoped by (--label / --label-any / --exclude-label), plus --assignee and --id. + | Filters AND-combine and never widen the set: a reclaimed lease must still be + | stale. + | + | Replicas and leases (federated deployments) + | ------------------------------------------- + | A lease is only meaningful on the replica that granted it. Every other + | replica's view of the holder's liveness is stale by up to one sync interval, + | so a reaper elsewhere can revert a unit that is very much alive over there. + | reclaim therefore records the granting replica on each lease and SKIPS a lease + | another replica granted, summarizing what it declined on stderr (one line per + | run; 'bd -v' expands it to the first 20 leases individually). Reap it where it + | was granted; use --any-replica only when that replica is permanently gone (or + | when this node was renamed and its own old leases now look foreign — an + | ordinary heartbeat keeps a lease alive but does not re-home it to the node + | heartbeating it). Prefer the narrow form '--any-replica --id ': bare + | --any-replica reverts EVERY foreign stale lease, live peers included. + | + | Two invariants the guard cannot enforce for you: + | + | grace window > sync interval, and lease TTL > sync interval. + | + | A TTL or grace shorter than the cadence at which replicas exchange state is + | meaningless across the bridge — the remote view is a full interval old by + | construction. Raise the TTL/grace above the sync interval, never the reverse. + | The guard is opt-in: set BEADS_NODE_ID, or run 'bd config set node_id ' + | (which writes the per-machine ~/.config/bd/config.yaml — never commit a node_id + | to the git-tracked .beads/config.yaml, or every clone reads the same name and + | the guard goes armed-but-inert). One id per STORE, not per host: machines that + | are clients of the same dolt sql-server are ONE replica and must share one value + | or leave it unset. There is no hostname fallback — the hostname names the client + | process's machine, not the store — so an unnamed deployment keeps the old, + | unguarded behavior instead of stranding its own work. + | + | Examples: + | bd reclaim # default grace window (2× the lease TTL) + | bd reclaim --older-than 10m # reclaim leases expired >10m ago + | bd reclaim --older-than 0s # reclaim every currently-expired lease + | bd reclaim --label lane-a # only this machine's claim partition + | bd reclaim --label-any lane-a,lane-b --exclude-label pinned + | bd reclaim --assignee zelda --assignee epona # only these workers' leases + | bd reclaim --id wy-abc --id wy-def # exactly these issues + | bd reclaim --any-replica # also reap leases granted by a departed replica + flag --any-replica type=bool default="false" usage="Also reclaim leases granted by ANOTHER replica (unsafe unless that replica is gone; see 'Replicas and leases')" + flag --assignee -a type=stringSlice default="[]" usage="Only reclaim leases held by these assignees (repeatable)" + flag --exclude-label type=stringSlice default="[]" usage="Never reclaim issues carrying ANY of these labels" + flag --id type=stringSlice default="[]" usage="Only reclaim these issue IDs (repeatable)" + flag --label -l type=stringSlice default="[]" usage="Only reclaim issues with ALL these labels (AND). Can combine with --label-any" + flag --label-any type=stringSlice default="[]" usage="Only reclaim issues with AT LEAST ONE of these labels (OR). Can combine with --label" + flag --older-than type=duration default="10m0s" usage="Only reclaim leases that expired at least this long ago (grace window)" + +bd recompute-blocked + use: "recompute-blocked" + short: "Recompute is_blocked for all issues (repairs stale flags after a pull)" + group: "maint" + hidden: false + runnable: true + long: + | Recompute the denormalized is_blocked flag for every issue and wisp. + | + | is_blocked is derived from the dependency graph and maintained automatically by + | local writes and by a post-pull recompute scoped to what the merge changed. If + | that scoped recompute is skipped — a recompute that failed after its merge + | committed, or a conflicted pull resolved by hand — the flag can go stale, and a + | later pull that merges nothing will not refresh it (bd-6dnrw.37). 'bd ready' + | trusts the flag, so stale values silently hide ready work or surface blocked + | work. + | + | This command runs the full recompute unconditionally and commits the result. + | It is idempotent: on a consistent database it changes nothing. Works in every + | storage mode — embedded, server, and proxied-server (unlike 'bd doctor', which + | is server-mode only). + | + | On a workspace connected to a bd serve backend ('bd connect') it is a no-op + | that exits 0: the server maintains is_blocked on every write, and the column + | lives in the server's database, so the repair is run there, by the server's + | operator. --json then reports {"rows_corrected": 0, "maintained_by": "server"}. + | + | Examples: + | bd recompute-blocked # Repair stale is_blocked flags + | bd recompute-blocked --json # Machine-parseable {"rows_corrected": N} + +bd remember + use: "remember \"\"" + short: "Store a persistent memory" + group: "setup" + hidden: false + runnable: true + long: + | Store a memory that persists across sessions and account rotations. + | + | Memories are injected at prime time (bd prime) so you have them + | in every session without manual loading. + | + | The positional arg is the memory CONTENT (the key is auto-generated from it + | unless --key is given). As a convenience, if the arg is a bare key naming an + | existing memory, it is RECALLED instead of stored (same as 'bd recall'); + | a bare key naming nothing is refused. Use --key to store slug-like content. + | + | Corpus budget (opt-in, off by default): set the memories.budget-chars config + | key to a byte ceiling for the whole memory corpus (sum of len(key)+len(content)). + | A write that would cross it is refused, and --force overrides; a write that + | lands at or above 80% of the budget warns. With the key unset nothing changes. + | bd prime's --max-memory-chars also counts bytes, but of each memory as + | injected, formatting included, so a budget equal to that cap does not + | guarantee prime injects every memory; set the budget below it for that. + | + | Examples: + | bd remember "always run tests with -race flag" + | bd remember "Dolt phantom DBs hide in three places" --key dolt-phantoms + | bd remember "auth module uses JWT not sessions" --key auth-jwt + | bd remember dolt-phantoms # bare existing key: reads it (= bd recall) + flag --force type=bool default="false" usage="Store even when the write would cross the memories.budget-chars corpus budget (no effect when the budget is unset)" + flag --key type=string default="" usage="Explicit key for the memory (auto-generated from content if not set). If a memory with this key already exists, it will be updated in place" + +bd rename + use: "rename " + short: "Rename an issue ID" + hidden: false + runnable: true + long: + | Rename an issue from one ID to another. + | + | This updates: + | - The issue's primary ID + | - All references in other issues (descriptions, titles, notes, etc.) + | - Dependencies pointing to/from this issue + | - Labels, comments, and events + | + | Examples: + | bd rename bd-w382l bd-dolt # Rename to memorable ID + | bd rename gt-abc123 gt-auth # Use descriptive ID + | + | Note: The new ID must use a valid prefix for this database. + +bd rename-prefix + use: "rename-prefix " + short: "Rename the issue prefix for all issues in the database" + group: "maint" + hidden: false + runnable: true + long: + | Rename the issue prefix for all issues in the database. + | This will update all issue IDs and all text references across all fields. + | + | USE CASES: + | - Shortening long prefixes (e.g., 'knowledge-work-' → 'kw-') + | - Rebranding project naming conventions + | - Consolidating multiple prefixes after database corruption + | - Migrating to team naming standards + | + | Prefix validation rules: + | - Allowed characters: lowercase letters, numbers, hyphens + | - Must start with a letter + | - Must end with a hyphen (e.g., 'kw-', 'work-') + | - Cannot be empty or just a hyphen + | + | Multiple prefix detection and repair: + | If issues have multiple prefixes (corrupted database), use --repair to consolidate them. + | The --repair flag will rename all issues with incorrect prefixes to the new prefix, + | preserving issues that already have the correct prefix. + | + | EXAMPLES: + | bd rename-prefix kw- # Rename from 'knowledge-work-' to 'kw-' + | bd rename-prefix mtg- --repair # Consolidate multiple prefixes into 'mtg-' + | bd rename-prefix team- --dry-run # Preview changes without applying + | + | NOTE: This is a rare operation. Most users never need this command. + flag --dry-run type=bool default="false" usage="Preview changes without applying them" + flag --repair type=bool default="false" usage="Repair database with multiple prefixes by consolidating them" + +bd reopen + use: "reopen [id...]" + short: "Reopen one or more closed issues" + group: "issues" + hidden: false + runnable: true + long: + | Reopen closed issues by setting status to 'open' and clearing the closed_at timestamp. + | This is more explicit than 'bd update --status open' and emits a Reopened event. + | + | Exit codes: 1 for general failures; 13 when the failure is a stale + | --if-revision guard (the precondition no longer held, nothing was written — + | another actor won the race, so retrying the same guard is pointless). + flag --if-revision type=string default="" usage="Apply the write only if the issue's current revision equals this value (the decimal int64 from `bd show --json`'s \"revision\" field). One id only: refused before any write when combined with more than one issue id. A mismatch writes nothing and exits 13 (vs 1 for other failures)." + flag --reason -r type=string default="" usage="Reason for reopening" + +bd repo + use: "repo" + short: "Manage multiple repository configuration" + group: "advanced" + hidden: false + runnable: false + long: + | Configure and manage multiple repository support for multi-repo hydration. + | + | Multi-repo support allows hydrating issues from multiple beads repositories + | into a single database for unified cross-repo issue tracking. + | + | Configuration is stored in .beads/config.yaml under the 'repos' section: + | + | repos: + | primary: "." + | additional: + | - ~/beads-planning + | - ~/work-repo + | + | Examples: + | bd repo add ~/beads-planning # Add planning repo + | bd repo add ../other-repo # Add relative path repo + | bd repo list # Show all configured repos + | bd repo remove ~/beads-planning # Remove by path + | bd repo sync # Sync from all configured repos + +bd repo add + use: "add " + short: "Add an additional repository to sync" + hidden: false + runnable: true + long: + | Add a repository path to the repos.additional list in config.yaml. + | + | The path should point to a directory containing a .beads folder. + | Paths can be absolute or relative (they are stored as-is). + | + | This modifies .beads/config.yaml, which is version-controlled and + | shared across all clones of this repository. + +bd repo list + use: "list" + short: "List all configured repositories" + hidden: false + runnable: true + long: + | List all repositories configured in .beads/config.yaml. + | + | Shows the primary repository (always ".") and any additional + | repositories configured for hydration. + +bd repo remove + use: "remove " + short: "Remove a repository from sync configuration" + hidden: false + runnable: true + long: + | Remove a repository path from the repos.additional list in config.yaml. + | + | The path must exactly match what was added (e.g., if you added "~/foo", + | you must remove "~/foo", not "/home/user/foo"). + | + | This command also removes any previously-hydrated issues from the database + | that came from the removed repository. + +bd repo sync + use: "sync" + short: "Manually trigger multi-repo sync" + hidden: false + runnable: true + long: + | Synchronize issues from all configured additional repositories. + | + | Reads issues.jsonl from each additional repository and imports them into + | the primary database with their original prefixes and source_repo set. + | Uses mtime caching to skip repos whose JSONL hasn't changed. + | + | Also triggers Dolt push/pull if a remote is configured. + flag --verbose type=bool default="false" usage="Show detailed sync progress" + +bd restore + use: "restore " + short: "Restore the pre-compaction content of a compacted issue" + group: "sync" + hidden: false + runnable: true + long: + | Restore the pre-compaction content of a compacted issue. + | + | When an issue is compacted, its description/design/notes/acceptance criteria + | are summarized and the originals are archived to a compaction snapshot. This + | command recovers that original content. + | + | By default it is read-only: it displays the archived content without modifying + | the database. Pass --apply to write the original content back into the issue + | and step its compaction level back down. + | + | If no archived snapshot exists (e.g. the issue was compacted by an older bd + | before snapshot archiving), restore falls back to a best-effort reconstruction + | from Dolt version history, which can only be displayed, not applied. + flag --apply type=bool default="false" usage="Write the restored content back into the issue (default: display only)" + +bd rules + use: "rules" + short: "Audit and compact Claude rules" + group: "maint" + hidden: false + runnable: false + +bd rules audit + use: "audit" + short: "Scan rules for contradictions and merge opportunities" + hidden: false + runnable: true + flag --path type=string default=".claude/rules/" usage="Path to rules directory" + flag --threshold type=float64 default="0.6" usage="Jaccard similarity threshold" + +bd rules compact + use: "compact" + short: "Merge related rules into composites" + hidden: false + runnable: true + flag --auto type=bool default="false" usage="Apply audit suggestions" + flag --dry-run type=bool default="false" usage="Preview without applying" + flag --group type=stringSlice default="[]" usage="Rule names to merge" + flag --path type=string default=".claude/rules/" usage="Path to rules directory" + +bd schema + use: "schema" + short: "Print the JSON Schema for bd's --json / export output" + hidden: false + runnable: true + annotations: {bd:skip_store="1"} + long: + | Print the JSON Schema for bd's canonical output record types. + | + | The schema is reflected from the same Go structs bd serializes, so it stays in + | lockstep with the actual --json / export output. Use it to generate typed + | consumer models (datamodel-code-generator, quicktype, ...) rather than + | hand-maintaining them. + | + | bd schema | jq '.types.issue' # the issue record schema + | bd schema | jq '.types.dependency' # the dependency record schema + +bd search + use: "search [query]" + short: "Search issues by text query" + group: "issues" + hidden: false + runnable: true + long: + | Search issues across title and ID (all statuses, including closed). + | + | ID-like queries (e.g., "bd-123", "hq-319") use fast exact/prefix matching. + | Text queries search titles. Use --desc-contains for description search. + | Use --status open (etc.) to narrow; closed issues are included by default + | so "was this already filed/fixed?" cannot silently answer no. Matches + | beyond --limit are dropped status-blind, so when hunting live work in a + | large DB, narrow with --status open or raise --limit. + | + | Examples: + | bd search "authentication bug" + | bd search "login" --status open + | bd search "database" --label backend --limit 10 + | bd search --query "performance" --assignee alice + | bd search "bd-5q" # Search by partial ID (fast prefix match) + | bd search "security" --priority-min 0 --priority-max 2 + | bd search "bug" --created-after 2025-01-01 + | bd search "refactor" --status open # Only open issues + | bd search "bug" --sort priority + | bd search "task" --sort created --reverse + | bd search "api" --desc-contains "endpoint" + | bd search "cleanup" --no-assignee --no-labels + flag --assignee -a type=string default="" usage="Filter by assignee" + flag --closed-after type=string default="" usage="Filter issues closed after date (YYYY-MM-DD or RFC3339)" + flag --closed-before type=string default="" usage="Filter issues closed before date (YYYY-MM-DD or RFC3339)" + flag --created-after type=string default="" usage="Filter issues created after date (YYYY-MM-DD or RFC3339)" + flag --created-before type=string default="" usage="Filter issues created before date (YYYY-MM-DD or RFC3339)" + flag --desc-contains type=string default="" usage="Filter by description substring (case-insensitive)" + flag --empty-description type=bool default="false" usage="Filter issues with empty or missing description" + flag --external-contains type=string default="" usage="Filter by external ref substring (case-insensitive)" + flag --has-metadata-key type=string default="" usage="Filter issues that have this metadata key set" + flag --label -l type=stringSlice default="[]" usage="Filter by labels (AND: must have ALL)" + flag --label-any type=stringSlice default="[]" usage="Filter by labels (OR: must have AT LEAST ONE)" + flag --limit -n type=int default="50" usage="Limit results (default: 50)" + flag --long type=bool default="false" usage="Show detailed multi-line output for each issue" + flag --metadata-field type=stringArray default="[]" usage="Filter by metadata field (key=value, repeatable)" + flag --no-assignee type=bool default="false" usage="Filter issues with no assignee" + flag --no-labels type=bool default="false" usage="Filter issues with no labels" + flag --notes-contains type=string default="" usage="Filter by notes substring (case-insensitive)" + flag --priority-max type=string default="" usage="Filter by maximum priority (inclusive, 0-4 or P0-P4)" + flag --priority-min type=string default="" usage="Filter by minimum priority (inclusive, 0-4 or P0-P4)" + flag --query type=string default="" usage="Search query (alternative to positional argument)" + flag --reverse -r type=bool default="false" usage="Invert the sort field's default direction (created/updated/closed default to newest-first, so --sort updated --reverse is oldest-first)" + flag --sort type=string default="" usage="Sort by field: priority, created, updated, closed, status, id, title, type, assignee" + flag --status -s type=string default="" usage="Filter by stored status (comma-separated for OR; open, in_progress, blocked, deferred, closed, all). Default searches all statuses including closed. Note: dependency-blocked issues use 'bd blocked'" + flag --type -t type=string default="" usage="Filter by type (bug, feature, task, epic, chore, decision, message, molecule, gate, spike, story, milestone); custom types require types.custom config, and an unknown type is an error. Aliases: feat/enhancement→feature, mol→molecule, dec/adr→decision, mr→merge-request" + flag --updated-after type=string default="" usage="Filter issues updated after date (YYYY-MM-DD or RFC3339)" + flag --updated-before type=string default="" usage="Filter issues updated before date (YYYY-MM-DD or RFC3339)" + +bd send-metrics + use: "send-metrics" + short: "Internal: flush queued telemetry events (spawned by bd)" + hidden: true + runnable: true + +bd serve + use: "serve" + short: "Serve the beads HTTP API over loopback" + hidden: false + runnable: true + long: + | Serve the beads HTTP API — the same work surface the CLI answers, for + | automation clients that would otherwise fork a bd subprocess per call. + | + | The wire contract is described by an OpenAPI document (/v0); GET + | /v0/beads/context reports which operations this build actually implements. + | + | DEPLOYMENT + | + | Pass an explicit port. The default 127.0.0.1:0 takes an ephemeral one, which + | is right for ad-hoc and test use — where the bound address printed on stdout + | is read immediately — but carries no mutual exclusion: two serves against one + | workspace then run side by side on different ports with no way to enumerate + | them. On a fixed port the second one fails to bind, which is the intended + | behavior. Concurrent serves are data-safe either way; claims are arbitrated + | in the SQL server. + | + | Run it under a supervisor. bd shuts down gracefully on SIGHUP as well as + | SIGINT and SIGTERM, so closing the terminal of a foreground bd serve stops it. + | + | PROBES + | + | GET /healthz is LIVENESS only: it answers from the process and never touches + | the database, so it stays green while the database is unreachable. For + | readiness use GET /v0/beads/ready?limit=1 — a real query, where 200 means + | ready and 503 means live but not ready. + | + | AUTHENTICATION + | + | Optional, and off by default on loopback — where the trust model is the + | loopback boundary itself, the same one the database behind it already relies + | on. --auth-token-file turns it on: every operation except GET /healthz then + | requires an "Authorization: Bearer " header, GET /v0/beads/context + | included, because it reports the repo root, beads directory and database name. + | + | The file holds ONE TOKEN PER LINE and every line is accepted. That is the + | rotation mechanism: write the new token alongside the old, roll the clients + | over, then delete the old line. The file is re-read while the server runs, so + | both the addition and the removal take effect within about a second and + | neither needs a restart. Write it atomically (a temp file plus rename; a + | Kubernetes secret mount already does this). + | + | There is deliberately no --auth-token flag. A credential passed as an + | argument is readable by every local user in the process listing. + | + | --allow-non-loopback REQUIRES a token file. Beyond loopback, reaching the + | address would otherwise be the whole authorization: any peer could read every + | issue and claim work as any actor. --insecure-no-auth is the explicit, + | auditable way to say you meant that anyway. + | + | The Host allowlist is what a service deployment usually trips over first. The + | DNS-rebinding check answers only to loopback spellings and the bind address, + | so a client dialing a service name gets 400 on every request; enumerate the + | names it dials with --allowed-host (repeatable). Matching is exact — no + | wildcards — and the startup log line prints the effective allowlist. + | + | WHAT THIS DOES NOT DO + | + | No TLS. Even with a token, the credential and every issue body travel in + | plaintext, so a deployment beyond loopback has to supply confidentiality + | itself — a service mesh, or a network boundary you already trust. + | + | Hooks do not fire. A hook is a user-controlled subprocess per mutation: in a + | concurrent server that is an unbounded latency multiplier and an orphaned + | child at shutdown, and its working-directory-derived hook lookup is + | meaningless in a server process. A CLI claim runs on_update; an HTTP claim + | does not. + | + | The per-command auto-commit machinery does not run. Durability is per request: + | a successful claim commits inside its own transaction, exactly as a proxied + | CLI claim does today. + | + | An actor on an HTTP request is caller-asserted provenance for the audit trail, + | not authenticated identity — the same thing it has always been on the CLI, + | where any local process can pass any --actor. + | + | It does not run under --readonly, and refuses to start rather than binding. + | Every server it binds publishes the issue-claim operation, and the capability + | set it advertises is a property of the build rather than of the flags on the + | process that started it — so a read-only server would advertise a write it + | could never land. + | + | DESTRUCTIVE OPERATIONS + | + | POST /v0/beads/issues:sweep deletes closed beads in bulk — the operation + | behind bd purge and bd prune — and nothing it deletes comes back. It shares + | the library surface those commands call, so it inherits their guards: pinned + | beads are never swept, and a durable sweep with neither a cutoff nor an id + | pattern is refused rather than clearing every closed bead in the workspace. + | Combined with the trust model above, that means anyone who can reach this + | address can erase closed work; bind it accordingly. + flag --addr type=string default="127.0.0.1:0" usage="Address to bind as IP:PORT; the host must be a numeric IP literal, and port 0 takes an ephemeral port" + flag --allow-non-loopback type=bool default="false" usage="Permit a bind beyond loopback. Requires --auth-token-file, since reaching the address would otherwise be the whole authorization" + flag --allowed-host type=stringArray default="[]" usage="Additional Host header value to answer to, e.g. a service DNS name. Repeatable; matched exactly, with no wildcards" + flag --auth-token-file type=string default="" usage="Require an Authorization: Bearer token from this file, one token per line, all accepted. Re-read while running, so rewriting it rotates tokens without a restart (env BEADS_SERVE_TOKEN_FILE)" + flag --insecure-no-auth type=bool default="false" usage="Serve a non-loopback bind with NO authentication. Every peer that can reach the address gets full read and claim access" + flag --large-apply-ceiling type=duration default="5m0s" usage="Whole-run budget for a POST issues:batchApply request over 100 items (a ceiling, not a target; requests at or under 100 items are unaffected). Must be positive. The orchestrator's stop grace must be at least this long plus 5s, or an external SIGKILL can cut off an in-flight large apply a graceful drain would otherwise have waited out; see engdocs/SERVE_RUNBOOK.md" + +bd set-state + use: "set-state =" + short: "Set operational state (creates event + updates label)" + group: "issues" + hidden: false + runnable: true + long: + | Atomically set operational state on an issue. + | + | This command: + | 1. Creates an event bead recording the state change (source of truth) + | 2. Removes any existing label for the dimension + | 3. Adds the new dimension:value label (fast lookup cache) + | + | State labels follow the convention :, for example: + | patrol:active, patrol:muted + | mode:normal, mode:degraded + | health:healthy, health:failing + | + | Examples: + | bd set-state agent-abc patrol=muted --reason "Investigating stuck worker" + | bd set-state agent-abc mode=degraded --reason "High error rate detected" + | bd set-state agent-abc health=healthy + | + | The --reason flag provides context for the event bead (recommended). + flag --reason type=string default="" usage="Reason for the state change (recorded in event)" + +bd setup + use: "setup [recipe]" + short: "Setup integration with AI editors" + group: "setup" + hidden: false + runnable: true + long: + | Setup integration files for AI editors and coding assistants. + | + | Recipes define where beads workflow instructions are written. Built-in recipes + | include cursor, claude, copilot, gemini, aider, factory, codex, mux, opencode, junie, kiro, windsurf, cody, and kilocode. + | + | Examples: + | bd setup cursor # Install Cursor IDE integration (rules + agent hooks) + | bd setup cursor --global # Install global Cursor hooks (~/.cursor/hooks.json) + | bd setup kiro # Install Kiro steering guidance + | bd setup codex # Install Codex skill + AGENTS.md guidance + native hooks + | bd setup codex --global # Install global Codex skill + guidance + native hooks + | bd setup copilot # Install Copilot CLI plugin + repository instructions + | bd setup mux --project # Install Mux workspace layer (.mux/AGENTS.md) + | bd setup mux --global # Install Mux global layer (~/.mux/AGENTS.md) + | bd setup mux --project --global # Install both Mux layers + | bd setup --list # Show all available recipes + | bd setup --print # Print the template to stdout + | bd setup -o rules.md # Write template to custom path + | bd setup --add myeditor .myeditor/rules.md # Add custom recipe + | + | Use 'bd setup --check' to verify installation status. + | Use 'bd setup --remove' to uninstall. + flag --add type=string default="" usage="Add a custom recipe with given name" + flag --check type=bool default="false" usage="Check if integration is installed" + flag --global type=bool default="false" usage="Install globally (claude/codex/cursor/mux; writes to ~/.claude/settings.json, $CODEX_HOME/AGENTS.md or ~/.codex/AGENTS.md, ~/.cursor/hooks.json, or ~/.mux/AGENTS.md)" + flag --list type=bool default="false" usage="List all available recipes" + flag --output -o type=string default="" usage="Write template to custom path" + flag --print type=bool default="false" usage="Print the template to stdout" + flag --project type=bool default="false" usage="Install for this project only (gemini/mux)" + flag --remove type=bool default="false" usage="Remove the integration" + flag --stealth type=bool default="false" usage="Use stealth mode (claude/gemini)" + +bd ship + use: "ship " + short: "Publish a capability for cross-project dependencies" + hidden: false + runnable: true + long: + | Ship a capability to satisfy cross-project dependencies. + | + | This command: + | 1. Finds issue with export: label + | 2. Validates issue is closed (or --force to override) + | 3. Adds provides: label + | + | External projects can depend on this capability using: + | bd dep add external:: + | + | The capability is resolved when the external project has a closed issue + | with the provides: label. + | + | Examples: + | bd ship mol-run-assignee # Ship the mol-run-assignee capability + | bd ship mol-run-assignee --force # Ship even if issue is not closed + | bd ship mol-run-assignee --dry-run # Preview without making changes + flag --dry-run type=bool default="false" usage="Preview without making changes" + flag --force type=bool default="false" usage="Ship even if issue is not closed" + +bd show + use: "show [id...] [--id=...] [--current]" + aliases: ["view"] + short: "Show issue details" + group: "issues" + hidden: false + runnable: true + flag --as-of type=string default="" usage="Show issue as it existed at a specific commit hash or branch (requires Dolt; commit hashes must be the full 32-character hash from 'bd history', not a prefix)" + flag --brief-deps type=bool default="false" usage="Reduce each dependency to its identity fields in JSON output (--json only; drops description, design, notes and acceptance criteria)" + flag --children type=bool default="false" usage="Show only the children of this issue" + flag --comments-tail type=int default="0" usage="Render only the last N comments in text output, preceded by one elision line naming how many older ones were hidden (text output only; 0, the default, renders every comment unchanged; N must be >= 0)" + flag --current type=bool default="false" usage="Show the currently active issue (in-progress, hooked, or last touched)" + flag --id type=stringArray default="[]" usage="Issue ID (use for IDs that look like flags, e.g., --id=gt--xyz)" + flag --include-comments type=bool default="false" usage="Stream full comment bodies in JSON output (--json only; may be slow on issues with many comments). Without it the comments field is absent entirely, not truncated: an issue with comments carries comment_count and comments_omitted=true, so check those before reading an absent comments field as none." + flag --include-dependents type=bool default="false" usage="Stream full dependent issues in JSON output (--json only; may be slow on hub beads)" + flag --local-time type=bool default="false" usage="Show timestamps in local time instead of UTC (date-only fields are always local)" + flag --long type=bool default="false" usage="Show all available fields (extended metadata, agent identity, gate fields, etc.)" + flag --refs type=bool default="false" usage="Show issues that reference this issue (reverse lookup)" + flag --short type=bool default="false" usage="Show compact one-line output per issue" + flag --thread type=bool default="false" usage="Show full conversation thread (for messages)" + flag --watch -w type=bool default="false" usage="Watch for changes and auto-refresh display" + +bd sql + use: "sql " + short: "Execute raw SQL against the beads database" + group: "maint" + hidden: false + runnable: true + long: + | Execute a raw SQL query against the underlying database (Dolt). + | + | Useful for debugging, maintenance, and working around bugs in higher-level commands. + | + | Examples: + | bd sql 'SELECT COUNT(*) FROM issues' + | bd sql 'SELECT id, title FROM issues WHERE status = "open" LIMIT 5' + | bd sql 'DELETE FROM dirty_issues WHERE issue_id = "bd-abc123"' + | bd sql --csv 'SELECT id, title, status FROM issues' + | + | The query is passed directly to the database. Reads (SELECT, WITH ... SELECT, + | SHOW, EXPLAIN) return results as a table (or JSON/CSV with --json/--csv). Writes + | (INSERT, UPDATE, DELETE, DDL) report the number of rows affected. Statements + | that may both write and return rows, such as CALL, are committed and print any + | rows they return (or "OK"). + | + | In proxied-server mode, multiple statements separated by ';' run as a single + | committed batch and report "OK", and --database runs the query against a + | different server database (equivalent to a session USE) without changing the + | project's configured database. + | + | WARNING: Direct database access bypasses the storage layer. Use with caution. + flag --csv type=bool default="false" usage="Output results in CSV format" + +bd stale + use: "stale" + short: "Show stale issues (not updated recently)" + group: "views" + hidden: false + runnable: true + long: + | Show issues that haven't been updated recently and may need attention. + | This helps identify: + | - In-progress issues with no recent activity (may be abandoned) + | - Open issues that have been forgotten + | - Issues that might be outdated or no longer relevant + flag --days -d type=int default="30" usage="Issues not updated in this many days" + flag --exclude-label type=stringSlice default="[]" usage="Exclude issues that have ANY of these labels" + flag --label -l type=stringSlice default="[]" usage="Filter by labels (AND: must have ALL). Can combine with --label-any" + flag --label-any type=stringSlice default="[]" usage="Filter by labels (OR: must have AT LEAST ONE). Can combine with --label" + flag --limit -n type=int default="50" usage="Maximum issues to show" + flag --status -s type=string default="" usage="Filter by status (open|in_progress|blocked|deferred)" + +bd state + use: "state " + short: "Query the current value of a state dimension" + group: "issues" + hidden: false + runnable: true + long: + | Query the current value of a state dimension from an issue's labels. + | + | State labels follow the convention :, for example: + | patrol:active + | mode:degraded + | health:healthy + | + | This command extracts the value for a given dimension. + | + | Examples: + | bd state witness-abc patrol # Output: active + | bd state witness-abc mode # Output: normal + | bd state witness-abc health # Output: healthy + +bd state list + use: "list " + short: "List all state dimensions on an issue" + hidden: false + runnable: true + long: + | List all state labels (dimension:value format) on an issue. + | + | This filters labels to only show those following the state convention. + | + | Example: + | bd state list witness-abc + | # Output: + | # patrol: active + | # mode: normal + | # health: healthy + +bd status + use: "status" + aliases: ["stats"] + short: "Show issue database overview and statistics" + group: "views" + hidden: false + runnable: true + long: + | Show a quick snapshot of the issue database state and statistics. + | + | This command provides a summary of issue counts by state (open, in_progress, + | blocked, closed), ready work, extended statistics (pinned issues, + | average lead time), and recent activity over the last 24 hours from git history. + | + | Similar to how 'git status' shows working tree state, 'bd status' gives you + | a quick overview of your issue database without needing multiple queries. + | + | Use cases: + | - Quick project health check + | - Onboarding for new contributors + | - Integration with shell prompts or CI/CD + | - Daily standup reference + | - Fast CI status checks that don't need blocked-count accuracy + | + | Examples: + | bd status # Show summary with activity + | bd status --no-activity # Skip git activity (faster) + | bd status --no-blocked # Skip slow blocked-count scan (faster) + | bd stats --no-blocked --json # JSON output without blocked count + | bd status --json # JSON format output + | bd status --assigned # Show issues assigned to current user + | bd stats # Alias for bd status + flag --all type=bool default="false" usage="Show all issues (default behavior)" + flag --assigned type=bool default="false" usage="Show issues assigned to current user" + flag --no-activity type=bool default="false" usage="Skip git activity summary (faster)" + flag --no-blocked type=bool default="false" usage="Skip blocked-count computation (faster on large rigs; not supported in proxied-server mode)" + +bd statuses + use: "statuses" + short: "List valid issue statuses" + group: "views" + hidden: false + runnable: true + long: + | List all valid issue statuses and their categories. + | + | Built-in statuses (open, in_progress, blocked, etc.) are always valid. + | Additional statuses can be configured via status.custom: + | + | bd config set status.custom "in_review:active,qa_testing:wip,on_hold:frozen" + | + | Categories control behavior: + | active — appears in 'bd ready' and default 'bd list' + | wip — excluded from 'bd ready', visible in default 'bd list' + | done — excluded from 'bd ready' and default 'bd list' + | frozen — excluded from 'bd ready' and default 'bd list' + | + | Statuses without a category (legacy format) are valid but excluded from 'bd ready'. + | + | Examples: + | bd statuses # List all statuses with icons and categories + | bd statuses --json # Output as JSON + | + +bd supersede + use: "supersede --with " + short: "Mark an issue as superseded by a replacement issue" + group: "deps" + hidden: false + runnable: true + long: + | Mark an issue as superseded by a different (replacement) issue. + | + | The superseded issue is automatically closed with a reference to the replacement. + | Useful for design docs, specs, and evolving artifacts. + | + | Examples: + | bd supersede bd-old --with bd-new # Mark bd-old as superseded by bd-new + flag --with type=string default="" annotations={cobra_annotation_bash_completion_one_required_flag=["true"]} usage="Replacement issue ID (required)" + +bd swarm + use: "swarm" + short: "Swarm management for structured epics" + group: "deps" + hidden: false + runnable: false + long: + | Swarm management commands for coordinating parallel work on epics. + | + | A swarm is a structured body of work defined by an epic and its children, + | with dependencies forming a DAG (directed acyclic graph) of work. + +bd swarm create + use: "create [epic-id]" + short: "Create a swarm molecule from an epic" + hidden: false + runnable: true + long: + | Create a swarm molecule to orchestrate parallel work on an epic. + | + | The swarm molecule: + | - Links to the epic it orchestrates + | - Has mol_type=swarm for discovery + | - Specifies a coordinator (optional) + | - Can be picked up by any coordinator agent + | + | If given a single issue (not an epic), it will be auto-wrapped: + | - Creates an epic with that issue as its only child + | - Then creates the swarm molecule for that epic + | + | Examples: + | bd swarm create bd-epic-123 # Create swarm for epic + | bd swarm create bd-epic-123 --coordinator=observer/ # With specific coordinator + | bd swarm create bd-task-456 # Auto-wrap single issue + flag --coordinator type=string default="" usage="Coordinator address (e.g., my-project/witness)" + flag --force type=bool default="false" usage="Create new swarm even if one already exists" + +bd swarm list + use: "list" + short: "List all swarm molecules" + hidden: false + runnable: true + long: + | List all swarm molecules with their status. + | + | Shows each swarm molecule with: + | - Progress (completed/total issues) + | - Active workers + | - Epic ID and title + | + | Examples: + | bd swarm list # List all swarms + | bd swarm list --json # Machine-readable output + +bd swarm status + use: "status [epic-or-swarm-id]" + short: "Show current swarm status" + hidden: false + runnable: true + long: + | Show the current status of a swarm, computed from beads. + | + | Accepts either: + | - An epic ID (shows status for that epic's children) + | - A swarm molecule ID (follows the link to find the epic) + | + | Displays issues grouped by state: + | - Completed: Closed issues + | - Active: Issues currently in_progress (with assignee) + | - Ready: Open issues with all dependencies satisfied + | - Blocked: Open issues waiting on dependencies + | + | The status is COMPUTED from beads, not stored separately. + | If beads changes, status changes. + | + | Examples: + | bd swarm status gt-epic-123 # Show swarm status by epic + | bd swarm status gt-swarm-456 # Show status via swarm molecule + | bd swarm status gt-epic-123 --json # Machine-readable output + +bd swarm validate + use: "validate [epic-id]" + short: "Validate epic structure for swarming" + hidden: false + runnable: true + long: + | Validate an epic's structure to ensure it's ready for swarm execution. + | + | Checks for: + | - Correct dependency direction (requirement-based, not temporal) + | - Orphaned issues (roots with no dependents) + | - Missing dependencies (leaves that should depend on something) + | - Cycles (impossible to resolve) + | - Disconnected subgraphs + | + | Reports: + | - Ready fronts (waves of parallel work) + | - Estimated worker-sessions + | - Maximum parallelism + | - Warnings for potential issues + | + | Examples: + | bd swarm validate gt-epic-123 # Validate epic structure + | bd swarm validate gt-epic-123 --verbose # Include detailed issue graph + flag --verbose type=bool default="false" usage="Include detailed issue graph in output" + +bd sync + use: "sync" + short: "Pull, check for conflicts, repair is_blocked, and push (the federation loop)" + group: "sync" + hidden: false + runnable: true + long: + | Run one full synchronization cycle against the Dolt remote. + | + | This is the loop every multi-machine beads deployment otherwise hand-rolls in + | shell: + | + | 1. pull from the remote + | 2. check for merge conflicts POSITIVELY, from the merge's own conflict rows + | and from Dolt's conflict tables — never inferred from the pull's exit + | status, which is not a trustworthy conflict signal in either direction + | 3. recompute the denormalized is_blocked flag, so dependency edges merged in + | from another replica do not leave 'bd ready' stale + | 4. push, retrying a bounded number of times when another replica wins the + | push race + | + | The repair in step 3 refuses to run while another writer has uncommitted changes + | to issues/dependencies. That is transient and not this sync's doing, so it is + | retried on the same budget as a push race rather than failing the run. A working + | set that is NOT transient exits 4 instead, because no amount of retrying will + | ever publish and only an operator can clear it. Two kinds of evidence say so: + | constraint violations on the dirty tables are detected positively and escalate + | on the very attempt that finds them; an abandoned uncommitted edit has no such + | positive signal, so it is only inferred once the same pending graph edits have + | blocked every attempt of several consecutive runs. + | + | Conflicts sync cannot resolve safely are NEVER auto-resolved: it halts before + | recomputing or pushing and exits 2, and repeated runs keep halting the same way + | until an operator resolves the divergence. (The pull underneath does auto-settle + | the conflict classes it can settle convergently — machine-local metadata, + | audit-only dependency rows, and last-write-wins on issue cells. Anything beyond + | those halts here.) Whether the halted merge was aborted or left live in the + | working set depends on the pull route, so the halt message reports which. + | + | Exit codes (a sync timer can branch on these without parsing output): + | + | 0 synced, or nothing to do + | 1 error (transport, auth, storage) + | 2 merge conflict — halted, nothing pushed, resolve it by hand + | 3 retries exhausted (push race, or a concurrent writer's dirty working set) + | — transient, nothing pushed, retry on the next tick + | 4 the dirty working set is stuck, not busy: identical pending graph edits + | blocked every attempt of several consecutive runs — nothing pushed, and no + | later tick will publish until an operator clears it + | + | On the default-remote path, a rig with no Dolt remote yet but a git origin + | configured adopts that origin as its Dolt remote first, exactly as 'bd dolt push' + | does — so 'bd sync' works as a first-time federation bring-up step instead of + | reporting 'no remote' and doing nothing. Passing --remote never adopts anything. + | + | This is not 'bd federation sync', which syncs with named peer towns and takes a + | --strategy ours|theirs to resolve whatever conflicts it meets. 'bd sync' targets + | the configured remote and has no such switch: what it cannot settle, it halts on. + | + | Examples: + | bd sync # sync with the default remote + | bd sync --remote mini # sync with a specific remote + | bd sync --attempts 5 # allow more push-race retries + | bd sync --json # machine-parseable outcome + flag --attempts type=int default="3" usage="Maximum pull/push attempts before reporting a transient retry exhaustion (exit 3)" + flag --no-adopt type=bool default="false" usage="Never derive a Dolt remote from git origin (also BD_NO_REMOTE_ADOPT=1)" + flag --remote type=string default="" usage="Sync with a specific named remote instead of the default" + flag --yes -y type=bool default="false" usage="Consent to adopting a Dolt remote derived from git origin when none is configured" + +bd tag + use: "tag &"'`}, want: []byte(`{"s":"&\"'"}`), }, - ) - for _, tc := range cases { + } { t.Run(tc.name, func(t *testing.T) { t.Parallel() got, err := canonicalDurableState(tc.state) @@ -118,9 +159,23 @@ func TestCanonicalDurableStateIsJCS(t *testing.T) { "id": "bd-1", "priority": json.Number("1.0"), "metadata": map[string]any{ - "weight": json.Number("1.50"), - "huge": json.Number("1E300"), - "ordinal": json.Number("9007199254740993"), // 2^53 + 1 + "weight": json.Number("1.50"), + // 1E-300, not 1E300: this test is about number FORM + // canonicalization (ES6 exponential notation), not the admission + // gate. 1E300 denotes an INTEGER value (10^300) past what + // binary64 holds exactly, so refuseUnrepresentableIntegers now + // refuses it -- see version_history_integer_admission_test.go. + // 1E-300 exercises the same exponential FORM without being an + // integer at all, so it stays in scope for this test. + "huge": json.Number("1E-300"), + // 2^53-1, the largest integer binary64 holds exactly. This was + // 2^53+1 until the admission gate began refusing literals that + // binary64 cannot hold: JCS would round such a literal to a + // DIFFERENT VALUE, collapsing two distinct states onto one + // durable_state. That case now lives in + // version_history_integer_admission_test.go, which asserts the + // refusal; this test stays about number FORM canonicalization. + "ordinal": json.Number("9007199254740991"), "tags": []any{json.Number("2.0"), "b", nil}, }, "raw": json.RawMessage(`{ "z" : 10.0e0 , "a" : true }`), @@ -132,9 +187,10 @@ func TestCanonicalDurableStateIsJCS(t *testing.T) { } // RFC 8785: keys sorted, no whitespace, numbers in ES6 Number::toString - // form (1.0 -> 1, 1.50 -> 1.5, 1E300 -> 1e+300, 2^53+1 -> the double it - // rounds to, 10.0e0 -> 10). - want := []byte(`{"id":"bd-1","metadata":{"huge":1e+300,"ordinal":9007199254740992,"tags":[2,"b",null],"weight":1.5},"priority":1,"raw":{"a":true,"z":10}}`) + // form (1.0 -> 1, 1.50 -> 1.5, 1E-300 -> 1e-300, 10.0e0 -> 10). An + // integer-valued literal past 2^53-1, any spelling, never reaches JCS now + // -- the admission gate refuses it first. + want := []byte(`{"id":"bd-1","metadata":{"huge":1e-300,"ordinal":9007199254740991,"tags":[2,"b",null],"weight":1.5},"priority":1,"raw":{"a":true,"z":10}}`) if !bytes.Equal(got, want) { t.Fatalf("canonicalDurableState =\n %s\nwant\n %s", got, want) } @@ -148,7 +204,7 @@ func TestCanonicalDurableStateIsJCS(t *testing.T) { if bytes.Equal(plain, got) { t.Fatalf("plain json.Marshal already equals the canonical form (%s); this test no longer proves canonicalization matters", plain) } - for _, nonCanonical := range []string{"1.0", "1.50", "1E300", "9007199254740993", "10.0e0"} { + for _, nonCanonical := range []string{"1.0", "1.50", "1E-300", "10.0e0"} { if !bytes.Contains(plain, []byte(nonCanonical)) { t.Errorf("plain marshal lost the non-canonical form %q, so the fixture no longer exercises it: %s", nonCanonical, plain) } diff --git a/internal/storage/issueops/version_history_integer_admission_test.go b/internal/storage/issueops/version_history_integer_admission_test.go new file mode 100644 index 000000000..9966afa88 --- /dev/null +++ b/internal/storage/issueops/version_history_integer_admission_test.go @@ -0,0 +1,186 @@ +package issueops + +import ( + "encoding/json" + "errors" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +func issueWithMetadata(meta string) types.Issue { + return types.Issue{ID: "be-1", Title: "t", Metadata: json.RawMessage(meta)} +} + +// A metadata integer past 2^53 used to be ROUNDED by jcs.Transform, which +// collapsed two distinct issue states onto one durable_state and therefore +// one content token. It must be refused instead, so the loss is loud. +func TestCanonicalDurableStateRefusesIntegerPastBinary64(t *testing.T) { + _, err := canonicalDurableState(issueWithMetadata(`{"n":9007199254740993}`)) + if err == nil { + t.Fatal("canonicalDurableState(metadata 9007199254740993) = nil error, want a refusal") + } + if !errors.Is(err, ErrIntegerNotRepresentable) { + t.Fatalf("error = %v, want ErrIntegerNotRepresentable", err) + } +} + +// The defect this admission gate exists to prevent, stated directly: two +// DISTINCT states must never render to the same bytes. +func TestCanonicalDurableStateNeverCollapsesTwoDistinctStates(t *testing.T) { + // Before the admission gate, BOTH of these canonicalized, and both to + // the same bytes: 2^53+1 rounded down onto 2^53. One content token for + // two live states. Now the unrepresentable side is refused, so the pair + // can never be confused for one another. + a, errA := canonicalDurableState(issueWithMetadata(`{"n":9007199254740993}`)) + b, errB := canonicalDurableState(issueWithMetadata(`{"n":9007199254740991}`)) + if errA == nil && errB == nil && string(a) == string(b) { + t.Fatalf("two distinct states produced identical durable_state %s", a) + } + if errA == nil { + t.Fatalf("the unrepresentable state canonicalized instead of being refused: %s", a) + } + if errB != nil { + t.Fatalf("the representable state was refused: %v", errB) + } +} + +// The bound itself, both sides of it, bare-integer spelling. +func TestCanonicalDurableStateIntegerBoundary(t *testing.T) { + for _, tc := range []struct { + name string + meta string + refused bool + }{ + {"2^53-1 accepted", `{"n":9007199254740991}`, false}, + {"2^53 refused", `{"n":9007199254740992}`, true}, + {"2^53+1 refused", `{"n":9007199254740993}`, true}, + {"negative past bound refused", `{"n":-9007199254740993}`, true}, + {"beyond int64 refused", `{"n":18446744073709551616}`, true}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := canonicalDurableState(issueWithMetadata(tc.meta)) + if tc.refused && err == nil { + t.Fatalf("%s: nil error, want refusal", tc.meta) + } + if !tc.refused && err != nil { + t.Fatalf("%s: %v, want acceptance", tc.meta, err) + } + }) + } +} + +// Ordinary fractions must keep working: they are not exactly representable +// either, but ES6 shortest-round-trip returns them to the same binary64 +// value, so they neither round to a different value nor collide. +// +// 1e300 is deliberately NOT in this list: it is a mathematical integer +// (10^300) whose magnitude vastly exceeds 2^53-1, so it is refused like any +// other unrepresentable integer, regardless of spelling. See +// TestCanonicalDurableStateRefusesHugeExponentInteger below. +func TestCanonicalDurableStateStillAcceptsOrdinaryDecimals(t *testing.T) { + for _, meta := range []string{`{"n":0.1}`, `{"n":1.0}`, `{"n":-2.5}`, `{"n":0}`} { + if _, err := canonicalDurableState(issueWithMetadata(meta)); err != nil { + t.Fatalf("canonicalDurableState(%s) = %v, want acceptance", meta, err) + } + } +} + +// 1e300 denotes the integer 10^300 at a magnitude vastly past 2^53-1, and +// is subject to the same collision defect this gate +// exists to close -- binary64 spacing near 10^300 is roughly 2^248, so a wide +// range of distinct large integers near 10^300 collapse onto that one +// double, same failure mode as the 2^53 boundary, larger window. The +// spec for this predicate is "value not form, any spelling, no exceptions" +// (see version_history.go's refuseUnrepresentableIntegers doc comment), +// applied literally that refuses 1e300 -- but two pre-gate tests assumed it +// stayed accepted, one of which lived right here until this admission gate +// (see version_history_durable_state_test.go's "huge" fixture, moved off +// 1E300 for the same reason). +// +// RESOLVED: REFUSE 1e300. The rule applies +// literally, with no notation carve-out -- admitting a spelling this large +// while refusing 9007199254740993 would be indefensible, since the collision +// window near 10^300 (binary64 spacing ~2^248) is vastly larger than the one +// at the 2^53 boundary this gate was built to close. This is final, not +// provisional. +func TestCanonicalDurableStateRefusesHugeExponentInteger(t *testing.T) { + _, err := canonicalDurableState(issueWithMetadata(`{"n":1e300}`)) + if err == nil { + t.Fatal("canonicalDurableState(metadata 1e300) = nil error, want a refusal") + } + if !errors.Is(err, ErrIntegerNotRepresentable) { + t.Fatalf("error = %v, want ErrIntegerNotRepresentable", err) + } +} + +// THE GAP QA FOUND IN THE FIRST CUT OF THIS GATE. The first patch's +// refuseUnrepresentableIntegers skipped any literal containing '.', 'e', or +// 'E' outright, reasoning that non-integer literals round-trip losslessly +// through ES6 shortest-round-trip. That reasoning covers genuinely +// fractional literals (0.1, 1.5) but not integer-VALUED literals written in +// decimal or exponential FORM: 9007199254740993.0, 9.007199254740993e15, and +// 90071992547409930e-1 all denote the same integer VALUE as the bare literal +// 9007199254740993, and all three walked straight past the first gate and +// canonicalized to the identical colliding target 9007199254740992 -- the +// exact defect class this gate exists to close, just reachable through +// spelling instead of magnitude. +// +// The predicate under test must inspect the VALUE (the binary64 nearest +// to the literal) rather than the literal's spelling, so it must +// refuse and accept the same values regardless of which of the three JSON +// number forms (integer, decimal, exponent) carries them. This is pinned +// here for the bound itself; ordinary small decimals are covered separately +// by TestCanonicalDurableStateStillAcceptsOrdinaryDecimals. +func TestCanonicalDurableStateIntegerBoundaryAllSpellings(t *testing.T) { + for _, tc := range []struct { + name string + lit string + refused bool + }{ + // at the bound (2^53-1 = 9007199254740991): every spelling accepted. + {"at bound, bare", `9007199254740991`, false}, + {"at bound, decimal", `9007199254740991.0`, false}, + {"at bound, exponent", `9.007199254740991e15`, false}, + + // one past the bound (2^53+1 = 9007199254740993): every spelling + // refused. The decimal and exponent rows are the QA-found gap. + {"past bound, bare", `9007199254740993`, true}, + {"past bound, decimal (THE GAP)", `9007199254740993.0`, true}, + {"past bound, exponent (THE GAP)", `9.007199254740993e15`, true}, + {"past bound, exponent negative-exp form (THE GAP)", `90071992547409930e-1`, true}, + } { + t.Run(tc.name, func(t *testing.T) { + meta := `{"n":` + tc.lit + `}` + _, err := canonicalDurableState(issueWithMetadata(meta)) + if tc.refused && err == nil { + t.Fatalf("metadata %s: nil error, want refusal", meta) + } + if !tc.refused && err != nil { + t.Fatalf("metadata %s: %v, want acceptance", meta, err) + } + if tc.refused && !errors.Is(err, ErrIntegerNotRepresentable) { + t.Fatalf("metadata %s: error = %v, want ErrIntegerNotRepresentable", meta, err) + } + }) + } +} + +// Same property as TestCanonicalDurableStateNeverCollapsesTwoDistinctStates, +// spelled in decimal form -- the exact QA-found gap stated as a distinctness +// property rather than a table row: two states differing only in a +// decimal-spelled metadata integer past 2^53 must never render to the same +// bytes. +func TestCanonicalDurableStateNeverCollapsesDecimalSpellingOfDistinctStates(t *testing.T) { + a, errA := canonicalDurableState(issueWithMetadata(`{"n":9007199254740993.0}`)) + b, errB := canonicalDurableState(issueWithMetadata(`{"n":9007199254740991.0}`)) + if errA == nil && errB == nil && string(a) == string(b) { + t.Fatalf("two distinct states produced identical durable_state %s", a) + } + if errA == nil { + t.Fatalf("the unrepresentable state (9007199254740993.0) canonicalized instead of being refused: %s", a) + } + if errB != nil { + t.Fatalf("the representable state (9007199254740991.0) was refused: %v", errB) + } +} diff --git a/internal/storage/issueops/version_history_number_admission_test.go b/internal/storage/issueops/version_history_number_admission_test.go new file mode 100644 index 000000000..f68193aa9 --- /dev/null +++ b/internal/storage/issueops/version_history_number_admission_test.go @@ -0,0 +1,298 @@ +package issueops + +import ( + "errors" + "math" + "math/rand" + "runtime" + "strconv" + "strings" + "testing" +) + +// admitNumber runs the admission gate over one JSON number literal in the +// position the mint meets it: an object member of an issue's metadata. +func admitNumber(lit string) error { + return refuseUnrepresentableIntegers([]byte(`{"n":` + lit + `}`)) +} + +// The admission rule, stated once for the tests below: a JSON number literal +// is admitted into a durable_state if and only if the binary64 nearest to it +// has magnitude at most 2^53-1, whatever the literal's spelling (integer, +// decimal or exponent), and a literal that overflows binary64 is refused. +// Ordinary fractions such as 0.1 stay admitted, and so do magnitudes too small +// for binary64, which round to zero. + +// A fraction whose nearest double lies at or beyond 2^53 used to be admitted: +// the old rule looked only at literals that denote an integer VALUE, and +// 9007199254740993.5 is not one. jcs.Transform then rounds it to the integer +// 9007199254740994, so two distinct issue states shared one durable_state, +// which is exactly what the gate exists to prevent. Refusing must depend on +// where the nearest double falls, not on whether the literal looks integral. +func TestNumberAdmissionRefusesFractionsWhoseNearestDoubleIsPastTheBound(t *testing.T) { + for _, tc := range []struct { + lit string + refused bool + why string + }{ + {"9007199254740993.5", true, "nearest double is 2^53+2"}, + {"9007199254740994.5", true, "nearest double is 2^53+2"}, + {"9007199254740991.5", true, "a tie between 2^53-1 and 2^53 that rounds to the even 2^53"}, + {"9007199254740991.75", true, "nearest double is 2^53"}, + {"-9007199254740993.5", true, "magnitude decides, not sign"}, + {"9007199254740990.5", false, "a tie that rounds to the even 2^53-2, inside the range"}, + {"9007199254740991.25", false, "nearest double is 2^53-1, inside the range"}, + {"9007199254740991.0", false, "exactly 2^53-1"}, + } { + t.Run(tc.lit, func(t *testing.T) { + err := admitNumber(tc.lit) + if tc.refused { + if !errors.Is(err, ErrIntegerNotRepresentable) { + t.Fatalf("admitNumber(%s) = %v, want ErrIntegerNotRepresentable (%s)", tc.lit, err, tc.why) + } + if _, mintErr := canonicalDurableState(issueWithMetadata(`{"n":` + tc.lit + `}`)); !errors.Is(mintErr, ErrIntegerNotRepresentable) { + t.Fatalf("canonicalDurableState(metadata %s) = %v, want ErrIntegerNotRepresentable", tc.lit, mintErr) + } + return + } + if err != nil { + t.Fatalf("admitNumber(%s) = %v, want acceptance (%s)", tc.lit, err, tc.why) + } + }) + } +} + +// numberAdmissionCorpus is every literal the closure property is checked +// over: the boundary cases the rule was written around, every spelling of the +// values on either side of 2^53, and pseudo-random doubles in three renderings. +// The seed is fixed so a failure names a literal that reproduces. +func numberAdmissionCorpus() []string { + corpus := []string{ + "0", "-0", "0.0", "-0.0", "1", "1.0", "-2.5", "0.1", "3.14159265358979323846", "0.30000000000000004", + "5e-324", "4.9e-324", "2.2250738585072014e-308", "1e-7", "1e-400", "1e-100000000", + "9007199254740991", "9007199254740992", "9007199254740993", "9.007199254740991e15", "90071992547409930e-1", + "9007199254740993.5", "9007199254740994.5", "9007199254740991.5", "9007199254740990.5", + "1727000000000000000", "1727000000000000123", "1e21", "1e300", "1.7976931348623157e308", + "123456789012345678901234567890", "18446744073709551616", + } + // Every spelling of the integers and near-integers either side of the bound. + for delta := int64(-6); delta <= 6; delta++ { + base := strconv.FormatInt(int64(1)<<53+delta, 10) + for _, frac := range []string{"", ".0", ".25", ".5", ".75", ".999999"} { + corpus = append(corpus, base+frac, "-"+base+frac) + } + } + rng := rand.New(rand.NewSource(20260930)) + for _, scale := range []float64{1, 1e3, 1e9, 1e15, 1e-9} { + for range 60 { + f := (rng.Float64()*2 - 1) * scale + corpus = append(corpus, + strconv.FormatFloat(f, 'g', -1, 64), + strconv.FormatFloat(f, 'e', 17, 64), + strconv.FormatFloat(f, 'f', -1, 64)) + } + } + for range 200 { + f := math.Float64frombits(rng.Uint64()) + if math.IsNaN(f) || math.IsInf(f, 0) { + continue + } + corpus = append(corpus, strconv.FormatFloat(f, 'g', -1, 64), strconv.FormatFloat(f, 'e', -1, 64)) + } + return corpus +} + +// The gate must be closed under its own canonicalization: whatever it admits +// canonicalizes to a form it also admits. Otherwise a value can pass at the +// door and become unmintable one step later, which is what 9007199254740991.5 +// did (it rounds to 2^53, and the canonical bytes are then refused). Checked as +// a property over a corpus, not by example. +func TestNumberAdmissionIsClosedUnderCanonicalization(t *testing.T) { + admitted := 0 + for _, lit := range numberAdmissionCorpus() { + doc := []byte(`{"n":` + lit + `}`) + if err := refuseUnrepresentableIntegers(doc); err != nil { + continue // refused literals are outside the property + } + admitted++ + canonical, err := jcsCanonicalize(doc) + if err != nil { + t.Errorf("literal %s: jcsCanonicalize: %v", lit, err) + continue + } + if err := refuseUnrepresentableIntegers(canonical); err != nil { + t.Errorf("literal %s is admitted but its canonical form %s is refused: %v", lit, canonical, err) + } + } + if admitted < 100 { + t.Fatalf("only %d corpus literals were admitted; the property is close to vacuous", admitted) + } +} + +// The classification must not depend on how large an exponent the literal +// spells. The old rule parsed every literal as an exact rational, so a huge +// exponent either cost a million-digit integer or fell outside what the +// parser accepts and came back as an invalid literal, a different class of +// error from the refusal it is. Overflow is a refusal; a magnitude too small +// for binary64 is admitted. +func TestNumberAdmissionClassifiesByMagnitudeWhateverTheExponent(t *testing.T) { + for _, tc := range []struct { + lit string + refused bool + }{ + {"1e100000000", true}, + {"1e1000000", true}, + {"1e309", true}, + {"-1e400", true}, + {"1.7976931348623159e308", true}, + {"1e-100000000", false}, + {"1e-400", false}, + {"-1e-400", false}, + {"5e-324", false}, + } { + t.Run(tc.lit, func(t *testing.T) { + err := admitNumber(tc.lit) + switch { + case tc.refused && !errors.Is(err, ErrIntegerNotRepresentable): + t.Fatalf("admitNumber(%s) = %v, want ErrIntegerNotRepresentable", tc.lit, err) + case !tc.refused && err != nil: + t.Fatalf("admitNumber(%s) = %v, want acceptance", tc.lit, err) + } + }) + } +} + +// The gate allocates nothing proportional to an exponent. Measured as an +// allocation count and never as wall time, so a loaded machine cannot flake it, +// and it is what distinguishes a classifier that builds a million-digit integer +// from one that does not. +// +// The count is exact only without the race detector. Under it sync.Pool drops +// one Put in four at random (sync/pool.go), and the refusal builds its error with +// fmt.Errorf, whose printer comes from a pool, so a call now and then allocates a +// printer the pool would have supplied: a literal that costs 22 allocations reads +// 23, or 24, on a run where a printer was dropped, and comparing two +// independently averaged samples with a strict > is a coin flip. That noise only +// ever ADDS allocations, so the fewest allocations over many single-call samples +// is the count without it, and it is the same on every run. The comparison stays +// strict, with no margin to tune, and it loses no sensitivity: a classifier that +// builds per-exponent state does so on every call, so it raises the fewest too. +func TestNumberAdmissionAllocationsDoNotGrowWithTheExponent(t *testing.T) { + // The chance that every one of these samples is noisy is under one in 10^19. + const samples = 32 + fewest := func(lit string) float64 { + doc := []byte(`{"n":` + lit + `}`) + least := math.Inf(1) + for range samples { + least = math.Min(least, testing.AllocsPerRun(1, func() { _ = refuseUnrepresentableIntegers(doc) })) + } + return least + } + baseline := fewest("1e400") + for _, lit := range []string{"1e1000000", "1e100000000", "-1e1000000"} { + if got := fewest(lit); got > baseline { + t.Errorf("%s allocates %v times per call against %v for 1e400: allocation grows with the exponent", lit, got, baseline) + } + } +} + +// TestNumberAdmissionBytesDoNotGrowWithTheExponent is the count bound's twin, and finding 6 +// of the #6661 review. The count bound passes a classifier that builds the number it is +// asked about: one big-integer allocation is one allocation whether it holds 400 bits or a +// hundred million. What grows with the exponent is then the size of the allocation, so this +// bounds bytes: the fewest bytes one call allocates for a literal with a huge exponent is +// no more than for a small one, plus a margin and a few bytes for each byte of literal (a +// refusal names the literal in its message). +// +// The fewest over many single-call samples, as in the count bound and for the same reason: +// whatever else allocates while a sample runs only ever ADDS bytes, so the minimum is the +// cost of the call itself. TotalAlloc is read before and after each call, with GOMAXPROCS +// pinned to one for the measurement as testing.AllocsPerRun does, so a background +// goroutine does not add to a sample. +func TestNumberAdmissionBytesDoNotGrowWithTheExponent(t *testing.T) { + const ( + samples = 32 + smallLiteral = "1e400" + // What the bound allows beyond the small literal's bytes: a margin, and a few + // bytes for each byte a longer literal adds to the refusal's message. + slackBytes = 1024 + perLitByte = 16 + ) + defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) + fewest := func(lit string) uint64 { + doc := []byte(`{"n":` + lit + `}`) + least := uint64(math.MaxUint64) + var before, after runtime.MemStats + for range samples { + runtime.ReadMemStats(&before) + _ = refuseUnrepresentableIntegers(doc) + runtime.ReadMemStats(&after) + least = min(least, after.TotalAlloc-before.TotalAlloc) + } + return least + } + baseline := fewest(smallLiteral) + for _, lit := range []string{"1e1000000", "1e100000000", "-1e1000000"} { + limit := baseline + slackBytes + perLitByte*uint64(max(len(lit)-len(smallLiteral), 0)) + if got := fewest(lit); got > limit { + t.Errorf("%s allocates %d bytes per call against %d for %s (limit %d): bytes grow with the exponent", lit, got, baseline, smallLiteral, limit) + } + } +} + +// The sentinel names the range it enforces. Its old wording said a literal +// was not exactly representable, which no longer describes what is refused: +// 9007199254740993.5 is a fraction, and the rule is about magnitude. The +// identifier keeps its historical name so nothing that matches it with +// errors.Is has to change; the text is what a person reads. +func TestIntegerNotRepresentableTextNamesTheIJSONRange(t *testing.T) { + const want = "number is outside the I-JSON exact-integer range (magnitude above 2^53-1)" + got := ErrIntegerNotRepresentable.Error() + if got != want { + t.Fatalf("ErrIntegerNotRepresentable.Error() = %q, want %q", got, want) + } + if !strings.Contains(got, "I-JSON") { + t.Errorf("sentinel text %q does not name I-JSON", got) + } + if strings.Contains(got, "cannot represent") { + t.Errorf("sentinel text %q still uses the old wording", got) + } + err := admitNumber("9007199254740993") + if err == nil || err.Error() != want+": 9007199254740993" { + t.Fatalf("refusal text = %v, want the sentinel followed by the offending literal", err) + } +} + +// Nothing the store already accepted becomes admitted or refused differently. +// Dolt does not hand a literal back the way it was written: an integer up to +// int64 is stored exactly and every other number is stored as a double, so what +// the mint sees is the right-hand column. Each row pins the verdict on that +// column, which is what production meets. The verdicts are the ones the rule +// had before it changed, so this stays green through the change and fails only +// if the new rule moves one. +func TestNumberAdmissionKeepsTheVerdictOnEveryLiteralAsTheStoreReturnsIt(t *testing.T) { + for _, tc := range []struct { + written string + returned string // what a Dolt JSON column hands back for it + refused bool + }{ + {"9007199254740993", "9007199254740993", true}, + {"1727000000000000123", "1727000000000000123", true}, + {"9007199254740993.5", "9007199254740994", true}, + {"1.0", "1", false}, + {"0.1", "0.1", false}, + {"3.14159265358979323846", "3.141592653589793", false}, + {"1e300", "1" + strings.Repeat("0", 300), true}, + {"123456789012345678901234567890", "123456789012345680000000000000", true}, + } { + t.Run(tc.written, func(t *testing.T) { + err := admitNumber(tc.returned) + if tc.refused && !errors.Is(err, ErrIntegerNotRepresentable) { + t.Fatalf("admitNumber(%s), the store's rendering of %s = %v, want a refusal", tc.returned, tc.written, err) + } + if !tc.refused && err != nil { + t.Fatalf("admitNumber(%s), the store's rendering of %s = %v, want acceptance", tc.returned, tc.written, err) + } + }) + } +} diff --git a/internal/storage/issueops/version_history_preenable_scan_test.go b/internal/storage/issueops/version_history_preenable_scan_test.go new file mode 100644 index 000000000..74f57b903 --- /dev/null +++ b/internal/storage/issueops/version_history_preenable_scan_test.go @@ -0,0 +1,680 @@ +package issueops + +import ( + "context" + "database/sql/driver" + "encoding/json" + "errors" + "fmt" + "go/ast" + "go/parser" + "go/token" + "io/fs" + "reflect" + "regexp" + "sort" + "strings" + "testing" + "time" + + "github.com/DATA-DOG/go-sqlmock" + + "github.com/steveyegge/beads/internal/storage/sqlbuild" + "github.com/steveyegge/beads/internal/types" +) + +// With versioned history on, the mint runs in the same transaction as the +// mutation that reaches it, so refusing at the mint IS refusing the write: a +// number outside the I-JSON range aborts the writer's own transaction and +// nothing it did is committed. The mint reads the whole issue, so the number +// can be in any field that holds one: in metadata, or in a gate's timeout, +// which encoding/json writes as a count of nanoseconds. The mint's reads run +// first and its two writes, the version row and the current_revision advance, +// come last, so a refusal must arrive after the reads and before either write. +// +// The mock scripts exactly the reads. It expects no INSERT into issue_versions +// and no UPDATE of issues.current_revision, so a mint that wrote before it +// refused would make the mock fail the call with an unexpected-statement error +// instead of the refusal asserted here. The caller's own rollback closes the +// transaction, as every store does when the mint returns an error. +// +// The refusal names the top-level field the number was found in, as well as the +// literal, so a person who reads it knows which part of the issue to fix. +func TestRecordVersionInTxRefusesANumberOutsideTheRangeAndWritesNothing(t *testing.T) { + for _, tc := range []struct { + name string + column string + value driver.Value + literal string + field string + }{ + {"a number in metadata", "metadata", `{"ts":1727000000000000000}`, "1727000000000000000", "metadata"}, + {"a gate timeout past 2^53-1 nanoseconds", "timeout_ns", int64(2600 * time.Hour), "9360000000000000", "timeout"}, + } { + t.Run(tc.name, func(t *testing.T) { + const id = "bd-9" + _, mock, tx := beginMockTx(t) + defer ScopeVersionedHistoryTransaction(tx, true)() + + values := issueRowValues(id, "carries an out-of-range number") + for i, col := range issueColumns() { + if col == tc.column { + values[i] = tc.value + } + } + mock.ExpectQuery(regexp.QuoteMeta("SELECT " + IssueSelectColumns + " FROM issues " + sqlbuild.LeaseJoin("issues") + " WHERE id = ?")). + WithArgs(id). + WillReturnRows(issueRows().AddRow(values...)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT label FROM labels WHERE issue_id = ? ORDER BY label")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"label"})) + // design §16.2b's write fence reads participation_generation right after the + // snapshot. A non-NULL value is a participating row, so the mint goes on to the + // refusal this test pins; a NULL one would be a legacy row and mint nothing. + mock.ExpectQuery(regexp.QuoteMeta("SELECT participation_generation FROM issues WHERE id = ?")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"participation_generation"}).AddRow(1)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT 1 FROM wisps LIMIT 1")). + WillReturnRows(sqlmock.NewRows([]string{"1"})) + mock.ExpectQuery(`FROM dependencies WHERE issue_id IN`). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"issue_id", "depends_on_id", "type", "created_at", "created_by", "metadata", "thread_id"})) + mock.ExpectQuery(regexp.QuoteMeta("SELECT epoch FROM store_epoch WHERE id = 1")). + WillReturnRows(sqlmock.NewRows([]string{"epoch"}).AddRow(1)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT COALESCE(MAX(revision), 0) + 1 FROM issue_versions WHERE issue_id = ?")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"next"}).AddRow(1)) + mock.ExpectRollback() + + err := RecordVersionInTx(context.Background(), tx, id, "actor") + if !errors.Is(err, ErrIntegerNotRepresentable) { + t.Fatalf("RecordVersionInTx = %v, want ErrIntegerNotRepresentable", err) + } + if !strings.Contains(err.Error(), id) { + t.Errorf("refusal %q does not name the issue %s", err, id) + } + if !strings.Contains(err.Error(), tc.literal) { + t.Errorf("refusal %q does not name the offending literal %s", err, tc.literal) + } + if !strings.Contains(err.Error(), fmt.Sprintf("%q", tc.field)) { + t.Errorf("refusal %q does not name the field %q the number was found in", err, tc.field) + } + if rbErr := tx.Rollback(); rbErr != nil { + t.Fatalf("rolling back the writer's transaction: %v", rbErr) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("the mint read or wrote something other than the scripted reads: %v", err) + } + }) + } +} + +// A legacy row (participation_generation NULL) holding the same out-of-range number is outside +// the mint's refusal: design §16.2b's write fence returns right after the snapshot, so the +// admission gate never runs and RecordVersionInTx returns nil. +// +// The mock scripts the snapshot, the labels and the fence's read returning NULL, and nothing after +// it. A mint that read the dependencies, the epoch or a revision, or wrote, before it decided to +// skip would fail the call with an unexpected-statement error instead of returning nil, so this is +// the cheapest pin of the fence's order against the gate. +func TestRecordVersionInTxSkipsALegacyRowBeforeTheAdmissionGate(t *testing.T) { + const id = "bd-9" + _, mock, tx := beginMockTx(t) + defer ScopeVersionedHistoryTransaction(tx, true)() + + values := issueRowValues(id, "a legacy row that carries an out-of-range number") + for i, col := range issueColumns() { + if col == "metadata" { + values[i] = `{"ts":1727000000000000000}` + } + } + mock.ExpectQuery(regexp.QuoteMeta("SELECT " + IssueSelectColumns + " FROM issues " + sqlbuild.LeaseJoin("issues") + " WHERE id = ?")). + WithArgs(id). + WillReturnRows(issueRows().AddRow(values...)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT label FROM labels WHERE issue_id = ? ORDER BY label")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"label"})) + mock.ExpectQuery(regexp.QuoteMeta("SELECT participation_generation FROM issues WHERE id = ?")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"participation_generation"}).AddRow(nil)) + mock.ExpectRollback() + + if err := RecordVersionInTx(context.Background(), tx, id, "actor"); err != nil { + t.Fatalf("RecordVersionInTx on a legacy row = %v, want nil: the fence skips it before the admission gate", err) + } + if rbErr := tx.Rollback(); rbErr != nil { + t.Fatalf("rolling back the writer's transaction: %v", rbErr) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("the mint read or wrote something after the fence skipped the row: %v", err) + } +} + +// TestRecordVersionAtInTxKeepsThePlaneRuleButNotTheFence pins what the +// test-support mint (RecordVersionAtInTx, mintUnfenced) does on the paths #6943 +// gave the shared body. +// +// - A row the wisps table holds, flags clear: the plane rule is not the fence, +// so the unfenced mint honours it like the other two kinds. The issues-table +// read finds nothing and the mint returns nil having written nothing, where +// before it would have inserted a version row no issues row points at. +// - An issues-table row flagged NoHistory: never versioned, and the unfenced +// mint never declares participation, so it returns right after the snapshot, +// without reading or stamping participation_generation. +// - A legacy row (participation_generation NULL), flags clear: the fence does +// not apply, so it mints, and the closing UPDATE advances current_revision +// alone, with no stamp. +// +// The mock scripts each sequence exactly, so an extra read or any write fails +// the call with an unexpected-statement error. +func TestRecordVersionAtInTxKeepsThePlaneRuleButNotTheFence(t *testing.T) { + const id = "bd-7" + at := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC) + issuesSnapshot := regexp.QuoteMeta("SELECT " + IssueSelectColumns + " FROM issues " + sqlbuild.LeaseJoin("issues") + " WHERE id = ?") + participation := regexp.QuoteMeta("SELECT participation_generation FROM issues WHERE id = ?") + + t.Run("a row the wisps table holds mints nothing", func(t *testing.T) { + _, mock, tx := beginMockTx(t) + mock.ExpectQuery(issuesSnapshot).WithArgs(id).WillReturnRows(issueRows()) + mock.ExpectQuery(regexp.QuoteMeta("SELECT " + IssueSelectColumns + " FROM wisps " + sqlbuild.LeaseJoin("wisps") + " WHERE id = ?")). + WithArgs(id). + WillReturnRows(issueRows().AddRow(issueRowValues(id, "a squashed wisp root, flags clear")...)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT label FROM wisp_labels WHERE issue_id = ? ORDER BY label")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"label"})) + mock.ExpectQuery(participation).WithArgs(id).WillReturnRows(sqlmock.NewRows([]string{"participation_generation"})) + mock.ExpectRollback() + + if err := RecordVersionAtInTx(context.Background(), tx, id, "actor", at); err != nil { + t.Fatalf("RecordVersionAtInTx on a wisps-table row = %v, want nil", err) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("the unfenced mint did something after finding no issues row: %v", err) + } + }) + + t.Run("an issues row flagged no-history is neither minted nor stamped", func(t *testing.T) { + _, mock, tx := beginMockTx(t) + values := issueRowValues(id, "no-history, on the issues plane") + for i, col := range issueColumns() { + if col == "no_history" { + values[i] = int64(1) + } + } + mock.ExpectQuery(issuesSnapshot).WithArgs(id).WillReturnRows(issueRows().AddRow(values...)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT label FROM labels WHERE issue_id = ? ORDER BY label")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"label"})) + mock.ExpectRollback() + + if err := RecordVersionAtInTx(context.Background(), tx, id, "actor", at); err != nil { + t.Fatalf("RecordVersionAtInTx on a no-history row = %v, want nil", err) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("the unfenced mint read or wrote something for a no-history row: %v", err) + } + }) + + t.Run("a legacy row is minted and left unstamped", func(t *testing.T) { + _, mock, tx := beginMockTx(t) + mock.ExpectQuery(issuesSnapshot).WithArgs(id). + WillReturnRows(issueRows().AddRow(issueRowValues(id, "legacy, history was off when it was made")...)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT label FROM labels WHERE issue_id = ? ORDER BY label")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"label"})) + mock.ExpectQuery(participation).WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"participation_generation"}).AddRow(nil)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT 1 FROM wisps LIMIT 1")). + WillReturnRows(sqlmock.NewRows([]string{"1"})) + mock.ExpectQuery(`FROM dependencies WHERE issue_id IN`). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"issue_id", "depends_on_id", "type", "created_at", "created_by", "metadata", "thread_id"})) + mock.ExpectQuery(regexp.QuoteMeta("SELECT epoch FROM store_epoch WHERE id = 1")). + WillReturnRows(sqlmock.NewRows([]string{"epoch"}).AddRow(1)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT COALESCE(MAX(revision), 0) + 1 FROM issue_versions WHERE issue_id = ?")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"next"}).AddRow(1)) + mock.ExpectExec(`INSERT INTO issue_versions`). + WithArgs(id, int64(1), 1, sqlmock.AnyArg(), "actor", at, sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(regexp.QuoteMeta("UPDATE issues SET current_revision = ?, updated_at = updated_at WHERE id = ?")). + WithArgs(int64(1), id). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectRollback() + + if err := RecordVersionAtInTx(context.Background(), tx, id, "actor", at); err != nil { + t.Fatalf("RecordVersionAtInTx on a legacy row = %v, want nil", err) + } + if err := tx.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("the unfenced mint did not mint a legacy row exactly once, unstamped: %v", err) + } + }) +} + +// refusalClass names what an admission verdict is, so two functions can be +// compared for agreement without depending on their exact wording. +func refusalClass(err error) string { + switch { + case err == nil: + return "admitted" + case errors.Is(err, ErrIntegerNotRepresentable): + return "number outside the I-JSON range" + case strings.Contains(err.Error(), "Duplicate key"): + return "duplicate key" + default: + return "other refusal" + } +} + +func issueWithTimeout(timeout time.Duration) types.Issue { + return types.Issue{ID: "be-1", Title: "t", IssueType: types.TypeGate, Timeout: timeout} +} + +// The check the pre-enable scan runs and the check the mint runs must never +// disagree, or a store could pass the scan, be switched on, and then refuse the +// first write to the row the scan cleared. So the check is the mint's own two +// steps behind one exported name, and this pins that they agree on every shape +// of issue. +// +// The domain is the WHOLE issue, because that is what the mint canonicalizes and +// what the scan hands the check. Metadata covers a number past the range, a +// fraction rounding past it, duplicate keys at the top level and nested, +// ordinary values, null, empty and an empty object, and text that is not JSON at +// all. The other field that can reach the range is a gate's timeout, a +// time.Duration that encoding/json writes as nanoseconds: 2^53-1 ns is about +// 104.25 days, so 2500h is admitted and 2600h is not. +func TestCheckIssueVersionableAgreesWithTheMint(t *testing.T) { + const maxExact = 1<<53 - 1 // 9007199254740991 ns, the last whole nanosecond count in range + for _, tc := range []struct { + name string + issue types.Issue + want string + }{ + {"number past the range", issueWithMetadata(`{"ts":1727000000000000000}`), "number outside the I-JSON range"}, + {"fraction rounding past the range", issueWithMetadata(`{"n":9007199254740993.5}`), "number outside the I-JSON range"}, + {"overflowing exponent", issueWithMetadata(`{"n":1e400}`), "number outside the I-JSON range"}, + {"number nested in an array", issueWithMetadata(`{"a":[1,{"b":-9007199254740993}]}`), "number outside the I-JSON range"}, + {"duplicate key", issueWithMetadata(`{"k":1,"k":2}`), "duplicate key"}, + {"nested duplicate key", issueWithMetadata(`{"a":{"k":1,"k":2}}`), "duplicate key"}, + {"ordinary values", issueWithMetadata(`{"a":1,"b":[0.1,2,"x"],"c":{"d":null}}`), "admitted"}, + {"number at the bound", issueWithMetadata(`{"n":9007199254740991}`), "admitted"}, + {"tiny magnitude", issueWithMetadata(`{"n":1e-400}`), "admitted"}, + {"null", issueWithMetadata(`null`), "admitted"}, + {"empty object", issueWithMetadata(`{}`), "admitted"}, + {"empty", issueWithMetadata(``), "admitted"}, + {"text that is not JSON", issueWithMetadata(`{"a":`), "other refusal"}, + + {"no timeout", issueWithTimeout(0), "admitted"}, + {"timeout 2500h", issueWithTimeout(2500 * time.Hour), "admitted"}, + {"timeout 2600h", issueWithTimeout(2600 * time.Hour), "number outside the I-JSON range"}, + {"timeout 8760h", issueWithTimeout(8760 * time.Hour), "number outside the I-JSON range"}, + {"negative timeout -2600h", issueWithTimeout(-2600 * time.Hour), "number outside the I-JSON range"}, + {"timeout of exactly 2^53-1 ns", issueWithTimeout(time.Duration(maxExact)), "admitted"}, + {"timeout of exactly 2^53 ns", issueWithTimeout(time.Duration(maxExact + 1)), "number outside the I-JSON range"}, + {"timeout in range beside ordinary metadata", func() types.Issue { + issue := issueWithTimeout(time.Hour) + issue.Metadata = json.RawMessage(`{"ok":1}`) + return issue + }(), "admitted"}, + } { + t.Run(tc.name, func(t *testing.T) { + check := CheckIssueVersionable(&tc.issue) + _, mint := canonicalDurableState(tc.issue) + if got := refusalClass(check); got != tc.want { + t.Errorf("CheckIssueVersionable = %v (%s), want %s", check, got, tc.want) + } + if got := refusalClass(mint); got != tc.want { + t.Errorf("canonicalDurableState = %v (%s), want %s", mint, got, tc.want) + } + if refusalClass(check) != refusalClass(mint) { + t.Errorf("the pre-enable check and the mint disagree: check %v, mint %v", check, mint) + } + }) + } +} + +// The scan runs the check over every issue the mint would version and skips +// the ones it would not, by the mint's own rule (IsWisp): ephemeral rows and +// no-history rows are never versioned, so a poisoned value in one can never +// abort a write and is not an obstacle to switching history on. The scan +// reports what it found in the order it was given, names each offender with +// the refusal the mint would return and the field it was found in, and finds +// nothing in a clean store. +// +// A gate whose timeout is over 105 days is the case that motivated checking the +// whole issue: its timeout is past 2^53-1 ns, so, if it participates in history, +// the mint refuses every write to it, and a scan that looked only at metadata +// cleared the switch over it. +func TestFindUnversionableFindsWhatTheMintWouldRefuse(t *testing.T) { + oversize := json.RawMessage(`{"ts":1727000000000000000}`) + overlong := 105 * 24 * time.Hour + issues := []*types.Issue{ + {ID: "bd-1", Metadata: oversize}, + {ID: "bd-2", Metadata: json.RawMessage(`{"k":1,"k":2}`)}, + {ID: "bd-3", Metadata: json.RawMessage(`{"ok":1}`)}, + {ID: "bd-4", Ephemeral: true, Metadata: oversize}, + {ID: "bd-5", NoHistory: true, Metadata: oversize}, + {ID: "bd-6"}, + {ID: "bd-7", Metadata: json.RawMessage(`{"n":9007199254740993.5}`)}, + {ID: "bd-8", Ephemeral: true, WispPlaneOverride: boolPtr(false), Metadata: oversize}, + {ID: "bd-9", WispPlaneOverride: boolPtr(true), Metadata: oversize}, + {ID: "bd-10", IssueType: types.TypeGate, Timeout: overlong}, + {ID: "bd-11", IssueType: types.TypeGate, Timeout: 2500 * time.Hour}, + {ID: "bd-12", IssueType: types.TypeGate, Ephemeral: true, Timeout: overlong}, + {ID: "bd-13", IssueType: types.TypeGate, Timeout: -overlong}, + } + + got := FindUnversionable(issues) + + want := []struct { + id string + class string + field string + }{ + {"bd-1", "number outside the I-JSON range", "metadata"}, + {"bd-2", "duplicate key", "metadata"}, + {"bd-7", "number outside the I-JSON range", "metadata"}, + // The override decides which plane the mint routes an issue to, and the + // scan follows it: bd-8 is versioned despite Ephemeral, bd-9 is not. + {"bd-8", "number outside the I-JSON range", "metadata"}, + {"bd-10", "number outside the I-JSON range", "timeout"}, + {"bd-13", "number outside the I-JSON range", "timeout"}, + } + if len(got) != len(want) { + t.Fatalf("FindUnversionable found %d issues %v, want %d", len(got), unversionableIDs(got), len(want)) + } + for i, w := range want { + if got[i].ID != w.id { + t.Fatalf("offender %d is %s, want %s (order of the input); got %v", i, got[i].ID, w.id, unversionableIDs(got)) + } + if class := refusalClass(got[i].Err); class != w.class { + t.Errorf("%s: refusal class %q (%v), want %q", w.id, class, got[i].Err, w.class) + } + if got[i].Field != w.field { + t.Errorf("%s: field %q, want %q", w.id, got[i].Field, w.field) + } + if !strings.Contains(got[i].Err.Error(), fmt.Sprintf("%q", w.field)) { + t.Errorf("%s: refusal %q does not name the field %q", w.id, got[i].Err, w.field) + } + } + + clean := []*types.Issue{ + {ID: "bd-1", Metadata: json.RawMessage(`{"ok":1,"f":0.1}`)}, + {ID: "bd-2"}, + {ID: "bd-3", Metadata: json.RawMessage(`null`)}, + {ID: "bd-4", Ephemeral: true, Metadata: oversize}, + {ID: "bd-5", IssueType: types.TypeGate, Timeout: 2500 * time.Hour}, + {ID: "bd-6", IssueType: types.TypeGate, Ephemeral: true, Timeout: overlong}, + } + if found := FindUnversionable(clean); len(found) != 0 { + t.Fatalf("a store with nothing the mint would refuse reported %v", unversionableIDs(found)) + } + if found := FindUnversionable(nil); len(found) != 0 { + t.Fatalf("no issues reported %v", unversionableIDs(found)) + } +} + +func unversionableIDs(found []UnversionableIssue) []string { + ids := make([]string, 0, len(found)) + for _, f := range found { + ids = append(ids, f.ID) + } + return ids +} + +// The scan does not hand the check the issue the mint sees. It reads a lite +// projection (the heavy text columns are left out, labels are not loaded) and +// never loads dependencies, which the mint adds before it canonicalizes. That is +// sound only while everything the scan leaves out is free of numbers: a number in +// a field the scan never loads is one it can never refuse and the mint will. The +// next three tests are how that stays true. They fail, with the way out, the day +// a field is added that breaks it. + +// fieldByJSONName finds the exported field of the struct type typ that +// encoding/json writes under name. +func fieldByJSONName(typ reflect.Type, name string) (reflect.StructField, bool) { + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + if !f.IsExported() { + continue + } + tag := f.Tag.Get("json") + if tag == "-" { + continue + } + jsonName := strings.Split(tag, ",")[0] + if jsonName == "" { + jsonName = f.Name + } + if jsonName == name { + return f, true + } + } + return reflect.StructField{}, false +} + +// heavyColumnProblems maps each column to its field of the issue type and reports +// every one that is missing or that can hold a number. A string or a slice of +// strings cannot: encoding/json writes both without a JSON number in them. +func heavyColumnProblems(columns []string, issue reflect.Type) []string { + var problems []string + for _, col := range columns { + f, ok := fieldByJSONName(issue, col) + if !ok { + problems = append(problems, fmt.Sprintf("column %q has no %s field written under that name: map it, then say whether it can hold a number", col, issue)) + continue + } + numberFree := f.Type.Kind() == reflect.String || + (f.Type.Kind() == reflect.Slice && f.Type.Elem().Kind() == reflect.String) + if !numberFree { + problems = append(problems, fmt.Sprintf("column %q is %s.%s (%s), which can hold a number the scan never reads but the mint refuses: load it in the scan or classify it lite", col, issue, f.Name, f.Type)) + } + } + return problems +} + +// TestTheScanProjectionOmitsOnlyNumberFreeFields pins that every column the +// scan's lite projection leaves out (HeavyDropList) is a string or a list of +// strings on the issue. +func TestTheScanProjectionOmitsOnlyNumberFreeFields(t *testing.T) { + if problems := heavyColumnProblems(HeavyDropList, reflect.TypeOf(types.Issue{})); len(problems) > 0 { + t.Fatalf("the scan's projection leaves out a column that can hold a number:\n %s", strings.Join(problems, "\n ")) + } +} + +// The guard above would pass vacuously if it never found anything to refuse, so +// it is run once against columns that must be refused: numbers, metadata (a +// verbatim JSON document), a column that maps to nothing, and the columns that +// really are number-free. +func TestTheHeavyColumnGuardRefusesWhatCanHoldANumber(t *testing.T) { + issue := reflect.TypeOf(types.Issue{}) + for _, col := range []string{"priority", "estimated_minutes", "timeout", "metadata", "created_at_unix"} { + if problems := heavyColumnProblems([]string{col}, issue); len(problems) != 1 { + t.Errorf("column %q: got %d problems %v, want exactly one", col, len(problems), problems) + } + } + for _, col := range []string{"description", "design", "acceptance_criteria", "notes", "waiters", "payload"} { + if problems := heavyColumnProblems([]string{col}, issue); len(problems) != 0 { + t.Errorf("column %q is number-free but was refused: %v", col, problems) + } + } + problems := heavyColumnProblems([]string{"priority"}, issue) + if len(problems) == 1 && !strings.Contains(problems[0], "load it in the scan or classify it lite") { + t.Errorf("the refusal %q does not say how to resolve it", problems[0]) + } +} + +var ( + timeType = reflect.TypeOf(time.Time{}) + rawMessageType = reflect.TypeOf(json.RawMessage(nil)) +) + +// numberBearingPaths walks typ the way encoding/json does and returns the path of +// everything that can write a JSON number or a value this walk cannot see into: +// an integer, unsigned integer or float (a time.Duration is an int64), a +// json.RawMessage, an interface, a map. It recurses through slices, arrays, +// pointers and structs, skips what json:"-" leaves out and the unexported fields, +// and treats a time.Time as the string it is written as. +func numberBearingPaths(typ reflect.Type, path string, onPath map[reflect.Type]bool) []string { + switch typ { + case timeType: + return nil + case rawMessageType: + return []string{path + " is a json.RawMessage, passed through verbatim"} + } + switch typ.Kind() { + case reflect.Bool, reflect.String: + return nil + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, + reflect.Float32, reflect.Float64: + return []string{fmt.Sprintf("%s is a %s", path, typ)} + case reflect.Interface, reflect.Map: + return []string{fmt.Sprintf("%s is a %s", path, typ.Kind())} + case reflect.Pointer, reflect.Slice, reflect.Array: + return numberBearingPaths(typ.Elem(), path, onPath) + case reflect.Struct: + if onPath[typ] { + return nil + } + onPath[typ] = true + defer delete(onPath, typ) + var found []string + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + if !f.IsExported() || f.Tag.Get("json") == "-" { + continue + } + found = append(found, numberBearingPaths(f.Type, path+"."+f.Name, onPath)...) + } + return found + default: + return []string{fmt.Sprintf("%s is a %s, which this walk cannot classify", path, typ.Kind())} + } +} + +// TestWhatTheMintAddsAndTheScanDoesNotLoadCarriesNoNumber covers the other half +// of what the scan leaves out. The mint adds the issue's dependencies before it +// canonicalizes, and the scan reads without labels, so a number anywhere in a +// Dependency, a Comment, a BondRef or a label would be refused by the mint and +// invisible to the scan. None carries one today; a field that could (a Weight +// int on Dependency) fails here, and the person who adds it decides whether the +// scan has to load it. +func TestWhatTheMintAddsAndTheScanDoesNotLoadCarriesNoNumber(t *testing.T) { + for _, tc := range []struct { + name string + typ reflect.Type + }{ + {"types.Dependency", reflect.TypeOf(types.Dependency{})}, + {"types.Comment", reflect.TypeOf(types.Comment{})}, + {"types.BondRef", reflect.TypeOf(types.BondRef{})}, + {"a label", reflect.TypeOf("")}, + {"the labels of an issue", reflect.TypeOf([]string(nil))}, + } { + t.Run(tc.name, func(t *testing.T) { + if found := numberBearingPaths(tc.typ, tc.name, map[reflect.Type]bool{}); len(found) > 0 { + t.Fatalf("a field the mint writes and the scan does not load can hold a number:\n %s", strings.Join(found, "\n ")) + } + }) + } +} + +// The walk is run against shapes it must flag and shapes it must not, for the +// same reason as the guard above. +func TestTheNumberFreeWalkFlagsEveryNumberBearingShape(t *testing.T) { + type weighted struct { + Weight int `json:"weight"` + } + type unsigned struct{ N uint32 } + type scored struct{ Score float64 } + type waiting struct{ Wait time.Duration } + type verbatim struct{ Blob json.RawMessage } + type anything struct{ Value any } + type keyed struct{ Extra map[string]string } + type nested struct{ Deps []*weighted } + type tagged struct { + Name string `json:"name"` + Tags []string `json:"tags"` + At time.Time `json:"at"` + Skipped int `json:"-"` + _ int + } + type recursive struct{ Next *recursive } + + for name, typ := range map[string]reflect.Type{ + "an int": reflect.TypeOf(weighted{}), + "an unsigned integer": reflect.TypeOf(unsigned{}), + "a float": reflect.TypeOf(scored{}), + "a time.Duration": reflect.TypeOf(waiting{}), + "a json.RawMessage": reflect.TypeOf(verbatim{}), + "an interface": reflect.TypeOf(anything{}), + "a map": reflect.TypeOf(keyed{}), + "an int behind slice+pointer": reflect.TypeOf(nested{}), + } { + if found := numberBearingPaths(typ, "x", map[reflect.Type]bool{}); len(found) == 0 { + t.Errorf("%s was not flagged", name) + } + } + for name, typ := range map[string]reflect.Type{ + "strings, a time, a skipped int and an unexported int": reflect.TypeOf(tagged{}), + "a type that contains itself": reflect.TypeOf(recursive{}), + } { + if found := numberBearingPaths(typ, "x", map[reflect.Type]bool{}); len(found) != 0 { + t.Errorf("%s was flagged: %v", name, found) + } + } +} + +// There is ONE check, CheckIssueVersionable, and the scan and the mint both go +// through it. A check over a part of the issue, the metadata alone as there once +// was, can pass what the mint refuses, and an exported one invites reuse by the +// next caller (a doctor check, say) that then inherits the gap. So no exported +// function in the package may be named for versionability beside the check and +// the scan that calls it. +func TestNoExportedCheckOverASubPartOfTheIssueExistsBesideCheckIssueVersionable(t *testing.T) { + fset := token.NewFileSet() + pkgs, err := parser.ParseDir(fset, ".", func(fi fs.FileInfo) bool { + return !strings.HasSuffix(fi.Name(), "_test.go") + }, parser.SkipObjectResolution) + if err != nil { + t.Fatalf("parse issueops package: %v", err) + } + allowed := map[string]bool{"CheckIssueVersionable": true, "FindUnversionable": true} + seen := map[string]bool{} + var stray []string + for _, pkg := range pkgs { + for _, file := range pkg.Files { + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Recv != nil || !fn.Name.IsExported() { + continue + } + if !strings.Contains(strings.ToLower(fn.Name.Name), "versionable") { + continue + } + seen[fn.Name.Name] = true + if !allowed[fn.Name.Name] { + stray = append(stray, fmt.Sprintf("%s (%s)", fn.Name.Name, fset.Position(fn.Pos()))) + } + } + } + } + sort.Strings(stray) + if len(stray) > 0 { + t.Errorf("an exported check over part of the issue exists beside CheckIssueVersionable: %s", strings.Join(stray, ", ")) + } + for name := range allowed { + if !seen[name] { + t.Errorf("%s was not found: this guard no longer sees the check it protects", name) + } + } +} diff --git a/internal/storage/issueops/version_history_scan.go b/internal/storage/issueops/version_history_scan.go new file mode 100644 index 000000000..855869325 --- /dev/null +++ b/internal/storage/issueops/version_history_scan.go @@ -0,0 +1,53 @@ +package issueops + +import ( + "errors" + + "github.com/steveyegge/beads/internal/types" +) + +// UnversionableIssue names one issue that RecordVersionInTx would refuse to +// version, and the refusal it would return. Field is the top-level field of the +// issue the refusal was found in ("metadata", "timeout"), empty when the refusal +// does not name one. +type UnversionableIssue struct { + ID string + Field string + Err error +} + +// FindUnversionable runs CheckIssueVersionable over every issue in issues that +// the mint would version and returns the ones it refuses, in the order they were +// given. It is the core of the check made when versioned history is switched on: +// with history on, a write that introduces a value the mint refuses aborts in its +// own transaction, but a row that already holds one -- written while history was +// off, or by a path that does not mint -- would, if it participates in history, +// fail every later write to it. The check is over the whole issue, as the mint's +// is, and not over its metadata alone: a gate's timeout past 2^53-1 nanoseconds is +// refused too. +// +// It skips the rows the mint never versions by IsWisp: ephemeral and no-history +// rows are never versioned, so a value they hold can never abort a write. It +// cannot skip legacy rows, because participation is not on types.Issue, so on a +// store with the write fence (design §16.2b) it is a deliberate +// over-approximation: the mint skips a legacy row whatever it holds, and this +// still refuses over it, which is the safe direction because it can only refuse +// more. It does no I/O; the caller loads the rows, which is what lets one +// function serve the direct store and the proxied route. +func FindUnversionable(issues []*types.Issue) []UnversionableIssue { + var found []UnversionableIssue + for _, issue := range issues { + if issue == nil || IsWisp(issue) { + continue + } + if err := CheckIssueVersionable(issue); err != nil { + var named *refusedFieldError + field := "" + if errors.As(err, &named) { + field = named.field + } + found = append(found, UnversionableIssue{ID: issue.ID, Field: field, Err: err}) + } + } + return found +} diff --git a/internal/storage/issueops/version_list.go b/internal/storage/issueops/version_list.go new file mode 100644 index 000000000..fdfc9f2f9 --- /dev/null +++ b/internal/storage/issueops/version_list.go @@ -0,0 +1,77 @@ +package issueops + +import ( + "context" + "database/sql" + "fmt" + + "github.com/steveyegge/beads/internal/storage" +) + +// ListVersionsInTx returns every retained version of issueID, newest first. +// +// No subquery wrapper here, deliberately: HistoryInTx wraps its select +// because dolt_history_issues is a Dolt SYSTEM table and the planner's +// max1Row optimization mis-assumes WHERE id=? yields one row. issue_versions +// is an ordinary user table with a composite (issue_id, revision) primary +// key, so that optimization does not apply and the wrapper would only cost a +// materialization. +// +// An issue with no versions returns an empty slice and no error -- that is a +// truthful "nothing retained here", and it is the CALLER's job to distinguish +// it from "the feature is off" and from "no such issue", which it cannot do +// from this result alone. +// +// A removed version's RemovedRestriction is one of the as-of read's four values: +// whatever else the column holds, a NULL or empty one included, is reported as +// unknown, exactly as AsOfReadInTx reports it. A version that was not removed +// carries none. +func ListVersionsInTx(ctx context.Context, tx DBTX, issueID string) ([]storage.IssueVersion, error) { + rows, err := tx.QueryContext(ctx, ` + SELECT + issue_id, revision, epoch, + COALESCE(change_actor, '') AS change_actor, + COALESCE(change_agent, '') AS change_agent, + COALESCE(change_message, '') AS change_message, + change_at, + COALESCE(attribution_status, '') AS attribution_status, + removed_at, + COALESCE(removed_reason, '') AS removed_reason, + COALESCE(removed_restriction, '') AS removed_restriction, + COALESCE(LENGTH(durable_state), 0) AS state_bytes + FROM issue_versions + WHERE issue_id = ? + ORDER BY revision DESC + `, issueID) + if err != nil { + return nil, fmt.Errorf("failed to list issue versions: %w", err) + } + defer func() { _ = rows.Close() }() + + var out []storage.IssueVersion + for rows.Next() { + var v storage.IssueVersion + var removedAt sql.NullTime + if err := rows.Scan( + &v.IssueID, &v.Revision, &v.Epoch, + &v.ChangeActor, &v.ChangeAgent, &v.ChangeMessage, &v.ChangeAt, + &v.AttributionStatus, + &removedAt, &v.RemovedReason, &v.RemovedRestriction, + &v.StateBytes, + ); err != nil { + return nil, fmt.Errorf("failed to scan issue version: %w", err) + } + if removedAt.Valid { + t := removedAt.Time + v.RemovedAt = &t + v.RemovedRestriction = string(NormalizeRemovedRestriction(v.RemovedRestriction)) + } else { + v.RemovedRestriction = "" + } + out = append(out, v) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("failed to read issue versions: %w", err) + } + return out, nil +} diff --git a/internal/storage/issueops/wake_defers_test.go b/internal/storage/issueops/wake_defers_test.go new file mode 100644 index 000000000..fae1b596e --- /dev/null +++ b/internal/storage/issueops/wake_defers_test.go @@ -0,0 +1,127 @@ +package issueops + +import ( + "context" + "database/sql" + "database/sql/driver" + "fmt" + "slices" + "sync/atomic" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + + "github.com/steveyegge/beads/internal/storage/sqlcount" +) + +// With versioned history off the mint is a no-op, so the sweep has no reason +// to look at an expired row before it wakes it, nor after. With history on it +// reads the woken row to mint its version; a later change that also checks +// each row against the mint before waking it (so that one unversionable row +// cannot abort the whole sweep) must keep that check free when history is +// off. +// +// The mock scripts exactly the statements a one-row sweep issues: the +// expired-row SELECT, the UPDATE, the event's same-content SELECT and its +// INSERT, and the empty wisps pass. Nothing else is expected, and the mock is +// reached through sqlcount, which counts every statement the sweep sends. So +// a sweep that loaded the row (or read its participation) before or after +// waking it fails the pin even if it swallowed the error sqlmock answers that +// statement with, which sqlmock's own checks would not see. The history-on +// run of the same script is the control: the mint's read must make the pin +// refuse it. +func TestWakeExpiredDefersWithHistoryOffLoadsNothingBeforeWaking(t *testing.T) { + if err := wakeAgainstScript(t, false); err != nil { + t.Fatalf("history off: %v", err) + } + t.Run("history on is refused by the same script", func(t *testing.T) { + err := wakeAgainstScript(t, true) + if err == nil { + t.Fatal("the sweep with history on passed the history-off script; " + + "the script no longer sees the reads history adds, so the history-off run above proves nothing") + } + t.Logf("history on, as expected: %v", err) + }) +} + +// wakeStatements is how many statements the script below holds, and so how +// many the history-off sweep may send. +const wakeStatements = 5 + +// wakeAgainstScript runs a one-row sweep on a mocked transaction scoped with +// versioned history as asked, against the script of the statements the +// history-off sweep issues. It returns why the sweep broke the script, or nil +// if it sent exactly the scripted statements and woke the scripted row. +func wakeAgainstScript(t *testing.T, history bool) error { + t.Helper() + mock, tx, counts := countedMockTx(t) + if history { + t.Cleanup(ScopeVersionedHistoryTransaction(tx, true)) + } + // Otherwise tx is not scoped for versioned history, which is how every + // transaction reads while it is off. + mock.ExpectQuery(`SELECT id FROM issues WHERE status = 'deferred'`). + WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow("bd-1")) + mock.ExpectExec(`UPDATE issues SET status = 'open', defer_until = NULL`). + WithArgs(sqlmock.AnyArg(), sqlmock.AnyArg(), "bd-1"). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectQuery(`SELECT id FROM events WHERE issue_id`). + WillReturnRows(sqlmock.NewRows([]string{"id"})) + mock.ExpectExec(`INSERT INTO events`). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectQuery(`SELECT id FROM wisps WHERE status = 'deferred'`). + WillReturnRows(sqlmock.NewRows([]string{"id"})) + + got, err := WakeExpiredDefersInTx(t.Context(), tx) + if err != nil { + return fmt.Errorf("the sweep failed against the script: %w", err) + } + if n := counts.Total(); n != wakeStatements { + return fmt.Errorf("the sweep sent %d statements, want exactly the %d scripted; "+ + "sqlmock refused each extra one with an error the sweep dropped", n, wakeStatements) + } + if err := mock.ExpectationsWereMet(); err != nil { + return fmt.Errorf("the sweep did not send the scripted statements: %w", err) + } + if !slices.Equal(got.Issues, []string{"bd-1"}) || len(got.Wisps) != 0 { + return fmt.Errorf("woken = issues %v, wisps %v, want [bd-1] and none", got.Issues, got.Wisps) + } + return nil +} + +var sqlmockSeq atomic.Int64 + +// countedMockTx begins a transaction on a fresh sqlmock connection that is +// reached through sqlcount, so a pin can count every statement the code +// under test sends, including one whose error it swallowed. +func countedMockTx(t *testing.T) (sqlmock.Sqlmock, *sql.Tx, *sqlcount.Counts) { + t.Helper() + dsn := fmt.Sprintf("issueops_counted_%d", sqlmockSeq.Add(1)) + mockDB, mock, err := sqlmock.NewWithDSN(dsn) + if err != nil { + t.Fatalf("sqlmock.NewWithDSN: %v", err) + } + counts := &sqlcount.Counts{} + db := sql.OpenDB(sqlcount.WrapConnector(sqlmockConnector{dsn: dsn, driver: mockDB.Driver()}, counts)) + t.Cleanup(func() { + _ = db.Close() + _ = mockDB.Close() + }) + mock.ExpectBegin() + tx, err := db.BeginTx(t.Context(), nil) + if err != nil { + t.Fatalf("BeginTx: %v", err) + } + t.Cleanup(func() { _ = tx.Rollback() }) + return mock, tx, counts +} + +// sqlmockConnector opens the sqlmock connection registered under dsn, for +// sql.OpenDB through a wrapping connector. +type sqlmockConnector struct { + dsn string + driver driver.Driver +} + +func (c sqlmockConnector) Connect(context.Context) (driver.Conn, error) { return c.driver.Open(c.dsn) } +func (c sqlmockConnector) Driver() driver.Driver { return c.driver } diff --git a/internal/storage/journalscan/BUILD.bazel b/internal/storage/journalscan/BUILD.bazel index 724b7b0d9..0b829365e 100644 --- a/internal/storage/journalscan/BUILD.bazel +++ b/internal/storage/journalscan/BUILD.bazel @@ -25,3 +25,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/storage/kvkeys/BUILD.bazel b/internal/storage/kvkeys/BUILD.bazel index 3b609a2ca..0c82c0ad2 100644 --- a/internal/storage/kvkeys/BUILD.bazel +++ b/internal/storage/kvkeys/BUILD.bazel @@ -25,3 +25,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/storage/leg_contract_wiring_test.go b/internal/storage/leg_contract_wiring_test.go index 3da2b632e..960efc16b 100644 --- a/internal/storage/leg_contract_wiring_test.go +++ b/internal/storage/leg_contract_wiring_test.go @@ -33,6 +33,30 @@ var neverSatisfiedTags = map[string]bool{"ignore": true, "never": true} const importerOneAccessorWaiverReason = "Importer has one accessor (uow.ImporterSource); " + "the store legs run bd import through the raw seam and implement no Importer role" +// asOfReadNoHTTPWireWaiverReason covers the five R7.1 as-of read contracts +// (backend/conformance/versioned_read_contract.go). Unlike the +// participation-generation cases, which run on this leg because their subject +// is a create or an update the client can send +// (internal/httpclient/served_participation_generation_test.go), the subject +// here is the read itself, AsOfReadFixture.Resolve, and it has no form on the +// wire: +// - R7.1's read is issueops.AsOfReadInTx. No publicops role reaches it and no +// wire operation serves it, so there is nothing for the client to call. +// - The wire carries neither selector (an instant, or a previously served +// version address) nor the gone/unknown refusal the read answers with. +// - The client's only point-in-time read, storage.DoltStorage.AsOf, is a +// Dolt commit-ref read, not R7.1, and it is on the client's unsupported +// allowlist (D8: v0 publishes no history surface). +// +// Binding Resolve to the reference store behind the served env would run the +// cases green, but as a property of that store, never of the client; the store +// legs already pin it. The waiver stands until the wire publishes an as-of +// read. +const asOfReadNoHTTPWireWaiverReason = "the read under test has no form on the http wire: R7.1's as-of read " + + "(issueops.AsOfReadInTx) is reached by no publicops role and no wire operation, the wire carries neither an " + + "instant/version-address selector nor a gone/unknown refusal, and the client's only point-in-time read, " + + "DoltStorage.AsOf, is a Dolt commit-ref read on its unsupported allowlist (D8)" + // The waivers of the three legs registered here. Each is registered beside its // leg rather than written into one literal, so a leg registered elsewhere // brings its waivers the same way; see unwiredContractEntrypoints. @@ -56,8 +80,170 @@ func init() { "RunIssueOperationsCreateReverseNonBlockingStagesConcreteTables": stagingWaiverReason, "RunIssueOperationsCreateParentChildRecomputesWaitsForClosure": stagingWaiverReason, }) + registerContractLegWaivers("http", map[string]string{ + "RunAsOfReadIsCompleteOnlyForTheAnsweringStoresHoldings": asOfReadNoHTTPWireWaiverReason, + "RunAsOfReadRefusesAsGoneOrUnknownNeverSubstitutingAnotherVersion": asOfReadNoHTTPWireWaiverReason, + "RunAsOfReadReportsTheAddressItServed": asOfReadNoHTTPWireWaiverReason, + "RunAsOfReadReturnsTheLatestVersionAtOrBeforeTStrictlyExcludingLater": asOfReadNoHTTPWireWaiverReason, + "RunAsOfReadSelectorAcceptsEitherAnInstantOrAVersionAddress": asOfReadNoHTTPWireWaiverReason, + + "RunCycleDetectorIncludeTracksFindsTheMoleculeRootShape": cycleTracksWireGapWaiverReason, + "RunCycleDetectorIncludeTracksIgnoresAPureTracksLoop": cycleTracksWireGapWaiverReason, + "RunCycleDetectorIncludeTracksWalksEachEdgeInItsStoredDirection": cycleTracksWireGapWaiverReason, + + "RunBootstrapperIdentifiesAFreshSubstrate": bootstrapperPermanentlyUnservableWaiverReason, + "RunBootstrapperLeavesTheSubstrateUntouchedWhenItCannotComplete": bootstrapperPermanentlyUnservableWaiverReason, + "RunBootstrapperRecordsExactlyOneHistoryEntry": bootstrapperPermanentlyUnservableWaiverReason, + "RunBootstrapperRecordsNoHistoryEntryOfItsOwn": bootstrapperPermanentlyUnservableWaiverReason, + "RunBootstrapperRefusesASubstrateCarryingOnlyAPrefix": bootstrapperPermanentlyUnservableWaiverReason, + "RunBootstrapperRefusesASubstrateCarryingOnlyAProjectID": bootstrapperPermanentlyUnservableWaiverReason, + "RunBootstrapperRefusesAnIdentifiedSubstrate": bootstrapperPermanentlyUnservableWaiverReason, + "RunBootstrapperRefusesAnInvalidRequestWithoutWriting": bootstrapperPermanentlyUnservableWaiverReason, + "RunBootstrapperStoresThePrefixWithoutItsTrailingHyphen": bootstrapperPermanentlyUnservableWaiverReason, + + "RunImporterRejectsAStaleRowAndNamesIt": importerOneAccessorWaiverReason, + "RunImporterReportsTheAbsentTargetItDroppedOnce": importerOneAccessorWaiverReason, + "RunImporterWiresTheCrossPlaneEdgeBetweenItsRows": importerOneAccessorWaiverReason, + "RunImporterReportsTheCycleEdgeItDropped": importerOneAccessorWaiverReason, + + "RunACarriedAddressKeepsResolvingAcrossLaterBumps": retentionEpochNoRoleWaiverReason, + "RunADestructiveOperationEnumeratesAffectedAddressesFirst": retentionEpochNoRoleWaiverReason, + "RunAHoldPreventsRemovalAndReportsInRetainedBounds": retentionEpochNoRoleWaiverReason, + "RunALostAddressStaysGoneAcrossASchemeChange": retentionEpochNoRoleWaiverReason, + "RunAStoreThatRemovesStateStillAnswersGoneDurably": retentionEpochNoRoleWaiverReason, + "RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone": retentionEpochNoRoleWaiverReason, + "RunAnAddressNeverResolvesToADifferentState": retentionEpochNoRoleWaiverReason, + "RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange": retentionEpochNoRoleWaiverReason, + "RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed": retentionEpochNoRoleWaiverReason, + "RunErasureMintsACorrectedVersionRatherThanEditingInPlace": retentionEpochNoRoleWaiverReason, + "RunEveryRetentionAnswerNamesItsProducingStore": retentionEpochNoRoleWaiverReason, + "RunForcingAHeldRemovalRecordsWhoWhenWhy": retentionEpochNoRoleWaiverReason, + "RunGoneIsDistinguishableFromUnknown": retentionEpochNoRoleWaiverReason, + "RunRemovalLeavesTheAddressAbleToAnswer": retentionEpochNoRoleWaiverReason, + "RunRemovalNeverReassignsASurvivingAddress": retentionEpochNoRoleWaiverReason, + "RunRemovalReasonIsRetentionErasureOrReorganizationDistinctly": retentionEpochNoRoleWaiverReason, + "RunRemovalReportsTheSurvivingRetainedWindow": retentionEpochNoRoleWaiverReason, + "RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose": retentionEpochNoRoleWaiverReason, + + "RunAdvisoryLeaseAloneDoesNotPreventTheInvariantViolation": crossRecordInvariantNoRoleWaiverReason, + "RunCrossRecordInvariantSurvivesTwoPassingPerRecordGuards": crossRecordInvariantNoRoleWaiverReason, + "RunInvariantRefusalNamesTheViolatedInvariant": crossRecordInvariantNoRoleWaiverReason, + "RunLeaseAcquisitionRecordsNoHistoryEntry": crossRecordInvariantNoRoleWaiverReason, + "RunMaximumEndpointMultiplicityIsAStoreInvariantNotACAS": crossRecordInvariantNoRoleWaiverReason, + "RunMemoryKeyAliasUniquenessIsAStoreInvariantNotACAS": crossRecordInvariantNoRoleWaiverReason, + "RunStoreInvariantTransactionScopesExactlyTheSpanningRecords": crossRecordInvariantNoRoleWaiverReason, + + "RunVersionReconcilerAdvancesBothMarkersOnAnUpgrade": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunVersionReconcilerCatchesUpToTheHighWaterMark": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunVersionReconcilerLeavesTheMarkersStandingWhenItCannotComplete": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunVersionReconcilerRecordsAWorkspaceWithNoMarkers": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunVersionReconcilerRecordsNoHistory": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunVersionReconcilerRefusesADowngradeWithoutAnError": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunVersionReconcilerRefusesAVersionBelowTheHighWaterMark": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunVersionReconcilerRefusesAnEmptyVersion": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunVersionReconcilerTreatsTheSameVersionAsANoOp": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunInitVerifierAnswersEmptyForAnUnidentifiedSubstrate": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunInitVerifierReportsAFailedReadAsAnError": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunInitVerifierReportsAPartialIdentityAsItStands": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + "RunInitVerifierWritesNothing": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason, + + "RunIssueOperationsUpdateClosedFieldsMatchClose": issueOperationsUpdateRawSeamWaiverReason, + "RunIssueOperationsUpdateRawMetadataTakesTheFunnelsValueShapes": issueOperationsUpdateRawSeamWaiverReason, + "RunIssueOperationsUpdateStampsStartedAtOnceOnTheFirstInProgress": issueOperationsUpdateRawSeamWaiverReason, + + "RunLifecycleUpdateExpectedVersionSingleWinnerWithDisjointColumnsUnderConcurrency": issuePatchFieldsNotOnUpdateWireWaiverReason, + "RunLifecycleUpdateExpectedVersionSingleWinnerAcrossUpdateAndCloseUnderConcurrency": issuePatchFieldsNotOnUpdateWireWaiverReason, + + "RunParticipationGenerationNoHistoryIssueCreateDeclaresParticipation": participationGenerationWireGapWaiverReason, + "RunParticipationGenerationUnflaggedWispCreateMintsNothing": participationGenerationWireGapWaiverReason, + "RunParticipationGenerationWispFlagClearMintsNothing": participationGenerationWireGapWaiverReason, + "RunParticipationGenerationWispRootSquashMintsNothing": participationGenerationWireGapWaiverReason, + }) } +// cycleTracksWireGapWaiverReason covers the one CycleDetector widening option +// the HTTP wire does not carry at all. +// +// issueops.DetectCyclesRequest.IncludeTracks is a WIDENING field consumed +// today only by `bd dep cycles` in-process. internal/httpapi/cycles.go calls +// DetectCycles with a bare issueops.DetectCyclesRequest{} — it decodes no +// query parameter for it — and internal/httpclient's httpCycleDetector reads +// the field and, finding no wire parameter to carry it, REFUSES the request +// with a typed, ledger-cited error (encode.RefusedError via refuse(), citing +// "L-cycles-tracks") rather than silently answering the narrower default +// walk. Neither side of the wire has any plumbing for this field, so the +// three IncludeTracks cases cannot be satisfied over HTTP — the client fails +// loudly instead of wiring a narrower answer, which is why these three remain +// unwired rather than run-and-skipped. +// +// No shipped slice adds a query parameter, spec capability token, or +// handshake entry for this option — see "L-cycles-tracks" in the in-repo +// divergence ledger, engdocs/design/http-divergence-ledger.md, which records +// it as a refuse row rather than a wired one. Closing this gap is a new +// slice — a query parameter plus spec/capability plumbing on both ends — not +// a missing test line, so the waiver stays until that slice exists. +const cycleTracksWireGapWaiverReason = "issueops.DetectCyclesRequest.IncludeTracks has no wire plumbing on " + + "either side of internal/httpapi or internal/httpclient today (cycles.go always calls DetectCycles with a " + + "zero-value request; the client's DetectCycles refuses the request via a typed, ledger-cited error — see " + + "\"L-cycles-tracks\" — rather than silently answering the narrower walk); no slice through S13 adds a wire " + + "parameter for it, so closing this is a new, not-yet-numbered slice rather than a missing test line" + +// retentionEpochNoRoleWaiverReason covers the eighteen RetentionFixture and +// EpochFixture cases (backend/conformance/retention_epoch_contract.go). +// All but four of the participation-generation cases run on this leg because +// their subject is a create or an update the client can send +// (internal/httpclient/served_participation_generation_test.go; those four +// stay waived under participationGenerationWireGapWaiverReason). These +// cases are different: every hook of these two fixtures IS the operation +// under test, and none has a form on the wire: +// - EpochFixture's hooks (CurrentEpoch, BumpEpoch, MintUnderEpoch, +// StillServes, Resolve, CurrentAddressFor, LoseVersion) are the R20 epoch +// operations themselves: methods on the concrete *DoltStore and +// *EmbeddedDoltStore over issueops' *InTx bodies, on no storage +// interface, no publicops role and no wire operation. Every call path +// into them starts in a test: the methods are called only from each +// store leg's own _test.go files (its EpochFixture, which the +// backend/conformance contracts drive, and its epoch tests), and the +// *InTx bodies only from those methods, from each other and from tests +// (the uow leg's fixture, through a test-only type assertion, and +// issueops' and the dolt leg's own tests). No command, role or server +// handler reaches them, so no client mutation touches epoch state either. +// - RetentionFixture's hooks (Resolve, Remove, Hold, ForceRemove, Erase, +// Mint) are retention operations no backend implements yet: every +// store leg wires them nil and its cases skip, and the wire has no +// removal, hold, erasure or gone/unknown resolve to bind them to. +// +// Binding the hooks to the reference store behind the served env would run +// the epoch cases green, but as a property of that store, never of the +// client; the store legs already pin it. The waiver stands until retention or +// epoch state gets a publicops role and a wire operation of its own, which +// would be a new role, not a missing test line. +const retentionEpochNoRoleWaiverReason = "every RetentionFixture/EpochFixture hook is the operation under test and " + + "none has a form on the http wire: the R20 epoch operations (CurrentEpoch, BumpEpoch, MintUnderEpoch, " + + "StillServes, Resolve, CurrentAddressFor, LoseVersion) are concrete-store methods on no storage interface, " + + "publicops role or wire operation, reached only from tests (each store leg's fixture and epoch tests call the " + + "methods, the uow fixture calls the issueops bodies through a test-only type assertion), and the retention " + + "hooks (Resolve, Remove, Hold, ForceRemove, Erase, Mint) are implemented by no backend and have no wire " + + "removal, hold, erasure or resolve; binding them to the served env's reference store would test that store, " + + "not the client" + +// crossRecordInvariantNoRoleWaiverReason covers the seven CrossRecordInvariantFixture +// cases, for the same shape of reason as retentionEpochNoRoleWaiverReason. +// +// CrossRecordInvariantFixture (backend/conformance/cross_record_invariant_contract.go) +// is likewise raw hooks with no publicops field — GuardedWrite, +// EnforceCrossRecordInvariant, AcquireAdvisoryLease, +// CountHistoryForSubject, MemoryKeyAliasWrite, GraphEdgeWrite — that assert a +// store's OWN invariant enforcement spanning more than one record at once, +// the kind of guarantee a storage engine's own transaction boundary gives, +// not a wire operation it exposes. dolt, embeddeddolt and uow wire it as the +// engines that hold that boundary; the http leg has none of its own to test. +const crossRecordInvariantNoRoleWaiverReason = "CrossRecordInvariantFixture carries raw per-record/cross-record " + + "storage hooks (GuardedWrite, EnforceCrossRecordInvariant, AcquireAdvisoryLease, CountHistoryForSubject, " + + "MemoryKeyAliasWrite, GraphEdgeWrite) with no publicops role behind them, asserting a storage engine's own " + + "transaction boundary rather than something exposed over a wire; the http leg has no transaction boundary " + + "of its own for this to test" + // bootstrapSplitWaiverReason covers the one pair of entrypoints that is a // RATIFIED PER-LEG SPLIT rather than a gap. // @@ -78,6 +264,24 @@ const bootstrapSplitWaiverReason = "the bootstrap history contracts are a ratifi "legs pin zero because `bd init` commits the identity itself, the unit-of-work leg pins one because the " + "proxied route has no other commit point; each leg wires its own half and the other half is not its promise" +// bootstrapperPermanentlyUnservableWaiverReason covers the nine Bootstrapper +// contracts: PERMANENTLY unservable over http, not merely unwired yet. +// +// internal/httpclient/accessors.go names Bootstrapper (alongside VersionReconciler +// and InitVerifier) as one of the THREE accessors still on the generated +// refusing shell for one reason: "PERMANENTLY UNSERVABLE — no wire operation +// and none coming." `bd init` runs its substrate-identification walk entirely +// client-side before any server exists to dial, so there is no v0 operation for +// an http accessor to bind to and none is coming — closing this gap is not a +// missing line, it is a wire operation nobody has designed. This waiver covers +// Bootstrapper only; VersionReconciler and InitVerifier share the same fate in +// the same comment but are out of scope for the change that added this waiver +// and remain counted against the ceiling until their own reviewed change +// names them too. +const bootstrapperPermanentlyUnservableWaiverReason = "internal/httpclient/accessors.go names Bootstrapper " + + "PERMANENTLY UNSERVABLE over http — no wire operation and none coming — because `bd init` resolves the " + + "substrate identity entirely client-side, before any server exists to dial" + // stagingWaiverReason is why the two staging contracts stop at the two // store-backed legs. // @@ -99,6 +303,123 @@ const stagingWaiverReason = "the unit-of-work provider commits every unit of wor "caller-held working set to stage into and no Commit hook to close one; these two cases assert what a " + "create sweeps into a commit the caller opened" +// versionReconcilerInitVerifierPermanentlyUnservableWaiverReason covers the +// thirteen VersionReconciler and InitVerifier contracts: PERMANENTLY +// unservable over http, not merely unwired yet. +// +// internal/httpclient/accessors.go names VersionReconciler and InitVerifier, +// alongside Bootstrapper, as the three accessors still on the generated +// refusing shell for one reason: "PERMANENTLY UNSERVABLE — no wire operation +// and none coming." Both share Bootstrapper's own fate and (InitVerifier +// shares BootstrapperFixture outright) the same cause: `bd init`'s substrate +// identification and the schema-version reconciliation it drives both run +// entirely client-side, against the on-disk substrate a server-mediated +// caller never touches directly, before or instead of any server existing to +// dial. There is no v0 operation for an http accessor to bind to and none is +// coming. This waiver was left out of the change that added +// bootstrapperPermanentlyUnservableWaiverReason (that change's own comment +// says so) and is added by this one. +const versionReconcilerInitVerifierPermanentlyUnservableWaiverReason = "internal/httpclient/accessors.go names " + + "VersionReconciler and InitVerifier PERMANENTLY UNSERVABLE over http, the same fate as Bootstrapper — no " + + "wire operation and none coming — because both run entirely client-side against the on-disk substrate " + + "(schema-version reconciliation and `bd init`'s own identity read) before or instead of any server existing " + + "to dial" + +// issueOperationsUpdateRawSeamWaiverReason covers the three +// IssueOperationsStagingFixture cases whose SUBJECT is the untyped UpdateRaw +// funnel itself, not merely a fixture that seeds through it. +// +// storage.UpdateIssue is on this client's unsupported allowlist by design +// (D8: re-routing a raw front door would put a second spelling of the edit +// beside the role's), so served_issue_operations_test.go binds UpdateRaw only +// to the REFERENCE store's own untyped funnel (env.reference.UpdateIssue), +// never to the client — see that file's own doc comment. That binding is +// sound for every case actually wired there because none of them takes the +// funnel AS ITS SUBJECT; these three do (RunIssueOperationsUpdateClosedFieldsMatchClose +// drives a reopen/reclose through it, RunIssueOperationsUpdateStampsStartedAtOnceOnTheFirstInProgress +// and RunIssueOperationsUpdateRawMetadataTakesTheFunnelsValueShapes assert +// what it writes). Wiring them against the reference store's funnel would +// assert a property of the store the server happens to share a process with, +// never of the client under test — the same kind of empty assertion binding +// UpdateRaw to the client would be in the other direction. There is no +// client-side UpdateRaw to bind instead: that is D8's allowlist decision, not +// a gap. +const issueOperationsUpdateRawSeamWaiverReason = "these three cases take the untyped UpdateRaw funnel itself as " + + "their subject; storage.UpdateIssue is on this client's unsupported allowlist by design (D8), so there is no " + + "client-side UpdateRaw to bind, and binding the reference store's own funnel instead (as this leg's other " + + "IssueOperationsStagingFixture cases do, to SEED preconditions) would assert a property of the store the " + + "server happens to share a process with, never of the client under test" + +// issuePatchFieldsNotOnUpdateWireWaiverReason covers the two +// LifecycleUpdateFixture concurrency cases whose racers patch +// IssuePatch.SpecID, .AwaitID, and/or .Owner against updateIssue. +// +// THIS IS PENDING, NOT PERMANENT: it is unbuilt work waiting on a wire +// change, not a boundary this leg can never cross. S4 wired the other two +// ExpectedVersion concurrency races (the plain Update race over +// Priority/Notes, and the Close race) against the real served HTTP harness, +// and both pass: precondition_failed decodes to storage.ErrVersionMismatch +// exactly as the local legs report it. These two cases cannot follow +// because SOME of their racers patch fields updateIssue refuses outright +// rather than ever sending — not a race outcome, a refusal before any +// request leaves the client. internal/httpclient/encode/ledger.go already +// names this gap per field (W-IssuePatch.SpecID, W-IssuePatch.Owner, D8 +// refuse-not-drop): neither IssuePatchBody nor +// ApplyPatchBody publishes spec_id at all, and Owner is excluded +// from IssuePatchBody specifically (ApplyPatchBody — issues:batchApply's body +// — does carry it, which is a different operation from updateIssue). Closing +// this gap means publishing those fields on IssuePatchBody, a wire change to +// the write role itself, not a client-side wiring exercise — tracked as a +// follow-up slice, S4b: publish owner/spec_id/await_id on the wire. await_id +// is published on both patch bodies behind issues.update.gates and sent by +// this client (W-IssuePatch.AwaitID retired), so only +// spec_id and owner remain S4b's. Until they land, these two contracts stay +// off this leg rather than asserting a race outcome against a request some of +// its racers never send. +const issuePatchFieldsNotOnUpdateWireWaiverReason = "PENDING, not permanent (tracked as S4b: publish " + + "owner/spec_id/await_id on the wire): two of the four ExpectedVersion concurrency contracts race " + + "IssuePatch.SpecID/.AwaitID/.Owner edits against updateIssue, and SpecID and Owner are refused outright by " + + "this client (W-IssuePatch.SpecID, W-IssuePatch.Owner in " + + "internal/httpclient/encode/ledger.go, D8 refuse-not-drop) rather than ever reaching the server, so the race " + + "never happens over this wire; await_id is sent behind issues.update.gates, and " + + "closing the rest of the gap means publishing spec_id and owner on IssuePatchBody, which is a wire change " + + "to the write role (S4b), not something this leg's test wiring can bind around today" + +// participationGenerationWireGapWaiverReason covers the four +// ParticipationGenerationFixture cases whose mutation has no form on this +// wire. The other cases run on the http leg +// (internal/httpclient/served_participation_generation_test.go): the client +// creates and updates, and the fixture flips the reference store's flag and +// reads its raw columns, as served_dualwrite_history_test.go does. +// +// Each waived case needs a mutation the client cannot send: +// - WispFlagClearMintsNothing clears a wisp's flag IN PLACE with the untyped +// UpdateIssue map {"wisp": false}. storage.UpdateIssue is on this client's +// unsupported allowlist (D8), and IssuePatch has no in-place flag member: +// its Persistence member moves the row between tables, which the +// wisp-arrival cases already run here. +// - WispRootSquashMintsNothing runs the close and that flag clear in ONE +// transaction. RunInTransaction is on the unsupported allowlist too, and +// the wire publishes no squash operation. +// - UnflaggedWispCreateMintsNothing creates an unflagged row in the wisps +// table through import's WispPlaneOverride = &true. The wire drops that +// member (roleIgnoredCreateIssueMembers in batchcreator.go), so an +// unflagged create lands in the issues table. +// - NoHistoryIssueCreateDeclaresParticipation has a no-history ISSUES-table +// create as its subject (WispPlaneOverride = &false). With that member +// dropped, a client create carrying no_history routes to the wisps table +// (TableRouting). Seeding the row through the reference store instead +// would make the create under test the store's own, a property of the +// store the server happens to share a process with, never of the client. +const participationGenerationWireGapWaiverReason = "PENDING, not permanent (no slice tracks it yet; each case runs " + + "on this leg once the wire publishes its mutation: an in-place wisp flag clear, a squash operation, or a create " + + "that names its table plane the way import's WispPlaneOverride does): " + + "the mutation this case needs has no form on the http wire: " + + "an in-place wisp flag clear is an untyped UpdateIssue map and the squash a RunInTransaction, both on this " + + "client's unsupported allowlist (D8), and IssuePatch.Persistence moves the row rather than clearing the flag in " + + "place; an unflagged wisps-table create and a no-history issues-table create both need WispPlaneOverride, " + + "which the wire drops (roleIgnoredCreateIssueMembers), so the first lands in issues and the second in wisps" + // TestEveryLegWiresEveryRoleContract fails when a backend leg skips a role // contract the conformance package exports. // @@ -367,6 +688,27 @@ func finalParamTypeName(fn *ast.FuncDecl) string { // file naming every entrypoint would otherwise satisfy this lock with source no // build compiles. Ordinary constraints — cgo, integration — are counted, // because a contract wired behind one is still wired. +// +// A REFERENCE IS NOT A PASS, and that gap is deliberate rather than a hole in +// this check. Several contracts (RetentionFixture, EpochFixture, BootstrapperFixture, +// VersionReconcilerFixture, ...) are written so a nil hook makes the case +// t.Skip loudly, naming the hook, rather than asserting nothing silently — +// see each fixture's own doc comment. That lets a leg wire the ENTRYPOINT +// (call conformance.RunX, satisfying this static check) while leaving some +// or all of its hooks nil, which runs for real as a skip, not a pass. This +// check cannot see past the call to know which hooks a wiring supplies, so +// it counts the reference as wired either way — a leg that did this would +// read as adopted here while its own `go test -v` output says SKIP. That +// divergence is this package's to prevent by review, the same way +// divergence_citation_gate_test.go (internal/httpclient) already holds the +// served tier's own skipKnownDivergence call sites to a named, ledger-cited +// reason instead of a bare t.Skip: a reviewer reading a wiring diff that adds +// a conformance.RunX reference should expect it to pass for real, or to carry +// a waiver in unwiredContractEntrypoints instead — not to compile a skip and +// call it adopted. As of this lock's current counts, no leg does this: every +// entrypoint a leg's sources name either has every hook that entrypoint's own +// cases need, or the gap is a named waiver here rather than a nil hook left +// standing behind a call this check would count as wired. func conformanceEntrypointsWiredBy(t *testing.T, dir string) (map[string]bool, []string) { t.Helper() files, err := filepath.Glob(filepath.Join(dir, "*_test.go")) diff --git a/internal/storage/memoryops/BUILD.bazel b/internal/storage/memoryops/BUILD.bazel index 5bdd40d2c..19b7f8a47 100644 --- a/internal/storage/memoryops/BUILD.bazel +++ b/internal/storage/memoryops/BUILD.bazel @@ -29,3 +29,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/storage/memoryops/memories.go b/internal/storage/memoryops/memories.go index a9c58e1ff..31dce53e5 100644 --- a/internal/storage/memoryops/memories.go +++ b/internal/storage/memoryops/memories.go @@ -84,9 +84,7 @@ func MemoriesFromConfig(all map[string]string) map[string]string { // destroyed. // // replaced is about the ROW, not the value: a memory stored as the empty string -// reports true even though a Recall of it would report Found false. See -// memoryops.RememberResult.Replaced, which states that divergence rather than -// smoothing it over. +// reports true, just as Recall reports it found. func RememberInTx(ctx context.Context, tx *sql.Tx, key, content string) (replaced bool, err error) { storageKey := StorageKey(key) replaced, err = configRowExistsInTx(ctx, tx, storageKey) @@ -99,31 +97,33 @@ func RememberInTx(ctx context.Context, tx *sql.Tx, key, content string) (replace return replaced, nil } -// RecallInTx reads one memory in the caller's transaction. A key nothing stored -// answers "" with a nil error: the seam cannot tell that from a row stored -// empty, and the role's Found field is where that conflation is stated. -func RecallInTx(ctx context.Context, tx *sql.Tx, key string) (string, error) { - return issueops.GetConfigInTx(ctx, tx, StorageKey(key)) +// RecallInTx reads one memory in the caller's transaction and reports whether +// its row exists. A stored empty value is therefore distinct from no row. +func RecallInTx(ctx context.Context, tx *sql.Tx, key string) (value string, found bool, err error) { + storageKey := StorageKey(key) + err = tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", storageKey).Scan(&value) + if errors.Is(err, sql.ErrNoRows) { + return "", false, nil + } + if err != nil { + return "", false, fmt.Errorf("recall memory %s: %w", storageKey, err) + } + return value, true, nil } // ForgetInTx removes one memory and returns what it held, both in the caller's // transaction — which is what makes the returned value the one that was // actually deleted rather than the one an earlier read happened to see. // -// found is Recall's found, not the row's: a memory stored as the empty string -// reports found false and IS NOT DELETED. That keeps Forget's answer and -// Recall's answer the same statement, which is what a front door printing -// "No memory with key ..." after a successful Recall would otherwise contradict. -// // The delete names the one encoded key. There is no LIKE and no prefix sweep in // it, so forgetting "a" cannot take "a-b" with it. func ForgetInTx(ctx context.Context, tx *sql.Tx, key string) (previous string, found bool, err error) { storageKey := StorageKey(key) - previous, err = issueops.GetConfigInTx(ctx, tx, storageKey) + previous, found, err = RecallInTx(ctx, tx, key) if err != nil { return "", false, err } - if previous == "" { + if !found { return "", false, nil } if err := issueops.DeleteConfigInTx(ctx, tx, storageKey); err != nil { diff --git a/internal/storage/role_accessor_decorator_test.go b/internal/storage/role_accessor_decorator_test.go index 58027bb5b..248f7d890 100644 --- a/internal/storage/role_accessor_decorator_test.go +++ b/internal/storage/role_accessor_decorator_test.go @@ -68,11 +68,11 @@ func roleAccessorNamesOf(surface reflect.Type) (names, unclassified []string) { } // TestEveryStoreRoleAccessorIsClassified fails when DoltStorage hands out an -// interface the census cannot place. Every one of the twenty-eight today is a +// interface the census cannot place. Every one of the thirty-one today is a // facade role, so this costs nothing and closes the path where a role surface // grows a package and the census quietly stops covering it. (roleAccessorNames // is derived, so the count is prose and only this sentence goes stale — but it -// does go stale, and the last three sweeps found it saying twenty-seven.) +// does go stale, and the last four sweeps found it behind.) func TestEveryStoreRoleAccessorIsClassified(t *testing.T) { _, unclassified := roleAccessorNamesOf(reflect.TypeOf((*DoltStorage)(nil)).Elem()) for _, accessor := range unclassified { @@ -151,69 +151,77 @@ func assertRoleAccessorsAreDeclared(t *testing.T, decorator reflect.Type) { } // roleAccessorStore is a DoltStorage whose only real methods are the -// twenty-eight role accessors, each answering with a distinguishable sentinel +// thirty-one role accessors, each answering with a distinguishable sentinel // so a test can tell a decorated surface from a passed-through one. type roleAccessorStore struct { DoltStorage - lifecycle issueops.Lifecycle - reader issueops.Reader - relations issueops.Relations - edges issueops.EdgeReader - blocking issueops.BlockingAnnotator - tree issueops.TreeWalker - graphCounter issueops.GraphCounter - counter issueops.Counter - settings issueops.WorkspaceConfig - memories memoryops.Memories - versions issueops.VersionReconciler - stats issueops.StatsReporter - cycles issueops.CycleDetector - commenter issueops.Commenter - claimer issueops.ReadyClaimer - closer issueops.BatchCloser - creator issueops.BatchCreator - editor issueops.DependencyEditor - applier issueops.BatchApplier - readyCounter issueops.ReadyCounter - querier issueops.Querier - sweeper issueops.Sweeper - deleter issueops.Deleter - bootstrapper issueops.Bootstrapper - verifier issueops.InitVerifier - metadataCAS issueops.MetadataCAS - releaser issueops.Releaser - err error + lifecycle issueops.Lifecycle + reader issueops.Reader + relations issueops.Relations + edges issueops.EdgeReader + blocking issueops.BlockingAnnotator + tree issueops.TreeWalker + graphCounter issueops.GraphCounter + batchGetter issueops.BatchGetter + counter issueops.Counter + settings issueops.WorkspaceConfig + memories memoryops.Memories + versions issueops.VersionReconciler + stats issueops.StatsReporter + cycles issueops.CycleDetector + commenter issueops.Commenter + claimer issueops.ReadyClaimer + closer issueops.BatchCloser + creator issueops.BatchCreator + editor issueops.DependencyEditor + applier issueops.BatchApplier + readyCounter issueops.ReadyCounter + querier issueops.Querier + sweeper issueops.Sweeper + deleter issueops.Deleter + bootstrapper issueops.Bootstrapper + verifier issueops.InitVerifier + metadataCAS issueops.MetadataCAS + releaser issueops.Releaser + leaseReclaimer issueops.LeaseReclaimer + heartbeater issueops.Heartbeater + blockedLister issueops.BlockedLister + err error } func newRoleAccessorStore() *roleAccessorStore { sentinel := &roleAccessorSentinel{} return &roleAccessorStore{ - memories: &memoryRoleSentinel{}, - lifecycle: sentinel, - reader: sentinel, - relations: sentinel, - edges: sentinel, - blocking: sentinel, - graphCounter: sentinel, - counter: sentinel, - settings: sentinel, - versions: sentinel, - stats: sentinel, - cycles: sentinel, - commenter: sentinel, - claimer: sentinel, - closer: sentinel, - creator: sentinel, - editor: sentinel, - applier: sentinel, - readyCounter: sentinel, - querier: sentinel, - sweeper: sentinel, - deleter: sentinel, - bootstrapper: sentinel, - verifier: sentinel, - metadataCAS: sentinel, - releaser: sentinel, + memories: &memoryRoleSentinel{}, + lifecycle: sentinel, + reader: sentinel, + relations: sentinel, + edges: sentinel, + blocking: sentinel, + graphCounter: sentinel, + batchGetter: sentinel, + counter: sentinel, + settings: sentinel, + versions: sentinel, + stats: sentinel, + cycles: sentinel, + commenter: sentinel, + claimer: sentinel, + closer: sentinel, + creator: sentinel, + editor: sentinel, + applier: sentinel, + readyCounter: sentinel, + querier: sentinel, + sweeper: sentinel, + deleter: sentinel, + bootstrapper: sentinel, + verifier: sentinel, + metadataCAS: sentinel, + releaser: sentinel, + leaseReclaimer: sentinel, + heartbeater: sentinel, + blockedLister: sentinel, } } @@ -272,6 +280,9 @@ func (s *roleAccessorStore) DependencyEditor() (issueops.DependencyEditor, error func (s *roleAccessorStore) GraphCounter() (issueops.GraphCounter, error) { return s.graphCounter, s.err } +func (s *roleAccessorStore) BatchGetter() (issueops.BatchGetter, error) { + return s.batchGetter, s.err +} func (s *roleAccessorStore) MetadataCAS() (issueops.MetadataCAS, error) { return s.metadataCAS, s.err } @@ -281,8 +292,17 @@ func (s *roleAccessorStore) BatchApplier() (issueops.BatchApplier, error) { func (s *roleAccessorStore) Releaser() (issueops.Releaser, error) { return s.releaser, s.err } +func (s *roleAccessorStore) LeaseReclaimer() (issueops.LeaseReclaimer, error) { + return s.leaseReclaimer, s.err +} +func (s *roleAccessorStore) Heartbeater() (issueops.Heartbeater, error) { + return s.heartbeater, s.err +} +func (s *roleAccessorStore) BlockedLister() (issueops.BlockedLister, error) { + return s.blockedLister, s.err +} -// roleAccessorSentinel implements twenty-seven of the twenty-eight roles at +// roleAccessorSentinel implements thirty of the thirty-one roles at // once — every one but memoryops.Memories, whose List collides with // issueops.Reader.List and needs the second sentinel below. // Nothing calls its methods; identity is the whole point. @@ -327,6 +347,9 @@ func (*roleAccessorSentinel) CountByGroup(context.Context, issueops.CountByGroup func (*roleAccessorSentinel) CountEdges(context.Context, issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) { return issueops.EdgeCountResult{}, nil } +func (*roleAccessorSentinel) GetMany(context.Context, issueops.GetManyRequest) (issueops.GetManyResult, error) { + return issueops.GetManyResult{}, nil +} func (*roleAccessorSentinel) GetSetting(context.Context, issueops.GetSettingRequest) (issueops.SettingResult, error) { return issueops.SettingResult{}, nil } @@ -404,6 +427,15 @@ func (*roleAccessorSentinel) CompareAndSetKey(context.Context, issueops.CompareA func (*roleAccessorSentinel) Release(context.Context, issueops.ReleaseRequest) (issueops.ReleaseResult, error) { return issueops.ReleaseResult{}, nil } +func (*roleAccessorSentinel) Reclaim(context.Context, issueops.ReclaimRequest) (issueops.ReclaimResult, error) { + return issueops.ReclaimResult{}, nil +} +func (*roleAccessorSentinel) Heartbeat(context.Context, issueops.HeartbeatRequest) (issueops.HeartbeatResult, error) { + return issueops.HeartbeatResult{}, nil +} +func (*roleAccessorSentinel) ListBlocked(context.Context, issueops.BlockedRequest) (issueops.BlockedResult, error) { + return issueops.BlockedResult{}, nil +} // memoryRoleSentinel is the memory role's sentinel, and the one role // memoryRoleSentinel is the remaining role's sentinel, and the one role @@ -436,10 +468,10 @@ func (*memoryRoleSentinel) List(context.Context, memoryops.ListRequest) (memoryo // paragraph rather than four near-identical ones (bd-8ri3m). Reads fire no // completion hooks, so IssueReader, IssueRelations, Counter, StatsReporter, // CycleDetector, EdgeReader, BlockingAnnotator, TreeWalker, GraphCounter, -// ReadyCounter, Querier and InitVerifier deliberately return the inner surface +// ReadyCounter, BlockedLister, Querier and InitVerifier deliberately return the inner surface // unwrapped, // each in its own hook_*.go. The ones in that column that are NOT reads are -// WorkspaceConfig, Memories, VersionReconciler, Bootstrapper, Sweeper and +// WorkspaceConfig, Memories, VersionReconciler, Bootstrapper, Sweeper, // Deleter: a settings write changes the workspace rather than a bead, a // remembered insight names no bead and there is no on_remember to fire, a // version marker names no bead at all, a bootstrap lands on a workspace whose @@ -466,12 +498,14 @@ func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T) {"MetadataCAS", func() (any, error) { return store.MetadataCAS() }, inner.metadataCAS, true}, {"BatchApplier", func() (any, error) { return store.BatchApplier() }, inner.applier, true}, {"Releaser", func() (any, error) { return store.Releaser() }, inner.releaser, true}, + {"LeaseReclaimer", func() (any, error) { return store.LeaseReclaimer() }, inner.leaseReclaimer, true}, {"IssueReader", func() (any, error) { return store.IssueReader() }, inner.reader, false}, {"IssueRelations", func() (any, error) { return store.IssueRelations() }, inner.relations, false}, {"EdgeReader", func() (any, error) { return store.EdgeReader() }, inner.edges, false}, {"BlockingAnnotator", func() (any, error) { return store.BlockingAnnotator() }, inner.blocking, false}, {"TreeWalker", func() (any, error) { return store.TreeWalker() }, inner.tree, false}, {"GraphCounter", func() (any, error) { return store.GraphCounter() }, inner.graphCounter, false}, + {"BatchGetter", func() (any, error) { return store.BatchGetter() }, inner.batchGetter, false}, {"Counter", func() (any, error) { return store.Counter() }, inner.counter, false}, {"WorkspaceConfig", func() (any, error) { return store.WorkspaceConfig() }, inner.settings, false}, {"Memories", func() (any, error) { return store.Memories() }, inner.memories, false}, @@ -484,6 +518,8 @@ func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T) {"Deleter", func() (any, error) { return store.Deleter() }, inner.deleter, false}, {"Bootstrapper", func() (any, error) { return store.Bootstrapper() }, inner.bootstrapper, false}, {"InitVerifier", func() (any, error) { return store.InitVerifier() }, inner.verifier, false}, + {"Heartbeater", func() (any, error) { return store.Heartbeater() }, inner.heartbeater, true}, + {"BlockedLister", func() (any, error) { return store.BlockedLister() }, inner.blockedLister, false}, } { t.Run(test.name, func(t *testing.T) { surface, err := test.got() @@ -523,12 +559,14 @@ func TestHookFiringStoreRoleAccessorsPropagateInnerErrors(t *testing.T) { {"MetadataCAS", func() (any, error) { return store.MetadataCAS() }}, {"BatchApplier", func() (any, error) { return store.BatchApplier() }}, {"Releaser", func() (any, error) { return store.Releaser() }}, + {"LeaseReclaimer", func() (any, error) { return store.LeaseReclaimer() }}, {"IssueReader", func() (any, error) { return store.IssueReader() }}, {"IssueRelations", func() (any, error) { return store.IssueRelations() }}, {"EdgeReader", func() (any, error) { return store.EdgeReader() }}, {"BlockingAnnotator", func() (any, error) { return store.BlockingAnnotator() }}, {"TreeWalker", func() (any, error) { return store.TreeWalker() }}, {"GraphCounter", func() (any, error) { return store.GraphCounter() }}, + {"BatchGetter", func() (any, error) { return store.BatchGetter() }}, {"Counter", func() (any, error) { return store.Counter() }}, {"WorkspaceConfig", func() (any, error) { return store.WorkspaceConfig() }}, {"Memories", func() (any, error) { return store.Memories() }}, @@ -541,6 +579,8 @@ func TestHookFiringStoreRoleAccessorsPropagateInnerErrors(t *testing.T) { {"Deleter", func() (any, error) { return store.Deleter() }}, {"Bootstrapper", func() (any, error) { return store.Bootstrapper() }}, {"InitVerifier", func() (any, error) { return store.InitVerifier() }}, + {"Heartbeater", func() (any, error) { return store.Heartbeater() }}, + {"BlockedLister", func() (any, error) { return store.BlockedLister() }}, } { t.Run(test.name, func(t *testing.T) { if _, err := test.got(); !errors.Is(err, want) { diff --git a/internal/storage/rowid/BUILD.bazel b/internal/storage/rowid/BUILD.bazel index 180d6fea9..b0f65270f 100644 --- a/internal/storage/rowid/BUILD.bazel +++ b/internal/storage/rowid/BUILD.bazel @@ -26,3 +26,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/storage/schema/BUILD.bazel b/internal/storage/schema/BUILD.bazel index 5108ff37d..68e8b9b75 100644 --- a/internal/storage/schema/BUILD.bazel +++ b/internal/storage/schema/BUILD.bazel @@ -13,6 +13,7 @@ go_library( "dirty_tables_error.go", "ignored_cursor_untrack.go", "lock.go", + "migrate_consent.go", "migration_content_hashes.go", "migration_repairs.go", "remote_migrate_gate.go", @@ -117,6 +118,10 @@ go_library( "migrations/ignored/0026_dep_rekey_dedup_marker.up.sql", "migrations/ignored/0027_add_wisps_current_revision.up.sql", "migrations/0069_widen_issue_versions_datetime_precision.up.sql", + "migrations/ignored/0028_add_wisps_participation_generation.up.sql", + "migrations/0070_add_participation_generation.up.sql", + "migrations/0071_add_removed_restriction.up.sql", + "migrations/0072_add_epoch_minted_addresses.up.sql", ], importpath = "github.com/steveyegge/beads/internal/storage/schema", visibility = ["//:__subpackages__"], @@ -146,10 +151,15 @@ go_test( "dolt_ignore_seed_test.go", "ignored_cursor_untrack_test.go", "lock_test.go", + "migrate_consent_test.go", "migration_0067_versioned_beads_test.go", "migration_0068_add_attribution_status_test.go", "migration_0069_datetime_precision_test.go", + "migration_0070_add_participation_generation_test.go", + "migration_0071_add_removed_restriction_test.go", + "migration_0072_add_epoch_minted_addresses_test.go", "migration_body_drain_test.go", + "migration_freeze_test.go", "migration_watchdog_test.go", "progress_test.go", "remote_migrate_gate_test.go", @@ -163,6 +173,7 @@ go_test( deps = [ "//internal/debug", "//internal/storage/depid", + "//internal/storage/issueops", "//internal/storage/rowid", "//internal/testutil", "@com_github_data_dog_go_sqlmock//:go-sqlmock", @@ -191,3 +202,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/storage/schema/cli_migrations.go b/internal/storage/schema/cli_migrations.go index ade8014c6..1d161cbc6 100644 --- a/internal/storage/schema/cli_migrations.go +++ b/internal/storage/schema/cli_migrations.go @@ -157,6 +157,26 @@ func cliCompatibleMigrationSQL(name, sqlText string) string { // 0067 creates both as plain DATETIME and 0068 retypes only // durable_state -- so both of 0069's MODIFYs always fire here too. return cliMigration0069WidenIssueVersionsDatetimePrecision + case "0070_add_participation_generation.up.sql": + // Direct DDL for the same reason as 0067: the source migration's + // PREPARE guards (INFORMATION_SCHEMA probes) are what make the raw + // .up.sql idempotent when replayed onto an already-migrated store, + // and the 2.2.x CLI no-ops a prepared ADD COLUMN. issues and wisps + // both exist by this point in the series (0067 creates the versioned + // columns on both) and neither carries participation_generation yet, + // so both of 0070's ALTERs always fire on a fresh bundle -- this + // substitute ALTERs wisps directly, the same as 0067's, so it + // belongs on cliSubstituteAssumesWispTables too. + return cliMigration0070AddParticipationGeneration + case "0071_add_removed_restriction.up.sql": + // Direct DDL for the same reason as 0067/0068: the source migration's + // PREPARE guard (an INFORMATION_SCHEMA probe) is what makes the raw + // .up.sql idempotent when replayed onto an already-migrated store, + // and the 2.2.x CLI no-ops a prepared ADD COLUMN. issue_versions is + // always present here -- 0067 runs earlier in the same fresh-bundle + // series -- and never carries removed_restriction yet, so the column + // always needs adding on a fresh bundle. + return cliMigration0071AddRemovedRestriction default: return sqlText } @@ -193,6 +213,11 @@ func cliSubstituteAssumesWispTables(name string) bool { // cliMigration0067AddVersionedBeadsSchema drops the source's // @wisps_cr_needs_add table-exists guard and ALTERs wisps directly. return true + case "0070_add_participation_generation.up.sql": + // cliMigration0070AddParticipationGeneration drops the source's + // @wisps_pg_needs_add table-exists guard and ALTERs wisps directly, + // the same shape 0067's override already uses for current_revision. + return true default: return false } @@ -290,6 +315,24 @@ ALTER TABLE issue_versions MODIFY COLUMN durable_state LONGBLOB;` const cliMigration0069WidenIssueVersionsDatetimePrecision = `ALTER TABLE issue_versions MODIFY COLUMN change_at DATETIME(6) NOT NULL; ALTER TABLE issue_versions MODIFY COLUMN removed_at DATETIME(6);` +// cliMigration0070AddParticipationGeneration is 0070 with its two guarded +// PREPARE blocks replaced by the direct ALTERs they would run on a fresh +// database: participation_generation BIGINT NULL on issues, mirrored +// inertly on wisps (design §16.3 steps 4-5, be-dt74u amendment, be-h89oq). +// issues and wisps both exist by this point in the series (0067 creates the +// versioned columns on both) and neither carries participation_generation +// yet, so both ALTERs always fire on a fresh bundle -- this substitute +// ALTERs wisps directly, the same as 0067's, so it belongs on +// cliSubstituteAssumesWispTables too. +const cliMigration0070AddParticipationGeneration = `ALTER TABLE issues ADD COLUMN participation_generation BIGINT NULL; +ALTER TABLE wisps ADD COLUMN participation_generation BIGINT NULL;` + +// cliMigration0071AddRemovedRestriction is 0071 with its one guarded PREPARE +// block replaced by the direct ALTER it would run on a fresh database. +// issue_versions is created earlier in the same series by 0067 and never +// carries removed_restriction yet, so the column always needs adding here. +const cliMigration0071AddRemovedRestriction = `ALTER TABLE issue_versions ADD COLUMN removed_restriction VARCHAR(30);` + const cliMigration0041SplitDependenciesTarget = `DELETE FROM dolt_nonlocal_tables; CALL DOLT_COMMIT('-Am', 'disable nonlocal tables for fk migrations'); SET FOREIGN_KEY_CHECKS = 0; diff --git a/internal/storage/schema/converged.go b/internal/storage/schema/converged.go index 587220485..3a2b606b1 100644 --- a/internal/storage/schema/converged.go +++ b/internal/storage/schema/converged.go @@ -99,7 +99,9 @@ func alreadyConverged(ctx context.Context, db DBConn, databaseName string, selec // deliberately non-ignored table that the next pull's auto-commit puts // into HEAD and push replicates fleet-wide. // - // Two always-succeeding reads on the hot path, both bounded to one row. + // Two SHOW TABLES listings on the hot path, safe to issue because + // selectTargetDatabase has put the session on the target (see + // readIgnoredCursorState). state, err := readIgnoredCursorState(ctx, db, qualifier) if err != nil { return false, err diff --git a/internal/storage/schema/converged_test.go b/internal/storage/schema/converged_test.go index 8eff9441e..67d26ead6 100644 --- a/internal/storage/schema/converged_test.go +++ b/internal/storage/schema/converged_test.go @@ -715,7 +715,7 @@ func TestAlreadyConvergedFailsClosedOnUnreadableState(t *testing.T) { db, mock := newMockDB(t) expectCurrentDatabase(mock, "testdb") - mock.ExpectQuery(`SELECT COUNT\(\*\) FROM information_schema\.tables`). + mock.ExpectQuery(regexp.QuoteMeta("SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = DATABASE()")). WillReturnError(sql.ErrConnDone) converged, err := alreadyConverged(context.Background(), db, "testdb", nil) diff --git a/internal/storage/schema/cursor_reality_test.go b/internal/storage/schema/cursor_reality_test.go index c41144fab..5fde1827f 100644 --- a/internal/storage/schema/cursor_reality_test.go +++ b/internal/storage/schema/cursor_reality_test.go @@ -5,13 +5,14 @@ import ( "database/sql" "errors" "regexp" + "slices" "strings" "testing" "github.com/DATA-DOG/go-sqlmock" ) -// stubSentinelTables replaces the INFORMATION_SCHEMA probe with a fixed answer +// stubSentinelTables replaces the table-existence probe with a fixed answer // for the duration of a test, following the issueRowCounter seam convention in // this package. The DBConn is never touched, so these run with no database. func stubSentinelTables(t *testing.T, present map[string]bool, probeErr error) *[]string { @@ -45,13 +46,48 @@ func stubSentinelColumns(t *testing.T, present map[string]bool, probeErr error) return &probed } +// expectSentinelColumnProbe mocks the real column-sentinel probe in order: the +// carrier table's existence through sentinelTableExists (a SHOW TABLES read), +// then — only when the table is there — the SHOW COLUMNS read. An absent column +// is an empty SHOW COLUMNS result set, not a zero count. +func expectSentinelColumnProbe(mock sqlmock.Sqlmock, sc schemaSentinelColumn, tablePresent, columnPresent bool) { + expectShowTable(mock, sc.table, tablePresent) + if !tablePresent { + return + } + rows := sqlmock.NewRows([]string{"Field", "Type", "Null", "Key", "Default", "Extra"}) + if columnPresent { + rows.AddRow(sc.column, "varchar(255)", "YES", "", nil, "") + } + mock.ExpectQuery(regexp.QuoteMeta("SHOW COLUMNS FROM " + sc.table + " LIKE '" + sc.column + "'")). + WillReturnRows(rows) +} + // allSentinelTables is the "everything the table sentinels ask for is present" -// shape, so column-sentinel cases can say so without repeating the list. +// shape, so column-sentinel cases can say so without repeating the list. Both +// the unconditional-floor-0 tables and the floored tables share the same +// sentinelTableExists probe, so both must be marked present here or a case +// meant to isolate one sentinel would spuriously trip another. func allSentinelTables() map[string]bool { - present := make(map[string]bool, len(ignoredSource.sentinelTables)) + present := make(map[string]bool, len(ignoredSource.sentinelTables)+len(ignoredSource.sentinelFlooredTables)) for _, table := range ignoredSource.sentinelTables { present[table] = true } + for _, st := range ignoredSource.sentinelFlooredTables { + present[st.table] = true + } + return present +} + +// allSentinelTablesExcept is allSentinelTables with the named tables absent, +// for cases that need every sentinel healthy except the one(s) under test. +// Variadic so a case can contradict two sentinels of the same kind at once, +// which is what pins the minimum a single loop accumulates. +func allSentinelTablesExcept(tables ...string) map[string]bool { + present := allSentinelTables() + for _, table := range tables { + delete(present, table) + } return present } @@ -103,12 +139,13 @@ func TestCursorRealityFloor(t *testing.T) { // These two cases document the two real-world shapes the stub seam // collapses: an absent leases table and a present-but-column-less leases // table both drive sentinelColumnExists to false - // (columns["leases.granted_node"] == false), because the real - // schemaColumnExists COUNT(*) is 0 for a missing table and a missing - // column alike. They deliberately exercise the same branch — the naming - // records intent, not a distinct seam path. Both floor at 11, which is - // what lets the replay heal both (0012 re-creates leases, 0016 adds the - // column) without reaching back to 0007. + // (columns["leases.granted_node"] == false), because the real probe + // reports a missing table (its existence read) and a missing column (its + // SHOW COLUMNS read) alike. They deliberately exercise the same branch — + // the naming records intent, not a distinct seam path; the probe itself + // is pinned by TestSentinelColumnProbeNeverAsksAMissingTable. Both floor + // at 11, which is what lets the replay heal both (0012 re-creates leases, + // 0016 adds the column) without reaching back to 0007. { name: "leases table absent", present: allSentinelTables(), @@ -139,6 +176,55 @@ func TestCursorRealityFloor(t *testing.T) { wantFloor: 0, wantLimited: false, }, + { + name: "events absent", + present: allSentinelTablesExcept("events"), + columns: map[string]bool{"leases.granted_node": true}, + wantFloor: 18, + wantLimited: true, + }, + { + name: "bd_events_journal absent", + present: allSentinelTablesExcept("bd_events_journal"), + columns: map[string]bool{"leases.granted_node": true}, + wantFloor: 21, + wantLimited: true, + }, + { + name: "bd_events_seq absent", + present: allSentinelTablesExcept("bd_events_seq"), + columns: map[string]bool{"leases.granted_node": true}, + wantFloor: 21, + wantLimited: true, + }, + { + // Two floored sentinels contradicted at once: the minimum must win + // WITHIN the floored loop, not only across loops. Without this + // case every case removes exactly one floored table, so the loop + // only ever reaches its !limited arm and `st.replayFloor < floor` + // is never evaluated against a floor an earlier absent sentinel + // already set — inverting it to `>` leaves the package green. The + // floors happen to ascend in slice order (18, 21, 21) today, so + // this is what keeps a future reordering or lower-floored addition + // from silently regressing to "last absent sentinel wins". + name: "events and bd_events_journal both absent", + present: allSentinelTablesExcept("events", "bd_events_journal"), + columns: map[string]bool{"leases.granted_node": true}, + wantFloor: 18, + wantLimited: true, + }, + { + // Combined contradiction across two different sentinel kinds: the + // true minimum (11, from the column) must win over the higher + // floored-table floor (18) the table loop finds first, proving the + // accumulator takes the minimum across both loops rather than + // whichever ran first. + name: "events absent and leases granted_node absent", + present: allSentinelTablesExcept("events"), + columns: map[string]bool{}, + wantFloor: 11, + wantLimited: true, + }, } { t.Run(tc.name, func(t *testing.T) { stubSentinelTables(t, tc.present, nil) @@ -255,6 +341,37 @@ func TestCurrentVersionClampsToSentinelFloor(t *testing.T) { columns: map[string]bool{"leases.granted_node": true}, want: latest, }, + { + name: "events absent, at-latest cursor", + raw: latest, + present: allSentinelTablesExcept("events"), + columns: map[string]bool{"leases.granted_node": true}, + want: 18, + }, + { + name: "bd_events_journal absent, at-latest cursor", + raw: latest, + present: allSentinelTablesExcept("bd_events_journal"), + columns: map[string]bool{"leases.granted_node": true}, + want: 21, + }, + { + name: "bd_events_seq absent, at-latest cursor", + raw: latest, + present: allSentinelTablesExcept("bd_events_seq"), + columns: map[string]bool{"leases.granted_node": true}, + want: 21, + }, + { + // Combined contradiction across two different sentinel kinds: the + // true minimum (11, from the column) must win over the higher + // floored-table floor (18). + name: "events absent and leases column absent, at-latest cursor", + raw: latest, + present: allSentinelTablesExcept("events"), + columns: map[string]bool{}, + want: 11, + }, } { t.Run(tc.name, func(t *testing.T) { stubSentinelTables(t, tc.present, nil) @@ -287,6 +404,45 @@ func TestCursorProbeErrorIsNotTreatedAsContradicted(t *testing.T) { } } +// The floored-table loop must surface a probe failure the same way, and the +// test above cannot reach it: its blanket error fails the floor-0 wisps probe +// and returns there. So each case reads every other sentinel table present and +// fails exactly one floored table. Reading that error as "absent" would clamp a +// healthy at-latest cursor to the table's replayFloor and replay the tail on a +// catalog nobody could read; skipping it would believe the cursor over a table +// that may be missing. +func TestFlooredTableProbeErrorIsNotTreatedAsContradicted(t *testing.T) { + if len(ignoredSource.sentinelFlooredTables) == 0 { + t.Fatal("ignoredSource has no floored sentinel tables; this guard is inert") + } + boom := errors.New("information_schema unavailable") + for _, failing := range ignoredSource.sentinelFlooredTables { + t.Run(failing.table, func(t *testing.T) { + present := allSentinelTables() + orig := sentinelTableExists + t.Cleanup(func() { sentinelTableExists = orig }) + sentinelTableExists = func(_ context.Context, _ DBConn, table string) (bool, error) { + if table == failing.table { + return false, boom + } + return present[table], nil + } + columnProbed := stubSentinelColumns(t, map[string]bool{"leases.granted_node": true}, nil) + + _, limited, err := ignoredSource.cursorRealityFloor(context.Background(), nil) + if !errors.Is(err, boom) { + t.Errorf("floored-table probe error was swallowed: err = %v", err) + } + if limited { + t.Error("an unreadable floored-table probe reported the cursor as contradicted") + } + if len(*columnProbed) != 0 { + t.Errorf("column sentinels %v were probed after a floored-table probe failed", *columnProbed) + } + }) + } +} + // The main series is deliberately unguarded: its tables are not clone-local, // so it cannot reach the contradicted state, and probing would add queries to // every store open for nothing. cursorRealityFloor must be a no-op for it — @@ -437,6 +593,84 @@ func TestSentinelColumnsAreCreatedByTheSeries(t *testing.T) { } } +// TestSentinelFlooredTablesAreCreatedByTheSeries is the floored-table +// analogue of TestSentinelColumnsAreCreatedByTheSeries: every sentinel in +// sentinelFlooredTables must be created by the series, strictly above its own +// replayFloor, and that floor must exclude ignored/0007's unguarded restamp +// the same way the column floor does. +// +// events does not use the __temp__ + RENAME pattern the other +// creators do: it carries the named, database-unique constraint +// fk_events_issue, so a temp twin errors "duplicate foreign key constraint +// name" on Dolt 2.2.2 (see ignored/0019's own comment). Its creator guards a +// plain CREATE TABLE behind a PREPAREd conditional on an INFORMATION_SCHEMA +// existence probe instead, so both creation shapes are detected here. +func TestSentinelFlooredTablesAreCreatedByTheSeries(t *testing.T) { + if len(ignoredSource.sentinelFlooredTables) == 0 { + t.Fatal("ignoredSource has no sentinel floored tables; the events/bd_events_journal/bd_events_seq guard is inert") + } + + bodies := make(map[int]string) + for _, mf := range ignoredSource.list() { + blob, err := ignoredSource.files.ReadFile(ignoredSource.dir + "/" + mf.name) + if err != nil { + t.Fatalf("read %s: %v", mf.name, err) + } + bodies[mf.version] = string(blob) + } + + // findVersion returns the lowest migration version whose body matches, or + // 0 when nothing does. + findVersion := func(re *regexp.Regexp) int { + found := 0 + for version, body := range bodies { + if !re.MatchString(body) { + continue + } + if found == 0 || version < found { + found = version + } + } + return found + } + + unguarded := findVersion(regexp.MustCompile(`(?i)UPDATE\s+wisps\s+SET\s+is_blocked\s*=\s*0\s*;`)) + if unguarded == 0 { + t.Fatal("the unguarded `UPDATE wisps SET is_blocked = 0` the replay floor exists to exclude is gone; re-derive the floor") + } + + for _, st := range ignoredSource.sentinelFlooredTables { + // Detect both creation shapes and accept whichever the series actually + // uses, rather than keying on the table's name: the PREPAREd + // conditional CREATE is required of any creator whose table carries a + // named, database-unique constraint (ignored/0019's own comment), so a + // future floored sentinel can legitimately arrive in either shape and + // must not fall through to the misleading "never created" failure. + // findVersion already returns the lowest match, so take the earlier of + // the two shapes if a table somehow uses both. + prepared := findVersion(regexp.MustCompile( + `(?i)IF\(@\w+\s*=\s*0,\s*'CREATE TABLE ` + regexp.QuoteMeta(st.table) + `\s*\(`)) + temp := findVersion(regexp.MustCompile(regexp.QuoteMeta("__temp__" + st.table))) + creator := prepared + if creator == 0 || (temp != 0 && temp < creator) { + creator = temp + } + if creator == 0 { + t.Errorf("sentinel floored table %q is never created by the %s series; re-running it could not repair that table", + st.table, ignoredSource.dir) + continue + } + if creator <= st.replayFloor { + t.Errorf("sentinel floored table %q is created by ignored/%04d, at or below its replayFloor %d; the clamped replay would skip the migration that heals it", + st.table, creator, st.replayFloor) + } + if st.replayFloor < unguarded { + t.Errorf("sentinel floored table %q replayFloor %d does not exclude ignored/%04d, whose unguarded UPDATE restamps wisps.updated_at", + st.table, st.replayFloor, unguarded) + } + } +} + // TestMigrationWorkNeededWhenWispTablesAbsent is gh 5033 end to end, through // the real short-circuit that caused it. Both cursors read at-latest, so // before this change migrationWorkNeeded returned false, MigrateUp did @@ -457,8 +691,7 @@ func TestMigrationWorkNeededWhenWispTablesAbsent(t *testing.T) { expectScalar(mock, "SELECT COALESCE(MAX(version), 0) FROM schema_migrations", "version", LatestVersion()) expectCursorProbe(mock, "ignored_schema_migrations", true) expectScalar(mock, "SELECT COALESCE(MAX(version), 0) FROM ignored_schema_migrations", "version", LatestIgnoredVersion()) - mock.ExpectQuery(regexp.QuoteMeta("FROM INFORMATION_SCHEMA.TABLES")). - WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0)) + expectShowTable(mock, ignoredSource.sentinelTables[0], false) needed, err := migrationWorkNeeded(context.Background(), db) if err != nil { @@ -487,12 +720,18 @@ func TestMigrationWorkNeededWhenLeaseGrantedNodeAbsent(t *testing.T) { expectScalar(mock, "SELECT COALESCE(MAX(version), 0) FROM schema_migrations", "version", LatestVersion()) expectCursorProbe(mock, "ignored_schema_migrations", true) expectScalar(mock, "SELECT COALESCE(MAX(version), 0) FROM ignored_schema_migrations", "version", LatestIgnoredVersion()) - for range ignoredSource.sentinelTables { - mock.ExpectQuery(regexp.QuoteMeta("FROM INFORMATION_SCHEMA.TABLES")). - WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + for _, table := range ignoredSource.sentinelTables { + expectShowTable(mock, table, true) + } + // The floored-table sentinels probe the same way and must all corroborate + // too, ahead of the column probe below. + for _, st := range ignoredSource.sentinelFlooredTables { + expectShowTable(mock, st.table, true) + } + // leases is present; only its granted_node column is missing. + for _, sc := range ignoredSource.sentinelColumns { + expectSentinelColumnProbe(mock, sc, true, false) } - mock.ExpectQuery(regexp.QuoteMeta("FROM INFORMATION_SCHEMA.COLUMNS")). - WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0)) needed, err := migrationWorkNeeded(context.Background(), db) if err != nil { @@ -506,6 +745,157 @@ func TestMigrationWorkNeededWhenLeaseGrantedNodeAbsent(t *testing.T) { } } +// TestIgnoredCursorReadWithLeasesAbsentIssuesNoFailingStatement is the +// missing-carrier shape end to end through the guarded cursor read every +// write-capable open performs. Every released tree (v1.1.0, v1.1.2, v1.2.x) +// has no leases table at all, and an out-of-band copy can arrive at-latest +// without it. The ordered mock admits exactly the carrier's existence read for +// the column sentinel: a SHOW COLUMNS sent to the absent table is unexpected, +// and currentVersion surfaces that rather than swallowing it the way atLatest +// does, so this fails if the probe ever issues the statement that pins a pooled +// Dolt session (be-bv7x). +func TestIgnoredCursorReadWithLeasesAbsentIssuesNoFailingStatement(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer db.Close() + + expectCursorProbe(mock, "ignored_schema_migrations", true) + expectScalar(mock, "SELECT COALESCE(MAX(version), 0) FROM ignored_schema_migrations", "version", LatestIgnoredVersion()) + for _, table := range ignoredSource.sentinelTables { + expectShowTable(mock, table, true) + } + for _, st := range ignoredSource.sentinelFlooredTables { + expectShowTable(mock, st.table, true) + } + for _, sc := range ignoredSource.sentinelColumns { + expectSentinelColumnProbe(mock, sc, false, false) + } + + got, err := ignoredSource.currentVersion(context.Background(), db) + if err != nil { + t.Fatalf("currentVersion with leases absent: %v", err) + } + if want := 11; got != want { + t.Errorf("currentVersion = %d, want the leases.granted_node replayFloor %d", got, want) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet ordered sentinel probes: %v", err) + } +} + +// TestSentinelColumnProbeNeverAsksAMissingTable pins the probe mechanism behind +// the column sentinel, through the real sentinelColumnExists and a stubbed +// sentinelTableExists. SHOW COLUMNS errors on a missing table, and with the +// store's multiStatements DSN a failing statement leaves the pooled Dolt +// session pinned to its pre-statement catalog, so tables that other +// connections create afterwards stay invisible to it (be-bv7x; reproduced on +// dolt 2.1.8 and 2.2.0). The carrier table must therefore be established by +// the existence probe, which answers an empty set rather than an error, before +// any SHOW COLUMNS is sent. The mock has no expectations: any statement at all +// fails the probe. +func TestSentinelColumnProbeNeverAsksAMissingTable(t *testing.T) { + if len(ignoredSource.sentinelColumns) == 0 { + t.Fatal("ignoredSource has no sentinel columns; this guard is inert") + } + probed := stubSentinelTables(t, allSentinelTables(), nil) + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer db.Close() + + for _, sc := range ignoredSource.sentinelColumns { + present, err := sentinelColumnExists(context.Background(), db, sc.table, sc.column) + if err != nil { + t.Fatalf("sentinelColumnExists(%s.%s) with the table absent: %v", sc.table, sc.column, err) + } + if present { + t.Errorf("sentinelColumnExists(%s.%s) = true with the table absent", sc.table, sc.column) + } + if !slices.Contains(*probed, sc.table) { + t.Errorf("carrier table %s was never probed for existence; probed %v", sc.table, *probed) + } + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } +} + +// TestSentinelColumnProbeReadsAPresentTableExactly covers the other half: once +// the carrier exists, SHOW COLUMNS answers, and its Field is compared exactly +// because '_' is a LIKE single-character wildcard. +func TestSentinelColumnProbeReadsAPresentTableExactly(t *testing.T) { + present := allSentinelTables() + for _, sc := range ignoredSource.sentinelColumns { + present[sc.table] = true + } + probed := stubSentinelTables(t, present, nil) + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer db.Close() + + showColumns := regexp.QuoteMeta("SHOW COLUMNS FROM leases LIKE 'granted_node'") + columns := []string{"Field", "Type", "Null", "Key", "Default", "Extra"} + mock.ExpectQuery(showColumns).WillReturnRows(sqlmock.NewRows(columns).AddRow("grantedXnode", "varchar(255)", "YES", "", nil, "")) + mock.ExpectQuery(showColumns).WillReturnRows(sqlmock.NewRows(columns)) + mock.ExpectQuery(showColumns).WillReturnRows(sqlmock.NewRows(columns).AddRow("granted_node", "varchar(255)", "YES", "", nil, "")) + + for i, want := range []bool{false, false, true} { + got, err := sentinelColumnExists(context.Background(), db, "leases", "granted_node") + if err != nil { + t.Fatalf("probe %d: sentinelColumnExists: %v", i, err) + } + if got != want { + t.Errorf("probe %d: sentinelColumnExists = %v, want %v", i, got, want) + } + } + if want := []string{"leases", "leases", "leases"}; !slices.Equal(*probed, want) { + t.Errorf("carrier existence probes = %v, want %v (one ahead of every SHOW COLUMNS)", *probed, want) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } +} + +// A failed carrier probe must surface, not read as "column absent": that would +// clamp a healthy at-latest cursor to the column's replayFloor and replay the +// tail on a catalog nobody could read — the same rule +// TestCursorProbeErrorIsNotTreatedAsContradicted pins for the table sentinels. +func TestSentinelColumnCarrierProbeErrorIsNotTreatedAsContradicted(t *testing.T) { + boom := errors.New("information_schema unavailable") + present := allSentinelTables() + orig := sentinelTableExists + t.Cleanup(func() { sentinelTableExists = orig }) + sentinelTableExists = func(_ context.Context, _ DBConn, table string) (bool, error) { + for _, sc := range ignoredSource.sentinelColumns { + if table == sc.table { + return false, boom + } + } + return present[table], nil + } + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer db.Close() + + _, limited, err := ignoredSource.cursorRealityFloor(context.Background(), db) + if !errors.Is(err, boom) { + t.Errorf("carrier probe error was swallowed: err = %v", err) + } + if limited { + t.Error("an unreadable carrier probe reported the cursor as contradicted") + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } +} + // TestMigrateAppliesUnderContradictedCursor closes the loop the work-needed // test cannot: deciding "work needed" is worthless if the applier then // re-reads the cursor raw, believes it, and applies nothing — MigrateUp would @@ -534,8 +924,7 @@ func TestMigrateAppliesUnderContradictedCursor(t *testing.T) { // The guarded read: cursor claims at-latest, sentinel probe contradicts it. expectCursorProbe(mock, "ignored_schema_migrations", true) expectScalar(mock, "SELECT COALESCE(MAX(version), 0) FROM ignored_schema_migrations", "version", LatestIgnoredVersion()) - mock.ExpectQuery(regexp.QuoteMeta("FROM INFORMATION_SCHEMA.TABLES")). - WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0)) + expectShowTable(mock, ignoredSource.sentinelTables[0], false) // The proof: the applier reaches ignored/0001's SQL. Fail it distinctively // rather than mocking the whole series. @@ -586,12 +975,17 @@ func TestMigrateStartsAboveTheFloorUnderColumnContradiction(t *testing.T) { // corroborate it, and only the leases column does not. expectCursorProbe(mock, "ignored_schema_migrations", true) expectScalar(mock, "SELECT COALESCE(MAX(version), 0) FROM ignored_schema_migrations", "version", LatestIgnoredVersion()) - for range ignoredSource.sentinelTables { - mock.ExpectQuery(regexp.QuoteMeta("FROM INFORMATION_SCHEMA.TABLES")). - WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + for _, table := range ignoredSource.sentinelTables { + expectShowTable(mock, table, true) + } + // The floored-table sentinels probe the same way and must all corroborate + // too, ahead of the column probe below. + for _, st := range ignoredSource.sentinelFlooredTables { + expectShowTable(mock, st.table, true) + } + for _, sc := range ignoredSource.sentinelColumns { + expectSentinelColumnProbe(mock, sc, true, false) } - mock.ExpectQuery(regexp.QuoteMeta("FROM INFORMATION_SCHEMA.COLUMNS")). - WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0)) boom := errors.New("stop here: the applier resumed above the floor") mock.ExpectExec(".*").WillReturnError(boom) @@ -653,3 +1047,84 @@ func TestPendingVersionsUnderFloorDoNotReArmAuxMarkers(t *testing.T) { t.Error("ignored/0007 is pending on a cursor-11 store; its unguarded UPDATE would restamp wisps.updated_at") } } + +// TestShowTableExistsAnswersLikeInformationSchema pins showTableExists to the +// INFORMATION_SCHEMA.TABLES count it replaced. Dolt's SHOW TABLES LIKE filter +// matches case-sensitively, while INFORMATION_SCHEMA — like every table +// reference — resolves names case-insensitively, so a LIKE-filtered probe +// reads a table stored as BD_EVENTS_SEQ as absent (dolt 2.1.8 and 2.2.0). The +// probe therefore reads the unfiltered listing and compares names +// case-insensitively and otherwise exactly: a '_' lookalike is not the table, +// and an empty listing is an absent table rather than an error. +func TestShowTableExistsAnswersLikeInformationSchema(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer db.Close() + + cases := []struct { + name string + tables []string + probe string + want bool + }{ + {name: "a LIKE lookalike is not the table", tables: []string{"issues", "wispxdependencies"}, probe: "wisp_dependencies", want: false}, + {name: "a name containing the table is not the table", tables: []string{"bd_events_journal", "bd_events_seq"}, probe: "events", want: false}, + {name: "empty database", tables: nil, probe: "wisp_dependencies", want: false}, + {name: "exact name among others", tables: []string{"issues", "wisp_dependencies", "wisps"}, probe: "wisp_dependencies", want: true}, + {name: "stored in another case", tables: []string{"issues", "BD_EVENTS_SEQ"}, probe: "bd_events_seq", want: true}, + } + for _, tc := range cases { + rows := sqlmock.NewRows([]string{"Tables_in_testdb"}) + for _, table := range tc.tables { + rows.AddRow(table) + } + mock.ExpectQuery("^SHOW TABLES$").WillReturnRows(rows) + } + for _, tc := range cases { + got, err := showTableExists(context.Background(), db, tc.probe) + if err != nil { + t.Fatalf("%s: showTableExists: %v", tc.name, err) + } + if got != tc.want { + t.Errorf("%s: showTableExists(%q) = %v, want %v", tc.name, tc.probe, got, tc.want) + } + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet expectations: %v", err) + } +} + +// TestCurrentVersionWithoutAUsableDatabaseIssuesNoFailingStatement is the +// be-bv7x rule for the cursor probe itself, which must succeed on any session. +// SHOW TABLES fails with no database selected (1105) and on a session whose +// database was dropped under it (1049), and a failing statement pins the +// pooled session to its pre-statement catalog. The schemata read answers 0 in +// both cases instead, so the probe stops there and reads the cursor as absent, +// exactly as the INFORMATION_SCHEMA.TABLES count did: the strict mock admits +// nothing after it. +func TestCurrentVersionWithoutAUsableDatabaseIssuesNoFailingStatement(t *testing.T) { + for _, src := range []migrationSource{mainSource, ignoredSource} { + t.Run(src.cursorTable, func(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer db.Close() + mock.ExpectQuery(regexp.QuoteMeta("SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = DATABASE()")). + WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0)) + + got, err := src.currentVersion(context.Background(), db) + if err != nil { + t.Fatalf("currentVersion without a usable database: %v", err) + } + if got != 0 { + t.Errorf("currentVersion without a usable database = %d, want 0", got) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) + } +} diff --git a/internal/storage/schema/ignored_cursor_untrack.go b/internal/storage/schema/ignored_cursor_untrack.go index 014d76dde..5a7f7d4f0 100644 --- a/internal/storage/schema/ignored_cursor_untrack.go +++ b/internal/storage/schema/ignored_cursor_untrack.go @@ -91,16 +91,21 @@ func (s ignoredCursorState) reconcileNeeded() bool { return s.needsUntrack || s.strayScratch } -// readIgnoredCursorState answers both halves of the gate in two -// always-succeeding reads. That property is not incidental: a Dolt session -// that issues a FAILING statement stays pinned to its pre-statement catalog -// snapshot for the rest of its pooled life (be-bv7x), and this runs on every -// writable open and every lock-free fast-path evaluation. +// readIgnoredCursorState answers both halves of the gate. On a healthy +// database that is two SHOW TABLES listings, HEAD's and the working set's; a +// dolt_ignore read joins them only when the cursor is tracked at HEAD. None of +// them may fail, and that is not incidental: a Dolt session that issues a +// FAILING statement stays pinned to its pre-statement catalog snapshot for the +// rest of its pooled life (be-bv7x), and this runs on every writable open and +// every lock-free fast-path evaluation. A SHOW TABLES listing fails with no +// database selected (1105) and on a session whose database was dropped (1049), +// so both callers must already have the session on the target database; a +// session that may have no usable database needs tableInCurrentDatabase. // // qualifier is the identifier-quoted database name selectTargetDatabase // returned, or empty when the session is already on the target database. The -// scratch probe needs no qualifier: it reads information_schema against -// DATABASE(), which both callers have already put on the target. +// scratch probe takes no qualifier: it lists the session's current database, +// which both callers have already made the target. func readIgnoredCursorState(ctx context.Context, db DBConn, qualifier string) (ignoredCursorState, error) { var state ignoredCursorState @@ -110,7 +115,10 @@ func readIgnoredCursorState(ctx context.Context, db DBConn, qualifier string) (i } state.needsUntrack = needsUntrack - stray, err := schemaTableExists(ctx, db, ignoredCursorUntrackTempTable) + // Both callers have the session on the target database (alreadyConverged + // after selectTargetDatabase, MigrateUp after its preparation), so this + // per-open read takes the SHOW TABLES prober. + stray, err := showTableExists(ctx, db, ignoredCursorUntrackTempTable) if err != nil { return state, fmt.Errorf("probing %s: %w", ignoredCursorUntrackTempTable, err) } diff --git a/internal/storage/schema/ignored_cursor_untrack_test.go b/internal/storage/schema/ignored_cursor_untrack_test.go index c69bdfc62..466834a2e 100644 --- a/internal/storage/schema/ignored_cursor_untrack_test.go +++ b/internal/storage/schema/ignored_cursor_untrack_test.go @@ -120,7 +120,7 @@ func expectIgnoredCursorGate(mock sqlmock.Sqlmock, qualifier string, tracked boo if tracked { expectIgnoreResolution(mock, qualifier, ignoredSource.cursorTable, matches) } - expectSchemaTableExists(mock, ignoredCursorUntrackTempTable, stray) + expectShowTable(mock, ignoredCursorUntrackTempTable, stray) } // expectIgnoredCursorHealNoop mocks the whole open-time reconcile on a healthy @@ -764,7 +764,7 @@ func TestAlreadyConvergedDeclinesOnALegacyTrackedCursor(t *testing.T) { expectDoltIgnoreRead(mock, unqualifiedDoltIgnore, seededIgnorePatterns(LatestVersion())) expectHeadTableProbe(mock, "", ignoredSource.cursorTable, true) expectIgnoreResolution(mock, "", ignoredSource.cursorTable, exactlyIgnored(true)) - expectSchemaTableExists(mock, ignoredCursorUntrackTempTable, false) + expectShowTable(mock, ignoredCursorUntrackTempTable, false) converged, err := alreadyConverged(context.Background(), db, "testdb", nil) if err != nil { @@ -793,7 +793,7 @@ func TestAlreadyConvergedDeclinesOnASurvivingScratchTable(t *testing.T) { expectNoMigrationWorkNeeded(mock) expectDoltIgnoreRead(mock, unqualifiedDoltIgnore, seededIgnorePatterns(LatestVersion())) expectHeadTableProbe(mock, "", ignoredSource.cursorTable, false) - expectSchemaTableExists(mock, ignoredCursorUntrackTempTable, true) + expectShowTable(mock, ignoredCursorUntrackTempTable, true) converged, err := alreadyConverged(context.Background(), db, "testdb", nil) if err != nil { @@ -820,7 +820,7 @@ func TestAlreadyConvergedAcceptsATrackedCursorTheOperatorUnignored(t *testing.T) expectDoltIgnoreRead(mock, unqualifiedDoltIgnore, seededIgnorePatterns(LatestVersion())) expectHeadTableProbe(mock, "", ignoredSource.cursorTable, true) expectIgnoreResolution(mock, "", ignoredSource.cursorTable, exactlyIgnored(false)) - expectSchemaTableExists(mock, ignoredCursorUntrackTempTable, false) + expectShowTable(mock, ignoredCursorUntrackTempTable, false) expectMigrationLockProbe(mock, "testdb", 1) converged, err := alreadyConverged(context.Background(), db, "testdb", nil) @@ -864,7 +864,7 @@ func TestAlreadyConvergedKeepsTheLockProbeLast(t *testing.T) { expectDoltIgnoreRead(mock, unqualifiedDoltIgnore, seededIgnorePatterns(LatestVersion())) expectHeadTableProbe(mock, "", ignoredSource.cursorTable, true) expectIgnoreResolution(mock, "", ignoredSource.cursorTable, exactlyIgnored(true)) - expectSchemaTableExists(mock, ignoredCursorUntrackTempTable, false) + expectShowTable(mock, ignoredCursorUntrackTempTable, false) if _, err := alreadyConverged(context.Background(), db, "testdb", nil); err != nil { t.Fatalf("alreadyConverged() error = %v", err) diff --git a/internal/storage/schema/lock.go b/internal/storage/schema/lock.go index e6c104b00..5f6602229 100644 --- a/internal/storage/schema/lock.go +++ b/internal/storage/schema/lock.go @@ -326,7 +326,14 @@ func MigrateUpWithLock(ctx context.Context, conn *sql.Conn, databaseName string, } } - applied, err = MigrateUp(ctx, conn) + // The same authority is consent for MigrateUp's own gate, which is that + // version-only test: an init that never sets local consent would otherwise + // be refused the retry of its own interrupted bootstrap. + migrate := MigrateUp + if o.freshBootstrapHeal != nil { + migrate = migrateUpConsented + } + applied, err = migrate(ctx, conn) var dirtyErr *DirtyTablesError if err != nil && o.freshBootstrapHeal != nil && errors.As(err, &dirtyErr) { // Authorization is checked after the dirty guard fires and while the @@ -347,7 +354,7 @@ func MigrateUpWithLock(ctx context.Context, conn *sql.Conn, databaseName string, if resetErr := drainFreshBootstrapReset(ctx, conn); resetErr != nil { return applied, errors.Join(err, fmt.Errorf("schema: fresh-bootstrap reset: %w", resetErr)) } - applied, err = MigrateUp(ctx, conn) + applied, err = migrate(ctx, conn) } return applied, err } diff --git a/internal/storage/schema/lock_test.go b/internal/storage/schema/lock_test.go index 2b0c1841a..d2a1c7eaf 100644 --- a/internal/storage/schema/lock_test.go +++ b/internal/storage/schema/lock_test.go @@ -511,18 +511,15 @@ func expectScalar(mock sqlmock.Sqlmock, query, column string, value any) { WillReturnRows(sqlmock.NewRows([]string{column}).AddRow(value)) } -// expectCursorProbe mocks the information_schema existence probe that -// migrationSource.currentVersion issues before it ever reads the cursor -// table. The probe was added by be-bv7x so a not-yet-created cursor table -// never poisons the pooled Dolt session with a failing statement. +// expectCursorProbe mocks the existence probe that migrationSource.currentVersion +// issues before it ever reads the cursor table: the schemata read proving the +// session has a usable current database, then the SHOW TABLES listing. The +// probe was added by be-bv7x so a not-yet-created cursor table never poisons +// the pooled Dolt session with a failing statement. func expectCursorProbe(mock sqlmock.Sqlmock, table string, exists bool) { - present := 0 - if exists { - present = 1 - } - mock.ExpectQuery(`SELECT COUNT\(\*\) FROM information_schema\.tables`). - WithArgs(table). - WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(present)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = DATABASE()")). + WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + expectShowTable(mock, table, exists) } func expectDoltStatusRows(mock sqlmock.Sqlmock) { @@ -805,27 +802,40 @@ func TestMigrateUpWithLockFreshBootstrapHealResetFailureStaysFatal(t *testing.T) } } -// expectIgnoredSentinelProbes mocks the INFORMATION_SCHEMA lookups -// currentVersion issues to confirm a non-zero ignored cursor against the -// schema it claims (gh 5033). They fire only for a non-zero cursor, in -// ignoredSource's table then column sentinel order. +// expectIgnoredSentinelProbes mocks the schema lookups currentVersion issues +// to confirm a non-zero ignored cursor against the schema it claims (gh 5033): +// a SHOW TABLES probe per sentinel and floored table (showTableExists), then +// per sentinel column its carrier table's existence and a SHOW COLUMNS read +// (expectSentinelColumnProbe). None of them uses INFORMATION_SCHEMA, whose +// predicates Dolt does not push down, because all of them run on every store +// open. They fire only for a non-zero cursor, in ignoredSource's table then +// floored-table then column sentinel order. func expectIgnoredSentinelProbes(mock sqlmock.Sqlmock, present bool) { - count := 0 - if present { - count = 1 - } - for range ignoredSource.sentinelTables { - mock.ExpectQuery(regexp.QuoteMeta("FROM INFORMATION_SCHEMA.TABLES")). - WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(count)) + for _, table := range ignoredSource.sentinelTables { + expectShowTable(mock, table, present) } if present { - for range ignoredSource.sentinelColumns { - mock.ExpectQuery(regexp.QuoteMeta("FROM INFORMATION_SCHEMA.COLUMNS")). - WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + for _, st := range ignoredSource.sentinelFlooredTables { + expectShowTable(mock, st.table, true) + } + for _, sc := range ignoredSource.sentinelColumns { + expectSentinelColumnProbe(mock, sc, true, true) } } } +// expectShowTable mocks one showTableExists probe: the database's unfiltered +// SHOW TABLES listing, which holds table only when it exists. An absent table +// is a listing without it, never a zero count. The listing always carries an +// unrelated table, so a probe that took any row as presence fails. +func expectShowTable(mock sqlmock.Sqlmock, table string, exists bool) { + rows := sqlmock.NewRows([]string{"Tables_in_testdb"}).AddRow("issues") + if exists { + rows.AddRow(table) + } + mock.ExpectQuery("^SHOW TABLES$").WillReturnRows(rows) +} + func TestMigrateUpWithLockFreshBootstrapHealProbeFailuresStayFatal(t *testing.T) { tests := []struct { name string @@ -1013,6 +1023,124 @@ func TestMigrateUpWithLockFreshBootstrapHealCapabilityIsOneShot(t *testing.T) { } } +// expectMigrateConsentReads mocks checkMigrateConsent's reads when no consent +// is held: the main cursor once for the fresh-database exemption, and again +// for the pending count. +func expectMigrateConsentReads(mock sqlmock.Sqlmock, cursor int) { + for range 2 { + expectCursorProbe(mock, "schema_migrations", true) + expectScalar(mock, "SELECT COALESCE(MAX(version), 0) FROM schema_migrations", "version", cursor) + } +} + +// TestMigrateUpWithLockFreshBootstrapHealIsMigrateConsent pins that heal +// authority is consent for MigrateUp's own gate, not just for the caller's +// migration gate. A retried server bootstrap finds the non-zero cursor its +// first pass left behind, and server-mode `bd init` records no local consent, +// so a version-only consent check would refuse the init the database it just +// created. Both migration passes are covered; sqlmock's ordered expectations +// fail either case on a consent read. +func TestMigrateUpWithLockFreshBootstrapHealIsMigrateConsent(t *testing.T) { + cases := map[string]func(t *testing.T, mock sqlmock.Sqlmock){ + "partially migrated": func(t *testing.T, mock sqlmock.Sqlmock) { + expectOnePendingMigration(t, mock) + }, + "partially migrated with dirty debris": func(t *testing.T, mock sqlmock.Sqlmock) { + expectDirtyGuardRefusal(t, mock) + expectFreshBootstrapIdentityMatch(mock) + mock.ExpectQuery(regexp.QuoteMeta("CALL DOLT_RESET('--hard')")). + WillReturnRows(sqlmock.NewRows([]string{"status"})) + expectOnePendingMigration(t, mock) + }, + } + for name, expectPasses := range cases { + t.Run(name, func(t *testing.T) { + failOnSwallowedAdvisory(t) + resetConsentState(t) + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("create sql mock: %v", err) + } + defer db.Close() + + ctx := context.Background() + conn, err := db.Conn(ctx) + if err != nil { + t.Fatalf("pin mock connection: %v", err) + } + defer conn.Close() + + lockName := MigrationLockName("testdb") + mock.ExpectQuery(regexp.QuoteMeta("SELECT GET_LOCK(?, ?)")). + WithArgs(lockName, migrationLockAcquireTimeoutSeconds). + WillReturnRows(sqlmock.NewRows([]string{"locked"}).AddRow(1)) + expectPasses(t, mock) + mock.ExpectQuery(regexp.QuoteMeta("SELECT RELEASE_LOCK(?)")). + WithArgs(lockName). + WillReturnRows(sqlmock.NewRows([]string{"released"}).AddRow(1)) + + applied, err := MigrateUpWithLock(ctx, conn, "testdb", + WithFreshBootstrapHeal(testFreshBootstrapHealCapability(), testBootstrapEndpoint)) + if err != nil { + t.Fatalf("MigrateUpWithLock() error = %v", err) + } + if applied != 1 { + t.Fatalf("MigrateUpWithLock() applied = %d, want 1", applied) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) + } +} + +// TestMigrateUpWithLockRefusesUnconsentedMigration is the control for the +// test above: the same behind database, opened without heal authority or +// consent, is refused under the lock before any write, and the lock is still +// released. +func TestMigrateUpWithLockRefusesUnconsentedMigration(t *testing.T) { + failOnSwallowedAdvisory(t) + resetConsentState(t) + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("create sql mock: %v", err) + } + defer db.Close() + + ctx := context.Background() + conn, err := db.Conn(ctx) + if err != nil { + t.Fatalf("pin mock connection: %v", err) + } + defer conn.Close() + + lockName := MigrationLockName("testdb") + expectConvergedFastPathMiss(mock, "testdb") + mock.ExpectQuery(regexp.QuoteMeta("SELECT GET_LOCK(?, ?)")). + WithArgs(lockName, migrationLockAcquireTimeoutSeconds). + WillReturnRows(sqlmock.NewRows([]string{"locked"}).AddRow(1)) + expectMigrateConsentReads(mock, LatestVersion()-1) + mock.ExpectQuery(regexp.QuoteMeta("SELECT RELEASE_LOCK(?)")). + WithArgs(lockName). + WillReturnRows(sqlmock.NewRows([]string{"released"}).AddRow(1)) + + applied, err := MigrateUpWithLock(ctx, conn, "testdb", WithDatabaseSelector(testDatabaseSelector)) + if applied != 0 { + t.Fatalf("MigrateUpWithLock() applied = %d, want 0", applied) + } + var consentErr *MigrateConsentError + if !errors.As(err, &consentErr) { + t.Fatalf("MigrateUpWithLock() error = %v, want *MigrateConsentError", err) + } + if consentErr.CurrentVersion != LatestVersion()-1 || consentErr.Pending != 1 { + t.Fatalf("refusal = v%d with %d pending, want v%d with 1 pending", + consentErr.CurrentVersion, consentErr.Pending, LatestVersion()-1) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } +} + // TestMigrateUpWithLockMigrationGate pins where WithMigrationGate's callback // sits: after the lock and after locked preparation (so the gate reads a // prepared, selected database), before MigrateUp (so a refusal applies no diff --git a/internal/storage/schema/migrate_consent.go b/internal/storage/schema/migrate_consent.go new file mode 100644 index 000000000..a8fcc9eba --- /dev/null +++ b/internal/storage/schema/migrate_consent.go @@ -0,0 +1,235 @@ +package schema + +import ( + "context" + "errors" + "fmt" + "os" + "strconv" +) + +// Migration consent (gastownhall Beads 1.2 release remediation). +// +// bd used to auto-apply pending schema migrations the first time a new binary +// opened an existing database — on ANY command, including reads. The 1.2.x +// releases turned that into a trap: users upgraded by a package manager had +// their databases migrated in place with no prompt, and older binaries then +// refuse the migrated database (schema-skew guard). The remote-migrate gate +// (#4259) already refuses the silent migration for remote-backed databases; +// this gate extends the same contract to EVERY existing database: bd never +// initiates a schema migration without explicit operator consent. +// +// Consent is any of: +// - `bd migrate schema` (the verb that names the migration; the root +// command records the intent via SetLocalMigrateConsent before the store +// opens — bare `bd migrate` reconciles metadata and does not consent), +// - --force on `bd migrate` or `bd migrate schema` (the remote-gate +// override, a strict superset), or +// - BD_ALLOW_MIGRATE=1 (scripted/CI form; BD_ALLOW_REMOTE_MIGRATE=1 is +// honored as an alias for continuity with the remote gate's hatch). +// +// Fresh databases (no schema_migrations table, version 0) are exempt: creating +// a database is consent for its schema. A server bootstrap holding +// fresh-bootstrap heal authority keeps that consent across a retry whose +// interrupted first pass left a non-zero cursor (MigrateUpWithLock). The same +// creation principle covers a workspace this invocation just CLONED into +// existence (`bd init --remote`, `bd bootstrap` sync) — those paths record the +// consent explicitly, and the #4259 remote-migrate gate still applies to them +// unchanged. Databases already at this binary's latest version never consult +// the gate. The ignored (clone-local, dolt_ignored) migration sequence is +// deliberately NOT gated on its own: it only materializes per-clone +// bookkeeping tables and runs on every fresh clone — but when the MAIN +// sequence is pending and unconsented, MigrateUp refuses before ANY write, +// ignored sequence and dolt_ignore seeding included. +// +// A refusal fails the open, except for the working-set-reconcile commands +// (bd dolt commit, bd vc commit), which commit at the current schema without +// migrating: the refusal comes before the #4566 dirty-table guard, whose +// documented recovery is that commit (WorkingSetWarning). + +// AllowMigrateEnv, when set to a boolean true ("1", "true", ...), consents to +// applying pending schema migrations to an existing database. It is consulted +// only when migrations are actually pending, so exporting it permanently does +// not warn on every store open. +const AllowMigrateEnv = "BD_ALLOW_MIGRATE" + +// localMigrateConsent is the programmatic consent recorded by +// `bd migrate schema` and by the paths that just cloned the database into +// existence. Process-local by design, like forceAllowRemoteMigrate: it cannot +// leak into child processes. +var localMigrateConsent bool + +// SetLocalMigrateConsent records (or clears) the in-process consent to apply +// pending schema migrations to an existing database. Set by the root command +// when the invoked command is `bd migrate schema`, before both +// autoMigrateOnVersionBump and the main store open. External test packages may +// reset it to false after each test case. +func SetLocalMigrateConsent(v bool) { localMigrateConsent = v } + +// MigrateConsentError is returned when bd would apply pending schema +// migrations to an existing database without operator consent. +type MigrateConsentError struct { + CurrentVersion int + LatestVersion int + Pending int + // UnrecognizedEnv carries a BD_ALLOW_MIGRATE value that was set but not + // understood (only boolean values consent), so a typo'd hatch fails with + // a hint instead of silently staying locked (0054-gate precedent, + // bd-6dnrw.34). + UnrecognizedEnv string +} + +func (e *MigrateConsentError) Error() string { + return fmt.Sprintf("%s — run `bd migrate schema`, or keep using a bd release that matches schema v%d", + e.Refusal(), e.CurrentVersion) +} + +// Refusal states what was refused without prescribing a remedy, for surfaces +// that carry the remedy separately and must not hand an agent a runnable +// migration (cmd/bd's JSON refusal, whose remedies live in Options). +func (e *MigrateConsentError) Refusal() string { + return fmt.Sprintf( + "database schema is at v%d; this bd requires v%d (%d pending migration(s)), and bd no longer migrates a database without explicit consent", + e.CurrentVersion, e.LatestVersion, e.Pending) +} + +// AgentDirective is the non-runnable instruction surfaced to agents in place +// of a ready-to-run migrate command, following the remote-migrate gate's +// convention (RemoteMigrateGateError.AgentDirective). Migrating is one-way, +// and whether anything still has to open this database with an older bd is +// not observable from this process, so the decision goes to the operator. +func (e *MigrateConsentError) AgentDirective() string { + return fmt.Sprintf( + "Operator decision required: this database is at schema v%d and this bd requires v%d. Migrating is ONE-WAY — "+ + "bd releases built for an older schema refuse the migrated database, and whether one still has to open it "+ + "is not observable from this process. Do NOT auto-run the migration or set a consent environment variable "+ + "to get past this refusal: surface migrate_consent.options to the operator and let them choose.", + e.CurrentVersion, e.LatestVersion) +} + +// Options returns the two mutually exclusive paths, migrate or keep the +// current schema, each gated on its precondition and annotated with its risk. +// The migrate command is reachable only through the operator's decision, +// never as a top-level hint. Its verb is the shared-store gate's consent verb +// too, so cmd/bd retargets both with the same --global rewrite. +func (e *MigrateConsentError) Options() []GateOption { + return []GateOption{ + { + ID: "migrate", + When: "the operator chooses to upgrade this database, and nothing that still opens it runs a bd release built for an older schema (confirmed with the operator)", + Commands: []string{SharedConsentCommand}, + Risk: fmt.Sprintf("one-way: v%d -> v%d; bd releases built for an older schema refuse the migrated database", e.CurrentVersion, e.LatestVersion), + }, + { + ID: "keep", + When: fmt.Sprintf("something still has to open this database with a bd release built for schema v%d", e.CurrentVersion), + Commands: []string{}, + Risk: "none to the database; this bd release refuses it until it is migrated, so keep using the release that matches it", + }, + } +} + +// UserMessage renders the full operator-facing refusal. +func (e *MigrateConsentError) UserMessage() string { + msg := fmt.Sprintf( + "This database is at schema v%d; this bd release uses schema v%d.\n"+ + "bd no longer upgrades a database automatically (see the release notes).\n"+ + "\n"+ + " To upgrade this database (one-way; older bd releases cannot read it):\n"+ + " bd migrate schema\n"+ + "\n"+ + " To keep the current schema, keep using the bd release that created it.\n"+ + "\n"+ + " Scripted/CI consent: BD_ALLOW_MIGRATE=1 bd \n", + e.CurrentVersion, e.LatestVersion) + if e.UnrecognizedEnv != "" { + msg += fmt.Sprintf( + "\nNote: %s=%q was set but not understood (use a boolean value, e.g. \"1\" or \"true\"), so it did not consent.\n", + AllowMigrateEnv, e.UnrecognizedEnv) + } + return msg +} + +// WorkingSetWarning renders the stderr warning for a working-set-reconcile +// open (bd dolt commit, bd vc commit) that continues past this refusal. The +// commit needs no migration, and MigrateUp refused before any write, so it +// runs on the current schema; the migration still waits for consent. Both +// storage modes print it (embeddeddolt's openWorkingSetReconcile, server +// mode's LenientOpen). +func (e *MigrateConsentError) WorkingSetWarning() string { + return fmt.Sprintf( + "Warning: %s.\n"+ + " Working-set reconcile command: continuing on schema v%d without\n"+ + " migrating; the commit applies to the working set at the current schema.\n"+ + " To upgrade this database afterwards (one-way): bd migrate schema\n", + e.Refusal(), e.CurrentVersion) +} + +// IsMigrateConsentError reports whether err (or any error it wraps) is a +// *MigrateConsentError. +func IsMigrateConsentError(err error) bool { + var e *MigrateConsentError + return errors.As(err, &e) +} + +// checkMigrateConsent refuses an unconsented migration of an existing +// database. Called at the top of MigrateUp, before any write (dolt_ignore +// seeding included). Returns nil for a fresh database (version 0), a database +// with no pending main-sequence migrations, or when consent was given. +func checkMigrateConsent(ctx context.Context, db DBConn) error { + if localMigrateConsent || forceAllowRemoteMigrate { + return nil // programmatic consent — skip the version reads entirely + } + current, err := mainSource.currentVersion(ctx, db) + if err != nil { + return fmt.Errorf("migrate consent: read current version: %w", err) + } + if current == 0 { + return nil // fresh database — creating it is consent for its schema + } + pending, err := mainSource.pendingVersions(ctx, db) + if err != nil { + return fmt.Errorf("migrate consent: read pending versions: %w", err) + } + return migrateConsentDecision(current, len(pending)) +} + +// migrateConsentDecision is checkMigrateConsent's pure decision core: nil when +// nothing is pending or consent was given (programmatic or env), a typed +// *MigrateConsentError otherwise. current is known to be > 0 here except when +// callers short-circuit earlier; a zero current is still treated as consent +// (fresh database). +func migrateConsentDecision(current, pending int) error { + if current == 0 || pending == 0 { + return nil + } + if localMigrateConsent || forceAllowRemoteMigrate { + return nil + } + unrecognized := "" + for _, env := range []string{AllowMigrateEnv, AllowRemoteMigrateEnv} { + v := os.Getenv(env) + if v == "" { + continue + } + allowed, perr := strconv.ParseBool(v) + if perr != nil { + if env == AllowMigrateEnv { + unrecognized = v + } + continue + } + if allowed { + fmt.Fprintf(defaultStderr(), + "Applying %d pending schema migration(s) (%s=%s): v%d -> v%d\n", + pending, env, v, current, LatestVersion()) + return nil + } + } + return &MigrateConsentError{ + CurrentVersion: current, + LatestVersion: LatestVersion(), + Pending: pending, + UnrecognizedEnv: unrecognized, + } +} diff --git a/internal/storage/schema/migrate_consent_test.go b/internal/storage/schema/migrate_consent_test.go new file mode 100644 index 000000000..40e75b08d --- /dev/null +++ b/internal/storage/schema/migrate_consent_test.go @@ -0,0 +1,164 @@ +package schema + +import ( + "errors" + "os" + "strings" + "testing" +) + +// TestMain grants migration consent for the whole package: the MigrateUp +// machinery tests exercise what runs BELOW the consent gate, exactly as +// production does once an operator has consented. The consent tests below +// clear the grant themselves via resetConsentState. +func TestMain(m *testing.M) { + SetLocalMigrateConsent(true) + os.Exit(m.Run()) +} + +// resetConsentState clears every consent source for one test case (undoing +// TestMain's package-wide grant) and restores it afterwards, so consent tests +// see a clean slate and machinery tests keep their grant. +func resetConsentState(t *testing.T) { + t.Helper() + SetLocalMigrateConsent(false) + SetForceAllowRemoteMigrate(false) + t.Cleanup(func() { + SetLocalMigrateConsent(true) + SetForceAllowRemoteMigrate(false) + }) + t.Setenv(AllowMigrateEnv, "") + t.Setenv(AllowRemoteMigrateEnv, "") +} + +func TestMigrateConsentDecision_FreshDB_Allows(t *testing.T) { + resetConsentState(t) + if err := migrateConsentDecision(0, 12); err != nil { + t.Fatalf("decision = %v, want nil for fresh database (current=0)", err) + } +} + +func TestMigrateConsentDecision_NothingPending_Allows(t *testing.T) { + resetConsentState(t) + if err := migrateConsentDecision(LatestVersion(), 0); err != nil { + t.Fatalf("decision = %v, want nil when nothing is pending", err) + } +} + +func TestMigrateConsentDecision_PendingNoConsent_Refuses(t *testing.T) { + resetConsentState(t) + err := migrateConsentDecision(53, 12) + var consentErr *MigrateConsentError + if !errors.As(err, &consentErr) { + t.Fatalf("decision = %v, want *MigrateConsentError", err) + } + if consentErr.CurrentVersion != 53 || consentErr.Pending != 12 { + t.Fatalf("error fields = v%d/%d pending, want v53/12", consentErr.CurrentVersion, consentErr.Pending) + } + if !IsMigrateConsentError(err) { + t.Fatalf("IsMigrateConsentError(err) = false, want true") + } + msg := consentErr.UserMessage() + for _, want := range []string{"bd migrate schema", AllowMigrateEnv} { + if !strings.Contains(msg, want) { + t.Fatalf("UserMessage missing %q:\n%s", want, msg) + } + } +} + +func TestMigrateConsentDecision_LocalConsent_Allows(t *testing.T) { + resetConsentState(t) + SetLocalMigrateConsent(true) + if err := migrateConsentDecision(53, 12); err != nil { + t.Fatalf("decision = %v, want nil with local consent set", err) + } +} + +func TestMigrateConsentDecision_ForceOverride_Allows(t *testing.T) { + resetConsentState(t) + SetForceAllowRemoteMigrate(true) + if err := migrateConsentDecision(53, 12); err != nil { + t.Fatalf("decision = %v, want nil with the migrate --force override set", err) + } +} + +func TestMigrateConsentDecision_EnvConsent_Allows(t *testing.T) { + for _, env := range []string{AllowMigrateEnv, AllowRemoteMigrateEnv} { + for _, v := range []string{"1", "true", "TRUE"} { + t.Run(env+"="+v, func(t *testing.T) { + resetConsentState(t) + t.Setenv(env, v) + if err := migrateConsentDecision(53, 12); err != nil { + t.Fatalf("decision = %v, want nil with %s=%s", err, env, v) + } + }) + } + } +} + +func TestMigrateConsentDecision_EnvFalse_Refuses(t *testing.T) { + resetConsentState(t) + t.Setenv(AllowMigrateEnv, "0") + if !IsMigrateConsentError(migrateConsentDecision(53, 12)) { + t.Fatalf("want refusal with %s=0", AllowMigrateEnv) + } +} + +func TestMigrateConsentDecision_UnparseableEnv_RefusesWithHint(t *testing.T) { + resetConsentState(t) + t.Setenv(AllowMigrateEnv, "yes-please") + err := migrateConsentDecision(53, 12) + var consentErr *MigrateConsentError + if !errors.As(err, &consentErr) { + t.Fatalf("decision = %v, want *MigrateConsentError", err) + } + if consentErr.UnrecognizedEnv != "yes-please" { + t.Fatalf("UnrecognizedEnv = %q, want the unparseable value surfaced", consentErr.UnrecognizedEnv) + } + if !strings.Contains(consentErr.UserMessage(), "yes-please") { + t.Fatalf("UserMessage does not surface the unparseable env value:\n%s", consentErr.UserMessage()) + } +} + +// TestMigrateConsentError_AgentSurfacesNameNoRemedy pins the #4259 directive +// convention cmd/bd's JSON refusal is built on: Refusal and AgentDirective are +// the top-level fields an agent reads, so neither may carry a runnable +// migration or a consent env var; the migrate command lives only in the +// operator-gated "migrate" option. +func TestMigrateConsentError_AgentSurfacesNameNoRemedy(t *testing.T) { + e := &MigrateConsentError{CurrentVersion: 65, LatestVersion: 69, Pending: 4} + for name, s := range map[string]string{"Refusal": e.Refusal(), "AgentDirective": e.AgentDirective()} { + for _, unwanted := range []string{SharedConsentCommand, "BD_ALLOW"} { + if strings.Contains(s, unwanted) { + t.Errorf("%s carries %q:\n%s", name, unwanted, s) + } + } + } + opts := e.Options() + if len(opts) != 2 || opts[0].ID != "migrate" || opts[1].ID != "keep" { + t.Fatalf("Options = %+v, want exactly migrate then keep", opts) + } + if len(opts[0].Commands) != 1 || opts[0].Commands[0] != SharedConsentCommand { + t.Errorf("migrate option commands = %q, want [%q]", opts[0].Commands, SharedConsentCommand) + } + if len(opts[1].Commands) != 0 { + t.Errorf("keep option commands = %q, want none", opts[1].Commands) + } +} + +// TestMigrateConsentError_WorkingSetWarning pins the warning a +// working-set-reconcile open prints when it continues past the refusal: it +// states the refusal and that the commit runs on the current schema, and it +// never offers the consent env var as the way forward. +func TestMigrateConsentError_WorkingSetWarning(t *testing.T) { + e := &MigrateConsentError{CurrentVersion: 65, LatestVersion: 69, Pending: 4} + w := e.WorkingSetWarning() + for _, want := range []string{e.Refusal(), "Working-set reconcile command: continuing on schema v65 without"} { + if !strings.Contains(w, want) { + t.Errorf("WorkingSetWarning missing %q:\n%s", want, w) + } + } + if strings.Contains(w, "BD_ALLOW") { + t.Errorf("WorkingSetWarning offers a consent env var:\n%s", w) + } +} diff --git a/internal/storage/schema/migration_0069_datetime_precision_test.go b/internal/storage/schema/migration_0069_datetime_precision_test.go index bc1883fa6..503be1b6d 100644 --- a/internal/storage/schema/migration_0069_datetime_precision_test.go +++ b/internal/storage/schema/migration_0069_datetime_precision_test.go @@ -39,20 +39,11 @@ const migration0069Down = "0069_widen_issue_versions_datetime_precision.down.sql const migration0069ChangeAtDatetimeGuard = "@issue_versions_change_at_needs_widen" const migration0069RemovedAtDatetimeGuard = "@issue_versions_removed_at_needs_widen" -// TestLatestVersionIncludesMigration0069 pins the real next free slot this -// migration claims, superseding 0068's own version of this test -// (LatestVersion() moved from 68 to 69 the moment this migration file was -// added). Deliberately a hardcoded literal for the same reason 0067's and -// 0068's were: LatestVersion() drifting to 69 for the wrong reason (an -// unrelated migration landing first) should still be caught by this test -// failing to explain why 69 is datetime-precision-shaped, which the CLI test -// below checks. -func TestLatestVersionIncludesMigration0069(t *testing.T) { - const want = 69 - if got := LatestVersion(); got != want { - t.Fatalf("LatestVersion() = %d, want %d (issue_versions change_at/removed_at DATETIME(6) migration slot claimed by be-hs42e.8)", got, want) - } -} +// TestLatestVersionIncludesMigration0069 (pinning LatestVersion() == 69) is +// superseded by TestLatestVersionIncludesMigration0070 +// (migration_0070_add_participation_generation_test.go) now that 0070 claims the +// next free slot; only one such pin lives at a time, matching how this +// test itself already superseded 0068's own version. // TestMigration0069WidensChangeAtAndRemovedAtPrecision is the pure-Go, // DB-independent half of the pin, mirroring diff --git a/internal/storage/schema/migration_0070_add_participation_generation_test.go b/internal/storage/schema/migration_0070_add_participation_generation_test.go new file mode 100644 index 000000000..0993347f2 --- /dev/null +++ b/internal/storage/schema/migration_0070_add_participation_generation_test.go @@ -0,0 +1,144 @@ +package schema + +import ( + "os" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/testutil" +) + +// Migration 0070 (design §16.3 steps 4-5, be-dt74u amendment, be-h89oq) adds +// a nullable participation_generation to issues, mirrored inertly on wisps. +// NULL means legacy-unmigrated; any non-NULL is a positive declaration +// sourced from store_epoch.epoch. RecordVersionInTx's write fence (design +// §16.2b, in internal/storage/issueops/version_history.go) reads this column +// to decide whether an update-shaped mutation against a legacy record mints +// a version row at all -- a create-shaped mutation stamps a fresh value +// instead. No backfill: NULL is the correct default for every existing row, +// on both planes. +// +// It was first drafted as steps 4-5 appended to the then-unmerged 0068; +// be-v33pa's own attribution_status-only version of 0068 shipped to main +// first (2026-09-28 15:46Z), which froze that file, so these steps have +// their own slot here (mayor ruling 2026-09-29 on tracker be-waare) -- the +// same reason 0069 got its own slot rather than landing as 0068's step 8. +// +// wisps.participation_generation is guarded on the wisps table existing as +// well as the column, mirroring 0067's wisps.current_revision guard exactly +// (see that migration's header): wisps is dolt-ignored/clone-local, so a +// clone that never synced the local wisp tables must no-op rather than +// abort. The clone-local twin for a workspace that never synced the wisps +// table at all is ignored/0028_add_wisps_participation_generation.up.sql. +const migration0070Up = "0070_add_participation_generation.up.sql" +const migration0070Down = "0070_add_participation_generation.down.sql" + +// TestLatestVersionIncludesMigration0070 (pinning LatestVersion() == 70) is +// superseded by TestLatestVersionIncludesMigration0071 +// (migration_0071_add_removed_restriction_test.go) now that 0071 claims the +// next free slot; only one such pin lives at a time, matching how this +// test itself already superseded 0069's own version. + +// TestMigration0070AddsParticipationGeneration is the pure-Go, DB-independent +// half of the pin, mirroring TestMigration0069WidensChangeAtAndRemovedAtPrecision's +// shape: it checks the frozen migration bytes and the CLI-bundle override +// text directly, no `dolt` binary required. +func TestMigration0070AddsParticipationGeneration(t *testing.T) { + upSQL, err := MigrationSQL(migration0070Up) + if err != nil { + t.Fatalf("MigrationSQL(%s) error = %v, want the migration file to exist", migration0070Up, err) + } + for _, want := range []string{ + "ALTER TABLE issues ADD COLUMN participation_generation BIGINT NULL", + "@issues_pg_needs_add", + "ALTER TABLE wisps ADD COLUMN participation_generation BIGINT NULL", + "@wisps_pg_needs_add", + } { + if !strings.Contains(upSQL, want) { + t.Errorf("0070 up migration missing %q (design §16.3 steps 4-5)\nfull SQL:\n%s", want, upSQL) + } + } + if n := strings.Count(upSQL, "COLUMN_NAME = 'participation_generation'"); n != 2 { + t.Errorf("0070 up migration has %d INFORMATION_SCHEMA probes for participation_generation, want 2 (one for issues, one for wisps)\nfull SQL:\n%s", n, upSQL) + } + if !strings.Contains(strings.ToUpper(upSQL), "PREPARE STMT FROM @SQL") { + t.Error("0070 up migration must keep its guarded PREPARE blocks — they are what make a raw .up.sql replay onto an already-migrated store a no-op, and Dolt accepts no unprepared conditional ADD COLUMN. Unwrapping it also invalidates cliMigration0070AddParticipationGeneration.") + } + + // The bundle override is what keeps the two PREPARE blocks above off the + // pre-2.3 CLI path. + bundle := cliCompatibleMigrationSQL(migration0070Up, upSQL) + for _, want := range []string{ + "ALTER TABLE issues ADD COLUMN participation_generation BIGINT NULL;", + "ALTER TABLE wisps ADD COLUMN participation_generation BIGINT NULL;", + } { + if !strings.Contains(bundle, want) { + t.Errorf("0070's CLI bundle substitute (cliMigration0070AddParticipationGeneration) missing direct DDL %q", want) + } + } + // Design §16.3 step 5 (be-dt74u amendment, be-h89oq) makes 0070's CLI + // substitute ALTER wisps directly, the same unconditional-wisps-ALTER + // shape 0067's current_revision override already uses (see + // cliSubstituteAssumesWispTables' 0067 case). + if !cliSubstituteAssumesWispTables(migration0070Up) { + t.Error("0070's CLI substitute ALTERs wisps unguarded, so it must be listed in cliSubstituteAssumesWispTables — a replay over a clone that never synced the wisp tables has to fall back to the frozen source text") + } + + // down.sql files are not part of the embedded FS (only migrations/*.up.sql + // is //go:embed'd — see mainSource.files), so unlike the up side above, + // this reads straight from disk by package-relative path, matching + // TestMigration0068AddsAttributionStatus's precedent. + downBytes, err := os.ReadFile("migrations/" + migration0070Down) + if err != nil { + t.Fatalf("read %s: %v, want the migration file to exist", migration0070Down, err) + } + downSQL := string(downBytes) + for _, want := range []string{ + "ALTER TABLE issues DROP COLUMN participation_generation", + "ALTER TABLE wisps DROP COLUMN participation_generation", + } { + if !strings.Contains(downSQL, want) { + t.Errorf("0070 down migration missing %q\nfull SQL:\n%s", want, downSQL) + } + } + // Only migrations/*.up.sql is embedded into the CLI fresh bundle + // (mainSource.files), so the pre-2.3 prepared-DDL hazard never reaches a + // down migration and the guard is free — 0068's/0069's downs are the + // precedent. + if !strings.Contains(strings.ToUpper(downSQL), "PREPARE STMT FROM @SQL") { + t.Error("0070 down migration must guard its DROP COLUMNs the way the up migration guards its ADD COLUMNs, so a partially-applied or already-rolled-back workspace rolls back safely") + } +} + +// TestMigration0070AddsParticipationGenerationThroughDoltCLI applies the full +// migration bundle through a real `dolt` binary (skipped without one — see +// testutil.RequireDoltBinary) and checks the shape acceptance criteria a +// pure-Go SQL-text check cannot: actual column type/nullability as Dolt +// reports it, on both planes. +func TestMigration0070AddsParticipationGenerationThroughDoltCLI(t *testing.T) { + testutil.RequireDoltBinary(t) + + dir := t.TempDir() + runDoltCommand(t, dir, "init", "--name", "test", "--email", "test@example.com") + runDoltSQL(t, dir, AllMigrationsSQL()) + + requireDoltDataType(t, dir, "issues", "participation_generation", "bigint", "YES") + requireDoltDataType(t, dir, "wisps", "participation_generation", "bigint", "YES") + + // No backfill: design §16.2a's "NULL = legacy-unmigrated" declaration + // needs every pre-existing (and freshly-inserted, pre-fence) row to read + // back NULL. Only issues is round-tripped here — the column is read and + // written on that plane; wisps carries it for schema-parity shape only + // (§16.2a) and is never read or written by this phase. + runDoltSQL(t, dir, `INSERT INTO issues (id, title, description, design, acceptance_criteria, notes) VALUES ('pg-1', 't', 'd', 'des', 'ac', 'n')`) + // id rides along with the target column: dolt sql -r csv emits no data + // line at all for a single-column result whose only value is NULL (just + // the header survives) -- reproduced identically against pre-existing + // unrelated nullable columns (assignee, closed_at), so it's a CSV-writer + // quirk, not something specific to this migration. A second, + // always-populated column keeps the row real. + rows := queryDoltCSV(t, dir, `SELECT id, participation_generation FROM issues WHERE id = 'pg-1'`) + if len(rows) != 1 || rows[0]["participation_generation"] != "" { + t.Fatalf("participation_generation for a freshly-inserted issues row = %v, want NULL (empty string in CSV form)", rows) + } +} diff --git a/internal/storage/schema/migration_0071_add_removed_restriction_test.go b/internal/storage/schema/migration_0071_add_removed_restriction_test.go new file mode 100644 index 000000000..5ca6598d5 --- /dev/null +++ b/internal/storage/schema/migration_0071_add_removed_restriction_test.go @@ -0,0 +1,163 @@ +package schema + +import ( + "os" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/testutil" +) + +// R7.1 as-of read (gastownhall/beads#5898 revision 9, gastownhall/beads#6136) +// adds one nullable column: issue_versions gains +// removed_restriction VARCHAR(30). issue_versions already carries removed_at +// and removed_reason (migration 0067), virgin and unused until this slice; +// AsOfReadInTx (internal/storage/issueops/asof_read.go) reads all three as +// the durable "this version row was removed" marker. removed_restriction +// carries the categorical restriction removed_at's presence alone cannot: +// gone_retention / gone_erasure / gone_reorganization / unknown, never +// live -- live is the absence of a value, not a stored one. + +const migration0071Up = "0071_add_removed_restriction.up.sql" +const migration0071Down = "0071_add_removed_restriction.down.sql" + +// TestLatestVersionIncludesMigration0071 (pinning LatestVersion() == 71) is +// superseded by TestLatestVersionIncludesMigration0072 +// (migration_0072_add_epoch_minted_addresses_test.go) now that 0072 claims +// the next free slot -- only one such pin lives at a time, matching how this +// test itself already superseded 0070's own version. + +// TestMigration0071AddsRemovedRestriction is a pure-Go, DB-independent check +// of the frozen migration bytes themselves — it runs even where no `dolt` +// binary is available. +// +// It pins the same guarded-PREPARE shape 0067/0068 use and for the same +// reason: the guard is what makes a raw replay of this file onto an +// already-migrated store a no-op, and Dolt accepts no unprepared conditional +// ADD COLUMN. The cost is the same pre-2.3 CLI hazard those migrations carry, +// so this migration needs the same direct-DDL override in +// cliCompatibleMigrationSQL, policed by the same two guard tests +// (TestBundleMigrationsWithPreparedALTERAreOverriddenOrJustified and +// TestAllMigrationsSQLUsesDirectDDLForKnownCLIIncompatibilities). +func TestMigration0071AddsRemovedRestriction(t *testing.T) { + upSQL, err := MigrationSQL(migration0071Up) + if err != nil { + t.Fatalf("MigrationSQL(%s) error = %v, want the migration file to exist", migration0071Up, err) + } + for _, want := range []string{ + "ALTER TABLE issue_versions ADD COLUMN removed_restriction VARCHAR(30)", + "COLUMN_NAME = 'removed_restriction'", + "@issue_versions_rr_needs_add", + } { + if !strings.Contains(upSQL, want) { + t.Errorf("0071 up migration missing %q\nfull SQL:\n%s", want, upSQL) + } + } + if !strings.Contains(strings.ToUpper(upSQL), "PREPARE STMT FROM @SQL") { + t.Error("0071 up migration must keep its guarded PREPARE block — it is what makes a raw .up.sql replay onto an already-migrated store a no-op, and Dolt accepts no unprepared conditional ADD COLUMN. Unwrapping it also invalidates cliMigration0071AddRemovedRestriction.") + } + // The bundle override is what keeps the PREPARE above off the pre-2.3 + // CLI path. Assert it directly rather than trusting the two schema_test + // assertions to stay pointed at this migration. + const wantDirectDDL = "ALTER TABLE issue_versions ADD COLUMN removed_restriction VARCHAR(30);" + if !strings.Contains(cliCompatibleMigrationSQL(migration0071Up, upSQL), wantDirectDDL) { + t.Errorf("0071's CLI bundle substitute missing direct DDL %q", wantDirectDDL) + } + if cliSubstituteAssumesWispTables(migration0071Up) { + t.Error("0071's CLI substitute touches only issue_versions, which has no wisps-side counterpart table — it must not be listed in cliSubstituteAssumesWispTables") + } + + // down.sql files are not part of the embedded FS (only migrations/*.up.sql + // is //go:embed'd — see mainSource.files), so unlike the up side above, + // this reads straight from disk by package-relative path, matching + // TestMigration0067AddsVersionedBeadsSchema's / TestMigration0068AddsAttributionStatus's + // precedent. + downBytes, err := os.ReadFile("migrations/" + migration0071Down) + if err != nil { + t.Fatalf("read %s: %v, want the migration file to exist", migration0071Down, err) + } + downSQL := string(downBytes) + for _, want := range []string{ + "ALTER TABLE issue_versions DROP COLUMN removed_restriction", + "COLUMN_NAME = 'removed_restriction'", + } { + if !strings.Contains(downSQL, want) { + t.Errorf("0071 down migration missing %q\nfull SQL:\n%s", want, downSQL) + } + } + // Only migrations/*.up.sql is embedded into the CLI fresh bundle + // (mainSource.files), so the pre-2.3 prepared-DDL hazard never reaches a + // down migration and the guard is free — 0060's/0067's/0068's downs are + // the precedent. + if !strings.Contains(strings.ToUpper(downSQL), "PREPARE STMT FROM @SQL") { + t.Error("0071 down migration must guard its DROP COLUMN the way the up migration guards its ADD COLUMN, so a partially-applied or already-rolled-back workspace rolls back safely") + } +} + +// TestMigration0071HeaderSpellsTheVocabularyTheCodeStores pins the header's +// vocabulary to the constants that store, read and label the column (finding 6 +// of the #6661 review). The header is the one place a writer learns which +// strings to store, and a writer follows it literally: it said gone-retention, +// the code compares gone_retention, so a row written from the header was not +// recognised and rendered without a label. Deriving the expected spellings +// from the constants keeps the two from drifting apart again. +// +// Pure Go, like TestMigration0071AddsRemovedRestriction: it reads the frozen +// bytes and needs no `dolt` binary. +func TestMigration0071HeaderSpellsTheVocabularyTheCodeStores(t *testing.T) { + upSQL, err := MigrationSQL(migration0071Up) + if err != nil { + t.Fatalf("MigrationSQL(%s) error = %v, want the migration file to exist", migration0071Up, err) + } + for _, stored := range []issueops.AsOfRestriction{ + issueops.AsOfRestrictionGoneRetention, + issueops.AsOfRestrictionGoneErasure, + issueops.AsOfRestrictionGoneReorganization, + issueops.AsOfRestrictionUnknown, + } { + if !strings.Contains(upSQL, string(stored)) { + t.Errorf("0071 header never spells the stored value %q", stored) + } + if hyphenated := strings.ReplaceAll(string(stored), "_", "-"); hyphenated != string(stored) && strings.Contains(upSQL, hyphenated) { + t.Errorf("0071 header spells %q as %q; the code stores and compares the underscore spelling, so a writer following the header stores a value that renders unlabeled", stored, hyphenated) + } + } +} + +// TestMigration0071AddsRemovedRestrictionThroughDoltCLI applies the full +// migration bundle through a real `dolt` binary (skipped without one — see +// testutil.RequireDoltBinary) and checks the shape acceptance criteria a +// pure-Go SQL-text check cannot: actual column type/nullability as Dolt +// reports it, and that the column stays NULL for a row that never sets it +// (Live is the absence of a value) while round-tripping any of the four +// restriction strings a row does set it to. +func TestMigration0071AddsRemovedRestrictionThroughDoltCLI(t *testing.T) { + testutil.RequireDoltBinary(t) + + dir := t.TempDir() + runDoltCommand(t, dir, "init", "--name", "test", "--email", "test@example.com") + runDoltSQL(t, dir, AllMigrationsSQL()) + + requireDoltColumnShape(t, dir, "issue_versions", "removed_restriction", "varchar(30)", "YES") + requireDoltNoRows(t, dir, "SELECT issue_id FROM issue_versions", "issue_versions") + + runDoltSQL(t, dir, `INSERT INTO issue_versions (issue_id, revision, epoch, change_at, attribution_status) VALUES ('iv-1', 1, 1, '2026-09-01 00:00:00', 'claimed')`) + // issue_id rides along as a non-NULL anchor column: queryDoltCSV trims the + // whole `dolt sql -r csv` output before parsing, and a row whose ONLY + // selected column is NULL renders as a bare blank line, which + // strings.TrimSpace swallows when it's the trailing line -- silently + // turning "one row, NULL value" into "zero rows" and passing the wrong + // assertion for the wrong reason. Selecting issue_id alongside keeps the + // row's CSV line non-blank so it survives the trim. + rows := queryDoltCSV(t, dir, `SELECT issue_id, removed_restriction FROM issue_versions WHERE issue_id = 'iv-1'`) + if len(rows) != 1 || rows[0]["removed_restriction"] != "" { + t.Fatalf("removed_restriction for a row that never set it = %v, want NULL/empty (Live is the absence of a value)", rows) + } + + runDoltSQL(t, dir, `INSERT INTO issue_versions (issue_id, revision, epoch, change_at, attribution_status, removed_at, removed_reason, removed_restriction) VALUES ('iv-2', 1, 1, '2026-09-01 00:00:00', 'claimed', '2026-09-02 00:00:00', 'retention window elapsed', 'gone_retention')`) + rows = queryDoltCSV(t, dir, `SELECT issue_id, removed_restriction FROM issue_versions WHERE issue_id = 'iv-2'`) + if len(rows) != 1 || rows[0]["removed_restriction"] != "gone_retention" { + t.Fatalf("removed_restriction round-trip failed post-migration: %v", rows) + } +} diff --git a/internal/storage/schema/migration_0072_add_epoch_minted_addresses_test.go b/internal/storage/schema/migration_0072_add_epoch_minted_addresses_test.go new file mode 100644 index 000000000..67389a0e0 --- /dev/null +++ b/internal/storage/schema/migration_0072_add_epoch_minted_addresses_test.go @@ -0,0 +1,184 @@ +package schema + +import ( + "os" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/testutil" +) + +// R20's epoch-transition enforcement (gastownhall/beads#5898 revision 9, +// #6136) adds one brand-new table, +// epoch_minted_addresses -- see +// migrations/0072_add_epoch_minted_addresses.up.sql for the full rationale. +// This migration is a plain, unguarded +// CREATE TABLE IF NOT EXISTS with no ALTER and no PREPARE, so it needs none +// of 0067/0068's CLI-hazard-override tests (already covered, for every +// migration including this one, by TestBundleMigrationsWithPreparedALTERAreOverriddenOrJustified +// and TestAllMigrationsSQLUsesDirectDDLForKnownCLIIncompatibilities). + +// TestLatestVersionIncludesMigration0072 pins the real next free slot this +// phase claims, superseding 0071's own version of this test +// (migration_0071_add_removed_restriction_test.go; only one such pin lives at +// a time, the same way 0071's superseded 0070's). +// +// This slice originally claimed 0069 too. It was renumbered because +// R7.1's removed_restriction migration -- a PARALLEL SIBLING of this branch, +// not an ancestor -- had also claimed 0069, and the two are now linearized: +// R7.1 goes first (it is published beneath gastownhall/beads#6661), this one +// takes the next contiguous slot. Both then moved up one more slot when +// upstream's 0069_widen_issue_versions_datetime_precision +// (gastownhall/beads#6675) landed first, and once more when +// gastownhall/beads#6943's 0070_add_participation_generation (the +// versioned-history write fence) was ordered ahead of them: migrations are +// numbered by landing order, so R7.1 is 0071 and this is 0072. +// Two files sharing a +// version number panic checkNoDuplicateVersions at store open, before any +// command's RunE, which bricks every bd invocation rather than merely +// reddening a package -- see the same hazard on #6358 vs #6008. +// +// Deliberately a hardcoded literal for the same reason 0070's and 0071's +// were: LatestVersion() drifting to 72 for the wrong reason (an unrelated +// migration landing first) should still be caught by this test failing to +// explain why 72 is epoch-minted-addresses-shaped. +func TestLatestVersionIncludesMigration0072(t *testing.T) { + const want = 72 + if got := LatestVersion(); got != want { + t.Fatalf("LatestVersion() = %d, want %d (epoch_minted_addresses migration slot claimed by gastownhall/beads#6664)", got, want) + } +} + +const migration0072Up = "0072_add_epoch_minted_addresses.up.sql" +const migration0072Down = "0072_add_epoch_minted_addresses.down.sql" + +// TestMigration0072RecordsSurvivalInTheAddressTable is a pure-Go, +// DB-independent check of the frozen migration bytes: it runs even where no +// `dolt` binary is available. +// +// An address's survival is RECORDED on its own row, not inferred from other +// rows (gastownhall/beads#6664, bee-ghosttrack review 5360880888, Major 1): +// carried_from names the root address of the lineage a token-scheme change +// carried the row from, and gone_at_epoch is the epoch the store lost it in. +// Both are NULL for a fresh mint. The index serves the two lookups that +// follow a lineage (the newest carry of a root, and every carry of a root to +// lose), and the CHECK is the database-level tripwire against a stale or +// rewound epoch being written into a loss marker. It is >=, not >, because a +// carry row is born at the new epoch and can be lost in that same epoch. +// +// The migration is edited IN PLACE and gains no ALTER and no second slot: +// 0072 has never been applied to a store, and an ALTER over an already-applied +// copy of the earlier shape would be a migration slot nothing may claim. +func TestMigration0072RecordsSurvivalInTheAddressTable(t *testing.T) { + upSQL, err := MigrationSQL(migration0072Up) + if err != nil { + t.Fatalf("MigrationSQL(%s) error = %v, want the migration file to exist", migration0072Up, err) + } + for _, want := range []string{ + "CREATE TABLE IF NOT EXISTS epoch_minted_addresses", + "address VARCHAR(255) NOT NULL,", + "store_id VARCHAR(255) NOT NULL,", + "minted_id VARCHAR(255) NOT NULL,", + "minted_epoch INT NOT NULL,", + "minted_at DATETIME NOT NULL,", + "carried_from VARCHAR(255) NULL,", + "gone_at_epoch INT NULL,", + "PRIMARY KEY (address),", + "INDEX idx_epoch_minted_addresses_carried_from (carried_from),", + "CONSTRAINT ck_epoch_minted_addresses_gone_not_before_mint CHECK (gone_at_epoch IS NULL OR gone_at_epoch >= minted_epoch)", + } { + if !strings.Contains(upSQL, want) { + t.Errorf("0072 up migration missing %q\nfull SQL:\n%s", want, upSQL) + } + } + + // Only the statements count here: the header comments describe the + // migration in words that would otherwise trip these checks. + statements := strings.ToUpper(stripSQLLineComments(upSQL)) + if strings.Contains(statements, "ALTER TABLE") { + t.Error("0072 up migration must not ALTER anything: the survival columns belong to its own CREATE TABLE, because the migration is edited in place while no store has applied it") + } + if strings.Contains(statements, "PREPARE") { + t.Error("0072 up migration must stay plain DDL: CREATE TABLE IF NOT EXISTS needs no guarded PREPARE, and adding one would put it on the pre-2.3 CLI hazard path") + } + if got := strings.Count(statements, "CREATE TABLE"); got != 1 { + t.Errorf("0072 up migration has %d CREATE TABLE statements, want exactly 1", got) + } + + // Only migrations/*.up.sql is embedded, so the down side reads from disk by + // package-relative path, as migration 0067's test does. + downBytes, err := os.ReadFile("migrations/" + migration0072Down) + if err != nil { + t.Fatalf("read %s: %v, want the migration file to exist", migration0072Down, err) + } + if !strings.Contains(string(downBytes), "DROP TABLE IF EXISTS epoch_minted_addresses") { + t.Errorf("0072 down migration must drop epoch_minted_addresses, got:\n%s", downBytes) + } +} + +// TestMigration0072RecordsSurvivalInTheAddressTableThroughDoltCLI applies the +// full migration bundle through a real `dolt` binary (skipped without one, see +// testutil.RequireDoltBinary) and checks what a pure-Go SQL-text check cannot: +// the column types and nullability Dolt reports, the index it actually built, +// and that the CHECK is enforced on both INSERT and UPDATE, with the boundary +// it is meant to have. +func TestMigration0072RecordsSurvivalInTheAddressTableThroughDoltCLI(t *testing.T) { + testutil.RequireDoltBinary(t) + + dir := t.TempDir() + runDoltCommand(t, dir, "init", "--name", "test", "--email", "test@example.com") + runDoltSQL(t, dir, AllMigrationsSQL()) + + requireDoltColumnShape(t, dir, "epoch_minted_addresses", "carried_from", "varchar(255)", "YES") + requireDoltDataType(t, dir, "epoch_minted_addresses", "gone_at_epoch", "int", "YES") + // The five columns the mint writes keep their shape, so the mint's + // five-column INSERT is unchanged. + requireDoltColumnShape(t, dir, "epoch_minted_addresses", "address", "varchar(255)", "NO") + requireDoltColumnShape(t, dir, "epoch_minted_addresses", "minted_epoch", "int", "NO") + requireDoltNoRows(t, dir, "SELECT address FROM epoch_minted_addresses", "epoch_minted_addresses") + requireDoltCount(t, dir, + `SELECT COUNT(*) AS c FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'epoch_minted_addresses' AND INDEX_NAME = 'idx_epoch_minted_addresses_carried_from' AND COLUMN_NAME = 'carried_from'`, + "1") + + // A fresh mint writes the five original columns and is a root row: both + // survival columns come out NULL with no change to the INSERT. + runDoltSQL(t, dir, `INSERT INTO epoch_minted_addresses (address, store_id, minted_id, minted_epoch, minted_at) VALUES ('root-a', 'store', 'record-a', 3, '2026-09-01 00:00:00')`) + requireDoltCount(t, dir, `SELECT COUNT(*) AS c FROM epoch_minted_addresses WHERE address = 'root-a' AND carried_from IS NULL AND gone_at_epoch IS NULL`, "1") + + // A carry row names the lineage root. + runDoltSQL(t, dir, `INSERT INTO epoch_minted_addresses (address, store_id, minted_id, minted_epoch, minted_at, carried_from) VALUES ('carry-a', 'store', 'record-a', 5, '2026-09-01 00:00:00', 'root-a')`) + requireDoltCount(t, dir, `SELECT COUNT(*) AS c FROM epoch_minted_addresses WHERE carried_from = 'root-a'`, "1") + + // The CHECK: an epoch lost in may not precede the epoch minted in. + if err := runDoltSQLExpectingError(t, dir, `UPDATE epoch_minted_addresses SET gone_at_epoch = 2 WHERE address = 'root-a'`); err == nil { + t.Error("UPDATE gone_at_epoch below minted_epoch succeeded, want the CHECK constraint to reject it") + } + if err := runDoltSQLExpectingError(t, dir, `INSERT INTO epoch_minted_addresses (address, store_id, minted_id, minted_epoch, minted_at, gone_at_epoch) VALUES ('bad-b', 'store', 'record-b', 4, '2026-09-01 00:00:00', 3)`); err == nil { + t.Error("INSERT with gone_at_epoch below minted_epoch succeeded, want the CHECK constraint to reject it") + } + // Equal is allowed: a carry row is born at the new epoch and can be lost in + // that same epoch. + runDoltSQL(t, dir, `UPDATE epoch_minted_addresses SET gone_at_epoch = 3 WHERE address = 'root-a'`) + requireDoltCount(t, dir, `SELECT COUNT(*) AS c FROM epoch_minted_addresses WHERE address = 'root-a' AND gone_at_epoch = 3`, "1") + // A later epoch is allowed too. + runDoltSQL(t, dir, `UPDATE epoch_minted_addresses SET gone_at_epoch = 9 WHERE address = 'carry-a'`) + requireDoltCount(t, dir, `SELECT COUNT(*) AS c FROM epoch_minted_addresses WHERE address = 'carry-a' AND gone_at_epoch = 9`, "1") + + // The address stays the primary key. + if err := runDoltSQLExpectingError(t, dir, `INSERT INTO epoch_minted_addresses (address, store_id, minted_id, minted_epoch, minted_at) VALUES ('root-a', 'store', 'record-a', 3, '2026-09-01 00:00:00')`); err == nil { + t.Error("duplicate address insert succeeded, want primary key violation") + } +} + +// stripSQLLineComments drops "--" comment lines so a check over a migration's +// statements is not tripped by the prose in its header. +func stripSQLLineComments(sqlText string) string { + var kept []string + for _, line := range strings.Split(sqlText, "\n") { + if strings.HasPrefix(strings.TrimSpace(line), "--") { + continue + } + kept = append(kept, line) + } + return strings.Join(kept, "\n") +} diff --git a/internal/storage/schema/migration_freeze_test.go b/internal/storage/schema/migration_freeze_test.go new file mode 100644 index 000000000..678762e11 --- /dev/null +++ b/internal/storage/schema/migration_freeze_test.go @@ -0,0 +1,183 @@ +package schema + +import ( + "crypto/sha256" + "encoding/hex" + "io/fs" + "testing" +) + +// Migration freeze (Beads 1.2 release remediation). +// +// Migrations 0001–0066 (and ignored/ 0001–0026) are SHIPPED: the 1.2.x +// releases published schema v65 to thousands of installs and the 1.3.x +// releases added 0066 and ignored/ 0025–0026, so these files are now the +// de-facto on-disk contract of every migrated database. Amending a shipped +// migration forks installed schemas from freshly-migrated ones — the exact +// skew the smart gate's fork-skew detection exists to catch at runtime. This +// test catches it in CI instead: the content hash of every shipped +// up-migration is pinned; any change must land as a NEW migration, numbered +// after the newest file in its directory. When a release ships new +// migrations, raise the floors below and pin their hashes. +// +// If this test fails because you edited a shipped migration: revert the edit +// and write a new migration. There is no legitimate reason to update a pinned +// hash for an already-released version. + +const ( + frozenMainThrough = 66 + frozenIgnoredThrough = 26 +) + +var frozenMigrationHashes = map[string]string{ + "0001_create_issues.up.sql": "0c9bc4d97e2c5ee5d276c952333b934cd7d7d18210997d6bfd72d17f0fdb14f0", + "0002_create_dependencies.up.sql": "9ca011fa0b24ddf26f689eebf347cc2f80dc90256b099d91b993ec82c4d74da5", + "0003_create_labels.up.sql": "1780f0dc941d97b74af53d5603646d05e83d94eee5a02ac68ccf929200deaec0", + "0004_create_comments.up.sql": "35ac76b3d0b2d6287cad1329c77c8a0562bb6310ba0ac34ae273d72d4bed0e2a", + "0005_create_events.up.sql": "c8cbe4bebbe0f92c8a0ccc2a1a0d11ad442635811c2dab093c34c9341a8499b2", + "0006_create_config.up.sql": "435f5ef129dd4999a9b393c98d633038f0e443280a26e63f7d4315bf025dab1f", + "0007_create_metadata.up.sql": "f92c4d3dd32cae489142de34c4706900736c91cdc53b0d54e87e71656b828dc9", + "0008_create_child_counters.up.sql": "99db9b4b5a785ddd209dff628364c4c1eff549c3ca5ec48a64c604b15ef95bfb", + "0009_create_issue_snapshots.up.sql": "269ef83f083766b7f2fd2dfd2814ef36a585ae4aa18bcab0468a713d48595e48", + "0010_create_compaction_snapshots.up.sql": "cb34cbe311fd89a17d72067f449a65089f2fc9a7c4b3774d54448db5ebc3d659", + "0011_create_repo_mtimes.up.sql": "bde5204466541dddb53a652fe58561c08b6b3c1fa7feb38a0a582d432d76bda6", + "0012_create_routes.up.sql": "68e8ef1fc336e8ca6973f6b927b09d3206a7ebd96db9c4cdceab52fb8498c431", + "0013_create_issue_counter.up.sql": "7ddb30dabe32a66197de78f62400f41d000cf43d0ba8ba2a3943536504dddcdb", + "0014_create_interactions.up.sql": "0e17f1cb9fc5ee5a7c43ca8e02b9fd59814f8fd4372f9ffb17b50c34388614ce", + "0015_create_federation_peers.up.sql": "6aa04b3f66566b243c9a4fc09136af5c17f0ffe947a489245e3c451b995a59b9", + "0016_default_config.up.sql": "5d556c01404eb06acfb9df2b20fde36a2e91bd8a7d14462acbd3c0ae928ea286", + "0017_create_ready_issues_view.up.sql": "4bab7acbe2d8e441f156cc5912f421dcb214b9b08d7958eacc8e3a7318ab5f57", + "0018_create_blocked_issues_view.up.sql": "84dc6a3950a5447e6665e3d98b43f11a7631dc4e53bab1be332d135e51c9511f", + "0019_wisps_dolt_ignore.up.sql": "3df660feb6b64c84ef74c408fe8f5840a2815936534362ed123122f795a21c26", + "0020_create_wisps.up.sql": "bca95662441635454b879bb44ca1e607df9c5efd8fd802be3d53a7371a5ced86", + "0021_create_wisp_auxiliary.up.sql": "d19284a2be70a448db7746ae009cb264dc86dac0d9094aae9fe80a713a08ee70", + "0022_wisp_dep_type_index.up.sql": "fc1375e64620cd4264516718d8f924d88131881f4c00c51471b7630c11b74a45", + "0023_add_no_history_column.up.sql": "d11cd7cb462239e49c0b2f9b93ac73771106d5450ebc3422bb7737748c6f967b", + "0024_create_custom_status_type_tables.up.sql": "816da3feeed531ca9787dca8d4b8072dd94b64d573cf4b6751c61f2390c88a68", + "0025_update_ready_issues_view.up.sql": "09782d195f22d620ba41802856f9eb6e1a10f68bc5bcc8f3616624f8c28b576a", + "0026_update_blocked_issues_view.up.sql": "33daef6b5a07364fc5f59ab59b0f5c677dcf98d9bd0866c7c3bea874f1f01348", + "0027_add_started_at.up.sql": "dd3b58a8bbed4c49e855a6002981a285f10b6094938534dd3da9b121155f24d6", + "0028_local_state_dolt_ignore.up.sql": "24a816406a6f40c66db98697869d172b2b4366b107788fdd00f44b99abee45c3", + "0029_create_local_metadata.up.sql": "b989fc49ab03e06ff6520f150d6958efdbd3f444b69b824f7b4bb283ca6f2b65", + "0030_migrate_local_metadata_keys.up.sql": "8d55135274c1c75e722e802b250911cc574d52a4ba74fbb13edde84f30f9b3a4", + "0031_wisp_events_created_at_index.up.sql": "2d5cf3a6d4245b48c1b893efcc17b9fa25f1ea807e61290cf54064451fc58d93", + "0032_drop_schema_migrations_applied_at.up.sql": "42b86d6b7352f7e158532cc67f4afa142dc2503ce9f780733c06fc9da3478751", + "0033_add_wisp_type_column.up.sql": "9256746bb0d6ad9ed9afba0f0501259f0a3599b7d7da507dd7d808a13c688c75", + "0034_add_spec_id_column.up.sql": "7add95ead971c57618cfbc52e5cb6771d872785bfc035bde12cd27a76358848e", + "0035_migrate_infra_to_wisps.up.sql": "f917fe319540155572f5c51618cbbe20ec8b9b669d5926d68e3a62629c317c5a", + "0036_cleanup_autopush_metadata.up.sql": "e55f1870c2bc031c574b495ebca650365a9c8088d7a8968fb86a19cab81267e8", + "0037_uuid_primary_keys.up.sql": "7526beadee13aa7d6ee2175e9a543210b07c1a4426c382f251ebd31eebe32745", + "0038_drop_hop_columns.up.sql": "002dc637d45840487c35a01ce15cee04872baa45c21f8e20170a4339135a38e7", + "0039_drop_child_counters_fk.up.sql": "db65f241d1e82da41f34b960abc912f78b72e7dc1cb6dd2298974308edf8b768", + "0040_ignored_tables_also_nonlocal_tables.up.sql": "c7068d67ad3e2b4852549e04d97f25814121de83db919e220bdcb9bdd9b61e5e", + "0041_split_dependencies_target.up.sql": "e84ef393576df31550570fd3217579b1880850c0645b7d2b6ad8cf55a18ac1c0", + "0042_add_on_update_cascade.up.sql": "9d0fbb3d02955d25442c4a628ac518236068a97ecf164edbc814216bd5a55adc", + "0043_drop_dependencies_generated_column.up.sql": "548b8a69ab82179b7ee7ab3cc87ef00b3ae28d5a3a4976f42364f6939e384668", + "0044_update_views_drop_depends_on_id.up.sql": "531524854cc0e2361817d1ad94ba9470b0e81e378a5422ffb8bce71f3500adf9", + "0045_update_blocked_view_drop_depends_on_id.up.sql": "395dcbf186deedb592d8ed144e0b7953455efa0ccf02076d3b63e5e5d05dc241", + "0046_add_is_blocked.up.sql": "4d6a5a5fc5e386f2c538b4f3574b82fb2ba025176997953a0a4fbd2a91cddf68", + "0047_recompute_mixed_is_blocked.up.sql": "4aff5a7cc2e1e0250ce4cdb911d010c936681871fb627bceee4b2dc4647dd0a1", + "0048_widen_event_value_columns.up.sql": "093c7a41145508879844d16cbe5acfa69baddbb19bf3e05f00bc08720adea657", + "0049_longtext_large_content_columns.up.sql": "3359343efb7c28e5803de07e9088670489615d151843d7f23705f3ca8dd6a1e8", + "0050_dependencies_deterministic_id.up.sql": "96265ff898753f3bb34549fafa18bbaeb67519705b8cf4e32e67f1058df6841a", + "0051_drop_aux_id_defaults.up.sql": "deb741d5ac5fc1e0cd2e60eb47e84f384ed3455b18d3e2f12cb4e935fe461059", + "0052_add_date_indexes.up.sql": "60ae32bc26c41da2e743c1172f73930d18482b8a98aea08b9de85f6009f9c01d", + "0053_repair_rig_wisps.up.sql": "f13909f0db89f48db694a782d1805eee7ee1b2b2e4dcb3d4b12352333cbcb330", + "0054_add_lease_columns.up.sql": "2e51058ba15be9d87415949bb03c2c7c2f0e0743c5ae0d3e819b617d95f61680", + "0055_move_leases_to_table.up.sql": "2237ddbe13f5a783c65da3bb1292d9a5d89a5f22fddb0c33d2db57f1492df22c", + "0056_add_comments_keyset_index.up.sql": "acc28e9b1aa7272c16c86fcb9fd4a2038ae47729a60b53bb75f3a9df05cd3a82", + "0057_events_value_columns_idempotent_longtext.up.sql": "f86e0f77be2e58affe1c485767b8dd450408d782c0413a41948ca0c0b6d72d06", + "0058_heal_wisp_dependencies_split_constraints.up.sql": "9c1c6d557a03e71cf6b49123831c9f5b5f910fcea3ca51e982ec4acce04ea6ec", + "0059_recompute_null_gate_is_blocked.up.sql": "f0186029a1c87d579b67e0540ec22ad0bd0fc59793b07f7d24a24e122b77c394", + "0060_add_storage_class.up.sql": "40419632ba75d92dfcf08e16e77a780f014172a17068f6021937df9086a24588", + "0061_content_derived_aux_ids.up.sql": "d2d65b92789f137da8ee586067c862a9c7744921ccac421e1b793f42050b62a2", + "0062_events_dolt_ignore.up.sql": "c7de6089997344784a71e7d82ea5e417baaf66320b4533d225a4a6bc3c74222a", + "0063_create_provenance_events.up.sql": "1ef173be07ca58d17cb09ba3b3f5ca0c96edfcace8d52ae3adde2fd27e8248bd", + "0064_create_events_journal.up.sql": "25ea9ad8e849dc7e32e7c5850631bedc63a5c5da3bdc58ccb2762fd7a6c758fc", + "0065_widen_wisp_comments_text.up.sql": "c7341bb977daff92e073db2579e63058cef88d43f1e09b13fa153a772caac2a6", + "0066_add_events_journal_actor.up.sql": "a524d42ba0eced9350edbf6402dc2952957ff8f75a896bc8339c4cbc8596c793", +} + +var frozenIgnoredMigrationHashes = map[string]string{ + "0001_create_local_state_tables.up.sql": "a73e9a486124f89e90d50f4597fd1d7ad08e5d0d654459ec87b7520b47f1bb5f", + "0002_create_wisp_child_counters.up.sql": "c575c6710169f2e697f3aca60f5f698acc8a64af0edb1e2305b9d377fd845f45", + "0003_split_wisp_dependencies_target.up.sql": "f82947deeafe589598e2a1802eddf17712bd322692f924bb5653b0fbd5c46a0d", + "0004_add_wisp_aux_fks.up.sql": "12e18a8bdd214d6f96625e78998433ccc9c2d0ef4d1a35307f2653e725c800b9", + "0005_drop_wisp_dependencies_generated_column.up.sql": "08780b28ddef6c15f5de558ea08d821b52610f810555739ee1d737779986c607", + "0006_add_wisp_is_blocked.up.sql": "4746f10d7040d0b7a9e127437356de87765d12d2d27ee37c9800191e6b619d14", + "0007_recompute_wisp_is_blocked.up.sql": "c3c8d92846a54183cc99afc09f779f6f5ba8030c16ce46b3ee750314bf134627", + "0008_widen_wisp_event_value_columns.up.sql": "51375854ec081d2e0b1434b5ff8b6d87092b891636214ebb9f1dbef22438cc1a", + "0009_aux_row_id_rekey_marker.up.sql": "3d1ee4f9dde3342d110474c8090a30c474edafe2290e4372a3fc4607c1fdc030", + "0010_drop_wisp_id_defaults.up.sql": "59d6644667b7e34f9d23261cb694d461ddd4953969e75519d370b0cce8afd0e8", + "0011_cleanup_orphaned_child_counters.up.sql": "0efade0ecb620420ee42127d3f67230da108e31f2ff3c4281855a8dc9e187ecd", + "0012_create_leases.up.sql": "e128a1301a2bcb967f684b09318aa5cf7ed9adb5f6dd7d412de3d67d1de2b28d", + "0013_add_wisp_row_lock.up.sql": "127a4af7012769e5f016b13b198b7a57ff8386a10f8a68ffb9ff204989564d1b", + "0014_add_wisp_comments_keyset_index.up.sql": "29ad3654218700481b9541331c714ecbbe96dc81c04dc83fba6bf8d35bed7fa4", + "0015_recompute_null_gate_wisp_is_blocked.up.sql": "e761d5c3ceb9610edbb2e1d153e82d235cc7d7f0b87f28a45bec43835e6a4e19", + "0016_add_lease_granted_node.up.sql": "31a55421b78d8c90db6cfba5bf8e99e87d6123271575282f761aa077e5d36386", + "0017_add_wisps_defer_until_index.up.sql": "1f031aaf2037280e62cbf604748a4157bf25e3a60b3392af7d74835c5059bdd8", + "0018_aux_row_id_rekey2_marker.up.sql": "3c2120bf55d15e71a9f96972007c3d914154d17ea37a2b51b44412e3e3df6ef1", + "0019_create_events.up.sql": "db072d67a403e60d5bcbe924b84e473adb09f2326d36ede82fcdab17bb1e2a87", + "0020_add_wisp_storage_class.up.sql": "9ff476e6c73a3a477aec95143d5cbf180517a9484f647447392576f13181a015", + "0021_widen_wisp_large_content_columns.up.sql": "3cfa1e07a3d02eb7f791814d9642a93b9af3bf63728943afa05dcb0e489919c8", + "0022_create_events_journal.up.sql": "3d0adcb9f5833b4ba70fb48f88e1043250796feb7173abe000ea4de85eb8b3a5", + "0023_repair_events_journal_shape.up.sql": "d0edd83ca4cfbc46bd17799c6497a70c8c011d130d08a00c71daf792ee1dcd51", + "0024_widen_wisp_comments_text.up.sql": "69a96330e00643dfeddc4bf6ae9bf3b743a3cfddd86f16dc7b8912758b1b570d", + "0025_add_events_journal_actor.up.sql": "c81ca9edc80c25f6ab4f92d05d6ea412a780b108d1ed83745027440e9723dceb", + "0026_dep_rekey_dedup_marker.up.sql": "dc5c1b9a74e42184451796068ecba1ca11d8ebd0fe7e8c4bd4900d0cfee30446", +} + +func verifyFrozenMigrations(t *testing.T, fsys fs.FS, dir string, frozen map[string]string, frozenThrough int) { + t.Helper() + entries, err := fs.ReadDir(fsys, dir) + if err != nil { + t.Fatalf("reading embedded %s: %v", dir, err) + } + seen := map[string]bool{} + for _, entry := range entries { + if entry.IsDir() { + continue + } + name := entry.Name() + version, err := parseVersion(name) + if err != nil { + t.Fatalf("unparseable migration filename %q: %v", name, err) + } + if version > frozenThrough { + continue // not yet released — frozen when a release ships it + } + want, ok := frozen[name] + if !ok { + t.Errorf("shipped migration %s (v%d <= frozen floor %d) has no pinned hash — a released version was renamed or replaced; restore the original file", name, version, frozenThrough) + continue + } + seen[name] = true + content, err := fs.ReadFile(fsys, dir+"/"+name) + if err != nil { + t.Fatalf("reading embedded %s/%s: %v", dir, name, err) + } + sum := sha256.Sum256(content) + if got := hex.EncodeToString(sum[:]); got != want { + t.Errorf("shipped migration %s was AMENDED (hash %s, pinned %s) — shipped migrations are frozen; land the change as a new migration instead", name, got, want) + } + } + for name := range frozen { + if !seen[name] { + t.Errorf("pinned migration %s is missing from the embedded FS — a released version was deleted or renamed", name) + } + } +} + +// TestShippedMigrationsAreFrozen pins the content of every up-migration that a +// release has shipped. See the file comment for the policy. +func TestShippedMigrationsAreFrozen(t *testing.T) { + verifyFrozenMigrations(t, upMigrations, "migrations", frozenMigrationHashes, frozenMainThrough) +} + +// TestShippedIgnoredMigrationsAreFrozen is the ignored-sequence twin. The +// ignored tables are clone-local, so an amendment does not fork synced +// history — but it DOES make freshly-materialized clones diverge from +// long-lived ones, the same class of bug one plane over. +func TestShippedIgnoredMigrationsAreFrozen(t *testing.T) { + verifyFrozenMigrations(t, upIgnoredMigrations, "migrations/ignored", frozenIgnoredMigrationHashes, frozenIgnoredThrough) +} diff --git a/internal/storage/schema/migrations/0070_add_participation_generation.down.sql b/internal/storage/schema/migrations/0070_add_participation_generation.down.sql new file mode 100644 index 000000000..e37d545f9 --- /dev/null +++ b/internal/storage/schema/migrations/0070_add_participation_generation.down.sql @@ -0,0 +1,34 @@ +-- Reverse of migration 0070 (participation_generation on issues and wisps, +-- design section 16.3 steps 4-5, be-dt74u amendment, be-h89oq), undone in +-- reverse order. +-- +-- issue_versions is guaranteed empty in any real rollback scenario for the +-- same reason 0068's NOT NULL-no-default is safe (Phase 2 is that table's +-- first writer), but this migration touches issues/wisps, not +-- issue_versions -- participation_generation is dropped unconditionally on +-- both planes if present, guarded on INFORMATION_SCHEMA the same way 0068's +-- down is, so a partially-applied or already-rolled-back workspace rolls +-- back safely. Only migrations/*.up.sql is embedded into the CLI fresh +-- bundle, so the PREPARE hazard (cli_prepared_ddl.go) never reaches this +-- file. +SET @issues_pg_has = ( + SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'issues' + AND COLUMN_NAME = 'participation_generation' +); +SET @sql = IF(@issues_pg_has > 0, + 'ALTER TABLE issues DROP COLUMN participation_generation', + 'SELECT 1'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +SET @wisps_pg_has = ( + SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'wisps' + AND COLUMN_NAME = 'participation_generation' +); +SET @sql = IF(@wisps_pg_has > 0, + 'ALTER TABLE wisps DROP COLUMN participation_generation', + 'SELECT 1'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/internal/storage/schema/migrations/0070_add_participation_generation.up.sql b/internal/storage/schema/migrations/0070_add_participation_generation.up.sql new file mode 100644 index 000000000..8cf0fb392 --- /dev/null +++ b/internal/storage/schema/migrations/0070_add_participation_generation.up.sql @@ -0,0 +1,69 @@ +-- Migration 0070: participation_generation on issues and wisps (design +-- section 16.3 steps 4-5, be-dt74u amendment, be-h89oq). +-- +-- Originally written as steps 4-5 appended to 0068_add_attribution_status +-- (be-h89oq's lineage), while that file was still unmerged. be-v33pa's own +-- attribution_status-only version of 0068 shipped to main first (2026-09-28 +-- 15:46Z), freezing that file's content -- scripts/check-migration-hygiene.sh +-- Check C protects any migration already shipped on the base branch, so +-- these steps move here instead of reconciling by editing 0068 (mayor ruling +-- 2026-09-29 on tracker be-waare). Numbered 0070: 0068 and 0069 are already +-- taken on origin/main, the latter by an unrelated migration +-- (widen_issue_versions_datetime_precision) that landed independently while +-- this lineage was in flight. +-- +-- participation_generation BIGINT NULL on issues, mirrored inertly on wisps. +-- NULL means legacy-unmigrated; any non-NULL is a positive declaration +-- sourced from store_epoch.epoch. RecordVersionInTx's write fence (design +-- §16.2b, in internal/storage/issueops/version_history.go) reads this column +-- to decide whether an update-shaped mutation against a legacy record mints +-- a version row at all -- a create-shaped mutation stamps a fresh value +-- instead. No backfill: NULL is the correct default for every existing row, +-- on both planes, so a plain ADD COLUMN with no DEFAULT is exactly what's +-- wanted. +-- +-- This migration must run before versioned history is turned on. The fence +-- reads this column on every flag-on mint of an issues-plane row, and on a +-- store without it that read fails, so the mutation fails with it rather +-- than skipping. With the flag off (the default) the seam returns before +-- the read, so a store below this migration writes exactly as before. +-- +-- Guarded the same way 0067/0068's ADD COLUMNs are (INFORMATION_SCHEMA probe +-- + PREPARE, since Dolt 2.2.3's ADD COLUMN has no MariaDB-only IF NOT +-- EXISTS), making a raw-SQL replay of this file a clean no-op on an +-- already-migrated store. Needs a CLI-bundle direct-DDL override +-- (cliMigration0070AddParticipationGeneration in cli_migrations.go), the same +-- dolthub/dolt#11345 escape hatch 0067/0068 use. +SET @issues_pg_needs_add = ( + SELECT IF(COUNT(*) = 0, 1, 0) + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'issues' + AND COLUMN_NAME = 'participation_generation' +); +SET @sql = IF(@issues_pg_needs_add = 1, + 'ALTER TABLE issues ADD COLUMN participation_generation BIGINT NULL', + 'SELECT 1'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- wisps.participation_generation -- shape parity only, never read or written +-- on this plane (design §16.2a). Guarded on the wisps table existing as well +-- as the column, mirroring 0067's wisps.current_revision guard exactly (see +-- that migration's header): wisps is dolt-ignored/clone-local, so a clone +-- that never synced the local wisp tables must no-op rather than abort. The +-- clone-local twin for a workspace that never synced the wisps table at all +-- is ignored/0028_add_wisps_participation_generation.up.sql. +SET @wisps_pg_needs_add = IF( + (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'wisps') > 0 + AND + (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'wisps' + AND COLUMN_NAME = 'participation_generation') = 0, + 1, 0 +); +SET @sql = IF(@wisps_pg_needs_add = 1, + 'ALTER TABLE wisps ADD COLUMN participation_generation BIGINT NULL', + 'SELECT 1'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/internal/storage/schema/migrations/0071_add_removed_restriction.down.sql b/internal/storage/schema/migrations/0071_add_removed_restriction.down.sql new file mode 100644 index 000000000..5c3f8bde6 --- /dev/null +++ b/internal/storage/schema/migrations/0071_add_removed_restriction.down.sql @@ -0,0 +1,16 @@ +-- Reverse of 0071: drop issue_versions.removed_restriction. +-- +-- Guarded on INFORMATION_SCHEMA the same way 0067/0068's downs are, so a +-- partially-applied or already-rolled-back workspace rolls back safely. +-- Only migrations/*.up.sql is embedded into the CLI fresh bundle, so the +-- PREPARE hazard (cli_prepared_ddl.go) never reaches this file. +SET @issue_versions_rr_has = ( + SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'issue_versions' + AND COLUMN_NAME = 'removed_restriction' +); +SET @sql = IF(@issue_versions_rr_has > 0, + 'ALTER TABLE issue_versions DROP COLUMN removed_restriction', + 'SELECT 1'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/internal/storage/schema/migrations/0071_add_removed_restriction.up.sql b/internal/storage/schema/migrations/0071_add_removed_restriction.up.sql new file mode 100644 index 000000000..e47123ed2 --- /dev/null +++ b/internal/storage/schema/migrations/0071_add_removed_restriction.up.sql @@ -0,0 +1,49 @@ +-- Migration 0071: R7.1 as-of read (gastownhall/beads#5898 revision 9, +-- gastownhall/beads#6136); conformance suite: backend/conformance/ +-- versioned_read_contract.go. +-- +-- issue_versions already carries removed_at DATETIME and removed_reason +-- VARCHAR(255) (migration 0067), virgin and unused until now: R7.1's +-- AsOfReadInTx (internal/storage/issueops/asof_read.go) reads them as the +-- durable "this version row was removed" marker on the resolved row, and +-- refuses a served answer whenever removed_at is set (R8: never silently +-- substitute a neighboring/surviving/current version). +-- +-- removed_restriction VARCHAR(30) is the one column this migration adds: the +-- categorical restriction (gone_retention / gone_erasure / +-- gone_reorganization / unknown) that removed_at's presence alone cannot +-- carry. Nullable and NULL for every existing row -- Live is the absence of +-- a value, never a stored one -- and populated only alongside removed_at, +-- never independently. 30 chars comfortably fits the longest local +-- constant (internal/storage/issueops/asof_read.go's AsOfRestriction, +-- "gone_reorganization", 19 bytes) with headroom, matching change_agent's +-- own no-tight-fit precedent elsewhere in this table. +-- +-- Forward-compatible with R17 (not yet implemented on this branch): R17's +-- eventual real hold/remove/erase primitives will be the production WRITER +-- of these three columns; R7.1 only reads them here. No future collision -- +-- this migration only adds the one column R17 will also need, it does not +-- claim the writing role. +-- +-- Guarded the same way 0067/0068 guard their ADD COLUMNs (see 0067's header +-- for the full explanation): no MariaDB-only IF NOT EXISTS on Dolt 2.2.3's +-- ADD COLUMN, so an INFORMATION_SCHEMA probe + PREPARE is the only +-- replay-safe shape. Needs a CLI-bundle direct-DDL override +-- (cliMigration0071AddRemovedRestriction in cli_migrations.go), the same +-- dolthub/dolt#11345 escape hatch 0067/0068 use, guarded by +-- TestBundleMigrationsWithPreparedALTERAreOverriddenOrJustified. +-- +-- No wisps twin: issue_versions has no wisps-side counterpart table (design +-- section 16.3), so cliSubstituteAssumesWispTables does not apply here +-- either, matching 0068. +SET @issue_versions_rr_needs_add = ( + SELECT IF(COUNT(*) = 0, 1, 0) + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'issue_versions' + AND COLUMN_NAME = 'removed_restriction' +); +SET @sql = IF(@issue_versions_rr_needs_add = 1, + 'ALTER TABLE issue_versions ADD COLUMN removed_restriction VARCHAR(30)', + 'SELECT 1'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/internal/storage/schema/migrations/0072_add_epoch_minted_addresses.down.sql b/internal/storage/schema/migrations/0072_add_epoch_minted_addresses.down.sql new file mode 100644 index 000000000..af8d83eea --- /dev/null +++ b/internal/storage/schema/migrations/0072_add_epoch_minted_addresses.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS epoch_minted_addresses; diff --git a/internal/storage/schema/migrations/0072_add_epoch_minted_addresses.up.sql b/internal/storage/schema/migrations/0072_add_epoch_minted_addresses.up.sql new file mode 100644 index 000000000..ec946cf8e --- /dev/null +++ b/internal/storage/schema/migrations/0072_add_epoch_minted_addresses.up.sql @@ -0,0 +1,64 @@ +-- epoch_minted_addresses: durable storage for R20 epoch-transition +-- enforcement (gastownhall/beads#5898 revision 9, +-- #6136). Independent of store_epoch (0067, #6135) -- that table holds only +-- the store-wide singleton epoch counter (the current generation number); +-- this table tracks the individual addresses minted under each generation, +-- which store_epoch has no room to hold. It is also independent of +-- expected_revision_records (R16, #6133) and any RetentionFixture/R17 +-- table: R20 epoch reasoning is evaluated on its own, without consulting +-- retention/erasure state, and this migration adds no R17 resolve, remove, +-- hold, force-remove, erase, or mint logic. +-- +-- One row per minted address, not one row per id: MintUnderEpoch is +-- deterministic in (store_id, id, epoch) -- see epochAddress() in +-- internal/storage/issueops/epoch_cas.go -- so minting the same id again +-- under the same epoch reproduces the same address and finds the same +-- row, while a later mint of that id under a bumped epoch produces a +-- DIFFERENT address and adds a new row alongside the old one. Old rows are +-- kept: StillServes and Resolve answer for any address from its own row, +-- whatever epoch it was minted in. +-- +-- Survival is RECORDED on the row, never inferred from other rows +-- (gastownhall/beads#6664, bee-ghosttrack review 5360880888, Major 1). +-- gone_at_epoch is NULL while the store serves the address and otherwise the +-- epoch the store lost it in; it is set once and never cleared, so a lost +-- address stays lost. carried_from is NULL for a fresh mint, and for a row a +-- token-scheme change carried to a new epoch it is the address of the +-- lineage's ROOT (never the previous carry), so every member of a lineage is +-- one indexed lookup from the newest. The index on carried_from serves exactly +-- the two lookups that follow a lineage: the newest carry of a root, and every +-- carry of a root when the lineage is lost. The CHECK is a database-level +-- tripwire against a stale or rewound epoch being written into a loss marker; +-- it is >=, not >, because a carry row is born at the new epoch and can be lost +-- in that same epoch. +-- +-- address is the PRIMARY KEY: it is the deterministic token the fixture's +-- StillServes/Resolve/CurrentAddressFor hooks look addresses up by, so it +-- must be unique and indexed; it is never recomputed from the other columns +-- at read time; it is written once, whatever the epoch was at mint time. +-- +-- store_id and minted_id are VARCHAR(255) for parity with this schema's +-- other identifier columns. minted_epoch is INT to match store_epoch.epoch's +-- own type. minted_at is DATETIME, not a nanosecond-precision integer: unlike +-- expected_revision_records.change_at_nanos (R16, 0069 on that slice), no +-- R20 contract case compares minted_at for exact round-tripping -- it exists +-- for observability only, so it follows store_epoch.bumped_at's own +-- DATETIME precedent rather than needing BIGINT. +-- +-- Plain, unguarded CREATE TABLE IF NOT EXISTS: a brand-new main-plane table +-- with no ALTER, no PREPARE, and no dolt-ignored (clone-local) table +-- involved, so none of cli_migrations.go's CLI-bundle overrides, an +-- ignored/ twin, or a nondeterminism-allowlist entry apply +-- (scripts/check-migration-hygiene.sh checks B-E). +CREATE TABLE IF NOT EXISTS epoch_minted_addresses ( + address VARCHAR(255) NOT NULL, + store_id VARCHAR(255) NOT NULL, + minted_id VARCHAR(255) NOT NULL, + minted_epoch INT NOT NULL, + minted_at DATETIME NOT NULL, + carried_from VARCHAR(255) NULL, + gone_at_epoch INT NULL, + PRIMARY KEY (address), + INDEX idx_epoch_minted_addresses_carried_from (carried_from), + CONSTRAINT ck_epoch_minted_addresses_gone_not_before_mint CHECK (gone_at_epoch IS NULL OR gone_at_epoch >= minted_epoch) +); diff --git a/internal/storage/schema/migrations/ignored/0028_add_wisps_participation_generation.up.sql b/internal/storage/schema/migrations/ignored/0028_add_wisps_participation_generation.up.sql new file mode 100644 index 000000000..4ed7a3c58 --- /dev/null +++ b/internal/storage/schema/migrations/ignored/0028_add_wisps_participation_generation.up.sql @@ -0,0 +1,36 @@ +-- Ignored migration 0028: ensure wisps.participation_generation exists on +-- every clone (design be-hs42e.3 §16.2-16.3 / be-h89oq / be-x8tpz). +-- +-- Synced migration 0070 adds participation_generation to issues and wisps -- +-- but wisps is dolt-ignored (migration 0019), so its schema is clone-local, +-- and a workspace that bootstraps or re-clones from a remote whose +-- schema_migrations cursor is already >= 0070 adopts the cursor without ever +-- executing 0070. Its wisps table would then permanently lack the column, +-- and the shared issues/wisps column lists would drift by one column between +-- the fresh-clone door and the fresh-init door. Same mechanism, same shape, +-- same fix as ignored/0013 (wisps.row_lock, wy-pt82l), ignored/0020 +-- (wisps.storage_class, wy-98eh5), and ignored/0027 (wisps.current_revision). +-- +-- Carried here for SHAPE only, exactly like 0070's own issues/wisps split: +-- nothing reads or writes this column on the wisps plane (design §16.2a). +-- wisps.row_lock and wisps.current_revision are the precedent for a column +-- that exists on both planes and means something on only one. +-- +-- The guard makes this a no-op on in-place-upgraded workspaces where synced +-- 0070 already added the column, and on workspaces with no local wisps table +-- yet. Definition mirrors 0070's own wisps.participation_generation guard +-- exactly: BIGINT NULL, no default, no backfill. +SET @needs_add = IF( + (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'wisps') > 0 + AND + (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'wisps' + AND COLUMN_NAME = 'participation_generation') = 0, + 1, 0 +); +SET @sql = IF(@needs_add = 1, + 'ALTER TABLE wisps ADD COLUMN participation_generation BIGINT NULL', + 'SELECT 1'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/internal/storage/schema/remote_migrate_gate.go b/internal/storage/schema/remote_migrate_gate.go index 5ca3d2a15..0d6075dd6 100644 --- a/internal/storage/schema/remote_migrate_gate.go +++ b/internal/storage/schema/remote_migrate_gate.go @@ -127,6 +127,20 @@ type RemoteMigrateGateError struct { // can report conflicts to resolve first. Set only when // FallbackReason == fallbackReasonDataBehind; meaningless otherwise. DataDiverged bool + + // Proxied marks a refusal raised on a proxied-server-mode open — the unit + // of work provider, which reaches its database only through the dbproxy. + // It changes WHERE the data-behind remedy can be run, not what it is: in + // that mode `bd dolt pull` is refused at the front door + // (proxy.dolt_pull.unsupported, cmd/bd/capability_registry.go), along with + // `bd dolt push`, `bd migrate` and `bd conflicts`. Printing the bare + // command there would hand the operator a remedy their own binary rejects, + // so the surfaces that name it say to run it where the database lives. + // + // Deliberately set by the provider after the gate returns rather than + // plumbed into the gate: the topology is the caller's fact, and every + // other injection site would have to pass a constant false. + Proxied bool } const ( @@ -268,7 +282,16 @@ func (e *RemoteMigrateGateError) fallbackReasonNote() string { case fallbackReasonSharedStore: why = "this store is shared (dolt sql-server); the first-mover auto-migrate is disabled here because it would lock out co-resident clients (#5920)" case fallbackReasonDataBehind: - why = "this clone is behind the remote in data commits it has not pulled, so it is not the first-mover it looks like on schema alone — migrating in place would diverge from those commits, and can leave every later `bd dolt pull` refusing to merge (#6575, #6368). Run `" + DataBehindRemedyCommand + "` first, then retry: this clone is then the true first-mover it looked like" + // UserMessage prints this note AFTER userBody, so on a proxied + // workspace an unqualified remedy makes the LAST paragraph tell the + // operator to type here the command the paragraph above just said the + // front door refuses. Gate it the same way dataBehindBody and + // Options() already do. + remedy := "Run `" + DataBehindRemedyCommand + "` first, then retry" + if e.Proxied { + remedy = "Run `" + DataBehindRemedyCommand + "` on the server host first (this workspace is in proxied-server mode, which refuses it — proxy.dolt_pull.unsupported), then retry here" + } + why = "this clone is behind the remote in data commits it has not pulled, so it is not the first-mover it looks like on schema alone — migrating in place would diverge from those commits, and can leave every later `bd dolt pull` refusing to merge (#6575, #6368). " + remedy + ": this clone is then the true first-mover it looked like" // Only promise the retry resolves itself where it actually does. On a // shared store the first-mover auto-migrate is suppressed regardless // (fallbackReasonSharedStore, #5920), so pulling clears THIS stop but @@ -322,6 +345,22 @@ func (e *RemoteMigrateGateError) dataBehindBody() string { " This clone has no commits of its own, so the pull is a pure fast-forward:\n" + " nothing local is merged or discarded.\n" } + if e.Proxied { + // The remedy is the same command; what changes is where it can be + // typed. This workspace reaches the database through the dbproxy, and + // the proxied front door refuses `bd dolt pull` outright — so leaving + // the line above unqualified would name a command this very binary + // rejects (gastownhall/beads#6575 follow-up). It sits after the shape + // clause because the conflict handling that clause describes moves to + // the same machine. + body += "" + + "\n" + + " That pull cannot be run from here: this workspace is in proxied-server mode,\n" + + " which refuses `" + DataBehindRemedyCommand + "` at the front door (proxy.dolt_pull.unsupported),\n" + + " along with `bd dolt push`, the bare `bd migrate` and `bd conflicts`. Run\n" + + " it — and any conflict resolution it needs — where the database lives: on\n" + + " the server host, from a workspace with direct access to that database.\n" + } body += "" + "\n" + " Then re-run what you just ran.\n" @@ -340,6 +379,26 @@ func (e *RemoteMigrateGateError) dataBehindBody() string { " until they are upgraded (#5920). Once the pull above has completed:\n" + " " + SharedConsentCommandForced + "\n" + " (" + SharedConsentCommandForcedGlobal + " for the shared global database)\n" + if e.Proxied { + // Unlike the pull, this consent step is NOT refused here, and + // saying otherwise would be wrong in the unsafe direction. The + // proxied capability registry keys on the command path + // (cmd/bd/capability_registry.go): it refuses the bare `migrate` + // verb and its hooks/issues/sync children, but permits + // `migrate schema`, so the two-word path passes + // validateProxyRegistryBeforeProvider to a proxied arm that + // reports the migration the provider open just applied under this + // verb's consent. A reader told it is blocked here tries it to + // confirm — and forceOrEnvConsent is honored BEFORE this stop is + // ever routed, so the wedge lands on the one topology that can + // still take it. State the real precondition instead: not where, + // but when. + body += "" + + " Unlike the pull, that consent step CAN be run from here: the proxied front\n" + + " door refuses the bare `bd migrate` verb, not `" + SharedConsentCommandForced + "`,\n" + + " and the provider open applies the migration under it. That is exactly why\n" + + " it has to wait — run it only after the pull on the server host completes.\n" + } } else { body += "" + " The migration then runs on its own: with nothing left to pull, this clone\n" + @@ -354,10 +413,28 @@ func (e *RemoteMigrateGateError) dataBehindBody() string { if e.Shared { // The consent command this arm prescribes is itself a forced migrate, // so the warning above has to say what makes that one different: the - // pull having already landed, not the flag. + // pull having already landed, not the flag. Named in full rather than + // as "the command above", which is ambiguous once the proxied clause + // below is also printed. body += "" + - " The same goes for the consent command above until the pull has finished:\n" + - " what makes it safe is that there is nothing left to pull by then.\n" + " The same holds for `" + SharedConsentCommandForced + "` until the pull has\n" + + " finished: what makes it safe is that there is nothing left to pull by then.\n" + } + if e.Proxied { + // Only the BARE `bd migrate` the warning above names is refused here. + // Two other surfaces carry the same forced consent and are both + // reachable from this workspace: the two-word `migrate schema` path, + // which no proxy refusal row matches, and the env hatch, which no + // command dispatch touches at all. forceOrEnvConsent reads both before + // this stop is routed, so a proxied warning that implies the topology + // already blocks the wedge would leave it open on the one topology + // that can still take it. + body += "" + + " Being in proxied-server mode does not put that out of reach: the front door\n" + + " refuses the bare `bd migrate` verb, not `" + SharedConsentCommandForced + "`, and\n" + + " " + AllowRemoteMigrateEnv + "=1 grants the same consent to ANY command, including\n" + + " the one you just ran. Both are honored before this stop is even reached, so\n" + + " do not reach for either to get past it.\n" } return body } @@ -484,6 +561,12 @@ func (e *RemoteMigrateGateError) AgentDirective() string { } else { d += " This clone has no commits of its own, so that pull is a pure fast-forward and discards nothing." } + if e.Proxied { + d += " This workspace is in proxied-server mode, where `" + DataBehindRemedyCommand + "` is refused at the " + + "front door (proxy.dolt_pull.unsupported) — do NOT attempt it here. The pull has to be run where the " + + "database lives (the server host, from a workspace with direct access to it); surface that to the " + + "operator rather than retrying locally." + } if e.Shared { d += " After the pull the migration still needs the operator's explicit consent (" + SharedConsentCommandForced + " — this store is remote-backed, so the bare verb does not unlock it; see SharedConsentCommandForced): " + @@ -523,7 +606,8 @@ func (e *RemoteMigrateGateError) AgentDirective() string { } } -// GateOption is one conditional remediation path for the remote-migrate gate. +// GateOption is one conditional remediation path for the remote-migrate gate +// (and the migration-consent gate, MigrateConsentError.Options). // It is intentionally conditional (When) and carries its Risk, so an agent // cannot treat any single command as the unconditional fix. type GateOption struct { @@ -568,8 +652,20 @@ func (e *RemoteMigrateGateError) Options() []GateOption { if e.DataDiverged { risk = "this clone also has commits of its own, so the pull MERGES; it can report conflicts that must be resolved before it completes (bd dolt pull --strategy ours|theirs on embedded storage, bd conflicts resolve on a server store). Nothing is discarded without that resolution" } + id := "pull-first" + if e.Proxied { + // An option an agent can read as runnable-here is the harm on this + // topology: the proxied front door refuses the command. Say WHERE + // in both the id and the precondition, so neither a Commands-only + // reader nor an id-only reader is misled. + id = "pull-first-on-server-host" + when = "always, for this stop, but NOT from this workspace: it is in proxied-server mode, where " + + DataBehindRemedyCommand + " is refused (proxy.dolt_pull.unsupported). Run it on the machine that " + + "hosts this database, from a workspace with direct access to it, then retry here" + risk += "; running it from this proxied workspace fails with proxy.dolt_pull.unsupported and changes nothing" + } pull := GateOption{ - ID: "pull-first", + ID: id, When: when, Commands: []string{DataBehindRemedyCommand}, Risk: risk, @@ -582,11 +678,24 @@ func (e *RemoteMigrateGateError) Options() []GateOption { // the bare verb's consent is read only on the no-remote arm — an // option whose command cannot succeed in the state that printed it // is worse than no option (see SharedConsentCommandForced). + consentWhen := "the pull above has completed AND every co-resident bd client of this server is upgraded to this binary (confirmed with the operator)" + consentRisk := "co-resident clients still on an older bd will refuse this database until upgraded; running it before the pull completes is the wedge this stop prevents. Its --force consents to migrating a remote-backed shared store (the bare verb's consent is read only with no remote configured); it does not make migrating while behind safe" + if e.Proxied { + // Unlike the pull, this command is NOT refused here: the + // capability registry permits the two-word "migrate schema" + // path, so it gets through and the provider open applies the + // migration under its consent. The precondition is therefore + // temporal, not locational — and it is the only thing between + // an agent on this topology and the wedge, because forced + // consent is honored before this stop is routed at all. + consentWhen += ". Unlike the pull this one IS runnable from this proxied workspace — the front door refuses the bare `bd migrate`, not this two-word path — so the pull-first half of this precondition is load-bearing here, not a formality" + consentRisk += ". Running it from this proxied workspace does NOT fail closed the way the pull does: the consent is honored before this stop is routed, and the provider open applies the migration" + } return []GateOption{pull, { ID: "migrate-shared-after-pulling", - When: "the pull above has completed AND every co-resident bd client of this server is upgraded to this binary (confirmed with the operator)", + When: consentWhen, Commands: []string{SharedConsentCommandForced}, - Risk: "co-resident clients still on an older bd will refuse this database until upgraded; running it before the pull completes is the wedge this stop prevents. Its --force consents to migrating a remote-backed shared store (the bare verb's consent is read only with no remote configured); it does not make migrating while behind safe", + Risk: consentRisk, }} } return []GateOption{pull} diff --git a/internal/storage/schema/schema.go b/internal/storage/schema/schema.go index b9dae90b6..2c95d0e9f 100644 --- a/internal/storage/schema/schema.go +++ b/internal/storage/schema/schema.go @@ -269,8 +269,8 @@ type SchemaBehindError struct { } func (e *SchemaBehindError) Error() string { - return fmt.Sprintf("schema version mismatch: database is at v%d, binary expects v%d, and the read-only open cannot migrate it; run any bd write command in that workspace to migrate, or set BD_IGNORE_SCHEMA_SKEW=1 to read anyway (queries touching newer schema may fail)", - e.DBVersion, e.BinaryVersion) + return fmt.Sprintf("schema version mismatch: database is at v%d, binary expects v%d; bd does not migrate a database without explicit consent — run `bd migrate schema` in that workspace to migrate, keep using a bd release that matches schema v%d, or set BD_IGNORE_SCHEMA_SKEW=1 to read anyway (queries touching newer schema may fail)", + e.DBVersion, e.BinaryVersion, e.DBVersion) } // IsSchemaBehindError reports whether err (or any error it wraps) is a @@ -332,6 +332,22 @@ type migrationSource struct { // TestSentinelTablesAreCreatedByTheSeries enforces the creating side only; // the dropping side is this comment. sentinelTables []string + // sentinelFlooredTables are clone-local tables whose absence contradicts an + // otherwise at-latest cursor, but — unlike sentinelTables — only back to + // each table's own replayFloor rather than unconditionally to 0. events, + // bd_events_journal, and bd_events_seq are dolt_ignored (never part of + // committed history, so a fresh clone can arrive at-latest without them) + // but floor-0 would replay ignored/0007's unguarded + // `UPDATE wisps SET is_blocked = 0` (see schemaSentinelColumn.replayFloor) + // for a table absence that says nothing about migrations that predate it. + // + // INVARIANT: no future migration in this series may DROP or RENAME a + // floored sentinel table. Older binaries in the field check their own + // sentinel list against the live schema, so removing one would make every + // healthy newer database read as "contradicted" to them and replay the + // series from their floor. TestSentinelFlooredTablesAreCreatedByTheSeries + // enforces the creating side only; the dropping side is this comment. + sentinelFlooredTables []schemaSentinelTable // sentinelColumns are clone-local columns whose absence contradicts an // otherwise at-latest cursor. Unlike a missing sentinel table, a missing // column disbelieves the cursor only back to the column's replayFloor: it @@ -347,6 +363,15 @@ type migrationSource struct { sentinelColumns []schemaSentinelColumn } +type schemaSentinelTable struct { + table string + // replayFloor is the highest cursor value this sentinel's absence still + // leaves believable — same semantics and the same two constraints as + // schemaSentinelColumn.replayFloor, applied to a whole table's presence + // instead of one column's. + replayFloor int +} + type schemaSentinelColumn struct { table string column string @@ -366,8 +391,8 @@ type schemaSentinelColumn struct { // — just without the timestamp damage. // (ii) The migration that creates the column AND the migration that // creates the table carrying it must both be ABOVE the floor, so the - // replay can still heal both shapes the single INFORMATION_SCHEMA - // COUNT(*) probe collapses: table absent entirely, and table present + // replay can still heal both shapes the column probe collapses + // (sentinelColumnExists): table absent entirely, and table present // but column-less. A floor above the table's creator would strand // the table-absent shape in a permanent re-migration loop. // @@ -391,12 +416,33 @@ var ( // missing; wisps is checked too so a partially materialized database // is caught by whichever is absent. sentinelTables: []string{"wisps", "wisp_dependencies"}, + // events is created by ignored/0019 (floor 18: everything at or below + // must stay out of the replay, and 0019 itself must stay in it) and + // bd_events_journal/bd_events_seq are both created by ignored/0022 + // (floor 21, same reasoning). All three are dolt_ignored and never + // part of committed history, so a clone can arrive with the cursor + // at-latest but without them — exactly the leases shape below, except + // a whole-table absence rather than a column-on-an-existing-table one. + // + // The journal tables are ignored unconditionally; events is the one + // version-gated pattern ({"events", 62} below), so strictly its + // ignore is only asserted once the main cursor reaches 0062. That is + // safe here rather than a hole: this replay runs on the ignored plane, + // which migrateUpAfterReconcile only reaches after the main pass + // succeeded, and a main pass from below 62 applies + // 0062_events_dolt_ignore, whose REPLACE INTO dolt_ignore lands + // before the ignored plane is touched. So the clamp can never have + // 0019 re-create events as tracked-at-HEAD. + sentinelFlooredTables: []schemaSentinelTable{ + {table: "events", replayFloor: 18}, + {table: "bd_events_journal", replayFloor: 21}, + {table: "bd_events_seq", replayFloor: 21}, + }, // A historical ignored-v16 ordinal collision can leave the local // leases table present but without the column frozen 0016 adds; a // database materialized out of band can be missing the leases table - // altogether. The single COLUMNS probe reads both shapes as absent and - // the replay heals both: 0012 re-creates the table, 0016 adds the - // column. + // altogether. The column probe reads both shapes as absent and the + // replay heals both: 0012 re-creates the table, 0016 adds the column. // // The floor of 11 is what keeps that heal from also being a data loss. // Every released tree (v1.1.0, v1.1.2, v1.2.x) tops the ignored series @@ -734,6 +780,21 @@ func MigrateUpTo(ctx context.Context, db DBConn, maxVersion int) (int, error) { } func MigrateUp(ctx context.Context, db DBConn) (int, error) { + // Consent gate first, before ANY write — dolt_ignore seeding included: an + // existing database with pending main-sequence migrations must stay + // byte-identical when the operator has not consented (see + // migrate_consent.go). Fresh and already-current databases pass through. + if err := checkMigrateConsent(ctx, db); err != nil { + return 0, err + } + return migrateUpConsented(ctx, db) +} + +// migrateUpConsented is MigrateUp past its consent gate. It exists for the one +// caller whose consent the gate's version test cannot see: an open holding +// fresh-bootstrap heal authority, which proves it created the database it is +// migrating (see MigrateUpWithLock). Every other caller goes through MigrateUp. +func migrateUpConsented(ctx context.Context, db DBConn) (int, error) { // Re-assert the canonical dolt_ignore patterns before anything else, and // in particular before the migrationWorkNeeded short-circuit: a database // whose migration cursors arrived at-latest without executing the seeding @@ -1348,28 +1409,40 @@ func (m migrationSource) bootstrapSQL() string { // hasContentHashColumn reports whether the cursor table already carries the // content_hash column. A not-yet-created table simply reports false. -// -// It probes a single table with SHOW COLUMNS rather than INFORMATION_SCHEMA.COLUMNS, -// whose predicate Dolt does not push down. The LIKE narrows the result set, but -// we still compare the Field name exactly because '_' is a LIKE single-character -// wildcard. func (m migrationSource) hasContentHashColumn(ctx context.Context, db DBConn) (bool, error) { - //nolint:gosec // G201: m.cursorTable is a hardcoded constant; the LIKE literal is fixed. - rows, err := db.QueryContext(ctx, "SHOW COLUMNS FROM "+m.cursorTable+" LIKE 'content_hash'") + return showColumnExists(ctx, db, m.cursorTable, "content_hash") +} + +// showColumnExists reports whether table carries column, probing the ONE table +// with SHOW COLUMNS rather than INFORMATION_SCHEMA.COLUMNS, whose predicate Dolt +// does not push down: on a server hosting ~30 databases the INFORMATION_SCHEMA +// form scanned every database and took 5-6 s per probe (measured 2026-09-17, +// portharbour, dolt 2.3.x), and cursorRealityFloor runs it on EVERY store open — +// a 15-store federated `gc ready` spent ~80 s of its 90 s here. SHOW COLUMNS on +// the same server answers in 0.15 s. +// +// The LIKE narrows the result set, but the Field name is still compared exactly +// because '_' is a LIKE single-character wildcard (the LIKE literal is left +// unescaped on purpose: the exact compare is the guard, and the repair-path +// mocks pin this literal form). A missing table reports false, as the +// INFORMATION_SCHEMA count did. table and column are the hardcoded +// identifiers the migration series names — never user input. +func showColumnExists(ctx context.Context, db DBConn, table, column string) (bool, error) { + //nolint:gosec // G201: table and the LIKE literal are migration-series constants. + rows, err := db.QueryContext(ctx, "SHOW COLUMNS FROM "+table+" LIKE '"+column+"'") if err != nil { - // SHOW COLUMNS errors on a missing table; the old INFORMATION_SCHEMA - // probe returned count 0 instead. Preserve that: an absent cursor table - // has no content_hash column. + // SHOW COLUMNS errors on a missing table; the INFORMATION_SCHEMA probe + // returned count 0 instead. Preserve that: an absent table has no columns. if dberrors.IsTableNotExist(err) { return false, nil } - return false, fmt.Errorf("checking %s.content_hash: %w", m.cursorTable, err) + return false, fmt.Errorf("checking %s.%s: %w", table, column, err) } defer func() { _ = rows.Close() }() cols, err := rows.Columns() if err != nil { - return false, fmt.Errorf("checking %s.content_hash: %w", m.cursorTable, err) + return false, fmt.Errorf("checking %s.%s: %w", table, column, err) } // SHOW COLUMNS returns Field, Type, Null, Key, Default, Extra (and possibly // more on some servers); scan every column into RawBytes and read the first @@ -1381,14 +1454,14 @@ func (m migrationSource) hasContentHashColumn(ctx context.Context, db DBConn) (b } for rows.Next() { if err := rows.Scan(dest...); err != nil { - return false, fmt.Errorf("checking %s.content_hash: %w", m.cursorTable, err) + return false, fmt.Errorf("checking %s.%s: %w", table, column, err) } - if len(cells) > 0 && string(cells[0]) == "content_hash" { + if len(cells) > 0 && string(cells[0]) == column { return true, nil } } if err := rows.Err(); err != nil { - return false, fmt.Errorf("checking %s.content_hash: %w", m.cursorTable, err) + return false, fmt.Errorf("checking %s.%s: %w", table, column, err) } return false, nil } @@ -1474,19 +1547,16 @@ func (m migrationSource) currentVersion(ctx context.Context, db DBConn) (int, er // not-yet-created cursor table poisons the pooled connection: tables // created afterwards on other connections stay invisible to this one for // the rest of its life in the pool (be-bv7x). - var cursorExists int - if err := db.QueryRowContext(ctx, - "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?", - m.cursorTable, - ).Scan(&cursorExists); err != nil { + cursorExists, err := tableInCurrentDatabase(ctx, db, m.cursorTable) + if err != nil { return 0, fmt.Errorf("probing %s existence: %w", m.cursorTable, err) } - if cursorExists == 0 { + if !cursorExists { return 0, nil } var current int - err := db.QueryRowContext(ctx, "SELECT COALESCE(MAX(version), 0) FROM "+m.cursorTable).Scan(¤t) + err = db.QueryRowContext(ctx, "SELECT COALESCE(MAX(version), 0) FROM "+m.cursorTable).Scan(¤t) if err != nil && err != sql.ErrNoRows { if dberrors.IsTableNotExist(err) { return 0, nil @@ -1525,7 +1595,7 @@ func (m migrationSource) currentVersion(ctx context.Context, db DBConn) (int, er // corroborates. limited is false when nothing is missing (believe the cursor as // read); otherwise floor is the highest version still believable — 0 for a // missing sentinel table, and the sentinel's replayFloor for a missing sentinel -// column. +// floored table or sentinel column. // // Clamping rather than erroring is deliberate: the series is written to be // re-runnable against a database that already has some of it. @@ -1537,8 +1607,10 @@ func (m migrationSource) currentVersion(ctx context.Context, db DBConn) (int, er // rather than merely diagnose. // // Sentinel tables are probed first and short-circuit the whole check: they -// floor at 0, so no column probe could lower the answer, and skipping it keeps -// this cheap on the path every store open takes. +// floor at 0, so no floored-table or column probe could lower the answer, and +// skipping it keeps this cheap on the path every store open takes. Floored +// tables are then probed together with columns, each clamping floor to the +// lowest replayFloor of anything found absent. func (m migrationSource) cursorRealityFloor(ctx context.Context, db DBConn) (int, bool, error) { for _, table := range m.sentinelTables { present, err := sentinelTableExists(ctx, db, table) @@ -1550,6 +1622,19 @@ func (m migrationSource) cursorRealityFloor(ctx context.Context, db DBConn) (int } } floor, limited := 0, false + for _, st := range m.sentinelFlooredTables { + present, err := sentinelTableExists(ctx, db, st.table) + if err != nil { + return 0, false, fmt.Errorf("checking %s sentinel floored table %s: %w", m.cursorTable, st.table, err) + } + if present { + continue + } + if !limited || st.replayFloor < floor { + floor = st.replayFloor + } + limited = true + } for _, column := range m.sentinelColumns { present, err := sentinelColumnExists(ctx, db, column.table, column.column) if err != nil { @@ -1568,19 +1653,114 @@ func (m migrationSource) cursorRealityFloor(ctx context.Context, db DBConn) (int // sentinelTableExists is a function variable for the same reason // issueRowCounter is: it lets the cursor-reality tests exercise the real -// decision without a live database. -var sentinelTableExists = func(ctx context.Context, db DBConn, table string) (bool, error) { - var n int - if err := db.QueryRowContext(ctx, - `SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES - WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`, - table).Scan(&n); err != nil { - return false, err +// decision without a live database. It runs on EVERY store open +// (cursorRealityFloor: the sentinel and floored-sentinel tables, and the +// column sentinel's carrier), so it takes the SHOW TABLES prober for the +// reason sentinelColumnExists takes SHOW COLUMNS. +var sentinelTableExists = showTableExists + +// showTableExists reports whether the session's current database holds table, +// probing with SHOW TABLES rather than INFORMATION_SCHEMA.TABLES. Dolt does not +// push the TABLES predicate down any more than the COLUMNS one: the probe walks +// the catalog of every database on the server. On a sql-server hosting 28 +// databases the INFORMATION_SCHEMA read costs 25-30 ms against 0.6 ms for the +// listing (dolt 2.1.8), and the open path asks a dozen times per bd write. +// +// It reads the unfiltered listing and compares names case-insensitively, which +// is what the INFORMATION_SCHEMA count it replaced answers: Dolt resolves and +// counts table names case-insensitively, but its SHOW TABLES LIKE filter +// matches case-sensitively, so a filtered probe would read a table stored as +// BD_EVENTS_SEQ as absent. The comparison is otherwise exact; without a LIKE +// pattern, '_' wildcards cannot match a lookalike either. +// +// Unlike the INFORMATION_SCHEMA count, SHOW TABLES errors when no database is +// selected or the selected one was dropped, so it is only for callers already +// on the target database: the cursor-existence probe in currentVersion, which +// must succeed on any session (be-bv7x), gates it with tableInCurrentDatabase. +// table is a migration-series constant, never user input. +func showTableExists(ctx context.Context, db DBConn, table string) (bool, error) { + rows, err := db.QueryContext(ctx, "SHOW TABLES") + if err != nil { + return false, fmt.Errorf("checking table %s: %w", table, err) } - return n > 0, nil + defer func() { _ = rows.Close() }() + + cols, err := rows.Columns() + if err != nil { + return false, fmt.Errorf("checking table %s: %w", table, err) + } + // SHOW TABLES returns Tables_in_ (plus Table_type on SHOW FULL TABLES + // and on some servers); the first column is the table name. + cells := make([]sql.RawBytes, len(cols)) + dest := make([]any, len(cols)) + for i := range cells { + dest[i] = &cells[i] + } + for rows.Next() { + if err := rows.Scan(dest...); err != nil { + return false, fmt.Errorf("checking table %s: %w", table, err) + } + if len(cells) > 0 && strings.EqualFold(string(cells[0]), table) { + return true, nil + } + } + if err := rows.Err(); err != nil { + return false, fmt.Errorf("checking table %s: %w", table, err) + } + return false, nil } -var sentinelColumnExists = schemaColumnExists +// tableInCurrentDatabase is showTableExists for a session that may have no +// usable database: the cursor-existence probe runs on any session, so it must +// never issue a statement that can fail (be-bv7x). SHOW TABLES fails with no +// database selected (1105) and on a session whose database was dropped under +// it (1049); the schemata read answers 0 in both cases instead, which reads +// the table as absent, exactly as the INFORMATION_SCHEMA.TABLES count with +// TABLE_SCHEMA = DATABASE() did. Both reads are one round trip each. +// +// The guard is check-then-act, not atomic: a DROP DATABASE landing between the +// two reads still fails the SHOW TABLES and pins the session. On a *sql.DB the +// two reads may also land on different pooled connections, so the guard holds +// only when every connection in the pool is on the same database (a DSN that +// names it). +func tableInCurrentDatabase(ctx context.Context, db DBConn, table string) (bool, error) { + var usable int + if err := db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = DATABASE()", + ).Scan(&usable); err != nil { + return false, err + } + if usable == 0 { + return false, nil + } + return showTableExists(ctx, db, table) +} + +// sentinelColumnExists runs on EVERY store open (cursorRealityFloor), so it +// takes the SHOW COLUMNS prober rather than schemaColumnExists's +// INFORMATION_SCHEMA form: 0.15 s against 5-6 s per probe on a Dolt server +// hosting ~30 databases (measured 2026-09-17). The repair paths keep +// schemaColumnExists as is — they run once per migration, not per open. +// +// SHOW COLUMNS fails on a missing table, and the carrier table is exactly what +// a release-lineage store lacks (no leases before ignored/0012). A failing +// statement is not free here: on the store's multiStatements DSN it pins the +// pooled Dolt session to its pre-statement catalog, so a table another +// connection creates afterwards stays "not found" on it (be-bv7x; reproduced +// on dolt 2.1.8 and 2.2.0). So the carrier's existence is read first through +// sentinelTableExists, whose read succeeds whether or not the table is there, +// and SHOW COLUMNS is only sent to a table that is. A missing table reads as a +// missing column, as the INFORMATION_SCHEMA count did. +var sentinelColumnExists = func(ctx context.Context, db DBConn, table, column string) (bool, error) { + present, err := sentinelTableExists(ctx, db, table) + if err != nil { + return false, fmt.Errorf("probing %s: %w", table, err) + } + if !present { + return false, nil + } + return showColumnExists(ctx, db, table, column) +} func (m migrationSource) pendingVersions(ctx context.Context, db DBConn) ([]int, error) { current, err := m.currentVersion(ctx, db) @@ -1823,6 +2003,11 @@ func scanRowByColumn(rows *sql.Rows) (CallRow, error) { // connection. Bodies that invoke a stored procedure (today 0040 and 0041, both // CALL DOLT_COMMIT) are routed through DrainCall so their result sets are // consumed; all other migrations keep the unchanged ExecContext path. +// +// sqlText is always a compile-time embedded migration body (go:embed above; +// frozen once merged per scripts/check-migration-hygiene.sh) — never runtime +// or user input. Executing it verbatim is the migration contract, so SAST +// "SQL injection" findings on this call are accepted by design. func execMigrationBody(ctx context.Context, db DBConn, sqlText string) error { if !procedureCallRe.MatchString(sqlText) { _, err := db.ExecContext(ctx, sqlText) diff --git a/internal/storage/schema/schema_test.go b/internal/storage/schema/schema_test.go index 2b10e591a..b63c0b553 100644 --- a/internal/storage/schema/schema_test.go +++ b/internal/storage/schema/schema_test.go @@ -1971,6 +1971,12 @@ func TestAllMigrationsSQLUsesDirectDDLForKnownCLIIncompatibilities(t *testing.T) // removed_at to DATETIME(6)), same shape as 0068's step 7. "ALTER TABLE issue_versions MODIFY COLUMN change_at DATETIME(6) NOT NULL;", "ALTER TABLE issue_versions MODIFY COLUMN removed_at DATETIME(6);", + // 0070: two-plane prepared ADD COLUMN, same shape as 0067. + "ALTER TABLE issues ADD COLUMN participation_generation BIGINT NULL;", + "ALTER TABLE wisps ADD COLUMN participation_generation BIGINT NULL;", + // 0071: single-plane prepared ADD COLUMN, same shape as 0068's + // attribution_status (no wisps twin -- issue_versions has none). + "ALTER TABLE issue_versions ADD COLUMN removed_restriction VARCHAR(30);", } { if !strings.Contains(got, want) { t.Fatalf("AllMigrationsSQL missing direct CLI DDL %q", want) @@ -2004,6 +2010,12 @@ func TestAllMigrationsSQLUsesDirectDDLForKnownCLIIncompatibilities(t *testing.T) // 0069 guards both of its MODIFYs the same way. "@issue_versions_change_at_needs_widen", "@issue_versions_removed_at_needs_widen", + // 0070 guards both planes' ALTERs the same way, mirroring 0067's pair. + "@issues_pg_needs_add", + "@wisps_pg_needs_add", + // 0071 guards its ALTER the same way; only its source text carries + // this probe. + "@issue_versions_rr_needs_add", } { if strings.Contains(got, forbidden) { t.Fatalf("AllMigrationsSQL contains source prepared-DDL guard %q", forbidden) @@ -2626,3 +2638,94 @@ DROP TABLE IF EXISTS wisps; requireDoltCount(t, dir, `SELECT COUNT(*) AS c FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'wisps'`, "0") } + +// TestShowTableExistsMatchesInformationSchemaOnDolt proves the per-open table +// probe (the unfiltered SHOW TABLES listing, names compared case-insensitively) +// agrees with the INFORMATION_SCHEMA.TABLES count it replaced, on a real Dolt. +// It covers every table the open path probes — both cursor tables, the +// sentinel and floored-sentinel tables, the column sentinel's carrier and the +// untrack scratch table — under bd's own dolt_ignore patterns, so all but +// schema_migrations live only in the working set. It also covers a name whose +// '_' LIKE-matches a different table, and a table stored in another case: Dolt +// resolves and counts table names case-insensitively there, but its SHOW +// TABLES LIKE filter does not. +func TestShowTableExistsMatchesInformationSchemaOnDolt(t *testing.T) { + testutil.RequireDoltBinary(t) + + dir := filepath.Join(t.TempDir(), "show-tables-probe") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("create probe dir: %v", err) + } + runDoltCommand(t, dir, "init", "--name", "test", "--email", "test@example.com") + + infoSchemaHas := func(table string) bool { + rows := queryDoltCSV(t, dir, fmt.Sprintf(` +SELECT COUNT(*) AS cnt +FROM INFORMATION_SCHEMA.TABLES +WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '%s'`, table)) + return len(rows) == 1 && rows[0]["cnt"] == "1" + } + // The same listing and comparison showTableExists makes. + showTablesHas := func(table string) bool { + for _, r := range queryDoltCSV(t, dir, "SHOW TABLES") { + for _, v := range r { + if strings.EqualFold(v, table) { + return true + } + } + } + return false + } + agree := func(state, table string, want bool) { + t.Helper() + if got := showTablesHas(table); got != want { + t.Fatalf("%s: SHOW TABLES reported %s present=%v, want %v", state, table, got, want) + } + if got := infoSchemaHas(table); got != want { + t.Fatalf("%s: INFORMATION_SCHEMA reported %s present=%v, want %v", state, table, got, want) + } + } + + probed := []string{mainSource.cursorTable, ignoredSource.cursorTable, ignoredCursorUntrackTempTable} + probed = append(probed, ignoredSource.sentinelTables...) + for _, st := range ignoredSource.sentinelFlooredTables { + probed = append(probed, st.table) + } + for _, sc := range ignoredSource.sentinelColumns { + probed = append(probed, sc.table) + } + + for _, table := range probed { + agree("empty database", table, false) + } + + for _, pattern := range doltIgnorePatterns { + runDoltSQL(t, dir, fmt.Sprintf("REPLACE INTO dolt_ignore VALUES ('%s', true)", pattern)) + } + for _, gated := range versionGatedDoltIgnorePatterns { + runDoltSQL(t, dir, fmt.Sprintf("REPLACE INTO dolt_ignore VALUES ('%s', true)", gated.pattern)) + } + runDoltSQL(t, dir, "CREATE TABLE "+mainSource.cursorTable+" (version INT PRIMARY KEY)") + runDoltSQL(t, dir, "CALL DOLT_COMMIT('-Am', 'committed cursor')") + for _, table := range probed { + if table == mainSource.cursorTable || table == ignoredCursorUntrackTempTable { + continue + } + runDoltSQL(t, dir, "CREATE TABLE "+table+" (id VARCHAR(64) PRIMARY KEY)") + } + requireDoltNoRows(t, dir, "SELECT table_name FROM dolt_status", "dolt_status after creating only dolt_ignored tables") + for _, table := range probed { + agree("migrated shape, dolt_ignored tables in the working set", table, table != ignoredCursorUntrackTempTable) + } + + // 'schemaxmigrations' LIKE-matches 'schema_migrations'; only the name + // comparison keeps it from reading as the cursor table once that is gone. + runDoltSQL(t, dir, "CREATE TABLE schemaxmigrations (id INT PRIMARY KEY)") + runDoltSQL(t, dir, "DROP TABLE "+mainSource.cursorTable) + agree("LIKE wildcard lookalike", mainSource.cursorTable, false) + + // A table stored in another case is the same table to Dolt. + runDoltSQL(t, dir, "RENAME TABLE bd_events_seq TO bd_events_seq_case") + runDoltSQL(t, dir, "RENAME TABLE bd_events_seq_case TO BD_EVENTS_SEQ") + agree("table stored in another case", "bd_events_seq", true) +} diff --git a/internal/storage/schema/smart_remote_migrate_gate.go b/internal/storage/schema/smart_remote_migrate_gate.go index ab26d88a2..97dc5b121 100644 --- a/internal/storage/schema/smart_remote_migrate_gate.go +++ b/internal/storage/schema/smart_remote_migrate_gate.go @@ -246,11 +246,12 @@ func routeAdoptFastForward(ctx context.Context, db DBConn, ref string, adopt *Fa // (behind == 0) and a purely-ahead clone (behind == 0, ahead >= 1) are still // permitted — they are genuine first-movers with nothing to pull. // -// adopt may be nil, or wire neither callback (the shared unit-of-work -// provider's injection site) — then there is no ancestry fact to read and -// routing stays exactly as it was before this check existed. With only -// IsStrictAncestor wired, the fact narrows to the ahead == 0 shape; the -// diverged shape then reads "not behind", which is the pre-widening +// adopt may be nil, or wire neither callback — then there is no ancestry fact +// to read and routing stays exactly as it was before this check existed. (The +// shared unit-of-work provider's injection site wires AheadBehind only; every +// other callback stays nil there deliberately, so no new auto-write path +// opens.) With only IsStrictAncestor wired, the fact narrows to the ahead == 0 +// shape; the diverged shape then reads "not behind", which is the pre-widening // behavior rather than a new hazard. // // Unlike routeAdoptFastForward, a query error is NOT folded into "false": diff --git a/internal/storage/schema/smart_remote_migrate_gate_test.go b/internal/storage/schema/smart_remote_migrate_gate_test.go index bc3bbc4b7..28093fc1c 100644 --- a/internal/storage/schema/smart_remote_migrate_gate_test.go +++ b/internal/storage/schema/smart_remote_migrate_gate_test.go @@ -1312,6 +1312,63 @@ func TestDataBehindRemedySurfaces(t *testing.T) { t.Error("IsDataBehind() = true on a nil receiver") } }) + + // Proxied-server mode is the one topology where the remedy command is + // correct and unrunnable at the same time: `bd dolt pull` is refused at the + // front door (proxy.dolt_pull.unsupported), as are `bd dolt push`, + // `bd migrate` and `bd conflicts`. Naming it unqualified there hands the + // operator a command their own binary rejects, which is how they end up + // reaching for the one hatch the proxy does NOT refuse. + t.Run("proxied surfaces say where the pull can be run", func(t *testing.T) { + proxied := func(shared bool) *RemoteMigrateGateError { + e := base(shared, false) + e.Proxied = true + return e + } + + for _, shared := range []bool{false, true} { + msg := proxied(shared).UserMessage() + for _, want := range []string{ + "proxied-server mode", "proxy.dolt_pull.unsupported", "server host", + DataBehindRemedyCommand, AllowRemoteMigrateEnv + "=1", + } { + if !strings.Contains(msg, want) { + t.Errorf("shared=%v: proxied body missing %q:\n%s", shared, want, msg) + } + } + d := proxied(shared).AgentDirective() + for _, want := range []string{"proxy.dolt_pull.unsupported", "do NOT attempt it here"} { + if !strings.Contains(d, want) { + t.Errorf("shared=%v: proxied AgentDirective missing %q:\n%s", shared, want, d) + } + } + opts := proxied(shared).Options() + if opts[0].ID != "pull-first-on-server-host" { + t.Errorf("shared=%v: pull option id = %q, want the host-qualified id", shared, opts[0].ID) + } + // The command itself is unchanged — it is the right command — so an + // agent that reads only Commands must find the qualification in the + // precondition it is required to check. + if len(opts[0].Commands) != 1 || opts[0].Commands[0] != DataBehindRemedyCommand { + t.Errorf("shared=%v: pull option commands = %v, want [%q]", shared, opts[0].Commands, DataBehindRemedyCommand) + } + if !strings.Contains(opts[0].When, "proxy.dolt_pull.unsupported") { + t.Errorf("shared=%v: pull option precondition must name the refusal:\n%s", shared, opts[0].When) + } + } + + // Nothing above may leak into the ordinary embedded/server-mode stop, + // whose remedy IS runnable where it is printed. + direct := base(true, false).UserMessage() + for _, forbidden := range []string{"proxied-server mode", "server host"} { + if strings.Contains(direct, forbidden) { + t.Errorf("non-proxied body gained %q:\n%s", forbidden, direct) + } + } + if base(true, false).Options()[0].ID != "pull-first" { + t.Error("non-proxied pull option id changed") + } + }) } // TestSmartGateEnabled pins the default-on contract: unset and unparseable diff --git a/internal/storage/sqlbuild/BUILD.bazel b/internal/storage/sqlbuild/BUILD.bazel index fbbbe7d4b..7ff089896 100644 --- a/internal/storage/sqlbuild/BUILD.bazel +++ b/internal/storage/sqlbuild/BUILD.bazel @@ -52,3 +52,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/storage/sqlbuild/filter.go b/internal/storage/sqlbuild/filter.go index 777f1fa9f..0fd9b0acf 100644 --- a/internal/storage/sqlbuild/filter.go +++ b/internal/storage/sqlbuild/filter.go @@ -296,19 +296,26 @@ func BuildIssueFilterClauses(query string, filter types.IssueFilter, tables Filt {"due_at", "<", filter.DueBefore}, } { if tc.v != nil { + // The UTC spelling of the instant, at whole seconds. The columns + // hold UTC wall clock; an engine whose column carries no zone + // (a SQL `timestamp` WITHOUT time zone) drops a literal's offset, + // so a bound spelled `+02:00` would compare as that wall clock. + // Spelled in UTC, every engine compares the instant. Dolt already + // honors the offset, so this changes nothing there. whereClauses = append(whereClauses, fmt.Sprintf("%s %s ?", tc.col, tc.op)) - args = append(args, tc.v.Format(time.RFC3339)) + args = append(args, tc.v.UTC().Format(time.RFC3339)) } } if filter.AfterCreatedAt != nil { - // Bind the cursor time as time.Time, not a formatted string: the issues/ - // wisps created_at columns are DATETIME (NUMERIC affinity), so an RFC3339 - // string parameter mis-compares on the SQLite backend, while a time.Time - // value compares correctly on every backend — the same binding EventsSince - // uses. It is bound twice under either order (the sargable upper bound - // and the strict bound), followed by the id tie-break. - ac := *filter.AfterCreatedAt + // Bind the cursor time as time.Time, not a formatted string — the same + // binding EventsSince uses — but in UTC. A driver can send a time.Time + // as its wall clock with no zone (embedded Dolt's does), and the + // columns hold UTC wall clock, so a cursor in another zone would page + // from the wrong position there. It is bound twice under either order + // (the sargable upper bound and the strict bound), followed by the id + // tie-break. + ac := filter.AfterCreatedAt.UTC() // AfterCreatedAt alone decides that a position was supplied; AfterPriority // decides which ORDER it is a position in. The two predicates are // ALTERNATIVES, never conjuncts: ANDing them would keep the created diff --git a/internal/storage/sqlbuild/filter_test.go b/internal/storage/sqlbuild/filter_test.go index 28db63ed0..08f3b2775 100644 --- a/internal/storage/sqlbuild/filter_test.go +++ b/internal/storage/sqlbuild/filter_test.go @@ -1,6 +1,11 @@ package sqlbuild -import "testing" +import ( + "testing" + "time" + + "github.com/steveyegge/beads/internal/types" +) // TestGlobToLikePattern exercises globToLikePattern directly against the // package that actually calls it from BuildIssueFilterClauses (be-ucslk4). @@ -35,3 +40,76 @@ func TestGlobToLikePattern(t *testing.T) { }) } } + +// TestTimeBoundsBindTheUTCInstant pins that every time bound is bound as the +// UTC spelling of its instant, truncated to whole seconds. The columns hold +// UTC wall clock, and an engine whose column carries no zone (a SQL +// `timestamp` WITHOUT time zone) reads a literal's wall clock and drops its +// offset, so a bound spelled `T+02:00` would compare two hours late there. +// Binding the UTC spelling makes an offset bound select exactly what its Z +// twin does on every engine (Dolt already honors the offset; the UTC spelling +// of the same instant is the same comparison there). +func TestTimeBoundsBindTheUTCInstant(t *testing.T) { + t.Parallel() + plus2 := time.FixedZone("UTC+2", 2*60*60) + at := time.Date(2026, 10, 17, 12, 0, 0, 900_000_000, plus2) // 10:00:00.9Z + const want = "2026-10-17T10:00:00Z" + bound := func(f *types.IssueFilter) { + f.CreatedAfter, f.CreatedBefore = &at, &at + f.UpdatedAfter, f.UpdatedBefore = &at, &at + f.ClosedAfter, f.ClosedBefore = &at, &at + f.StartedAfter, f.StartedBefore = &at, &at + f.DeferAfter, f.DeferBefore = &at, &at + f.DueAfter, f.DueBefore = &at, &at + } + var filter types.IssueFilter + bound(&filter) + _, args, err := BuildIssueFilterClauses("", filter, IssuesFilterTables) + if err != nil { + t.Fatalf("BuildIssueFilterClauses: %v", err) + } + if len(args) != 12 { + t.Fatalf("args = %v, want the 12 time bounds", args) + } + for i, arg := range args { + if arg != want { + t.Errorf("arg %d = %v, want %q (the bound's UTC instant at whole seconds)", i, arg, want) + } + } +} + +// TestKeysetCursorBindsTheUTCInstant pins that the keyset cursor is bound as +// its instant in UTC, still as a time.Time. A driver can send a time.Time as +// its wall clock with no zone (embedded Dolt's does), and the columns hold UTC +// wall clock, so a cursor in another zone would page from the wrong position +// there. Both orders bind the cursor twice. +func TestKeysetCursorBindsTheUTCInstant(t *testing.T) { + t.Parallel() + plus2 := time.FixedZone("UTC+2", 2*60*60) + cur := time.Date(2026, 10, 17, 12, 0, 0, 0, plus2) + want := time.Date(2026, 10, 17, 10, 0, 0, 0, time.UTC) + p := 2 + for _, tc := range []struct { + name string + filter types.IssueFilter + nargs int + at []int // the cursor's positions in the bound args + }{ + {"created order", types.IssueFilter{AfterCreatedAt: &cur, AfterID: "bd-42"}, 3, []int{0, 1}}, + {"priority order", types.IssueFilter{AfterPriority: &p, AfterCreatedAt: &cur, AfterID: "bd-42"}, 5, []int{2, 3}}, + } { + _, args, err := BuildIssueFilterClauses("", tc.filter, IssuesFilterTables) + if err != nil { + t.Fatalf("%s: BuildIssueFilterClauses: %v", tc.name, err) + } + if len(args) != tc.nargs { + t.Fatalf("%s: args = %v, want %d", tc.name, args, tc.nargs) + } + for _, i := range tc.at { + got, ok := args[i].(time.Time) + if !ok || !got.Equal(want) || got.Location() != time.UTC { + t.Errorf("%s: arg %d = %v (%T), want the time.Time %v", tc.name, i, args[i], args[i], want) + } + } + } +} diff --git a/internal/storage/sqlclass/BUILD.bazel b/internal/storage/sqlclass/BUILD.bazel index db106a867..3682f5ad7 100644 --- a/internal/storage/sqlclass/BUILD.bazel +++ b/internal/storage/sqlclass/BUILD.bazel @@ -26,3 +26,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/storage/sqlcount/BUILD.bazel b/internal/storage/sqlcount/BUILD.bazel index 66d03210a..3abb00ede 100644 --- a/internal/storage/sqlcount/BUILD.bazel +++ b/internal/storage/sqlcount/BUILD.bazel @@ -19,3 +19,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/storage/storage.go b/internal/storage/storage.go index 0a934f2e3..1ea0d8d86 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -44,6 +44,10 @@ var ( // guarded close. See issueops.CloseOpenChildrenError. type CloseOpenChildrenError = issueops.CloseOpenChildrenError +// VersionMismatchError reports the expected and current row versions that +// refused a guarded write. See issueops.VersionMismatchError. +type VersionMismatchError = issueops.VersionMismatchError + // ErrNotOwner is returned when an actor tries to unclaim an issue that is claimed // by a different actor. Releasing another actor's claim requires the force // escape hatch (bd unclaim --force), reserved for admin/reaper use. @@ -282,6 +286,12 @@ type Storage interface { // EdgeReader (that one answers with the stored ROWS, outbound only). Reads // fire no hooks, as for IssueReader. GraphCounter() (issueops.GraphCounter, error) + // BatchGetter returns the guarded batch-read surface for this store: many + // issues by id, hydrated, in ONE snapshot. Its own role rather than a mode + // of IssueReader because a miss here is a RESULT FIELD (Missing) and not + // ErrNotFound — a batch GET is a set read, not a precondition on every + // member succeeding. Reads fire no hooks, as for IssueReader. + BatchGetter() (issueops.BatchGetter, error) // ReadyCounter returns the guarded ready-count surface for this store: the // size of the ready set, which is the number `bd ready`'s pagination // publishes and which no other role answers. Counter's predicate is a @@ -368,6 +378,41 @@ type Storage interface { // assignee and status, which is on_update — the same event the journal // already records for it. See hook_releaser.go. Releaser() (issueops.Releaser, error) + // LeaseReclaimer returns the lease-sweep surface for this store: revert + // every lease that has been held past its deadline back to its + // pre-claim state, for a caller that is a clock rather than a human or a + // request. + // + // It is a WRITE role and its hook decorator WRAPS: a reclaim changes + // assignee and status per reverted row, which is on_update, the same + // event Releaser fires. See hook_lease_reclaimer.go. + LeaseReclaimer() (issueops.LeaseReclaimer, error) + // Heartbeater returns the lease-refresh surface for this store: push the + // lease the caller holds on one issue forward by the store's TTL. + // + // It is a WRITE role and its hook decorator WRAPS: a refresh writes only + // the ephemeral lease row and fires nothing, but a re-arm (a live claim + // with no lease row, HeartbeatResult.Rearmed) is recorded as a mutation + // and fires on_update once. That is why RoleFiresHooks answers true for + // it, and a server must take it off a peeled store. See + // hook_heartbeater.go. + Heartbeater() (issueops.Heartbeater, error) + // BlockedLister returns the blocked-listing surface for this store: what + // `bd blocked` prints. It is a READ role and its hook decorator passes it + // through (hook_blocked_lister.go); the external-dependency decorator + // overrides it so the listing names unsatisfied external blockers, as its + // GetBlockedIssues does. + BlockedLister() (issueops.BlockedLister, error) + + // MoleculeStepper returns the advance-a-molecule surface for this store: + // find a molecule's next ready step after one closed and, on request, + // claim it — the operation behind `bd close --continue`. Every local + // backend answers issueops.NewMoleculeStepper composed over its own + // roles; a remote backend serves it over its wire. + // + // It is a WRITE role and its hook decorator WRAPS: a claimed step fires + // on_update, as every claim does. + MoleculeStepper() (issueops.MoleculeStepper, error) // Issue CRUD CreateIssue(ctx context.Context, issue *types.Issue, actor string) error @@ -388,6 +433,9 @@ type Storage interface { // when the current assignee differs. UnclaimIssueIfAssignee(ctx context.Context, id string, actor string, expectedAssignee string) error UpdateIssueType(ctx context.Context, id string, issueType string, actor string) error + // CloseIssue is the raw close: it applies neither the close guards nor + // close policy, except over HTTP, where it closes with force and a template + // — the one guard force never bypasses — still refuses. CloseIssue(ctx context.Context, id string, reason string, actor string, session string) error // CloseIssueChecked closes an issue, but refuses with ErrCloseOpenChildren // when it has open parent-child dependents, or ErrCloseBlocked when it has a @@ -399,9 +447,16 @@ type Storage interface { // (no TOCTOU). When opts.ExpectedVersion is non-nil it adds an orthogonal // optimistic-concurrency precondition: the close proceeds only if the issue's // current RowVersion still equals *opts.ExpectedVersion, else it refuses with - // ErrVersionMismatch atomically (Force does NOT bypass this check). Already- - // closed is an idempotent success with Unchanged=true; a missing issue returns - // ErrNotFound. + // ErrVersionMismatch atomically (Force does NOT bypass this check). After + // the version check and before the child and blocker policy it applies the + // close guards in the same transaction: a template refuses with + // *issueops.TemplateReadOnlyError whatever Force says, and unless Force is + // set a pinned issue refuses with *issueops.PinnedError and one assigned to + // someone other than actor with *issueops.CloseNotAssigneeError. Already- + // closed is an idempotent success with Unchanged=true and skips the guards; + // a missing issue returns ErrNotFound. CloseIssue above is the raw close and + // applies neither the guards nor the policy, except that over HTTP, where + // the template guard has no bypass on the wire, a template still refuses. CloseIssueChecked(ctx context.Context, id string, actor string, opts CloseIssueOptions) (CloseIssueResult, error) DeleteIssue(ctx context.Context, id string) error SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) @@ -628,7 +683,7 @@ type Storage interface { type CloseIssueOptions struct { Reason string Session string - Force bool // bypass the is_blocked guard (mirrors `bd close --force`) + Force bool // bypass close policy and the pin and assignee guards, never the template (mirrors `bd close --force`) // ExpectedVersion, when non-nil, gates the close on an optimistic-concurrency // check: the close proceeds only if the issue's current RowVersion (the // row_lock token) equals *ExpectedVersion, otherwise it refuses with @@ -993,6 +1048,171 @@ type ExternalDependencyQueryStore interface { GetExternalBlockingDependencyRecords(ctx context.Context) (map[string][]*types.Dependency, error) } +// BlockersBatchStore is IsBlocked for many ids in a bounded number of reads. +// The answer holds exactly the ids IsBlocked reports blocked, each mapped to +// the blocker list IsBlocked returns for it (nil when it has none); an id +// IsBlocked reports unblocked, or that names no row, is absent. Decorators +// that annotate a page of ids (the external-dependency policy's +// BlockingAnnotator) use it instead of one IsBlocked per id, and fall back to +// that loop on a store without it. It answers for the raw store alone, with no +// external-dependency policy applied (no `external:` blocker is ever in it), so +// it is meant to be called from inside that policy's decorator, not probed +// through UnwrapStore by a caller holding the decorated store. +type BlockersBatchStore interface { + IsBlockedWithBlockersBatch(ctx context.Context, ids []string) (map[string][]string, error) +} + +// RemoteBackendStore is implemented by a DoltStorage that is a pure network +// client of a remote bd serve process (a registered backend whose +// backends.Backend.Remote is true — see internal/storage/backends). It is +// metadata about the store's transport, not a policy decision. Such a store +// serves its ROLES natively and only a slice of the legacy DoltStorage +// method seam, so a decorator that builds role views must compose over the +// inner store's roles rather than rebuild them from that seam: the +// external-deps decorator consults it for exactly that (remote_roles.go). +// It never decides whether a policy runs — the decorator asks +// ExternalDependencyPolicyProber whether to skip its client-side enforcement. +type RemoteBackendStore interface { + IsRemoteBackendStore() bool +} + +// CallerAttributionLimitedStore is implemented by a DoltStorage whose write +// transport cannot carry two caller-authored attribution members: +// +// - a history entry's Provenance label (UpdateRequest.Provenance, +// ReopenRequest.Provenance), because the serving process labels the +// entries it writes itself; +// - a patch's ClosedBySession, which only the close operation carries. +// +// Its role implementations refuse those members rather than drop them, since a +// library caller may mean them. A front door that knows its own value is +// derivable or advisory — `bd reopen`'s fixed "bd: reopen " label, the +// ambient CLAUDE_SESSION_ID on `bd update -s closed` — omits it for such a +// store instead of failing the write; cmd/bd/remote_backend.go records +// which members it omits and why. +type CallerAttributionLimitedStore interface { + CallerAttributionLimited() bool +} + +// Pinger is implemented by a DoltStorage whose cheapest honest liveness check +// is not an issue query. `bd ping` uses it when present and falls back to a +// one-row SearchIssues otherwise. A remote store implements it with its +// authenticated handshake read, which reaches the serving process and checks +// the credential and the workspace pin without touching an issue table its +// legacy method seam may not serve at all. +type Pinger interface { + Ping(ctx context.Context) error +} + +// ExternalDependencyPolicyProber is implemented by a DoltStorage that can +// answer whether the remote server it talks to already enforces bd's +// external-dependency policy itself (design 3.6, "External-dependency server +// policy": upstream's storage.ServerEnforcedPolicy / PolicyEnforcedByServer). +// The external-deps decorator consults this — never RemoteBackendStore, which +// only shapes how it composes its roles — before skipping its own client-side +// enforcement: a remote store whose +// server advertises the capability (httpapi's policy.external_dependencies) +// has already enforced the policy before answering, so a second client-side +// pass would be redundant. A store that does not implement this interface, or +// that implements it and reports false — including a remote store whose +// server is silent on the capability — gets the ordinary client-side +// enforcement. The policy is never silently skipped merely because the store +// is remote. +type ExternalDependencyPolicyProber interface { + ServerEnforcesExternalDependencyPolicy(ctx context.Context) (bool, error) +} + +type livePolicyProbeKey struct{} + +// WithLivePolicyProbe marks ctx as carrying a claim or a close: an +// ExternalDependencyPolicyProber asked under it must answer from the server, +// never from a cache another process wrote. A read can tolerate a cached +// answer for its TTL; a write guard cannot, since a stale "the server +// enforces it" would skip the client-side refusal of externally blocked work. +func WithLivePolicyProbe(ctx context.Context) context.Context { + return context.WithValue(ctx, livePolicyProbeKey{}, true) +} + +// LivePolicyProbe reports whether ctx was marked by WithLivePolicyProbe. +func LivePolicyProbe(ctx context.Context) bool { + live, _ := ctx.Value(livePolicyProbeKey{}).(bool) + return live +} + +// MoleculeAutoCloseProber is implemented by a DoltStorage whose closes may not +// accept issueops.CloseRequest.AutoCloseMolecule — today exactly +// httpclient.Store, whose server advertises it with +// issues.close.autoCloseMolecule. Every local backend runs the auto-close in +// the close's own transaction and does not implement this. +// +// A server that does not advertise it (an older bd serve, or a server whose +// orchestrator owns the molecule lifecycle, as gc does) is answered false, and +// the caller closes WITHOUT the flag: asking for it there is refused before +// dialing, and the molecule's auto-close is that server's to run. +type MoleculeAutoCloseProber interface { + ServesMoleculeAutoClose(ctx context.Context) (bool, error) +} + +// ServesMoleculeAutoClose reports whether closes through s may set +// issueops.CloseRequest.AutoCloseMolecule (MoleculeAutoCloseProber, looked up +// through every decorator). A store that does not implement the prober runs +// the auto-close itself and is answered true. A probe that fails is answered +// true as well: the close dials the same handshake and reports its failure, +// so nothing is hidden by asking for the auto-close. +func ServesMoleculeAutoClose(ctx context.Context, s DoltStorage) bool { + prober, ok := UnwrapStore(s).(MoleculeAutoCloseProber) + if !ok { + return true + } + served, err := prober.ServesMoleculeAutoClose(ctx) + return err != nil || served +} + +// MoleculeAdvanceProber is implemented by a DoltStorage whose MoleculeStepper +// may not be served — today exactly httpclient.Store, whose server advertises +// it with issues.advanceMolecule. Every local backend composes the stepper +// over its own roles and does not implement this. +type MoleculeAdvanceProber interface { + ServesMoleculeAdvance(ctx context.Context) (bool, error) +} + +// ServesMoleculeAdvance reports whether s's MoleculeStepper can run +// (MoleculeAdvanceProber, looked up through every decorator). A store that +// does not implement the prober runs the advance itself and is answered true. +// A probe that fails returns its error. +// +// `bd close --continue` asks BEFORE it closes: the advance is a second +// operation after the close commits, so refusing it only then would leave +// the step closed and the next step unclaimed. That is also why a failed +// probe is not answered true, as ServesMoleculeAutoClose answers it: the +// close would commit and only the advance, dialing the same handshake, would +// fail — the half-done state the question exists to avoid. +func ServesMoleculeAdvance(ctx context.Context, s DoltStorage) (bool, error) { + prober, ok := UnwrapStore(s).(MoleculeAdvanceProber) + if !ok { + return true, nil + } + return prober.ServesMoleculeAdvance(ctx) +} + +// ExcludeIDsUnsupportedStore is implemented by a DoltStorage whose ready-work +// reads cannot express types.WorkFilter.ExcludeIDs over their own transport. +// Today that is exactly httpclient.Store: the v0 wire's listReadyWork and +// countReadyWork operations publish no id-exclusion parameter, so the http +// bridge refuses rather than silently widening the result set whenever a +// filter carries any (design 3.6 / L12, "every field it cannot express +// refuses"). +// +// The external-deps decorator consults this before deciding how to apply its +// OWN additional exclusions (issues blocked by an unsatisfied +// external:: dependency): a store that answers true here +// gets those exclusions applied client-side in Go instead of folded into the +// filter handed down, so the policy still runs — design 3.6 says it is never +// silently skipped — without tripping the wire's own refusal. +type ExcludeIDsUnsupportedStore interface { + ExcludeIDsUnsupported() bool +} + // Transaction provides atomic multi-operation support within a single database transaction. // // The Transaction interface exposes a subset of storage methods that execute within diff --git a/internal/storage/storagecontract/BUILD.bazel b/internal/storage/storagecontract/BUILD.bazel index dab3ad5b1..b8e628c32 100644 --- a/internal/storage/storagecontract/BUILD.bazel +++ b/internal/storage/storagecontract/BUILD.bazel @@ -20,3 +20,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/storage/unsupportedgen/BUILD.bazel b/internal/storage/unsupportedgen/BUILD.bazel new file mode 100644 index 000000000..0a9b6c0d5 --- /dev/null +++ b/internal/storage/unsupportedgen/BUILD.bazel @@ -0,0 +1,96 @@ +load("@rules_go//go:def.bzl", "go_binary", "go_library", "go_test") + +go_library( + name = "unsupportedgen_lib", + srcs = ["main.go"], + importpath = "github.com/steveyegge/beads/internal/storage/unsupportedgen", + visibility = ["//visibility:private"], + deps = ["//internal/storage"], +) + +go_binary( + name = "unsupportedgen", + embed = [":unsupportedgen_lib"], + visibility = ["//:__subpackages__"], +) + +go_test( + name = "unsupportedgen_test", + srcs = ["main_test.go"], + data = ["//internal/httpclient:go_srcs"], + embed = [":unsupportedgen_lib"], +) + +# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + ), + visibility = ["//:__subpackages__"], +) + +# --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/storage/unsupportedgen/main.go b/internal/storage/unsupportedgen/main.go new file mode 100644 index 000000000..6f2f899c6 --- /dev/null +++ b/internal/storage/unsupportedgen/main.go @@ -0,0 +1,382 @@ +// Command unsupportedgen regenerates the typed-unsupported shell a client +// package embeds to satisfy a storage capability interface it only partially +// implements by hand. +// +// It does NOT take a hand-maintained -skip list. The whole point of this tool +// is to make the "which methods does the shell need to cover" question +// self-answering: it parses the target package's own .go sources (every file +// except _test.go files and the file it is about to overwrite) for methods +// already declared on the given -receiver, and generates a stub for every +// OTHER method of -type storage interface is not already covered. A +// hand-written method and a generated stub can therefore never collide on the +// same selector — there is nothing to keep in sync by hand, and nothing to +// drift. +// +// Written from scratch for the S3 native-program reconciliation: this is NOT +// a port of bd-enterprise's generator (which this client's lift did not carry +// over) — only the shape of the file it must reproduce (unsupported_gen.go, +// lifted with bd-enterprise's generator before this tool existed) was read to +// match its style. +// +// Usage (see internal/httpclient/unsupported.go's //go:generate line): +// +// go run ../../storage/unsupportedgen -type DoltStorage -pkg httpclient -receiver Store -out unsupported_gen.go +package main + +import ( + "bytes" + "flag" + "fmt" + "go/ast" + "go/format" + "go/parser" + "go/token" + "log" + "os" + "path/filepath" + "reflect" + "regexp" + "sort" + "strings" + + "github.com/steveyegge/beads/internal/storage" +) + +// registry maps a -type flag value to the reflected interface it names. Adding +// a type this tool can generate a shell for is one line here; there is no +// string-based reflection trick that gets around naming it, because Go cannot +// look up a type by its source name at runtime. +var registry = map[string]reflect.Type{ + "DoltStorage": reflect.TypeOf((*storage.DoltStorage)(nil)).Elem(), +} + +func main() { + typeName := flag.String("type", "", "name of the interface to shell, from the registry in this file (e.g. DoltStorage)") + pkgName := flag.String("pkg", "", "package clause for the generated file") + receiver := flag.String("receiver", "", "base receiver type name (without *) whose existing methods this tool must not shadow") + scanDir := flag.String("scandir", ".", "directory holding the hand-written sources to scan for existing methods") + out := flag.String("out", "", "output file path, relative to scandir") + extraSkip := flag.String("skip", "", "comma-separated extra method names to exclude, beyond what the scan finds (rarely needed)") + flag.Parse() + + if *typeName == "" || *pkgName == "" || *receiver == "" || *out == "" { + log.Fatal("unsupportedgen: -type, -pkg, -receiver and -out are all required") + } + ifaceType, ok := registry[*typeName] + if !ok { + log.Fatalf("unsupportedgen: %q is not in this tool's registry (add it in main.go)", *typeName) + } + + outPath := filepath.Join(*scanDir, *out) + handWritten, err := scanHandWrittenMethods(*scanDir, *receiver, outPath) + if err != nil { + log.Fatalf("unsupportedgen: scanning %s: %v", *scanDir, err) + } + for _, name := range strings.Split(*extraSkip, ",") { + if name = strings.TrimSpace(name); name != "" { + handWritten[name] = true + } + } + + src, skipped, err := generate(*pkgName, *typeName, ifaceType, handWritten) + if err != nil { + log.Fatalf("unsupportedgen: %v", err) + } + if err := os.WriteFile(outPath, src, 0o600); err != nil { + log.Fatalf("unsupportedgen: writing %s: %v", outPath, err) + } + fmt.Fprintf(os.Stderr, "unsupportedgen: wrote %s (%d methods stubbed, %d left to the hand-written set)\n", + outPath, ifaceType.NumMethod()-skipped, skipped) +} + +// scanHandWrittenMethods parses every .go file in dir except _test.go files +// and the generator's own output file, and returns the set of method names +// declared with a receiver of type recv or *recv anywhere in the package. That +// set is exactly the method names this tool must NOT shell: generating a stub +// for one would make its selector ambiguous against the hand-written one. +func scanHandWrittenMethods(dir, recv, outPath string) (map[string]bool, error) { + absOut, err := filepath.Abs(outPath) + if err != nil { + return nil, err + } + found := map[string]bool{} + fset := token.NewFileSet() + entries, err := os.ReadDir(dir) + if err != nil { + return nil, err + } + for _, entry := range entries { + name := entry.Name() + if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + path := filepath.Join(dir, name) + if absPath, err := filepath.Abs(path); err == nil && absPath == absOut { + continue // this is the file we are about to overwrite + } + file, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 { + continue + } + if receiverBaseName(fn.Recv.List[0].Type) == recv { + found[fn.Name.Name] = true + } + } + } + return found, nil +} + +// receiverBaseName strips a leading "*" from a receiver type expression and +// returns its identifier, e.g. "*Store" and "Store" both yield "Store". +func receiverBaseName(expr ast.Expr) string { + if star, ok := expr.(*ast.StarExpr); ok { + expr = star.X + } + if ident, ok := expr.(*ast.Ident); ok { + return ident.Name + } + return "" +} + +// qualifiedLeak matches a package-path-qualified identifier the way a generic +// instantiation's reflect.Type.Name() leaks it, e.g. +// "github.com/steveyegge/beads/internal/types.Issue". It requires at least one +// "/" so it never matches an already-short name like "context.Context" or +// "types.IssueFilter". +var qualifiedLeak = regexp.MustCompile(`[A-Za-z0-9_.\-]+(?:/[A-Za-z0-9_.\-]+)+\.[A-Za-z_][A-Za-z0-9_]*`) + +// importSet collects the packages a generated file's method bodies reference, +// keyed by import path, so the output needs no hand-maintained import block. +type importSet map[string]string // import path -> local alias (last path segment) + +func (s importSet) add(pkgPath string) string { + if pkgPath == "" { + return "" + } + alias := pkgPath + if i := strings.LastIndex(pkgPath, "/"); i >= 0 { + alias = pkgPath[i+1:] + } + s[pkgPath] = alias + return alias +} + +// formatType renders t as the Go syntax a stub's signature can use, collecting +// every package it names into imports as it goes. +// +// A plain reflect.Type.String() is NOT enough on its own: for a generic +// instantiation (this package's one case is storage.Iter[T]), reflect leaks +// the type argument's FULL import path into both String() and Name() rather +// than the short package name every other case gets +// ("storage.Iter[github.com/steveyegge/beads/internal/types.Issue]" instead of +// "storage.Iter[types.Issue]"). This function walks the type structurally so +// composite types are built from already-short recursive calls, and for the +// generic-name case specifically, desanitizes the leaked argument with +// qualifiedLeak before recording its package and splicing it back in. +func formatType(t reflect.Type, imports importSet) string { + // A DEFINED type (Name() != "") with a composite underlying kind — e.g. + // encoding/json.RawMessage, whose Kind() is Slice over its underlying + // []byte — must be named by its declaration, not rebuilt structurally from + // its underlying kind: "[]uint8" is a different type than json.RawMessage + // as far as the compiler's interface-satisfaction check is concerned, even + // though they share a representation. Only an UNNAMED composite (a literal + // "[]string" or "map[string]int" parameter, Name()=="") falls through to + // the structural cases below. + if t.Name() != "" && t.PkgPath() != "" { + return namedType(t, imports) + } + + switch t.Kind() { + case reflect.Ptr: + return "*" + formatType(t.Elem(), imports) + case reflect.Slice: + return "[]" + formatType(t.Elem(), imports) + case reflect.Array: + return fmt.Sprintf("[%d]%s", t.Len(), formatType(t.Elem(), imports)) + case reflect.Map: + return fmt.Sprintf("map[%s]%s", formatType(t.Key(), imports), formatType(t.Elem(), imports)) + case reflect.Chan: + return "chan " + formatType(t.Elem(), imports) + case reflect.Func: + in := make([]string, t.NumIn()) + for i := range in { + if t.IsVariadic() && i == len(in)-1 { + in[i] = "..." + formatType(t.In(i).Elem(), imports) + continue + } + in[i] = formatType(t.In(i), imports) + } + out := make([]string, t.NumOut()) + for i := range out { + out[i] = formatType(t.Out(i), imports) + } + switch len(out) { + case 0: + return fmt.Sprintf("func(%s)", strings.Join(in, ", ")) + case 1: + return fmt.Sprintf("func(%s) %s", strings.Join(in, ", "), out[0]) + default: + return fmt.Sprintf("func(%s) (%s)", strings.Join(in, ", "), strings.Join(out, ", ")) + } + } + + if t.Name() != "" { + return t.Name() // predeclared: string, int, bool, error, ... + } + if t.Kind() == reflect.Interface && t.NumMethod() == 0 { + return "interface{}" + } + // Not expected anywhere in storage.DoltStorage today (no bare func types or + // anonymous structs/interfaces in its method set); fail loudly rather than + // emit something a human has to notice is wrong later. + log.Fatalf("unsupportedgen: unhandled anonymous type %s (kind %s) — formatType needs a case for it", t.String(), t.Kind()) + panic("unreachable") +} + +// reflectAliasCanonical maps a (pkgPath, name) pair that reflect reports for +// a known language-level alias's underlying type back to the alias's own +// declared (pkgPath, name), so unsupportedgen's output is stable across Go +// toolchains that change what an alias's underlying type reflects as. +// +// Go 1.27 made encoding/json.RawMessage an alias of +// encoding/json/jsontext.Value. Aliases have no runtime identity of their +// own — reflect only ever sees the underlying type — but which type counts as +// "underlying" moved: on 1.26 and earlier, reflect.TypeOf(json.RawMessage(nil)) +// reports (encoding/json, RawMessage) directly (RawMessage was a defined +// type, not an alias, at that point); starting in 1.27 it reports the new +// alias target, (encoding/json/jsontext, Value). storage.DoltStorage's +// MergeMetadata signature did not change between toolchains, so the +// generator's output must not either; this table is the fix-up. +// +// Add an entry here (never a one-off special case elsewhere in this file) if +// a future Go stdlib release aliases another type this generator formats. +var reflectAliasCanonical = map[[2]string][2]string{ + {"encoding/json/jsontext", "Value"}: {"encoding/json", "RawMessage"}, +} + +// namedType renders a DEFINED type (t.Name() != "" && t.PkgPath() != "") as +// its package-qualified declaration name, desanitizing a generic +// instantiation's leaked type-argument path the same way formatType's doc +// comment describes, and normalizing a known reflect-visible alias target +// (reflectAliasCanonical) back to the name a human wrote in source. +func namedType(t reflect.Type, imports importSet) string { + pkgPath, name := t.PkgPath(), t.Name() + if canon, ok := reflectAliasCanonical[[2]string{pkgPath, name}]; ok { + pkgPath, name = canon[0], canon[1] + } + if open := strings.IndexByte(name, '['); open >= 0 && strings.HasSuffix(name, "]") { + base := name[:open] + args := qualifiedLeak.ReplaceAllStringFunc(name[open+1:len(name)-1], func(leak string) string { + dot := strings.LastIndex(leak, ".") + return imports.add(leak[:dot]) + leak[dot:] + }) + alias := imports.add(pkgPath) + return fmt.Sprintf("%s.%s[%s]", alias, base, args) + } + alias := imports.add(pkgPath) + return alias + "." + name +} + +type stubMethod struct { + name string + params []string + results []string +} + +// generate produces the full source of the typed-unsupported shell: a stub for +// every method of iface not in handWritten. It returns the number of methods +// it left alone (the hand-written complement) alongside the formatted source. +func generate(pkgName, typeName string, iface reflect.Type, handWritten map[string]bool) ([]byte, int, error) { + imports := importSet{} + var methods []stubMethod + skipped := 0 + for i := 0; i < iface.NumMethod(); i++ { + m := iface.Method(i) + if handWritten[m.Name] { + skipped++ + continue + } + mt := m.Type + sm := stubMethod{name: m.Name} + for p := 0; p < mt.NumIn(); p++ { + sm.params = append(sm.params, formatType(mt.In(p), imports)) + } + for r := 0; r < mt.NumOut(); r++ { + sm.results = append(sm.results, formatType(mt.Out(r), imports)) + } + // errUnsupported only has an error to hand back, so a stub can only + // speak for a method whose last (or only) result is literally an + // error. Every method this tool has ever had to stub satisfies that; + // a future storage.DoltStorage method that does not needs a + // hand-written implementation (which puts it in the scanned, + // hand-written set and this tool never sees it), not a guess here. + if len(sm.results) == 0 || sm.results[len(sm.results)-1] != "error" { + log.Fatalf("unsupportedgen: %s's last result is not error (results: %v) — "+ + "it cannot be shelled by errUnsupported; implement it by hand instead", m.Name, sm.results) + } + methods = append(methods, sm) + } + sort.Slice(methods, func(i, j int) bool { return methods[i].name < methods[j].name }) + + var b bytes.Buffer + fmt.Fprintf(&b, "// Code generated by unsupportedgen (internal/storage/unsupportedgen); DO NOT EDIT.\n") + fmt.Fprintf(&b, "// Regenerate with `go generate ./...` after a storage.%s interface change.\n\n", typeName) + fmt.Fprintf(&b, "package %s\n\n", pkgName) + + if len(imports) > 0 { + paths := make([]string, 0, len(imports)) + for p := range imports { + paths = append(paths, p) + } + sort.Strings(paths) + b.WriteString("import (\n") + for _, p := range paths { + fmt.Fprintf(&b, "\t%q\n", p) + } + b.WriteString(")\n\n") + } + + shellName := "unsupported" + typeName + fmt.Fprintf(&b, "// %s is the generated typed-unsupported shell for storage.%s.\n", shellName, typeName) + fmt.Fprintf(&b, "// Every method returns *storage.ErrUnsupported via errUnsupported; embed it and\n") + fmt.Fprintf(&b, "// override the real slice. DO NOT hand-edit — regenerate with `go generate ./...`.\n") + fmt.Fprintf(&b, "type %s struct{}\n\n", shellName) + + for _, m := range methods { + var resultDecl string + switch len(m.results) { + case 0: + resultDecl = "" + case 1: + resultDecl = fmt.Sprintf(" (err %s)", m.results[0]) + default: + named := make([]string, len(m.results)) + for i, r := range m.results[:len(m.results)-1] { + named[i] = "_ " + r + } + named[len(named)-1] = "err " + m.results[len(m.results)-1] + resultDecl = fmt.Sprintf(" (%s)", strings.Join(named, ", ")) + } + params := make([]string, len(m.params)) + for i, p := range m.params { + params[i] = "_ " + p + } + fmt.Fprintf(&b, "func (%s) %s(%s)%s {\n", shellName, m.name, strings.Join(params, ", "), resultDecl) + fmt.Fprintf(&b, "\terr = errUnsupported(%q)\n", m.name) + b.WriteString("\treturn\n}\n\n") + } + + fmt.Fprintf(&b, "// NOTE: partial shell (%d of %d methods generated; %d left to this package's hand-written set).\n", + len(methods), iface.NumMethod(), skipped) + + formatted, err := format.Source(b.Bytes()) + if err != nil { + return nil, 0, fmt.Errorf("formatting generated source: %w\n--- unformatted ---\n%s", err, b.String()) + } + return formatted, skipped, nil +} diff --git a/internal/storage/unsupportedgen/main_test.go b/internal/storage/unsupportedgen/main_test.go new file mode 100644 index 000000000..7b0f1f3dc --- /dev/null +++ b/internal/storage/unsupportedgen/main_test.go @@ -0,0 +1,86 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +// TestGeneratedShellIsFresh is the anti-drift check this tool never had: it +// runs exactly the same scan-then-generate pipeline main() runs for the one +// registered consumer (internal/httpclient's unsupported_gen.go, built from +// storage.DoltStorage with receiver Store), and compares the result byte for +// byte against the checked-in file. A storage.DoltStorage interface change, +// a hand-written method added or removed from httpclient's Store, or an edit +// to this generator's own output shape that nobody reran `go generate` after +// is caught here instead of silently drifting until someone notices the +// shell no longer matches what the generator would produce today. +// +// Regenerate with: go generate ./internal/httpclient (see unsupported.go's +// //go:generate line, which this test mirrors). +func TestGeneratedShellIsFresh(t *testing.T) { + const ( + typeName = "DoltStorage" + pkgName = "httpclient" + receiver = "Store" + outName = "unsupported_gen.go" + ) + + // httpclient lives two levels up from this package + // (internal/storage/unsupportedgen -> internal/httpclient). + scanDir := filepath.Join("..", "..", "httpclient") + outPath := filepath.Join(scanDir, outName) + + ifaceType, ok := registry[typeName] + if !ok { + t.Fatalf("%q is not in this tool's registry (add it in main.go)", typeName) + } + + handWritten, err := scanHandWrittenMethods(scanDir, receiver, outPath) + if err != nil { + t.Fatalf("scanning %s: %v", scanDir, err) + } + + want, _, err := generate(pkgName, typeName, ifaceType, handWritten) + if err != nil { + t.Fatalf("generate: %v", err) + } + + got, err := os.ReadFile(outPath) + if err != nil { + t.Fatalf("reading checked-in %s: %v", outPath, err) + } + + if string(got) != string(want) { + t.Fatalf("%s is stale: it does not match what this generator produces today.\n"+ + "This file is generated and must not be hand-edited.\n"+ + "Regenerate it with:\n"+ + " go generate ./internal/httpclient", outPath) + } +} + +// TestScanHandWrittenMethodsExcludesOwnOutput pins the one correctness +// property the freshness check above silently depends on: scanning must +// never see the generator's own prior output as "hand-written," or every +// method the shell currently stubs would get treated as already covered and +// the next regeneration would stub nothing at all. +func TestScanHandWrittenMethodsExcludesOwnOutput(t *testing.T) { + scanDir := filepath.Join("..", "..", "httpclient") + outPath := filepath.Join(scanDir, "unsupported_gen.go") + + handWritten, err := scanHandWrittenMethods(scanDir, "Store", outPath) + if err != nil { + t.Fatalf("scanning %s: %v", scanDir, err) + } + + // unsupportedDoltStorage's receiver is unsupportedDoltStorage, not Store, + // so none of its stub method names should ever land in the Store-receiver + // hand-written set purely by virtue of being in the output file -- but to + // catch a regression where the output file itself was scanned anyway, + // assert directly that scanning skipped it: a method this generator is + // known to stub today (AsOf, from storage.DoltStorage's version-control + // family) must not appear as hand-written on Store. + if handWritten["AsOf"] { + t.Error(`handWritten["AsOf"] = true, want false -- scanHandWrittenMethods appears to have scanned its own output file`) + } +} diff --git a/internal/storage/uow/BUILD.bazel b/internal/storage/uow/BUILD.bazel index e181e1fcc..19101d195 100644 --- a/internal/storage/uow/BUILD.bazel +++ b/internal/storage/uow/BUILD.bazel @@ -7,12 +7,15 @@ go_library( "batch_applier.go", "batch_closer.go", "batch_creator.go", + "batchgetter.go", + "blocked_lister.go", "blocked_recheck.go", "blockingannotator.go", "bootstrapper.go", "commenter.go", "counter.go", "cycle_detector.go", + "delete_fence.go", "deleter.go", "dependency_editor.go", "dolt_sql_provider.go", @@ -23,15 +26,18 @@ go_library( "events_journal.go", "external_doltserver_provider.go", "graph_counter.go", + "heartbeater.go", "importer.go", "init_verifier.go", "issue_claimer.go", "issue_operations.go", "issue_reader.go", "journal_maintenance.go", + "lease_reclaimer.go", "maintenance.go", "memories.go", "metadata_cas.go", + "molecule.go", "notifying.go", "pool.go", "querier.go", @@ -68,6 +74,7 @@ go_library( "//internal/storage/memoryops", "//internal/storage/schema", "//internal/storage/sqlbuild", + "//internal/storage/versioncontrolops", "//internal/types", "//internal/workapi", "//issueops", @@ -84,7 +91,7 @@ go_library( # ~6-8s apiece, and the package needs ~7 min serially (TestBatchApplyContract # alone ~1 min: BoundsTheItemCount applies 1000+1001 real items), past the # default medium 300s. size/shard_count cover that configless run, the same -# workload uow_dolt_test (8 shards) and uow_docker_test (4 shards) run. +# workload uow_dolt_test (8 shards) runs. go_test( name = "uow_test", size = "large", @@ -93,6 +100,8 @@ go_test( "batch_apply_contract_test.go", "batch_closer_contract_test.go", "batch_creator_contract_test.go", + "batch_getter_contract_test.go", + "blocked_lister_contract_test.go", "blocked_recheck_race_test.go", "blocking_annotator_contract_test.go", "bootstrapper_contract_test.go", @@ -101,6 +110,7 @@ go_test( "counter_contract_test.go", "cross_record_invariant_contract_test.go", "cycle_detector_contract_test.go", + "data_behind_migrate_gate_test.go", "deleter_contract_test.go", "dependency_editor_contract_test.go", "dolt_sql_provider_lock_test.go", @@ -108,11 +118,14 @@ go_test( "doltserver_provider_test.go", "doltserver_tx_test.go", "dualwrite_history_contract_test.go", + "dualwrite_participation_generation_contract_test.go", "edge_reader_contract_test.go", "errors_test.go", "expected_revision_contract_test.go", "external_doltserver_provider_test.go", "graph_counter_contract_test.go", + "heartbeater_contract_test.go", + "history_off_differential_test.go", "importer_contract_test.go", "importer_uow_test.go", "issue_claimer_test.go", @@ -125,6 +138,7 @@ go_test( "journal_contract_test.go", "journal_delete_actor_test.go", "journal_scope_test.go", + "lease_reclaimer_contract_test.go", "lifecycle_close_reopen_contract_test.go", "lifecycle_create_contract_test.go", "lifecycle_role_hooks_test.go", @@ -134,6 +148,7 @@ go_test( "memories_contract_test.go", "metadata_cas_contract_test.go", "metadata_patch_dolt_test.go", + "molecule_contract_test.go", "notifying_integration_test.go", "notifying_parity_test.go", "notifying_test.go", @@ -161,6 +176,7 @@ go_test( "version_reconcile_boot_test.go", "version_reconcile_integration_test.go", "version_reconciler_contract_test.go", + "versioned_read_contract_test.go", "workspace_config_contract_test.go", ], data = [ @@ -183,6 +199,7 @@ go_test( "//internal/storage/dbproxy/server", "//internal/storage/domain", "//internal/storage/domain/db", + "//internal/storage/historyoffequiv", "//internal/storage/issueops", "//internal/storage/schema", "//internal/testutil", @@ -199,45 +216,11 @@ go_test( ], ) -# The container-backed uow tests as pr.yml's "Test (storage domain + uow)" job -# runs them (no -short; each test starts its own dolt sql-server container), -# with BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 so a missing container fails instead -# of skipping. It repeats uow_test's `env` (go_test_variant.sh cannot inherit -# it). uow_test itself stays untagged: under --config=prcore those tests skip. -# -# Tags: -# requires-docker: needs a docker daemon; excluded from --config=prcore/ci, -# selected by --config=docker. -# no-remote-exec: the daemon is on the host, not on remote workers. -sh_test( - name = "uow_docker_test", - size = "large", - srcs = ["//tools/bazel:go_test_variant.sh"], - args = ["$(rootpath :uow_test)"], - data = [ - ":uow_test", - "//cmd/bd:bd_for_tests", - ], - # Pinned to the container backend (the docker lane is the A/B control); - # rule env beats --test_env, so =local on the command line cannot flip it. - env = { - "BEADS_TEST_BD_BINARY": "$(rlocationpath //cmd/bd:bd_for_tests)", - "BEADS_TEST_DOLT_SERVER": "container", - "BEADS_TEST_REQUIRE_DOLT_CONTAINER": "1", - }, - # ~12 min unsharded under -race on a loaded host (large allows 15). - shard_count = 4, - tags = [ - "no-remote-exec", - "requires-docker", - ], -) - -# uow_test as pr.yml's "Test (storage domain + uow)" job runs it (no -short), +# uow_test as the retired "Test (storage domain + uow)" job ran it (no -short), # on the dolt-server lane: every server the tests ask internal/testutil for is # a `dolt sql-server` child of the test process, so the target runs on remote # workers. It repeats uow_test's `env` (go_test_variant.sh cannot inherit it). -# GOMAXPROCS=4 is the job's runner shape. uow_docker_test is the A/B control. +# GOMAXPROCS=4 is the job's runner shape. # 8 shards keep each under ~2 min remotely (the package is ~7 min in the job). # # Tags: @@ -277,3 +260,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/storage/uow/batch_applier.go b/internal/storage/uow/batch_applier.go index aba391947..c566ef2db 100644 --- a/internal/storage/uow/batch_applier.go +++ b/internal/storage/uow/batch_applier.go @@ -218,9 +218,10 @@ func (r *uowApplyRun) applyCreate(ctx context.Context, index int, item *publicop return err } prepared, err := storageissueops.PreparePublicCreateRequest(publicops.CreateRequest{ - Actor: r.plan.Actor, - Issue: item.Issue, - ForceIDPrefix: r.plan.ForceIDPrefix, + Actor: r.plan.Actor, + Issue: item.Issue, + ForceIDPrefix: r.plan.ForceIDPrefix, + DefaultPriority: item.DefaultPriority, }, storageissueops.PublicCreateContext{ IssuePrefix: createContext.IssuePrefix, AllowedPrefixes: createContext.AllowedPrefixes, @@ -310,7 +311,7 @@ func (r *uowApplyRun) applyUpdate(ctx context.Context, index int, item *publicop if err := validateUpdateRequest(request); err != nil { return itemErr(err) } - updated, err := r.runUpdate(ctx, request) + updated, err := r.runUpdate(ctx, request, true) if err != nil { return itemErr(err) } @@ -332,7 +333,10 @@ func (r *uowApplyRun) applyUpdate(ctx context.Context, index int, item *publicop // change. ga-v2k49 is a concrete instance of that drift: claimChanged's actor // comparison here and there diverged (one verbatim, one not) until both were // found and fixed independently. -func (r *uowApplyRun) runUpdate(ctx context.Context, request publicops.UpdateRequest) (publicops.UpdateResult, error) { +// +// guardTemplate is false only for the metadata splice, which finishes a create +// item of this request rather than modifying an existing row. +func (r *uowApplyRun) runUpdate(ctx context.Context, request publicops.UpdateRequest, guardTemplate bool) (publicops.UpdateResult, error) { spec, err := updateSpec(request) if err != nil { return publicops.UpdateResult{}, validationError(err) @@ -346,6 +350,11 @@ func (r *uowApplyRun) runUpdate(ctx context.Context, request publicops.UpdateReq return publicops.UpdateResult{}, err } if updatePreconditionsHold(request, before) { + if guardTemplate { + if err := storageissueops.AuthorizeTemplateUpdate(before, request); err != nil { + return publicops.UpdateResult{}, err + } + } if err := authorizeAssigneeTransfer(ctx, r.uw, before, request); err != nil { return publicops.UpdateResult{}, err } @@ -453,6 +462,9 @@ func (r *uowApplyRun) applyDepAdd(ctx context.Context, index int, item *publicop if source == target { return itemErr(fmt.Errorf("%w: %s", publicops.ErrSelfDependency, source)) } + if err := publicops.CheckDottedChildDependency(source, target, item.Type); err != nil { + return itemErr(err) + } sourceWisp, sourceMine := r.planes[source] targetWisp, targetMine := r.planes[target] if sourceMine && targetMine && sourceWisp != targetWisp { @@ -462,11 +474,19 @@ func (r *uowApplyRun) applyDepAdd(ctx context.Context, index int, item *publicop if err != nil { return itemErr(err) } + metadata := item.Metadata + if item.HasSpawner { + metadata, err = storageissueops.StampWaitsForSpawnerID(item.Type, item.Metadata, target) + if err != nil { + return itemErr(fmt.Errorf("%w: %v", publicops.ErrValidation, err)) + } + } dep := &types.Dependency{ IssueID: source, DependsOnID: target, Type: item.Type, - Metadata: item.Metadata, + Metadata: metadata, + ThreadID: item.ThreadID, } if _, err := r.uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, r.plan.Actor, domain.BulkAddDepsOpts{ SkipPerEdgeCycleCheck: r.plan.SkipPerEdgeCycleCheck, @@ -519,11 +539,13 @@ func (r *uowApplyRun) spliceMetadataRefs(ctx context.Context) error { return err } id := r.result.Items[index].IssueID + // Unguarded for templates, as the store-backed splice is: it finishes + // this request's own create. updated, err := r.runUpdate(ctx, publicops.UpdateRequest{ Actor: r.plan.Actor, IssueID: id, Patch: publicops.IssuePatch{Metadata: publicops.MetadataPatch{Set: set}}, - }) + }, false) if err != nil { return &publicops.ItemError{Index: index, Kind: publicops.ItemCreate, Key: item.Create.Key, IssueID: id, Err: err} } diff --git a/internal/storage/uow/batch_apply_contract_test.go b/internal/storage/uow/batch_apply_contract_test.go index 255a7c879..557d8a2fe 100644 --- a/internal/storage/uow/batch_apply_contract_test.go +++ b/internal/storage/uow/batch_apply_contract_test.go @@ -115,6 +115,18 @@ func TestBatchApplyContract(t *testing.T) { t.Run("NormalizesTheWaitsForGate", func(t *testing.T) { conformance.RunBatchApplyNormalizesTheWaitsForGate(t, ctx, fixture) }) + t.Run("StampsSpawnerIDOnlyWhenNamed", func(t *testing.T) { + conformance.RunBatchApplyStampsSpawnerIDOnlyWhenNamed(t, ctx, fixture) + }) + t.Run("CarriesThreadIDOntoTheStoredEdge", func(t *testing.T) { + conformance.RunBatchApplyCarriesThreadIDOntoTheStoredEdge(t, ctx, fixture) + }) + t.Run("CarriesThreadIDOntoAnExistingEdge", func(t *testing.T) { + conformance.RunBatchApplyCarriesThreadIDOntoAnExistingEdge(t, ctx, fixture) + }) + t.Run("RefusesAThreadIDLongerThanItsColumn", func(t *testing.T) { + conformance.RunBatchApplyRefusesAThreadIDLongerThanItsColumn(t, ctx, fixture) + }) t.Run("SplicesAForwardMetadataRef", func(t *testing.T) { conformance.RunBatchApplySplicesAForwardMetadataRef(t, ctx, fixture) }) @@ -145,6 +157,24 @@ func TestBatchApplyContract(t *testing.T) { t.Run("RefusesAnUnusableRequest", func(t *testing.T) { conformance.RunBatchApplyRefusesAnUnusableRequest(t, ctx, fixture) }) + t.Run("UpdateItemsRefuseATemplate", func(t *testing.T) { + conformance.RunBatchApplyUpdateItemsRefuseATemplate(t, ctx, fixture) + }) + t.Run("SplicesTheMetadataOfATemplateItCreates", func(t *testing.T) { + conformance.RunBatchApplySplicesTheMetadataOfATemplateItCreates(t, ctx, fixture) + }) + t.Run("CloseItemsAnswerToTheCloseGuards", func(t *testing.T) { + conformance.RunBatchApplyCloseItemsAnswerToTheCloseGuards(t, ctx, fixture) + }) + t.Run("RefusesADottedChildGatedOnItsOwnParent", func(t *testing.T) { + conformance.RunBatchApplyRefusesADottedChildGatedOnItsOwnParent(t, ctx, fixture) + }) + t.Run("AppliesTheDefaultPriority", func(t *testing.T) { + conformance.RunBatchApplyAppliesTheDefaultPriority(t, ctx, fixture) + }) + t.Run("CarriesTheGateMembers", func(t *testing.T) { + conformance.RunBatchApplyCarriesTheGateMembers(t, ctx, fixture) + }) } func newUOWBatchApplyFixture(t *testing.T, ctx context.Context, prefix string) conformance.BatchApplyFixture { diff --git a/internal/storage/uow/batch_closer.go b/internal/storage/uow/batch_closer.go index e29707f42..43cfed688 100644 --- a/internal/storage/uow/batch_closer.go +++ b/internal/storage/uow/batch_closer.go @@ -73,6 +73,24 @@ func (o *batchCloser) CloseBatch(ctx context.Context, request publicops.CloseBat } } + if request.AutoCloseMolecule { + closedAt := make([]int, 0, len(result.Outcomes)) + stepIDs := make([]string, 0, len(result.Outcomes)) + for i, outcome := range result.Outcomes { + if outcome.Err == nil { + closedAt = append(closedAt, i) + stepIDs = append(stepIDs, outcome.IssueID) + } + } + autos, err := CloseCompletedMoleculesInUOW(ctx, uw, stepIDs, request.Actor, request.Session) + if err != nil { + return publicops.CloseBatchResult{}, "", err + } + for j, i := range closedAt { + result.Outcomes[i].AutoClosedMolecule, result.Outcomes[i].MoleculeAutoCloseRefusal = autos[j].Root, autos[j].Refusal + } + } + if claimFilter != nil && landed > 0 { claimed, err := ClaimNextInUOW(ctx, uw, request.Actor, *claimFilter) if err != nil { diff --git a/internal/storage/uow/batch_closer_contract_test.go b/internal/storage/uow/batch_closer_contract_test.go index 43640e738..4ca8d2b4e 100644 --- a/internal/storage/uow/batch_closer_contract_test.go +++ b/internal/storage/uow/batch_closer_contract_test.go @@ -47,6 +47,7 @@ func TestBatchCloserContract(t *testing.T) { {name: "AllRefusedBatchRecordsNoHistory", prefix: "bc-nohistory", run: conformance.RunBatchCloserAllRefusedBatchRecordsNoHistory}, {name: "DoesNotMutateTheCallerRequest", prefix: "bc-snapshot", run: conformance.RunBatchCloserDoesNotMutateTheCallerRequest}, {name: "SettlesTheDependersOfWhatItClosed", prefix: "bc-blocked", run: conformance.RunBatchCloserSettlesTheDependersOfWhatItClosed}, + {name: "ItemsAnswerToTheCloseGuards", prefix: "bc-guard", run: conformance.RunBatchCloserItemsAnswerToTheCloseGuards}, } { t.Run(test.name, func(t *testing.T) { test.run(t, ctx, newUOWBatchCloserFixture(t, provider, test.prefix)) diff --git a/internal/storage/uow/batch_creator_contract_test.go b/internal/storage/uow/batch_creator_contract_test.go index 0bc5f74fb..99621f472 100644 --- a/internal/storage/uow/batch_creator_contract_test.go +++ b/internal/storage/uow/batch_creator_contract_test.go @@ -61,6 +61,9 @@ func TestBatchCreatorContract(t *testing.T) { t.Run("EchoesSubSecondTimestamps", func(t *testing.T) { conformance.RunBatchCreatorEchoesSubSecondTimestamps(t, ctx, fixture) }) + t.Run("AppliesTheDefaultPriority", func(t *testing.T) { + conformance.RunBatchCreatorAppliesTheDefaultPriority(t, ctx, fixture) + }) } func newUOWBatchCreatorFixture(t *testing.T, ctx context.Context, prefix string) conformance.BatchCreatorFixture { diff --git a/internal/storage/uow/batch_getter_contract_test.go b/internal/storage/uow/batch_getter_contract_test.go new file mode 100644 index 000000000..9821923b4 --- /dev/null +++ b/internal/storage/uow/batch_getter_contract_test.go @@ -0,0 +1,94 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestBatchGetterContract runs the BatchGetter contract against the +// unit-of-work provider. +// +// For most roles this is the wiring where a genuine seam divergence shows up, +// because the unit of work is a second body. NOT FOR THIS ROLE: it reaches the +// same issueops.ExecuteGetMany through the domain repository, whose runner +// publishes exactly the DBTX method set that function takes. What this leg +// checks is the WRAPPER — that the request survives the trip and that +// ErrValidation still matches errors.Is after crossing two layers whose +// siblings wrap their errors. +// +// One provider for the whole suite and NO t.Parallel: this backend has no +// per-test copy-on-write branch, so the tables are database-global. Every case +// scopes itself by the ids it seeded. +func TestBatchGetterContract(t *testing.T) { + ctx := context.Background() + fixture := newUOWBatchGetterFixture(t, ctx, "bge") + + t.Run("FindsRequestedIssues", func(t *testing.T) { + conformance.RunBatchGetterFindsRequestedIssues(t, ctx, fixture) + }) + t.Run("ReportsMissingIDs", func(t *testing.T) { + conformance.RunBatchGetterReportsMissingIDs(t, ctx, fixture) + }) + t.Run("CollapsesRepeatedIDs", func(t *testing.T) { + conformance.RunBatchGetterCollapsesRepeatedIDs(t, ctx, fixture) + }) + t.Run("AnswersInRequestOrder", func(t *testing.T) { + conformance.RunBatchGetterAnswersInRequestOrder(t, ctx, fixture) + }) + t.Run("ResolvesIDsExactly", func(t *testing.T) { + conformance.RunBatchGetterResolvesIDsExactly(t, ctx, fixture) + }) + t.Run("AnswersAnEmptyRequest", func(t *testing.T) { + conformance.RunBatchGetterAnswersAnEmptyRequest(t, ctx, fixture) + }) + t.Run("RefusesAnUnusableRequest", func(t *testing.T) { + conformance.RunBatchGetterRefusesAnUnusableRequest(t, ctx, fixture) + }) + t.Run("RefusesOverTheCap", func(t *testing.T) { + conformance.RunBatchGetterRefusesOverTheCap(t, ctx, fixture) + }) + t.Run("AcceptsExactlyTheCap", func(t *testing.T) { + conformance.RunBatchGetterAcceptsExactlyTheCap(t, ctx, fixture) + }) + t.Run("LeavesTheRequestAlone", func(t *testing.T) { + conformance.RunBatchGetterLeavesTheRequestAlone(t, ctx, fixture) + }) + t.Run("SharesOneReadStructurally", func(t *testing.T) { + conformance.RunBatchGetterSharesOneReadStructurally(t, ctx, fixture) + }) + t.Run("HydratesLabels", func(t *testing.T) { + conformance.RunBatchGetterHydratesLabels(t, ctx, fixture) + }) + t.Run("CrossesBothPlanes", func(t *testing.T) { + conformance.RunBatchGetterCrossesBothPlanes(t, ctx, fixture) + }) + t.Run("WritesNothing", func(t *testing.T) { + conformance.RunBatchGetterWritesNothing(t, ctx, fixture) + }) +} + +func newUOWBatchGetterFixture(t *testing.T, ctx context.Context, prefix string) conformance.BatchGetterFixture { + t.Helper() + provider := newUOWRoleFixtureProvider(t, ctx, prefix) + // Through the capability accessor, not NewBatchGetter: a provider that + // stopped offering the role is the regression, and a constructor call would + // hide it. + source, ok := provider.(BatchGetterSource) + if !ok { + t.Fatalf("provider %T does not offer the BatchGetter accessor", provider) + } + getter, err := source.BatchGetter() + if err != nil { + t.Fatalf("BatchGetter(): %v", err) + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.BatchGetterFixture{ + IssuePrefix: kit.IssuePrefix, + BatchGetter: getter, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/uow/batchgetter.go b/internal/storage/uow/batchgetter.go new file mode 100644 index 000000000..adbd54cc1 --- /dev/null +++ b/internal/storage/uow/batchgetter.go @@ -0,0 +1,49 @@ +package uow + +import ( + "context" + "fmt" + + publicops "github.com/steveyegge/beads/issueops" +) + +// BatchGetterSource is the capability accessor a unit-of-work provider offers +// for the batch-read role, the sibling of CounterSource and GraphCounterSource. +type BatchGetterSource interface { + BatchGetter() (publicops.BatchGetter, error) +} + +// batchGetter answers a GetMany through a unit of work. +type batchGetter struct { + provider UnitOfWorkProvider +} + +// BatchGetter returns the guarded batch-read surface for this provider. +func (p *doltSQLProvider) BatchGetter() (publicops.BatchGetter, error) { + return NewBatchGetter(p) +} + +// NewBatchGetter constructs a public BatchGetter backed by provider. +func NewBatchGetter(provider UnitOfWorkProvider) (publicops.BatchGetter, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new batch getter: unit-of-work provider must not be nil") + } + return &batchGetter{provider: provider}, nil +} + +var _ publicops.BatchGetter = (*batchGetter)(nil) + +// GetMany reaches domain.IssueSQLRepository.GetMany inside ONE read-only unit +// of work, the same seam CountEdges reaches DependencyUseCase.CountEdges +// through: the request's whole vocabulary is validated inside the shared +// body (issueops.ExecuteGetMany), so this leg does no pre-check of its own. +func (c *batchGetter) GetMany(ctx context.Context, request publicops.GetManyRequest) (publicops.GetManyResult, error) { + return RunTxRead(ctx, c.provider, func(ctx context.Context, uw UnitOfWork) (publicops.GetManyResult, error) { + return GetManyInUOW(ctx, uw, request) + }) +} + +// GetManyInUOW is the BatchGetter body, run inside the caller's unit of work. +func GetManyInUOW(ctx context.Context, uw UnitOfWork, request publicops.GetManyRequest) (publicops.GetManyResult, error) { + return uw.IssueUseCase().GetMany(ctx, request) +} diff --git a/internal/storage/uow/blocked_lister.go b/internal/storage/uow/blocked_lister.go new file mode 100644 index 000000000..4b1e103ba --- /dev/null +++ b/internal/storage/uow/blocked_lister.go @@ -0,0 +1,50 @@ +package uow + +import ( + "context" + "fmt" + + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + publicops "github.com/steveyegge/beads/issueops" +) + +// BlockedListerSource is the capability accessor a unit-of-work provider +// offers for the blocked-listing role. +type BlockedListerSource interface { + BlockedLister() (publicops.BlockedLister, error) +} + +// blockedLister lists the blocked issues through a unit of work. +type blockedLister struct { + provider UnitOfWorkProvider +} + +// BlockedLister returns the blocked-listing surface for this provider. +func (p *doltSQLProvider) BlockedLister() (publicops.BlockedLister, error) { + return NewBlockedLister(p) +} + +// NewBlockedLister constructs a public BlockedLister backed by provider. +func NewBlockedLister(provider UnitOfWorkProvider) (publicops.BlockedLister, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new blocked lister: unit-of-work provider must not be nil") + } + return &blockedLister{provider: provider}, nil +} + +var _ publicops.BlockedLister = (*blockedLister)(nil) + +// ListBlocked answers one blocked listing inside one read-only unit of work, +// through the use case's GetBlockedIssues: the same body the store legs run +// (issueops.GetBlockedIssuesInTx), and, under a provider that applies the +// external-dependency policy, that provider's decoration of it. +func (l *blockedLister) ListBlocked(ctx context.Context, req publicops.BlockedRequest) (publicops.BlockedResult, error) { + filter := storageissueops.BlockedFilter(req) + return RunTxRead(ctx, l.provider, func(ctx context.Context, uw UnitOfWork) (publicops.BlockedResult, error) { + items, err := uw.IssueUseCase().GetBlockedIssues(ctx, filter) + if err != nil { + return publicops.BlockedResult{}, err + } + return storageissueops.BlockedResultOf(items), nil + }) +} diff --git a/internal/storage/uow/blocked_lister_contract_test.go b/internal/storage/uow/blocked_lister_contract_test.go new file mode 100644 index 000000000..1c38f51c3 --- /dev/null +++ b/internal/storage/uow/blocked_lister_contract_test.go @@ -0,0 +1,31 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestBlockedListerContract runs the BlockedLister contract against the +// unit-of-work provider, through its own capability accessor. +func TestBlockedListerContract(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "blk") + source, ok := provider.(BlockedListerSource) + if !ok { + t.Fatalf("provider %T does not offer the BlockedLister accessor", provider) + } + lister, err := source.BlockedLister() + if err != nil { + t.Fatalf("BlockedLister(): %v", err) + } + kit := newUOWRoleFixtureKit(provider, "blk") + conformance.RunBlockedLister(t, ctx, conformance.BlockedListerFixture{ + IssuePrefix: kit.IssuePrefix, + BlockedLister: lister, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + }) +} 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/counter.go b/internal/storage/uow/counter.go index 03a155788..467712fa2 100644 --- a/internal/storage/uow/counter.go +++ b/internal/storage/uow/counter.go @@ -85,11 +85,14 @@ func (c *counter) CountByGroup(ctx context.Context, req publicops.CountByGroupRe } // countFilter builds the storage filter from the unit of work the call already -// holds, loading configuration only when IncludeInfra can read it — the same two -// decisions the store-backed body makes, through the same builder. +// holds, loading configuration only when IncludeInfra or ExcludeStatus can +// read it — the same two decisions the store-backed body makes, through the +// same builder. ExcludeStatus needs the workspace's custom status names so +// BuildCountFilter's validation does not refuse a status the workspace itself +// defines (PR #7199 review). func countFilter(ctx context.Context, uw UnitOfWork, req publicops.CountRequest) (types.IssueFilter, error) { var cfg workapi.ListConfig - if req.IncludeInfra { + if req.IncludeInfra || len(req.ExcludeStatus) > 0 { loaded, err := workapi.LoadUOWListConfig(ctx, uw) if err != nil { return types.IssueFilter{}, err diff --git a/internal/storage/uow/counter_contract_test.go b/internal/storage/uow/counter_contract_test.go index 45e4de73b..9936e77e1 100644 --- a/internal/storage/uow/counter_contract_test.go +++ b/internal/storage/uow/counter_contract_test.go @@ -5,6 +5,9 @@ import ( "testing" "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" ) // TestCounterContract runs the Counter contract against the unit-of-work @@ -65,6 +68,33 @@ func TestCounterContract(t *testing.T) { t.Run("WritesNothing", func(t *testing.T) { conformance.RunCounterWritesNothing(t, ctx, fixture) }) + t.Run("ParentIDScopesToChildren", func(t *testing.T) { + conformance.RunCounterParentIDScopesToChildren(t, ctx, fixture) + }) + t.Run("NoParentExcludesChildren", func(t *testing.T) { + conformance.RunCounterNoParentExcludesChildren(t, ctx, fixture) + }) + t.Run("ExcludeTypesNarrowsThePredicate", func(t *testing.T) { + conformance.RunCounterExcludeTypesNarrowsThePredicate(t, ctx, fixture) + }) + t.Run("ExcludeStatusNarrowsThePredicate", func(t *testing.T) { + conformance.RunCounterExcludeStatusNarrowsThePredicate(t, ctx, fixture) + }) + t.Run("ParentIDMatchesListCardinality", func(t *testing.T) { + conformance.RunCounterParentIDMatchesListCardinality(t, ctx, fixture) + }) + t.Run("NoParentMatchesListCardinality", func(t *testing.T) { + conformance.RunCounterNoParentMatchesListCardinality(t, ctx, fixture) + }) + t.Run("ExcludeTypesMatchesListCardinality", func(t *testing.T) { + conformance.RunCounterExcludeTypesMatchesListCardinality(t, ctx, fixture) + }) + t.Run("ParentIDIncludesAWispChild", func(t *testing.T) { + conformance.RunCounterParentIDIncludesAWispChild(t, ctx, fixture) + }) + t.Run("ParentIDAndExcludeStatusComposeOnAClosedChild", func(t *testing.T) { + conformance.RunCounterParentIDAndExcludeStatusComposeOnAClosedChild(t, ctx, fixture) + }) } func newUOWCounterFixture(t *testing.T, ctx context.Context, prefix string) conformance.CounterFixture { @@ -80,12 +110,99 @@ func newUOWCounterFixture(t *testing.T, ctx context.Context, prefix string) conf if err != nil { t.Fatalf("Counter(): %v", err) } + readerSource, ok := provider.(IssueReaderSource) + if !ok { + t.Fatalf("provider %T does not offer the IssueReader accessor", provider) + } + reader, err := readerSource.IssueReader() + if err != nil { + t.Fatalf("IssueReader(): %v", err) + } kit := newUOWRoleFixtureKit(provider, prefix) return conformance.CounterFixture{ - IssuePrefix: kit.IssuePrefix, - Counter: counter, - CreateIssue: kit.CreateIssue, - CreateWisp: kit.CreateWisp, - CountHistory: kit.CountHistory, + IssuePrefix: kit.IssuePrefix, + Counter: counter, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + CountHistory: kit.CountHistory, + AddDependency: kit.AddDependency, + List: reader.List, + } +} + +// TestCounterExcludeStatusAcceptsAWorkspaceCustomStatusWithoutIncludeInfra +// pins the PR #7199 review's blocker fix on the unit-of-work leg: countFilter +// must load the workspace's list configuration when ExcludeStatus is +// non-empty, not only when IncludeInfra is set, so BuildCountFilter's +// validation sees the workspace's own custom statuses. A leg-level test, not +// a conformance case, because CounterFixture cannot drive a +// workspace-configured custom status (counter_contract.go's CounterFixture +// doc) — this needs a real provider with status.custom set. +// +// Its own provider (not newUOWCounterFixture's), so status.custom does not +// leak into the other subtests sharing that fixture's one database. +func TestCounterExcludeStatusAcceptsAWorkspaceCustomStatusWithoutIncludeInfra(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "cntcs") + + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + return "set status.custom", uw.ConfigUseCase().SetConfig(ctx, "status.custom", "review,qa") + }); err != nil { + t.Fatalf("SetConfig(status.custom): %v", err) + } + + const openID = "cntcs-open" + const reviewID = "cntcs-review" + for _, id := range []string{openID, reviewID} { + id := id + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + _, err := uw.IssueUseCase().CreateIssue(ctx, domain.CreateIssueParams{ + Issue: &types.Issue{ + ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + }, + ExplicitID: id, + CreateOnly: true, + }, "tester") + return "seed " + id, err + }); err != nil { + t.Fatalf("CreateIssue(%s): %v", id, err) + } + } + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + return "move to review", uw.IssueUseCase().UpdateIssue(ctx, reviewID, map[string]any{ + "status": types.Status("review"), + }, "tester") + }); err != nil { + t.Fatalf("UpdateIssue(%s) to review: %v", reviewID, err) + } + + source, ok := provider.(CounterSource) + if !ok { + t.Fatalf("provider %T does not offer the Counter accessor", provider) + } + counter, err := source.Counter() + if err != nil { + t.Fatalf("Counter(): %v", err) + } + + scope := publicops.CountRequest{IDFilter: openID + "," + reviewID} + total, err := counter.Count(ctx, scope) + if err != nil { + t.Fatalf("Count(unfiltered): %v", err) + } + if total.Total != 2 { + t.Fatalf("Count(unfiltered).Total = %d, want 2", total.Total) + } + + // IncludeInfra left UNSET: before the fix this refused with "invalid + // exclude-status \"review\"" because the config load was gated on + // IncludeInfra alone. + scope.ExcludeStatus = []string{"review"} + result, err := counter.Count(ctx, scope) + if err != nil { + t.Fatalf("Count(exclude-status=review, IncludeInfra unset): %v, want the custom status accepted", err) + } + if result.Total != 1 { + t.Fatalf("Count(exclude-status=review).Total = %d, want 1", result.Total) } } diff --git a/internal/storage/uow/data_behind_migrate_gate_test.go b/internal/storage/uow/data_behind_migrate_gate_test.go new file mode 100644 index 000000000..7cd51cba2 --- /dev/null +++ b/internal/storage/uow/data_behind_migrate_gate_test.go @@ -0,0 +1,288 @@ +package uow + +import ( + "context" + "errors" + "fmt" + "regexp" + "strings" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/steveyegge/beads/internal/storage/schema" +) + +// dataBehindCurrent is a schema cursor at or above the convergence floor +// (schema.LastNonDeterministicMigration) and below this binary's latest, so the +// smart gate reaches the equal-version first-mover arm with migrations still +// pending — the only arm where the #6575 ancestry check runs. +const dataBehindCurrent = 65 + +// expectSmartGateDataBehindRoute mocks the smart router's reads for a clone +// that is LEVEL with the cached remote ref on schema and BEHIND it in data: +// the local hashes, the active branch, the remote ref's hashes (identical, so +// no skew and the same max version), and finally the ahead/behind commit +// counts the #6575 check reads through the injected adopter. +// +// The last query is the one that did not happen before this fix: with a nil +// adopter localDataBehind short-circuits, so the route ended at +// smartAutoMigrate and the refusal reported shared-store instead. +func expectSmartGateDataBehindRoute(mock sqlmock.Sqlmock, ahead, behind int) { + hashes := func() *sqlmock.Rows { + return sqlmock.NewRows([]string{"version", "content_hash"}). + AddRow(dataBehindCurrent-1, "hash-a"). + AddRow(dataBehindCurrent, "hash-b") + } + ref := "remotes/origin/main" + + mock.ExpectQuery(regexp.QuoteMeta("SELECT version, content_hash FROM schema_migrations")). + WillReturnRows(hashes()) + mock.ExpectQuery(regexp.QuoteMeta("SELECT active_branch()")). + WillReturnRows(sqlmock.NewRows([]string{"branch"}).AddRow("main")) + mock.ExpectQuery(regexp.QuoteMeta(fmt.Sprintf("SHOW TABLES AS OF '%s' LIKE 'schema_migrations'", ref))). + WillReturnRows(sqlmock.NewRows([]string{"table"}).AddRow("schema_migrations")) + mock.ExpectQuery(regexp.QuoteMeta(fmt.Sprintf("SHOW COLUMNS FROM schema_migrations AS OF '%s' LIKE 'content_hash'", ref))). + WillReturnRows(sqlmock.NewRows([]string{"column"}).AddRow("content_hash")) + mock.ExpectQuery(regexp.QuoteMeta(fmt.Sprintf("SELECT version, content_hash FROM schema_migrations AS OF '%s'", ref))). + WillReturnRows(hashes()) + // versioncontrolops.LocalAheadBehind — reached only through a wired + // AheadBehind callback. + mock.ExpectQuery(`FROM dolt_log AS OF`). + WillReturnRows(sqlmock.NewRows([]string{"ahead", "behind"}).AddRow(ahead, behind)) +} + +// TestInitSchemaProxiedDataBehind covers the proxied/`bd serve` open path's +// half of gastownhall/beads#6575. +// +// The store-open gate on this path passed a nil adopter, so localDataBehind +// had no ancestry fact to read and the route could never emit smartDataBehind. +// A proxied clone that was level on schema and behind in data therefore +// reported the blunt shared-store refusal — whose body is the designated- +// migrator recipe, `bd migrate --force` then `bd dolt push`. In this state that +// recipe IS the #6368 wedge the stop exists to prevent, so the refusal was safe +// (the shared arm suppresses the auto-migrate either way) while the guidance it +// printed was not. +func TestInitSchemaProxiedDataBehind(t *testing.T) { + // newProxiedProvider returns a provider over a fresh mock with the two + // escape hatches pinned off, so the gate is reached on its own merits. + newProxiedProvider := func(t *testing.T) (*doltSQLProvider, sqlmock.Sqlmock) { + t.Helper() + t.Setenv(schema.AllowRemoteMigrateEnv, "0") + t.Setenv(schema.SmartGateEnv, "1") + t.Cleanup(func() { + schema.SetSharedMigrateConsent(false) + schema.SetForceAllowRemoteMigrate(false) + }) + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("create sql mock: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + return &doltSQLProvider{ + defaultBranch: defaultBranch, + db: db, + serverEndpoint: "tcp:127.0.0.1:3306", + proxiedServerMode: true, + }, mock + } + + t.Run("routes to the data-behind stop instead of the blunt shared-store one", func(t *testing.T) { + p, mock := newProxiedProvider(t) + + lockName := expectBehindDatabaseThroughPreparation(mock, "beads", dataBehindCurrent) + expectSharedGateProbe(mock, dataBehindCurrent, 1) + expectSmartGateDataBehindRoute(mock, 0, 2) + // Nothing between the route and the lock release: the refusal must land + // before MigrateUp issues its first statement. + expectLockRelease(mock, lockName) + + err := p.initSchema(context.Background(), "beads") + var gateErr *schema.RemoteMigrateGateError + if !errors.As(err, &gateErr) { + t.Fatalf("initSchema() error = %T (%v), want *schema.RemoteMigrateGateError", err, err) + } + if !gateErr.IsDataBehind() { + t.Fatalf("FallbackReason = %q, Decision = %q — want the #6575 data-behind stop", + gateErr.FallbackReason, gateErr.Decision) + } + if !gateErr.Shared { + t.Error("Shared = false; this provider only ever serves a shared database") + } + if !gateErr.Proxied { + t.Error("Proxied = false; every refusal from this provider is a proxied-server-mode refusal") + } + + // The finding, stated as an assertion: the body an operator reads must + // not hand them the migrate-in-place recipe while they are still behind. + body := gateErr.UserMessage() + for _, forbidden := range []string{"bd migrate --force\n", "designated migrator"} { + if strings.Contains(body, forbidden) { + t.Errorf("proxied data-behind body still prescribes %q:\n%s", forbidden, body) + } + } + if !strings.Contains(body, schema.DataBehindRemedyCommand) { + t.Errorf("body must name the pull:\n%s", body) + } + // ...and because `bd dolt pull` is refused at the proxied front door, + // the body has to say where it can actually be run. + for _, want := range []string{"proxied-server mode", "proxy.dolt_pull.unsupported", "server host"} { + if !strings.Contains(body, want) { + t.Errorf("proxied body missing %q:\n%s", want, body) + } + } + // The env hatch is not the only consent surface that stays reachable + // here: the proxied capability registry keys on the command path and + // permits `migrate schema`, so the forced schema verb gets through too + // (pinned in cmd/bd by TestProxyMaintenanceAllowsTheSharedConsentVerb). + // Both are read by forceOrEnvConsent before this stop is routed, so a + // warning that names only the refused bare `bd migrate --force` leaves + // the wedge reachable on exactly this topology. + for _, want := range []string{schema.AllowRemoteMigrateEnv + "=1", schema.SharedConsentCommandForced} { + if !strings.Contains(body, want) { + t.Errorf("proxied body must warn about the reachable consent surface %q:\n%s", want, body) + } + } + + opts := gateErr.Options() + if len(opts) != 2 || opts[0].ID != "pull-first-on-server-host" { + t.Fatalf("Options() = %+v, want the host-qualified pull plus the consent step", opts) + } + for _, o := range opts { + for _, c := range o.Commands { + if c == "bd migrate --force" || c == "bd bootstrap" { + t.Errorf("option %q offers %q, measured not to work in this state", o.ID, c) + } + } + } + + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) + + // The counterfactual for the topology flag. This same provider is the one + // `bd serve` builds for a SERVER-mode workspace, where `bd dolt pull` is + // not refused — telling that operator to go find another machine would be + // the same class of wrong guidance in the other direction. + t.Run("a server-mode open keeps the runnable-here remedy", func(t *testing.T) { + p, mock := newProxiedProvider(t) + p.proxiedServerMode = false + + lockName := expectBehindDatabaseThroughPreparation(mock, "beads", dataBehindCurrent) + expectSharedGateProbe(mock, dataBehindCurrent, 1) + expectSmartGateDataBehindRoute(mock, 0, 2) + expectLockRelease(mock, lockName) + + err := p.initSchema(context.Background(), "beads") + var gateErr *schema.RemoteMigrateGateError + if !errors.As(err, &gateErr) { + t.Fatalf("initSchema() error = %T (%v), want *schema.RemoteMigrateGateError", err, err) + } + if !gateErr.IsDataBehind() { + t.Fatalf("FallbackReason = %q — the stop itself is topology-independent", gateErr.FallbackReason) + } + if gateErr.Proxied { + t.Error("Proxied = true for a server-mode open") + } + if body := gateErr.UserMessage(); strings.Contains(body, "server host") { + t.Errorf("server-mode body must keep the runnable-here pull:\n%s", body) + } + if id := gateErr.Options()[0].ID; id != "pull-first" { + t.Errorf("server-mode pull option id = %q, want %q", id, "pull-first") + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) + + t.Run("a level clone is unaffected", func(t *testing.T) { + // The counterfactual for the wiring: same route, behind == 0. Reading + // the ancestry must not turn a genuine first-mover into a data-behind + // stop — it stays the shared-store refusal it was before this fix. + p, mock := newProxiedProvider(t) + + lockName := expectBehindDatabaseThroughPreparation(mock, "beads", dataBehindCurrent) + expectSharedGateProbe(mock, dataBehindCurrent, 1) + expectSmartGateDataBehindRoute(mock, 0, 0) + expectLockRelease(mock, lockName) + + err := p.initSchema(context.Background(), "beads") + var gateErr *schema.RemoteMigrateGateError + if !errors.As(err, &gateErr) { + t.Fatalf("initSchema() error = %T (%v), want *schema.RemoteMigrateGateError", err, err) + } + if gateErr.IsDataBehind() { + t.Error("a level clone must not reach the data-behind stop") + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) + + t.Run("read-only open prints the pull-first block, not the consent template", func(t *testing.T) { + // readThroughRefusedMigration's template names the shared consent verb + // for every refusal. For this stop that verb is doubly wrong: the + // remedy is the pull, and a remote-backed shared store never reads the + // bare verb's consent at all (schema.SharedConsentCommandForced). + p, mock := newProxiedProvider(t) + p.readOnly = true + + lockName := expectBehindDatabaseThroughPreparation(mock, "beads", dataBehindCurrent) + expectSharedGateProbe(mock, dataBehindCurrent, 1) + expectSmartGateDataBehindRoute(mock, 1, 2) // diverged shape + expectLockRelease(mock, lockName) + mock.ExpectExec(regexp.QuoteMeta("USE `beads`")). + WillReturnResult(sqlmock.NewResult(0, 0)) + + var initErr error + stderr := captureStderr(t, func() { + initErr = p.initSchema(context.Background(), "beads") + }) + if initErr != nil { + t.Fatalf("initSchema() error = %v, want nil — reads keep working on the old schema", initErr) + } + for _, want := range []string{ + "Read-only command", "without migrating", + schema.DataBehindRemedyCommand, "MERGES", "server host", + } { + if !strings.Contains(stderr, want) { + t.Errorf("read-through warning missing %q:\n%s", want, stderr) + } + } + // Two-sided: the template's "run 'bd migrate schema'" line must be gone + // for this stop. Scrub the forms that DO work first — every forced form + // contains the bare verb as a substring. + scrubbed := strings.ReplaceAll(stderr, schema.SharedConsentCommandForcedGlobal, "") + scrubbed = strings.ReplaceAll(scrubbed, schema.SharedConsentCommandForced, "") + if strings.Contains(scrubbed, schema.SharedConsentCommand) { + t.Errorf("read-through still prescribes the bare consent verb:\n%s", stderr) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) +} + +// TestDataBehindAdopterWiring pins the shape of the injected adopter, not just +// its effect. Only AheadBehind is wired: it is the complete #6575 predicate, +// while leaving IsStrictAncestor/WorkingSetClean nil keeps routeAdoptFastForward +// returning false, so the remote-AHEAD arm on this path keeps the plain adopt +// directive it had before. FastForward must stay nil — it is a WRITE that would +// promote the schema for every co-resident client of this server. +func TestDataBehindAdopterWiring(t *testing.T) { + for _, readOnly := range []bool{false, true} { + a := dataBehindAdopter(readOnly) + if a.AheadBehind == nil { + t.Fatal("AheadBehind must be wired; it is the whole point of the injection") + } + if a.FastForward != nil { + t.Error("FastForward must stay nil: a fast-forward here promotes the schema for every co-resident client") + } + if a.IsStrictAncestor != nil || a.WorkingSetClean != nil { + t.Error("IsStrictAncestor/WorkingSetClean must stay nil so the remote-ahead arm is unchanged") + } + if a.ReadOnly != readOnly { + t.Errorf("ReadOnly = %v, want %v", a.ReadOnly, readOnly) + } + } +} diff --git a/internal/storage/uow/delete_fence.go b/internal/storage/uow/delete_fence.go new file mode 100644 index 000000000..e880feae7 --- /dev/null +++ b/internal/storage/uow/delete_fence.go @@ -0,0 +1,151 @@ +package uow + +import ( + "context" + "database/sql" + "database/sql/driver" + "errors" + "fmt" + "hash/fnv" + "time" +) + +const ( + // deleteFenceLockPrefix namespaces this fence within Dolt/MySQL's + // GET_LOCK name space, which is server-wide rather than per-database + // (mirrors internal/storage/dolt's deleteFenceLockPrefix and + // schema.MigrationLockName's bd_schema_init: prefix, same reason): two + // beads databases sharing one Dolt sql-server must not collide on the + // same issue id. + deleteFenceLockPrefix = "bd_delete:" + // deleteFenceLockNameMaxLength mirrors MySQL/Dolt's 64-byte GET_LOCK name limit. + deleteFenceLockNameMaxLength = 64 + // deleteFenceLockTimeoutSeconds bounds how long a guarded delete waits to + // enter the fence. It must comfortably exceed RunTxResult's own + // DefaultTxRetryMaxElapsed (15s): a racer waiting its turn can be queued + // behind another racer that is itself retrying a serialization failure + // for up to that long. + deleteFenceLockTimeoutSeconds = 20 + // deleteFenceReleaseTimeout bounds the RELEASE_LOCK call, run on its own + // context so a caller-canceled ctx cannot strand the lock held. + deleteFenceReleaseTimeout = 5 * time.Second +) + +// ErrDeleteFenceUnavailable marks a transient failure to acquire the per-row +// delete fence lock (timeout or connection error), distinct from a version +// mismatch: it means this guarded delete never got a chance to check the +// row's version at all. +var ErrDeleteFenceUnavailable = errors.New("delete fence lock unavailable") + +// deleteFenceLockName returns a Dolt/MySQL named-lock key within the 64-byte +// limit, hashing down to fnv64a when the readable form would not fit — +// mirrors internal/storage/dolt's deleteFenceLockName (and, one level further +// back, schema.MigrationLockName). +func deleteFenceLockName(databaseName, id string) string { + raw := deleteFenceLockPrefix + databaseName + ":" + id + if len(raw) <= deleteFenceLockNameMaxLength { + return raw + } + h := fnv.New64a() + _, _ = h.Write([]byte(databaseName + ":" + id)) + return fmt.Sprintf("%s%016x", deleteFenceLockPrefix, h.Sum64()) +} + +// withDeleteFence serializes guarded (ExpectedVersion-checked) deletes for a +// single id against each other on a Dolt sql-server, the proxied-mode / +// bd-serve twin of internal/storage/dolt's (*DoltStore).withDeleteFence +// (mc-zndi7.73). +// +// Dolt's commit-time merge treats two concurrent transactions that each +// delete the same row as identical diffs ("row absent") and lands BOTH with +// no conflict — unlike a concurrent update/close racing the same delete, +// which already collides for real because its row_lock bump is a genuine +// edit the merge must reconcile against the delete. That asymmetry is the +// bug: every same-token deleter exits 0, and there is no schema cell a +// guarded delete can write to manufacture a real conflict, because the row +// it would write to is the row it is erasing. +// +// A session-scoped GET_LOCK, acquired before fn runs and released only after +// fn returns, turns that silent double-delete into a queue instead: the +// loser's unit of work begins only after the winner's has already committed +// and is durable, so its existence probe inside deleteInUOW finds the row +// gone and fails through the ordinary NotFoundError path instead of silently +// "succeeding" a second time. No schema or migration change is needed — +// GET_LOCK/RELEASE_LOCK are built-in Dolt/MySQL session primitives, already +// an established repo idiom (schema.MigrateUpWithLock, +// internal/storage/dolt's own delete fence). +// +// UNLIKE internal/storage/dolt's fence, the lock connection here is NOT the +// connection fn's write runs on: fn is left free to call RunTxResult, which +// draws its own (possibly several, across retries) connection from p.db the +// ordinary way. That is safe for exactly the reason the dolt-package fence's +// doc calls out as the hazard to avoid there: THIS provider's pool is never +// constrained to a single connection (no cmd/bd call site ever calls +// SetPoolLimits on the proxied-server or bd-serve UOW chain — see pool.go), +// so a dedicated lock connection can never starve the write of its own +// connection. What matters for correctness is not which physical connection +// runs the write but WHEN its transaction begins: fn (and therefore every +// snapshot it establishes, across every retry) starts only after GET_LOCK has +// already returned success, so a queued loser's first read can only ever +// observe the winner's commit as already landed and durable. +func withDeleteFence(ctx context.Context, p *doltSQLProvider, id string, fn func() error) error { + conn, err := p.db.Conn(ctx) + if err != nil { + return fmt.Errorf("delete fence: acquire connection: %w", err) + } + defer func() { _ = conn.Close() }() + + dbName, err := currentDatabaseName(ctx, conn) + if err != nil { + return fmt.Errorf("delete fence: %w", err) + } + + lockName := deleteFenceLockName(dbName, id) + var locked sql.NullInt64 + if err := conn.QueryRowContext(ctx, "SELECT GET_LOCK(?, ?)", lockName, deleteFenceLockTimeoutSeconds).Scan(&locked); err != nil { + return fmt.Errorf("delete fence: acquire lock: %w: %w", ErrDeleteFenceUnavailable, err) + } + if !locked.Valid || locked.Int64 != 1 { + return fmt.Errorf("delete fence: acquire lock: %w: timed out after %ds", ErrDeleteFenceUnavailable, deleteFenceLockTimeoutSeconds) + } + defer releaseDeleteFenceLock(conn, lockName) + + return fn() +} + +// currentDatabaseName reads the database conn's session is attached to. +// doltSQLProvider carries no database field of its own (the name lives only +// in the DSN each pool connection was opened with), and every connection +// drawn from p.db is already attached to it — buildDSN always includes the +// database component — so SELECT DATABASE() reliably reports the same name +// internal/storage/dolt's fence reads from its store's own field. +func currentDatabaseName(ctx context.Context, conn *sql.Conn) (string, error) { + var name sql.NullString + if err := conn.QueryRowContext(ctx, "SELECT DATABASE()").Scan(&name); err != nil { + return "", fmt.Errorf("select database(): %w", err) + } + return name.String, nil +} + +// releaseDeleteFenceLock releases a lock acquired by withDeleteFence from the +// same session, after fn has returned. It runs on its own short-lived context +// so a caller-canceled ctx cannot strand the lock held past this call. +// +// An unexpected result discards the physical connection (same defensive +// pattern internal/storage/dolt's releaseDeleteFenceLock and schema's +// discardConn use) rather than returning it to the pool: the lock's true +// state on that session is now unknown, and handing it to another caller +// could let a future guarded delete believe it holds the fence when it does +// not. +func releaseDeleteFenceLock(conn *sql.Conn, lockName string) { + cleanupCtx, cancel := context.WithTimeout(context.Background(), deleteFenceReleaseTimeout) + defer cancel() + + var released sql.NullInt64 + err := conn.QueryRowContext(cleanupCtx, "SELECT RELEASE_LOCK(?)", lockName).Scan(&released) + if err != nil || !released.Valid || released.Int64 != 1 { + _ = conn.Raw(func(driverConn any) error { + return driver.ErrBadConn + }) + } +} diff --git a/internal/storage/uow/deleter.go b/internal/storage/uow/deleter.go index ad3b808c6..11358aceb 100644 --- a/internal/storage/uow/deleter.go +++ b/internal/storage/uow/deleter.go @@ -64,16 +64,51 @@ func (d *deleter) Delete(ctx context.Context, req publicops.DeleteRequest) (publ return deleteInUOW(ctx, uw, req) }) } - return RunTxResult(ctx, d.provider, func(ctx context.Context, uw UnitOfWork) (publicops.DeleteResult, string, error) { - result, err := deleteInUOW(ctx, uw, req) - if err != nil || result.Deleted == 0 { - // A deletion that removed nothing labels nothing: the role - // promises at most one history entry per call and none for a - // no-op. - return result, "", err + + write := func(ctx context.Context) (publicops.DeleteResult, error) { + return RunTxResult(ctx, d.provider, func(ctx context.Context, uw UnitOfWork) (publicops.DeleteResult, string, error) { + result, err := deleteInUOW(ctx, uw, req) + if err != nil || result.Deleted == 0 { + // A deletion that removed nothing labels nothing: the role + // promises at most one history entry per call and none for a + // no-op. + return result, "", err + } + return result, fmt.Sprintf("bd: delete %d issue(s)", result.Deleted), nil + }) + } + + // A guarded (ExpectedVersion-checked) delete additionally runs under the + // per-id delete fence (mc-zndi7.73): without it, two same-token deletes + // race to identical "row absent" diffs that Dolt's commit-time merge + // lands with no conflict, so every racer exits 0 — see withDeleteFence's + // doc for the full design. Every doltSQLProvider here IS a real Dolt + // sql-server session (proxied mode or bd serve; there is no embedded + // backend in this package), so unlike internal/storage/dolt's fence + // (scoped to serverMode only) this one applies whenever a guard is + // present, with no mode check. + // + // d.provider is unwrapped first because the real chain + // (wireProxiedUOWProvider) wraps the bare *doltSQLProvider in a + // notifyingProvider and then an externaldeps uowProvider — both of which + // pass THEMSELVES, not the inner provider, to NewDeleter, so d.provider + // is a decorator here in every real deployment, never the bare provider. + if req.ExpectedVersion != nil { + if sp, ok := UnwrapProvider(d.provider).(*doltSQLProvider); ok { + var result publicops.DeleteResult + err := withDeleteFence(ctx, sp, req.IDs[0], func() error { + var ferr error + result, ferr = write(ctx) + return ferr + }) + if err != nil { + return publicops.DeleteResult{}, err + } + return result, nil } - return result, fmt.Sprintf("bd: delete %d issue(s)", result.Deleted), nil - }) + } + + return write(ctx) } // deleteInUOW is the whole deletion on one unit of work, shared by the preview @@ -129,8 +164,7 @@ func deleteInUOW(ctx context.Context, uw UnitOfWork, req publicops.DeleteRequest // duplicates before either ran. if req.ExpectedVersion != nil { if current := present[req.IDs[0]].RowVersion; current != *req.ExpectedVersion { - return publicops.DeleteResult{}, fmt.Errorf("%w: expected %d, got %d", - publicops.ErrVersionMismatch, *req.ExpectedVersion, current) + return publicops.DeleteResult{}, &publicops.VersionMismatchError{Expected: *req.ExpectedVersion, Current: current} } } diff --git a/internal/storage/uow/dependency_editor_contract_test.go b/internal/storage/uow/dependency_editor_contract_test.go index 02b91a878..3d2cc274a 100644 --- a/internal/storage/uow/dependency_editor_contract_test.go +++ b/internal/storage/uow/dependency_editor_contract_test.go @@ -32,6 +32,7 @@ func TestUOWDependencyEditorContract(t *testing.T) { {name: "SameTypeReAddIsIdempotent", run: conformance.RunDependencyEditorSameTypeReAddIsIdempotent}, {name: "SameTypeReAddWithChangedMetadataMintsOneVersion", run: conformance.RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion}, {name: "SameTypeReAddWithIdenticalMetadataIsANoOp", run: conformance.RunDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp}, + {name: "SameTypeReAddWithChangedThreadMintsOneVersion", run: conformance.RunDependencyEditorSameTypeReAddWithChangedThreadMintsOneVersion}, {name: "RepeatsWithinOneRequestCollapse", run: conformance.RunDependencyEditorRepeatsWithinOneRequestCollapse}, {name: "AttributesItsEventsToTheActor", run: conformance.RunDependencyEditorAttributesItsEventsToTheActor}, {name: "RetypeRefusalLeavesTheOriginalEdge", run: conformance.RunDependencyEditorRetypeRefusalLeavesTheOriginalEdge}, @@ -65,6 +66,7 @@ func TestUOWDependencyEditorContract(t *testing.T) { {name: "AcceptsADiamond", run: conformance.RunDependencyEditorAcceptsADiamond}, {name: "GateScopeFollowsTheEdgeType", run: conformance.RunDependencyEditorGateScopeFollowsTheEdgeType}, {name: "AcceptsBlockingAcrossIssueTypes", run: conformance.RunDependencyEditorAcceptsBlockingAcrossIssueTypes}, + {name: "RefusesADottedChildGatedOnItsOwnParent", run: conformance.RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent}, } { t.Run(test.name, func(t *testing.T) { test.run(t, ctx, fixture) diff --git a/internal/storage/uow/dolt_sql_provider.go b/internal/storage/uow/dolt_sql_provider.go index e7681d800..23d49c6a8 100644 --- a/internal/storage/uow/dolt_sql_provider.go +++ b/internal/storage/uow/dolt_sql_provider.go @@ -24,6 +24,7 @@ import ( db "github.com/steveyegge/beads/internal/storage/domain/db" "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/storage/schema" + "github.com/steveyegge/beads/internal/storage/versioncontrolops" ) const ( @@ -54,6 +55,10 @@ type doltSQLProvider struct { // preview it still bootstraps and migrates normally — it only changes what // happens when the migration gate REFUSES; see providerOptions.readOnly. readOnly bool + // proxiedServerMode: the workspace that opened this provider is in + // proxied-server mode, so the commands the proxied front door refuses are + // off the table for its operator; see providerOptions.proxiedServerMode. + proxiedServerMode bool // eventsJournalEnabled activates the durable events journal for THIS // provider instance only. See SetEventsJournalEnabled. eventsJournalEnabled atomic.Bool @@ -134,6 +139,17 @@ type providerOptions struct { // working through the upgrade window. That is the same warn-and-continue // contract embeddeddolt gives its read-only-command intent. readOnly bool + // proxiedServerMode records that the WORKSPACE is in proxied-server mode, + // which this provider cannot infer: it is the single funnel for the + // proxied CLI and for `bd serve`'s own provider on a SERVER-mode + // workspace, and both front a Dolt sql-server through the same dbproxy. + // The distinction matters to exactly one thing — which commands the front + // door refuses. In proxied mode `bd dolt pull` is rejected before it opens + // anything (proxy.dolt_pull.unsupported), so the #6575 data-behind stop + // has to name where that pull can be run; on a server-mode workspace the + // same command works, and saying otherwise would be the same class of + // wrong guidance in the other direction. + proxiedServerMode bool } // WithPreview opens the provider for a non-mutating preview command. @@ -146,6 +162,13 @@ func WithReadOnly() ProviderOption { return func(o *providerOptions) { o.readOnly = true } } +// WithProxiedServerMode marks the open as belonging to a proxied-server-mode +// workspace. See providerOptions.proxiedServerMode: only the refusal guidance +// depends on it, and only the proxied CLI open may set it. +func WithProxiedServerMode() ProviderOption { + return func(o *providerOptions) { o.proxiedServerMode = true } +} + func applyProviderOptions(opts []ProviderOption) providerOptions { var resolved providerOptions for _, opt := range opts { @@ -285,10 +308,18 @@ func (p *doltSQLProvider) initSchemaAttempt(ctx context.Context, database string // database by the time it runs, so a fresh bootstrap reads version 0 // and passes. schema.WithMigrationGate(func(ctx context.Context, c *sql.Conn) error { - return schema.CheckSharedStoreMigrateGate(ctx, c, "", nil, nil) + return schema.CheckSharedStoreMigrateGate(ctx, c, "", nil, dataBehindAdopter(p.readOnly)) })); err != nil { var gateErr *schema.RemoteMigrateGateError if errors.As(err, &gateErr) { + // The gate reads the database, never the workspace, so it cannot + // know which commands this operator's front door will refuse. Only + // a proxied-server-mode workspace refuses `bd dolt pull`, and this + // provider also serves `bd serve` on a server-mode workspace, + // where that pull works — so the flag is the caller's, not a + // property of being behind a proxy (gastownhall/beads#6575 + // follow-up). + gateErr.Proxied = p.proxiedServerMode if p.readOnly { return readThroughRefusedMigration(ctx, conn, database, gateErr) } @@ -302,6 +333,39 @@ func (p *doltSQLProvider) initSchemaAttempt(ctx context.Context, database string return nil } +// dataBehindAdopter injects the one ancestry fact the smart gate's #6575 +// data-behind check needs on this path. Without it localDataBehind short- +// circuits on a nil adopter, so a proxied store that is level on schema and +// BEHIND the remote in data could never route to smartDataBehind: it reported +// the blunt shared-store refusal instead, whose body names `bd migrate --force` +// and `bd dolt push` — the designated-migrator recipe, which in this state is +// the #6368 wedge the stop exists to prevent. The refusal itself was always +// safe here (the shared arm suppresses the first-mover auto-migrate whatever +// the ancestry says); the guidance it printed was not. +// +// Only AheadBehind is wired, deliberately. It is the complete data-behind +// predicate (behind >= 1 whatever ahead is, plus which shape), so the stop is +// fully covered — while leaving IsStrictAncestor/WorkingSetClean nil keeps +// routeAdoptFastForward returning false, so the remote-AHEAD arm still routes +// to the same plain adopt directive it does today. Nothing but the data-behind +// state changes message. FastForward stays nil for a stronger reason: the +// fast-forward is a WRITE that would promote the schema for every co-resident +// client of this server, which is exactly what the shared gate refuses to do +// unattended (#5920), and CheckSharedStoreMigrateGate suppresses it on a +// shared store regardless. +func dataBehindAdopter(readOnly bool) *schema.FastForwardAdopter { + return &schema.FastForwardAdopter{ + AheadBehind: func(ctx context.Context, db schema.DBConn, ref string) (int, int, error) { + return versioncontrolops.LocalAheadBehind(ctx, db, ref) + }, + // No FastForward is wired above, so canAutoFastForward is already + // false and this flag changes nothing today. Set anyway so the + // adopter's safety invariant ("ReadOnly means cannot write here") + // does not come to depend on that coincidence. + ReadOnly: readOnly, + } +} + // readThroughRefusedMigration serves a read command from a database the // migration gate refused to migrate: warn, attach at the current schema, and // carry on. Writes remain refused (they open without WithReadOnly), so the @@ -327,6 +391,19 @@ func readThroughRefusedMigration(ctx context.Context, conn *sql.Conn, database s // the refusal, which is the actionable half. return backoff.Permanent(gateErr) } + // #6575: the data-behind stop's remedy is the pull, and the consent verb + // this template names does not unlock a remote-backed shared store at all + // (schema.SharedConsentCommandForced). Print that stop's own block, which + // REPLACES the migrate-or-adopt framing rather than decorating it, and say + // only what read-through adds on top. + if gateErr.IsDataBehind() { + fmt.Fprintf(os.Stderr, + "Warning: %[1]s"+ + " Read-only command: continuing on schema v%[2]d without migrating.\n"+ + " Writes stay blocked until the steps above are done.\n", + gateErr.UserMessage(), gateErr.CurrentVersion) + return nil + } fmt.Fprintf(os.Stderr, "Warning: %[1]v\n"+ " Read-only command: continuing on schema v%[2]d without migrating.\n"+ @@ -783,6 +860,7 @@ func openAndInitSchema(ctx context.Context, ep proxy.Endpoint, database, rootUse expectedProjectID: expectedProjectID, preview: opts.preview, readOnly: opts.readOnly, + proxiedServerMode: opts.proxiedServerMode, } } diff --git a/internal/storage/uow/dolt_sql_provider_lock_test.go b/internal/storage/uow/dolt_sql_provider_lock_test.go index d276cbe57..e897f83f2 100644 --- a/internal/storage/uow/dolt_sql_provider_lock_test.go +++ b/internal/storage/uow/dolt_sql_provider_lock_test.go @@ -173,9 +173,10 @@ func TestInitSchemaConvergenceProbeRunsWithNoSessionDatabase(t *testing.T) { // migrationWorkNeeded's first question, reached only because the probe put // the session on the database itself. The cursor is far behind this // binary, so there is real work and the fast path declines. - mock.ExpectQuery(`SELECT COUNT\(\*\) FROM information_schema\.tables`). - WithArgs("schema_migrations"). + mock.ExpectQuery(regexp.QuoteMeta("SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = DATABASE()")). WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + mock.ExpectQuery("^SHOW TABLES$"). + WillReturnRows(sqlmock.NewRows([]string{"Tables_in_beads"}).AddRow("schema_migrations")) mock.ExpectQuery(regexp.QuoteMeta("SELECT COALESCE(MAX(version), 0) FROM schema_migrations")). WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow(1)) diff --git a/internal/storage/uow/doltserver_provider_test.go b/internal/storage/uow/doltserver_provider_test.go index b6b03f7d0..dab2f6174 100644 --- a/internal/storage/uow/doltserver_provider_test.go +++ b/internal/storage/uow/doltserver_provider_test.go @@ -115,6 +115,69 @@ func TestNewDoltServerUOWProvider_HappyPath(t *testing.T) { t.Cleanup(func() { _ = provider.Close(context.Background()) }) } +// TestNewDoltServerUOWProvider_CarriesProxiedServerMode pins the link of the +// proxied-server marker that the data-behind gate tests cannot see: they build +// the provider with the field already set, so they stay green if the open +// stops copying the option into the providers it builds, the one the gate +// runs on included. Both polarities, because the open `bd serve` makes for a +// server-mode workspace passes no option and must keep the runnable-here +// remedy. The two opens share one server. +func TestNewDoltServerUOWProvider_CarriesProxiedServerMode(t *testing.T) { + testutil.RequireDoltBinary(t) + bin, err := exec.LookPath("dolt") + require.NoError(t, err) + + bdBin := buildBDBinary(t) + prev := proxy.ResolveExecutable + proxy.ResolveExecutable = func() (string, error) { return bdBin, nil } + t.Cleanup(func() { proxy.ResolveExecutable = prev }) + + t.Setenv("HOME", t.TempDir()) + + port, err := proxy.PickFreePort() + require.NoError(t, err) + storeRootDir := t.TempDir() + shutdownOnInterrupt(t, storeRootDir) + verifiedShutdownCleanup(t, storeRootDir) + cfgPath := writeServerConfig(t, port) + logPath := filepath.Join(t.TempDir(), "server.log") + + for _, tt := range []struct { + name string + opts []ProviderOption + want bool + }{ + {name: "server-mode open", want: false}, + {name: "proxied-server open", opts: []ProviderOption{WithProxiedServerMode()}, want: true}, + } { + t.Run(tt.name, func(t *testing.T) { + provider, err := NewDoltServerUOWProvider( + context.Background(), + storeRootDir, + "beads", + logPath, + cfgPath, + proxy.BackendLocalServer, + "root", + "", + bin, + 0, + 0, + false, + "", + tt.opts..., + ) + require.NoError(t, err) + require.NotNil(t, provider) + t.Cleanup(func() { _ = provider.Close(context.Background()) }) + + sqlProvider, ok := provider.(*doltSQLProvider) + require.True(t, ok, "NewDoltServerUOWProvider returned %T, want *doltSQLProvider", provider) + assert.Equal(t, tt.want, sqlProvider.proxiedServerMode, "provider.proxiedServerMode") + }) + } +} + func TestNewDoltServerUOWProvider_ConcurrentInstantiation(t *testing.T) { testutil.RequireDoltBinary(t) bin, err := exec.LookPath("dolt") diff --git a/internal/storage/uow/doltserver_tx.go b/internal/storage/uow/doltserver_tx.go index 4fd396e7a..beebf330b 100644 --- a/internal/storage/uow/doltserver_tx.go +++ b/internal/storage/uow/doltserver_tx.go @@ -5,9 +5,16 @@ import ( "database/sql" "database/sql/driver" "errors" + "fmt" + "log" + "slices" + "time" + + "github.com/cenkalti/backoff/v4" "github.com/steveyegge/beads/internal/storage/domain/db" "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/storage/schema" ) type doltServerTx struct { @@ -80,6 +87,156 @@ func (t *doltServerTx) Commit(ctx context.Context, message string) error { return t.closeOpenTxAfterFailure(ctx, err) } +const ( + // scopedCommitMaxElapsed bounds the retries of CommitScoped's Dolt commit. + // It is short for the reason the DoltStore's postTxCommitMaxElapsed is: + // the failure is logged rather than returned, so a long fight for a commit + // the next one on the branch carries anyway buys nothing. + scopedCommitMaxElapsed = 5 * time.Second + // scopedCommitGrace pads the detached context past the retry budget. The + // budget only stops scheduling attempts; the deadline is what cancels one + // already hung in flight. + scopedCommitGrace = 2 * time.Second +) + +// CommitScoped commits the transaction and then makes a Dolt commit of +// exactly tables (plus the versioned-history tables when this transaction +// could have minted) named message: DOLT_ADD per table, then +// DOLT_COMMIT('-m') — never '-Am', so another writer's uncommitted change +// elsewhere in the working set is neither committed nor attributed to this +// message. With nothing staged, or under a deferred version commit +// (dolt.auto-commit batch/off), there is no Dolt commit. +// +// THE DOLT COMMIT RUNS AFTER THE SQL COMMIT, never inside the transaction: +// the ordering contract of the DoltStore funnel (runIssueOperationTxWithMessage, +// LatentLabsSpace/NEXUS#92). DOLT_ADD stages whole tables from the session's +// transaction root, so staging inside the open transaction builds the Dolt +// commit from its BEGIN-time snapshot and can write rows a concurrent writer +// committed in the meantime back to their old values. Committed first, this +// transaction's writes go through Dolt's commit-time merge with those +// writers, and the DOLT_ADD on the same pinned session, now outside any +// transaction, stages the merged state. +// +// A serialization failure of the SQL COMMIT is returned for the caller to redo +// the whole unit of work, as Commit's is. Once the SQL COMMIT succeeds the +// write is durable, so the Dolt commit after it never fails CommitScoped (see +// commitStagedTables). +func (t *doltServerTx) CommitScoped(ctx context.Context, tables []string, message string) error { + if t.done { + return errors.New("uow: commit: already done") + } + if message == "" || len(tables) == 0 || issueops.VersionCommitDeferred(ctx) { + return t.Commit(ctx, "") + } + // Resolved before the commit, while the versioned-history scope is bound + // to the pinned session. + staged := append([]string(nil), tables...) + if issueops.VersionedHistoryEnabledFor(t.conn) { + for _, table := range issueops.VersionedHistoryStagedTables() { + if !slices.Contains(staged, table) { + staged = append(staged, table) + } + } + } + if _, err := t.conn.ExecContext(ctx, "COMMIT;"); err != nil { + if isSerializationError(err) { + return err + } + return t.closeOpenTxAfterFailure(ctx, err) + } + t.done = true + clean := t.commitStagedTables(ctx, staged, message) + if t.recheckBlockedAfterCommit(ctx, issueops.TakeBlockedRecheck(t.conn)) && clean { + t.releaseConn() + } else { + t.poisonConn() + } + return nil +} + +// commitStagedTables is CommitScoped's Dolt commit, made on the pinned session +// after the transaction committed. It runs detached from the caller's +// cancellation on its own short budget, so a deadline landing after the SQL +// COMMIT does not skip it, and replays only the conflicts that leave nothing +// behind (serialization failures and Dolt's @@autocommit rollback, which is +// how a conflict surfaces outside a transaction), so re-staging and +// committing again is safe. That is doltAddAndCommitPostTx's retry. +// +// A failure is logged, never returned: the write is durable, and an error +// would make RunTxScoped replay a committed unit of work, which for a +// heartbeat re-arm then reports a refresh. The change rides the next Dolt +// commit on the branch, as a failed post-transaction commit does in the +// DoltStore funnel. Unlike the funnel, this leg counts nothing: uow records +// no metrics, so bd.db.post_tx_commit_dropped, the funnel's counter for the +// same drop, never sees one made here, and the log line is its only signal. +// It reports whether the session may go back to the pool; after a failure its +// state is unknown (a statement cut off mid-flight, or under @@autocommit=0 +// the implicit transaction a DOLT_ADD opened), so it may not. +func (t *doltServerTx) commitStagedTables(ctx context.Context, tables []string, message string) bool { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), scopedCommitMaxElapsed+scopedCommitGrace) + defer cancel() + + bo := backoff.NewExponentialBackOff() + bo.InitialInterval = txRetryInitialInterval + bo.MaxElapsedTime = scopedCommitMaxElapsed + var lastErr error + err := backoff.Retry(func() error { + err := t.stageAndCommitOnce(ctx, tables, message) + if err == nil { + return nil + } + lastErr = err + if isSerializationError(err) || isDoltAutocommitRollbackError(err) { + return err + } + return backoff.Permanent(err) + }, backoff.WithContext(bo, ctx)) + if err != nil && lastErr != nil && !errors.Is(err, lastErr) { + // The deadline expiring between attempts returns the bare context + // error; keep the last real failure, the only diagnostic of a dropped + // commit. + err = fmt.Errorf("%w (last attempt: %w)", err, lastErr) + } + if err != nil { + log.Printf("warning: uow: dolt commit %q failed after its SQL commit (data already committed; change rides the next dolt commit): %v", message, err) + return false + } + return true +} + +// stageAndCommitOnce is one attempt at commitStagedTables: stage each table, +// then commit the staged set alone. +func (t *doltServerTx) stageAndCommitOnce(ctx context.Context, tables []string, message string) error { + for _, table := range tables { + if err := schema.DrainCall(ctx, t.conn, "CALL DOLT_ADD(?)", table); err != nil { + return fmt.Errorf("dolt add %s: %w", table, err) + } + } + // Sessions on one branch share the working set, so a concurrent writer's + // Dolt commit can already have taken this transaction's rows under its + // own message, leaving nothing staged here: skip the empty commit Dolt + // would refuse. The same race between this check and the commit surfaces + // as "nothing to commit", which here means exactly that and not a lost + // write (the SQL COMMIT has landed), so it is no failure either; it is + // logged, as the DoltStore funnel logs it, so the missing audit line is + // explicable. + staged, err := issueops.HasStagedChanges(ctx, t.conn) + if err != nil { + return err + } + if !staged { + return nil + } + err = schema.DrainCall(ctx, t.conn, "CALL DOLT_COMMIT('-m', ?)", message) + if err != nil { + if !issueops.IsNothingToCommitError(err) { + return fmt.Errorf("dolt commit: %w", err) + } + log.Printf("uow: dolt commit %q made no dolt commit (nothing to commit): the staged change was most likely absorbed into a concurrent writer's commit (data already committed)", message) + } + return nil +} + // commitStatement picks the statement that ends the open transaction on the // pinned session for a commit named message. func (t *doltServerTx) commitStatement(ctx context.Context, message string) (string, []interface{}, error) { @@ -95,12 +252,15 @@ func (t *doltServerTx) commitStatement(ctx context.Context, message string) (str } // An empty message selects the EPHEMERAL commit form (bd-aq0ql): a plain // SQL COMMIT persists the transaction's writes into the working set - // without minting a Dolt commit or history. It has two entry points: + // without minting a Dolt commit or history. It has these entry points: // - // - uow.RunTxEphemeral, for work that touches ONLY dolt_ignored state — - // today the leases table (bd-lrgn1), whose heartbeats must never create - // commits. RunTx/RunTxResult treat an empty commitMsg as "nothing to - // commit" and never call Commit at all, so they cannot reach it that way. + // - uow.RunTxEphemeral, for work that touches ONLY dolt_ignored state. + // RunTx/RunTxResult treat an empty commitMsg as "nothing to commit" and + // never call Commit at all, so they cannot reach it that way. + // - uow.RunTxScoped, for an attempt that names no tables — a lease + // refresh (bd-lrgn1), which writes only the dolt_ignored leases table + // and must never create a commit. A heartbeat that re-arms names its + // tables instead and takes the scoped commit. // - RunTx/RunTxResult under a deferred-version-commit context, via the // blanking just above (GH#4995). There the writes are ordinary versioned // rows and the ONLY-dolt_ignored-state rationale does not apply: the diff --git a/internal/storage/uow/doltserver_tx_test.go b/internal/storage/uow/doltserver_tx_test.go index 036291ba8..b665ea1dc 100644 --- a/internal/storage/uow/doltserver_tx_test.go +++ b/internal/storage/uow/doltserver_tx_test.go @@ -20,6 +20,7 @@ import ( "testing" "github.com/DATA-DOG/go-sqlmock" + mysql "github.com/go-sql-driver/mysql" "github.com/steveyegge/beads/internal/storage/issueops" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -285,3 +286,134 @@ func TestDoltServerTxRunTxWithDeferredContextSkipsDoltCommit(t *testing.T) { require.NoError(t, mock.ExpectationsWereMet()) assert.Equal(t, 1, p.db.Stats().OpenConnections) } + +// matchHasStaged matches the staged-set check issueops.HasStagedChanges runs +// before CommitScoped's DOLT_COMMIT('-m'). +const matchHasStaged = `SELECT COUNT\(\*\) FROM dolt_status WHERE staged = 1` + +// expectScopedDoltCommit arms one attempt of CommitScoped's Dolt commit: a +// DOLT_ADD per table, the staged-set check reporting staged rows, and, when +// something is staged, a DOLT_COMMIT('-m') answering commitErr. +func expectScopedDoltCommit(mock sqlmock.Sqlmock, tables []string, staged int, message string, commitErr error) { + for _, table := range tables { + mock.ExpectQuery(`CALL DOLT_ADD\(\?\)`).WithArgs(table). + WillReturnRows(sqlmock.NewRows([]string{"status"}).AddRow(0)) + } + mock.ExpectQuery(matchHasStaged).WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(staged)) + if staged == 0 { + return + } + commit := mock.ExpectQuery(`CALL DOLT_COMMIT\('-m', \?\)`).WithArgs(message) + if commitErr != nil { + commit.WillReturnError(commitErr) + } else { + commit.WillReturnRows(sqlmock.NewRows([]string{"hash"}).AddRow("c0ffee")) + } +} + +// TestDoltServerTxCommitScopedCommitsSQLBeforeDoltCommit pins the +// LatentLabsSpace/NEXUS#92 ordering on the uow leg: CommitScoped ends the SQL +// transaction with a plain COMMIT and only then stages and Dolt-commits its +// tables, on the same pinned session. Staged inside the open transaction, +// DOLT_ADD builds the Dolt commit from the transaction's start snapshot and +// writes a concurrent writer's committed rows back to their old values. +func TestDoltServerTxCommitScopedCommitsSQLBeforeDoltCommit(t *testing.T) { + p, mock := newMockTxProvider(t) + mock.ExpectExec("START TRANSACTION").WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec(matchPlainCommit).WillReturnResult(sqlmock.NewResult(0, 0)) + expectScopedDoltCommit(mock, []string{"events", "issues"}, 2, "bd: re-arm lease x", nil) + + tx, err := p.BeginTx(context.Background()) + require.NoError(t, err) + + require.NoError(t, tx.(ScopedCommitter).CommitScoped(context.Background(), []string{"events", "issues"}, "bd: re-arm lease x")) + require.NoError(t, mock.ExpectationsWereMet(), "the SQL COMMIT must come first, then DOLT_ADD per table and DOLT_COMMIT('-m')") + assert.Equal(t, 1, p.db.Stats().OpenConnections, "a cleanly committed session may return to the pool") + require.ErrorContains(t, tx.Commit(context.Background(), ""), "already done") +} + +// TestDoltServerTxCommitScopedSwallowsAFailedDoltCommit: once the SQL COMMIT +// has landed the write is durable, so a Dolt commit that fails after it must +// not fail CommitScoped (RunTxScoped would replay a committed unit of work). +// The session, whose state the failed statement leaves unknown, is discarded. +func TestDoltServerTxCommitScopedSwallowsAFailedDoltCommit(t *testing.T) { + p, mock := newMockTxProvider(t) + mock.ExpectExec("START TRANSACTION").WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec(matchPlainCommit).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery(`CALL DOLT_ADD\(\?\)`).WithArgs("issues").WillReturnError(errors.New("dolt add exploded")) + + tx, err := p.BeginTx(context.Background()) + require.NoError(t, err) + + require.NoError(t, tx.(ScopedCommitter).CommitScoped(context.Background(), []string{"issues"}, "bd: re-arm lease x"), + "a committed write must not be reported as failed") + require.NoError(t, mock.ExpectationsWereMet(), "a failure other than a conflict is not retried") + assert.Equal(t, 0, p.db.Stats().OpenConnections, "the session must be discarded, not pooled") + require.ErrorContains(t, tx.Commit(context.Background(), ""), "already done") +} + +// TestDoltServerTxCommitScopedRetriesAConflictedDoltCommit: outside a +// transaction, a Dolt commit that conflicts with a concurrent writer is rolled +// back as an @@autocommit merge conflict (1105), not 1213, and is retried like +// one. +func TestDoltServerTxCommitScopedRetriesAConflictedDoltCommit(t *testing.T) { + p, mock := newMockTxProvider(t) + mock.ExpectExec("START TRANSACTION").WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec(matchPlainCommit).WillReturnResult(sqlmock.NewResult(0, 0)) + conflict := &mysql.MySQLError{Number: 1105, Message: "Merge conflict detected, @autocommit transaction rolled back"} + expectScopedDoltCommit(mock, []string{"issues"}, 1, "bd: re-arm lease x", conflict) + expectScopedDoltCommit(mock, []string{"issues"}, 1, "bd: re-arm lease x", nil) + + tx, err := p.BeginTx(context.Background()) + require.NoError(t, err) + + require.NoError(t, tx.(ScopedCommitter).CommitScoped(context.Background(), []string{"issues"}, "bd: re-arm lease x")) + require.NoError(t, mock.ExpectationsWereMet(), "the conflicted attempt must be staged and committed again") + assert.Equal(t, 1, p.db.Stats().OpenConnections, "a session whose retry committed may return to the pool") +} + +// TestDoltServerTxCommitScopedReturnsASerializationFailure: a serialization +// failure of the SQL COMMIT is returned for RunTxScoped to redo the whole unit +// of work, and no Dolt commit follows a COMMIT that did not land. +func TestDoltServerTxCommitScopedReturnsASerializationFailure(t *testing.T) { + p, mock := newMockTxProvider(t) + mock.ExpectExec("START TRANSACTION").WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec(matchPlainCommit).WillReturnError(&mysql.MySQLError{Number: 1213, Message: "serialization failure"}) + + tx, err := p.BeginTx(context.Background()) + require.NoError(t, err) + + err = tx.(ScopedCommitter).CommitScoped(context.Background(), []string{"issues"}, "bd: re-arm lease x") + require.True(t, isSerializationError(err), "err = %v, want the serialization failure", err) + require.NoError(t, mock.ExpectationsWereMet(), "nothing may be staged or committed after a failed COMMIT") +} + +// TestDoltServerTxCommitScopedMakesNoEmptyDoltCommit: a concurrent writer's +// Dolt commit can take this transaction's rows before its own Dolt commit +// runs, seen either before the commit (nothing staged) or by it ("nothing to +// commit"). Neither is a failure: unlike Commit's in-transaction commit, the +// rows are already committed. +func TestDoltServerTxCommitScopedMakesNoEmptyDoltCommit(t *testing.T) { + for _, tc := range []struct { + name string + staged int + commitErr error + }{ + {name: "nothing staged", staged: 0}, + {name: "nothing to commit", staged: 1, commitErr: errors.New("nothing to commit")}, + } { + t.Run(tc.name, func(t *testing.T) { + p, mock := newMockTxProvider(t) + mock.ExpectExec("START TRANSACTION").WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec(matchPlainCommit).WillReturnResult(sqlmock.NewResult(0, 0)) + expectScopedDoltCommit(mock, []string{"issues"}, tc.staged, "bd: re-arm lease x", tc.commitErr) + + tx, err := p.BeginTx(context.Background()) + require.NoError(t, err) + + require.NoError(t, tx.(ScopedCommitter).CommitScoped(context.Background(), []string{"issues"}, "bd: re-arm lease x")) + require.NoError(t, mock.ExpectationsWereMet()) + assert.Equal(t, 1, p.db.Stats().OpenConnections, "the session is clean and may return to the pool") + }) + } +} diff --git a/internal/storage/uow/dualwrite_participation_generation_contract_test.go b/internal/storage/uow/dualwrite_participation_generation_contract_test.go new file mode 100644 index 000000000..42cf07f8e --- /dev/null +++ b/internal/storage/uow/dualwrite_participation_generation_contract_test.go @@ -0,0 +1,388 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" +) + +// TestParticipationGenerationFence runs the design §16.2(b) write-fence +// contract (backend/conformance/dualwrite_participation_generation_contract.go) +// against the unit-of-work provider. Like TestDualWriteContract, this is an +// engine check rather than a second vote: all three legs share +// RecordVersionInTx's one body, and this is the only leg where the mutation's +// own commit is assembled by composition rather than opened directly against +// a *sql.DB. +func TestParticipationGenerationFence(t *testing.T) { + ctx := context.Background() + fixture := newUOWParticipationGenerationFixture(t, ctx, "pg") + + t.Run("CreateWithFlagOnStampsAValue", func(t *testing.T) { + conformance.RunParticipationGenerationCreateWithFlagOnStampsAValue(t, ctx, fixture) + }) + t.Run("CreateWithFlagOffLeavesLegacyNull", func(t *testing.T) { + conformance.RunParticipationGenerationCreateWithFlagOffLeavesLegacyNull(t, ctx, fixture) + }) + t.Run("SkipsUpdateOnLegacyRecord", func(t *testing.T) { + conformance.RunParticipationGenerationSkipsUpdateOnLegacyRecord(t, ctx, fixture) + }) + t.Run("ProceedsForPromotedRecord", func(t *testing.T) { + conformance.RunParticipationGenerationProceedsForPromotedRecord(t, ctx, fixture) + }) + t.Run("FlagOffSkipsUpdateOnParticipatingRecord", func(t *testing.T) { + conformance.RunParticipationGenerationFlagOffSkipsUpdateOnParticipatingRecord(t, ctx, fixture) + }) + t.Run("FenceIgnoresSchemaSkewHatch", func(t *testing.T) { + conformance.RunParticipationGenerationFenceIgnoresSchemaSkewHatch(t, ctx, fixture) + }) + t.Run("WispPromotionBeginsHistory", func(t *testing.T) { + conformance.RunParticipationGenerationWispPromotionBeginsHistory(t, ctx, fixture) + }) + t.Run("WispPersistenceMoveBeginsHistory", func(t *testing.T) { + conformance.RunParticipationGenerationWispPersistenceMoveBeginsHistory(t, ctx, fixture) + }) + t.Run("WispFlagClearMintsNothing", func(t *testing.T) { + conformance.RunParticipationGenerationWispFlagClearMintsNothing(t, ctx, fixture) + }) + t.Run("WispRootSquashMintsNothing", func(t *testing.T) { + conformance.RunParticipationGenerationWispRootSquashMintsNothing(t, ctx, fixture) + }) + t.Run("UnflaggedWispCreateMintsNothing", func(t *testing.T) { + conformance.RunParticipationGenerationUnflaggedWispCreateMintsNothing(t, ctx, fixture) + }) + t.Run("NoHistoryIssueCreateDeclaresParticipation", func(t *testing.T) { + conformance.RunParticipationGenerationNoHistoryIssueCreateDeclaresParticipation(t, ctx, fixture) + }) + t.Run("LegacyNoHistoryIssueStaysLegacy", func(t *testing.T) { + conformance.RunParticipationGenerationLegacyNoHistoryIssueStaysLegacy(t, ctx, fixture) + }) +} + +// TestParticipationGenerationFixtureKitIsWired is this leg's half of the +// explicit per-leg guardrail design §8.5 calls for in place of AST +// auto-discovery — see the dolt leg's TestParticipationGenerationFixtureKitIsWired +// for why the guardrail is needed even though TestEveryLegWiresEveryRoleContract's +// scan already enumerates and confirms wiring for every +// RunParticipationGenerationXxx entrypoint. +func TestParticipationGenerationFixtureKitIsWired(t *testing.T) { + ctx := context.Background() + fixture := newUOWParticipationGenerationFixture(t, ctx, "pgk") + + if fixture.SetFlag == nil { + t.Error("ParticipationGenerationFixture.SetFlag is nil") + } + if fixture.Mutate == nil { + t.Error("ParticipationGenerationFixture.Mutate is nil") + } + if fixture.MutateExisting == nil { + t.Error("ParticipationGenerationFixture.MutateExisting is nil") + } + if fixture.CreateWisp == nil { + t.Error("ParticipationGenerationFixture.CreateWisp is nil") + } + if fixture.PromoteWisp == nil { + t.Error("ParticipationGenerationFixture.PromoteWisp is nil") + } + if fixture.MovePersistent == nil { + t.Error("ParticipationGenerationFixture.MovePersistent is nil") + } + if fixture.ClearWispFlag == nil { + t.Error("ParticipationGenerationFixture.ClearWispFlag is nil") + } + if fixture.SquashWispRoot == nil { + t.Error("ParticipationGenerationFixture.SquashWispRoot is nil") + } + if fixture.CreateUnflaggedWisp == nil { + t.Error("ParticipationGenerationFixture.CreateUnflaggedWisp is nil") + } + if fixture.CreateNoHistoryIssue == nil { + t.Error("ParticipationGenerationFixture.CreateNoHistoryIssue is nil") + } + if fixture.CurrentRevision == nil { + t.Error("ParticipationGenerationFixture.CurrentRevision is nil") + } + if fixture.VersionRowCount == nil { + t.Error("ParticipationGenerationFixture.VersionRowCount is nil") + } + if fixture.ParticipationGeneration == nil { + t.Error("ParticipationGenerationFixture.ParticipationGeneration is nil") + } + if fixture.InWispsTable == nil { + t.Error("ParticipationGenerationFixture.InWispsTable is nil") + } +} + +// TestParticipationGenerationUpsertCreate pins the write fence (design +// §16.2b) on the unit-of-work create that is not CreateOnly, the default for +// bd batch, bd todo, tracker sync and mol port. That create's insert is an +// upsert, so db.Insert has to tell a new row (create-shaped mint: stamp the +// column) from an existing one the upsert resolved to (update-shaped: fenced +// when legacy). TestParticipationGenerationFence cannot see that choice: its +// Mutate is CreateOnly, and so is every served create (createParams), so no +// other leg reaches this branch at all. +// +// PromoteOverDualPresenceKeepsLegacy asks the same question of +// PromoteFromEphemeralInTx's upsert: a wisp whose id the issues plane already +// holds (GH#4455's dual presence, written the way a store corrupted before +// that fix holds it) is promoted onto that existing row. +// WispOverLegacyIssuesRowKeepsItLegacy asks it of the wisps-table half of the +// same db.Insert (bd mol port's CreateWisp): that insert never creates an +// issues row, so the only issues row its mint can reach is a twin that +// already held the id. +func TestParticipationGenerationUpsertCreate(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "pgu") + fixture := uowParticipationGenerationFixtureFor(t, provider, "pgu") + + setFlag := func(t *testing.T, enabled bool) { + t.Helper() + if err := fixture.SetFlag(ctx, enabled); err != nil { + t.Fatalf("setting versioned history to %v: %v", enabled, err) + } + } + upsert := func(t *testing.T, id, title string) { + t.Helper() + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + _, err := uw.IssueUseCase().CreateIssue(ctx, domain.CreateIssueParams{ + Issue: &types.Issue{ + ID: id, Title: title, IssueType: types.TypeTask, Status: types.StatusOpen, + }, + ExplicitID: id, + }, "actor") + return "upsert " + id, err + }); err != nil { + t.Fatalf("upsert-creating %s: %v", id, err) + } + } + requireState := func(t *testing.T, id string, wantStamped bool, wantVersions int, why string) { + t.Helper() + gen, err := fixture.ParticipationGeneration(ctx, id) + if err != nil { + t.Fatalf("reading participation_generation for %s: %v", id, err) + } + if stamped := gen != nil; stamped != wantStamped { + t.Errorf("participation_generation for %s stamped=%v, want %v: %s", id, stamped, wantStamped, why) + } + versions, err := fixture.VersionRowCount(ctx, id) + if err != nil { + t.Fatalf("counting version rows for %s: %v", id, err) + } + if versions != wantVersions { + t.Errorf("version row count for %s = %d, want %d: %s", id, versions, wantVersions, why) + } + } + + t.Run("NewRowIsCreateShaped", func(t *testing.T) { + setFlag(t, true) + id := "pgu-new" + upsert(t, id, "t-"+id) + requireState(t, id, true, 1, "an upsert that inserted the row is a create, so it stamps the column and begins the history") + }) + t.Run("LegacyRowStaysLegacy", func(t *testing.T) { + setFlag(t, false) + id := "pgu-legacy" + upsert(t, id, "t-"+id) + requireState(t, id, false, 0, "a create with history off leaves the row legacy") + setFlag(t, true) + upsert(t, id, "resynced-"+id) + requireState(t, id, false, 0, "an upsert that resolved to a legacy row is update-shaped and fenced; stamping it would promote a legacy record (R2.3)") + }) + t.Run("StampedRowMintsOnce", func(t *testing.T) { + setFlag(t, true) + id := "pgu-stamped" + upsert(t, id, "t-"+id) + upsert(t, id, "resynced-"+id) + requireState(t, id, true, 2, "an upsert that resolved to a participating row mints exactly one more version") + }) + t.Run("PromoteOverDualPresenceKeepsLegacy", func(t *testing.T) { + setFlag(t, false) + id := "pgu-dual" + if err := fixture.Mutate(ctx, id); err != nil { + t.Fatalf("creating legacy %s: %v", id, err) + } + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + _, err := uw.RawSQLUseCase().Exec(ctx, + "INSERT INTO wisps (id, title, status, priority, issue_type, ephemeral, created_at, updated_at) "+ + "SELECT id, title, status, priority, issue_type, 1, created_at, updated_at FROM issues WHERE id = ?", id) + return "plant wisp twin " + id, err + }); err != nil { + t.Fatalf("planting a wisps-table twin of %s: %v", id, err) + } + setFlag(t, true) + if err := fixture.PromoteWisp(ctx, id); err != nil { + t.Fatalf("promoting %s: %v", id, err) + } + if inWisps, err := fixture.InWispsTable(ctx, id); err != nil { + t.Fatalf("checking the wisps table for %s: %v", id, err) + } else if inWisps { + t.Fatalf("%s is still in the wisps table after its promote", id) + } + requireState(t, id, false, 0, "a promote whose upsert resolved to an existing legacy issues row is update-shaped and fenced; stamping it would promote a legacy record (R2.3)") + }) + t.Run("WispOverLegacyIssuesRowKeepsItLegacy", func(t *testing.T) { + setFlag(t, false) + id := "pgu-wisp-twin" + upsert(t, id, "t-"+id) + requireState(t, id, false, 0, "a create with history off leaves the row legacy") + setFlag(t, true) + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + _, err := uw.IssueUseCase().CreateWisp(ctx, domain.CreateIssueParams{ + Issue: &types.Issue{ + ID: id, Title: "wisp-" + id, IssueType: types.TypeTask, Status: types.StatusOpen, Ephemeral: true, + }, + ExplicitID: id, + }, "actor") + return "wisp upsert " + id, err + }); err != nil { + t.Fatalf("wisp-creating %s over its issues row: %v", id, err) + } + if inWisps, err := fixture.InWispsTable(ctx, id); err != nil { + t.Fatalf("checking the wisps table for %s: %v", id, err) + } else if !inWisps { + t.Fatalf("%s is not in the wisps table after its wisp create; the case needs both planes to hold the id", id) + } + requireState(t, id, false, 0, "a wisps-table insert never creates the issues row the seam snapshots, so its mint is update-shaped and fenced; stamping that legacy twin would promote a legacy record (R2.3)") + }) +} + +func newUOWParticipationGenerationFixture(t *testing.T, ctx context.Context, prefix string) conformance.ParticipationGenerationFixture { + t.Helper() + return uowParticipationGenerationFixtureFor(t, newUOWRoleFixtureProvider(t, ctx, prefix), prefix) +} + +// uowParticipationGenerationFixtureFor is newUOWParticipationGenerationFixture +// over a provider the caller already holds, for a test that also drives that +// provider directly. +func uowParticipationGenerationFixtureFor(t *testing.T, provider UnitOfWorkProvider, prefix string) conformance.ParticipationGenerationFixture { + t.Helper() + // Through the capability accessor's operator half, the same way + // newUOWVersionedHistoryProvider reaches it above — SetFlag here needs to + // toggle more than once per case, so this fixture keeps its own handle + // rather than fixing the flag once at construction the way + // newUOWVersionedHistoryProvider does for the dual-write fixture. + configurer, ok := provider.(storage.VersionedHistoryConfigurer) + if !ok { + t.Fatalf("provider %T does not implement storage.VersionedHistoryConfigurer", provider) + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.ParticipationGenerationFixture{ + IssuePrefix: prefix, + SetFlag: func(ctx context.Context, enabled bool) error { + configurer.SetVersionedHistoryEnabled(enabled) + return nil + }, + Mutate: func(ctx context.Context, id string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + _, err := uw.IssueUseCase().CreateIssue(ctx, domain.CreateIssueParams{ + Issue: &types.Issue{ + ID: id, Title: "t-" + id, IssueType: types.TypeTask, Status: types.StatusOpen, + }, + ExplicitID: id, + CreateOnly: true, + }, "actor") + return "create " + id, err + }) + }, + MutateExisting: func(ctx context.Context, id string) error { + // A different value than Mutate gave it, not a re-assertion of the + // same title: DiscardNoopIssueUpdates would discard the latter + // before it ever reached the fence this contract is testing. + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + return "update " + id, uw.IssueUseCase().UpdateIssue(ctx, id, + map[string]any{"title": "updated-" + id}, "actor") + }) + }, + CreateWisp: func(ctx context.Context, id string) error { + return kit.CreateWisp(ctx, &types.Issue{ + ID: id, Title: "t-" + id, IssueType: types.TypeTask, Status: types.StatusOpen, Ephemeral: true, + }, "actor") + }, + PromoteWisp: func(ctx context.Context, id string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + return "promote " + id, uw.IssueUseCase().PromoteWisp(ctx, id, "actor") + }) + }, + MovePersistent: func(ctx context.Context, id string) error { + // ApplyUpdate's persistence step, which runs MovePersistence and + // so MoveIssuePersistenceInTx's own mint, not a guarded update's. + persistent := types.PersistenceModePersistent + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + _, err := uw.IssueUseCase().ApplyUpdate(ctx, id, domain.UpdateSpec{Persistence: &persistent}, "actor") + return "move persistent " + id, err + }) + }, + ClearWispFlag: func(ctx context.Context, id string) error { + // UpdateWisp, as the molecule writer routes bd mol squash's flag + // clear for a row it found on the wisp plane. + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + return "clear wisp flag " + id, uw.IssueUseCase().UpdateWisp(ctx, id, + map[string]any{"wisp": false}, "actor") + }) + }, + SquashWispRoot: func(ctx context.Context, id string) error { + // The proxied bd mol squash's shape: CloseWisp then UpdateWisp in + // the one unit of work the squash commits. + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + if _, err := uw.IssueUseCase().CloseWisp(ctx, id, domain.CloseIssueParams{Reason: "squashed"}, "actor"); err != nil { + return "", err + } + return "squash " + id, uw.IssueUseCase().UpdateWisp(ctx, id, + map[string]any{"wisp": false}, "actor") + }) + }, + CreateUnflaggedWisp: func(ctx context.Context, id string) error { + // CreateWisp routes by the call, so neither flag is needed to land + // the row in the wisps table. + return kit.CreateWisp(ctx, &types.Issue{ + ID: id, Title: "t-" + id, IssueType: types.TypeTask, Status: types.StatusOpen, + }, "actor") + }, + CreateNoHistoryIssue: func(ctx context.Context, id string) error { + // CreateIssue routes by the call, so the NoHistory flag rides on an + // issues-table row without moving it to the wisps table. + return kit.CreateIssue(ctx, &types.Issue{ + ID: id, Title: "t-" + id, IssueType: types.TypeTask, Status: types.StatusOpen, NoHistory: true, + }, "actor") + }, + CurrentRevision: func(ctx context.Context, id string) (int64, error) { + var revision int64 + err := kit.QueryScalar(ctx, "SELECT current_revision FROM issues WHERE id = ?", []any{id}, &revision) + return revision, err + }, + VersionRowCount: func(ctx context.Context, id string) (int, error) { + var count int + err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM issue_versions WHERE issue_id = ?", []any{id}, &count) + return count, err + }, + ParticipationGeneration: func(ctx context.Context, id string) (*int64, error) { + // scanRawSQLValue refuses a NULL numeric destination outright + // (issue_operations_contract_test.go's frozen scaffolding surface, + // bd-kue5t) rather than decaying it to zero, so a bare + // participation_generation read cannot scan into *sql.NullInt64 the + // way the dolt/embeddeddolt legs' std-library Scan does. epoch is + // seeded at 1 and only ever increments (version_history.go), so a + // stamped participation_generation is always >= 1 and -1 is an + // unambiguous "still NULL" sentinel for the COALESCE. + var gen int64 + if err := kit.QueryScalar(ctx, + "SELECT COALESCE(participation_generation, -1) FROM issues WHERE id = ?", []any{id}, &gen); err != nil { + return nil, err + } + if gen == -1 { + return nil, nil + } + return &gen, nil + }, + InWispsTable: func(ctx context.Context, id string) (bool, error) { + var rows int + if err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM wisps WHERE id = ?", []any{id}, &rows); err != nil { + return false, err + } + return rows > 0, nil + }, + } +} diff --git a/internal/storage/uow/edgereader.go b/internal/storage/uow/edgereader.go index bc4e456da..f288f1bd6 100644 --- a/internal/storage/uow/edgereader.go +++ b/internal/storage/uow/edgereader.go @@ -5,6 +5,7 @@ import ( "fmt" storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" publicops "github.com/steveyegge/beads/issueops" ) @@ -51,33 +52,49 @@ func (r *edgeReader) ReadEdges(ctx context.Context, request publicops.EdgeReadRe return publicops.EdgeReadResult{Anchors: []publicops.AnchorEdges{}}, nil } return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) (publicops.EdgeReadResult, error) { - present := make(map[string]struct{}, len(anchors)) - issues, err := uw.IssueUseCase().GetIssuesByIDs(ctx, anchors) - if err != nil { - return publicops.EdgeReadResult{}, err - } - for _, issue := range issues { - if issue != nil { - present[issue.ID] = struct{}{} - } - } - wisps, err := uw.IssueUseCase().GetWispsByIDs(ctx, anchors) - if err != nil { - return publicops.EdgeReadResult{}, err - } - for _, wisp := range wisps { - if wisp != nil { - present[wisp.ID] = struct{}{} - } - } - edges, err := uw.DependencyUseCase().GetIssueDependencyRecords(ctx, anchors) - if err != nil { - return publicops.EdgeReadResult{}, err - } - // The type filter and the order run HERE rather than in the reads - // above, so both implementations narrow and order through one function; - // a filter pushed into one side's query would put the narrowing in SQL - // on one backend and in Go on the other. - return storageissueops.FinishEdgeRead(anchors, present, edges, request.Types), nil + return readEdgesInUOW(ctx, uw, anchors, request.Types) }) } + +// ReadEdgesInUOW is the EdgeReader body, run inside the caller's unit of work. +func ReadEdgesInUOW(ctx context.Context, uw UnitOfWork, request publicops.EdgeReadRequest) (publicops.EdgeReadResult, error) { + if err := storageissueops.ValidateEdgeReadRequest(request); err != nil { + return publicops.EdgeReadResult{}, err + } + anchors := storageissueops.EdgeReadAnchors(request.IDs) + if len(anchors) == 0 { + return publicops.EdgeReadResult{Anchors: []publicops.AnchorEdges{}}, nil + } + return readEdgesInUOW(ctx, uw, anchors, request.Types) +} + +func readEdgesInUOW(ctx context.Context, uw UnitOfWork, anchors []string, depTypes []types.DependencyType) (publicops.EdgeReadResult, error) { + present := make(map[string]struct{}, len(anchors)) + issues, err := uw.IssueUseCase().GetIssuesByIDs(ctx, anchors) + if err != nil { + return publicops.EdgeReadResult{}, err + } + for _, issue := range issues { + if issue != nil { + present[issue.ID] = struct{}{} + } + } + wisps, err := uw.IssueUseCase().GetWispsByIDs(ctx, anchors) + if err != nil { + return publicops.EdgeReadResult{}, err + } + for _, wisp := range wisps { + if wisp != nil { + present[wisp.ID] = struct{}{} + } + } + edges, err := uw.DependencyUseCase().GetIssueDependencyRecords(ctx, anchors) + if err != nil { + return publicops.EdgeReadResult{}, err + } + // The type filter and the order run HERE rather than in the reads + // above, so both implementations narrow and order through one function; + // a filter pushed into one side's query would put the narrowing in SQL + // on one backend and in Go on the other. + return storageissueops.FinishEdgeRead(anchors, present, edges, depTypes), nil +} diff --git a/internal/storage/uow/errors.go b/internal/storage/uow/errors.go index 217d5904e..b0323a42d 100644 --- a/internal/storage/uow/errors.go +++ b/internal/storage/uow/errors.go @@ -33,6 +33,21 @@ func isSerializationError(err error) bool { return false } +// isDoltAutocommitRollbackError reports whether err is Dolt rolling back a +// statement it ran under @@autocommit because the statement's commit-time +// merge conflicted with a concurrent writer (MySQL 1105, "Merge conflict +// detected, @autocommit transaction rolled back"). Outside an explicit +// transaction this, not 1213, is how such a conflict surfaces, and like a +// serialization failure it guarantees the statement left nothing behind. It +// mirrors the DoltStore's classifier of the same name. +func isDoltAutocommitRollbackError(err error) bool { + var mysqlErr *mysql.MySQLError + return errors.As(err, &mysqlErr) && + mysqlErr.Number == 1105 && + (mysqlErr.Message == "Merge conflict detected, @autocommit transaction rolled back" || + strings.HasPrefix(mysqlErr.Message, "Merge conflict detected, @autocommit transaction rolled back.")) +} + // isDatabaseExistsError reports whether err is the server refusing a bare // CREATE DATABASE because the database already exists (MySQL 1007, // ER_DB_CREATE_EXISTS). The message fallback matches how the rest of the diff --git a/internal/storage/uow/errors_test.go b/internal/storage/uow/errors_test.go index 0796af0ac..1a9d8ce77 100644 --- a/internal/storage/uow/errors_test.go +++ b/internal/storage/uow/errors_test.go @@ -59,6 +59,37 @@ func TestIsDatabaseNotFoundError(t *testing.T) { } } +// The DoltStore's table for its twin classifier, plus the prefix boundary: +// commitStagedTables replays exactly what this accepts, so a false positive +// re-runs a Dolt commit that failed for another reason. +func TestIsDoltAutocommitRollbackError(t *testing.T) { + exact := &mysql.MySQLError{ + Number: 1105, + Message: "Merge conflict detected, @autocommit transaction rolled back", + } + + for _, tt := range []struct { + name string + err error + want bool + }{ + {name: "nil", err: nil, want: false}, + {name: "exact typed Dolt rollback", err: fmt.Errorf("dolt commit: %w", exact), want: true}, + {name: "typed Dolt rollback with recovery guidance", err: &mysql.MySQLError{Number: 1105, Message: exact.Message + ". @autocommit must be disabled"}, want: true}, + {name: "typed text running on past the message", err: &mysql.MySQLError{Number: 1105, Message: exact.Message + "ward"}, want: false}, + {name: "untyped matching text", err: errors.New(exact.Error()), want: false}, + {name: "other typed 1105", err: &mysql.MySQLError{Number: 1105, Message: "Merge conflict detected"}, want: false}, + {name: "typed connection-like 1105", err: &mysql.MySQLError{Number: 1105, Message: "connection lost while validating commit"}, want: false}, + {name: "same text wrong code", err: &mysql.MySQLError{Number: 1213, Message: exact.Message}, want: false}, + } { + t.Run(tt.name, func(t *testing.T) { + if got := isDoltAutocommitRollbackError(tt.err); got != tt.want { + t.Fatalf("isDoltAutocommitRollbackError(%v) = %t, want %t", tt.err, got, tt.want) + } + }) + } +} + func TestClassifyUseDatabaseError(t *testing.T) { // The exact server errors observed from dolt 2.1.8 against a credential // granted only one database. diff --git a/internal/storage/uow/expected_revision_contract_test.go b/internal/storage/uow/expected_revision_contract_test.go index 53f17947d..a1ccfa1b4 100644 --- a/internal/storage/uow/expected_revision_contract_test.go +++ b/internal/storage/uow/expected_revision_contract_test.go @@ -8,11 +8,21 @@ import ( ) // TestExpectedRevisionContract wires this leg into the R16/R17 -// expected-revision contract. Phase 0 leaves every hook nil in every -// backend's fixture kit (architecture §12), so each case below skips by -// name; this file exists so TestEveryLegWiresEveryRoleContract counts this -// leg, and so the cases start running for real the moment this leg's fixture -// kit grows a non-nil hook. +// expected-revision contract. Every hook is nil (architecture §12's Phase 0 +// default), so each case below skips by name; this file exists so +// TestEveryLegWiresEveryRoleContract counts this leg, and so the cases +// start running for real the moment this leg grows a real +// CompareAndSetVersion (gastownhall/beads#6358). +// +// This leg previously wired every hook to an honest "not implemented" stub +// instead of leaving them nil, so each case ran for real and +// failed for that documented reason rather than skipping. That premise — +// that a later slice would give this leg its CompareAndSetVersion — went +// stale once review moved the real implementation to +// gastownhall/beads#6358 instead; a stub whose failure message blames a +// bead that will never land it is worse than an honest skip, so this file +// reverts to nil hooks (gastownhall/beads#6664, bee-ghosttrack review +// 5268699223). func TestExpectedRevisionContract(t *testing.T) { ctx := context.Background() fixture := conformance.ExpectedRevisionFixture{IssuePrefix: "erev"} diff --git a/internal/storage/uow/heartbeater.go b/internal/storage/uow/heartbeater.go new file mode 100644 index 000000000..75151c829 --- /dev/null +++ b/internal/storage/uow/heartbeater.go @@ -0,0 +1,84 @@ +package uow + +import ( + "context" + "fmt" + + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + publicops "github.com/steveyegge/beads/issueops" +) + +// HeartbeaterSource is the capability accessor a unit-of-work provider offers +// for the lease-refresh role, the sibling of LeaseReclaimerSource. +type HeartbeaterSource interface { + Heartbeater() (publicops.Heartbeater, error) +} + +// heartbeater refreshes a held lease through a unit of work. +type heartbeater struct { + provider UnitOfWorkProvider +} + +// Heartbeater returns the lease-refresh surface for this provider. +func (p *doltSQLProvider) Heartbeater() (publicops.Heartbeater, error) { + return NewHeartbeater(p) +} + +// NewHeartbeater constructs a public Heartbeater backed by provider. +func NewHeartbeater(provider UnitOfWorkProvider) (publicops.Heartbeater, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new heartbeater: unit-of-work provider must not be nil") + } + return &heartbeater{provider: provider}, nil +} + +var _ publicops.Heartbeater = (*heartbeater)(nil) + +// Heartbeat reaches domain.IssueUseCase.RenewLease inside ONE unit of work. A +// refresh touches only the dolt_ignored leases table, so it mints no Dolt +// commit and records nothing in dolt_log; a re-arm is recorded as a mutation +// and commits like one. A serialization loser (a heartbeat racing a reclaim, +// release or close) is replayed against a fresh unit of work. +// +// VALIDATION HAPPENS BEFORE THE UNIT OF WORK OPENS, as on the dolt and +// embedded-dolt legs: a refusal then costs no connection. The shared body +// validates again inside the transaction. +func (h *heartbeater) Heartbeat(ctx context.Context, request publicops.HeartbeatRequest) (publicops.HeartbeatResult, error) { + if err := storageissueops.ValidateHeartbeatRequest(request); err != nil { + return publicops.HeartbeatResult{}, err + } + // A lease refusal commits (it may have deleted an orphaned lease row) and + // is reported after the commit; see HeartbeatRefusalCommits. + // + // THE COMMIT IS SCOPED (RunTxScoped). A refresh or a refusal writes only + // the dolt_ignored leases table and commits with the plain SQL COMMIT: no + // working-set scan, no Dolt commit, and so nothing another writer left + // uncommitted (a batch-mode edit) is swept into a heartbeat commit. A + // re-arm is recorded as a mutation and commits exactly the tables + // LeaseRearmVersionCommit names, never DOLT_COMMIT('-Am'), in a Dolt + // commit made after the SQL COMMIT (ScopedCommitter): built inside the + // transaction, it would write an issues row a concurrent writer changed + // meanwhile back to its value at this heartbeat's start. + type outcome struct { + result publicops.HeartbeatResult + refusal error + } + out, err := RunTxScoped(ctx, h.provider, func(ctx context.Context, uw UnitOfWork) (outcome, []string, string, error) { + result, err := uw.IssueUseCase().RenewLease(ctx, request) + if storageissueops.HeartbeatRefusalCommits(err) { + return outcome{refusal: err}, nil, "", nil + } + if err != nil { + return outcome{}, nil, "", err + } + tables, msg := storageissueops.LeaseRearmVersionCommit(request.IssueID, result.Rearmed) + return outcome{result: result}, tables.Sorted(), msg, nil + }) + if err != nil { + return publicops.HeartbeatResult{}, err + } + if out.refusal != nil { + return publicops.HeartbeatResult{}, out.refusal + } + return out.result, nil +} diff --git a/internal/storage/uow/heartbeater_contract_test.go b/internal/storage/uow/heartbeater_contract_test.go new file mode 100644 index 000000000..6148049d6 --- /dev/null +++ b/internal/storage/uow/heartbeater_contract_test.go @@ -0,0 +1,339 @@ +package uow + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + + "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// TestHeartbeaterContract runs the Heartbeater contract against the +// unit-of-work provider, which reaches internal/storage/issueops. +// ExecuteHeartbeatInTx through domain.IssueUseCase.RenewLease inside one unit +// of work committed with RunTxScoped: the SQL-only form for a refresh, the +// scoped commit for a re-arm. +func TestHeartbeaterContract(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + fixture := newUOWHeartbeaterFixture(t, ctx, "hbc") + t.Run("RefreshesTheHoldersLease", func(t *testing.T) { + conformance.RunHeartbeaterRefreshesTheHoldersLease(t, ctx, fixture) + }) + t.Run("ChangesNothingOnTheRow", func(t *testing.T) { + conformance.RunHeartbeaterChangesNothingOnTheRow(t, ctx, fixture) + }) + t.Run("AGuardedWriteWithThePreHeartbeatRevisionStillWins", func(t *testing.T) { + conformance.RunHeartbeaterAGuardedWriteWithThePreHeartbeatRevisionStillWins(t, ctx, fixture) + }) + t.Run("RefusesAForeignHolder", func(t *testing.T) { + conformance.RunHeartbeaterRefusesAForeignHolder(t, ctx, fixture) + }) + t.Run("RefusesAfterClose", func(t *testing.T) { + conformance.RunHeartbeaterRefusesAfterClose(t, ctx, fixture) + }) + t.Run("RefusesAfterRelease", func(t *testing.T) { + conformance.RunHeartbeaterRefusesAfterRelease(t, ctx, fixture) + }) + t.Run("RefusesAfterReclaim", func(t *testing.T) { + conformance.RunHeartbeaterRefusesAfterReclaim(t, ctx, fixture) + }) + t.Run("RefusesAfterStatusMovedOffInProgress", func(t *testing.T) { + conformance.RunHeartbeaterRefusesAfterStatusMovedOffInProgress(t, ctx, fixture) + }) + t.Run("RefusesAWisp", func(t *testing.T) { + conformance.RunHeartbeaterRefusesAWisp(t, ctx, fixture) + }) + t.Run("RearmsAHandDoledClaim", func(t *testing.T) { + conformance.RunHeartbeaterRearmsAHandDoledClaim(t, ctx, fixture) + }) + t.Run("AnswersNotFoundForAnAbsentID", func(t *testing.T) { + conformance.RunHeartbeaterAnswersNotFoundForAnAbsentID(t, ctx, fixture) + }) + t.Run("RefusesABlankOrOverLongActor", func(t *testing.T) { + conformance.RunHeartbeaterRefusesABlankOrOverLongActor(t, ctx, fixture) + }) + t.Run("DoesNotMutateTheRequest", func(t *testing.T) { + conformance.RunHeartbeaterDoesNotMutateTheRequest(t, ctx, fixture) + }) + t.Run("CommitsOnlyItsOwnTables", func(t *testing.T) { + conformance.RunHeartbeaterCommitsOnlyItsOwnTables(t, ctx, fixture) + }) + t.Run("ASameSecondHeartbeatIsNotARearm", func(t *testing.T) { + conformance.RunHeartbeaterASameSecondHeartbeatIsNotARearm(t, ctx, fixture) + }) + t.Run("RefusesAnOrphanedLeaseOnAReleasedIssue", func(t *testing.T) { + conformance.RunHeartbeaterRefusesAnOrphanedLeaseOnAReleasedIssue(t, ctx, fixture) + }) + t.Run("RefusesAnOrphanedLeaseOnAClosedIssue", func(t *testing.T) { + conformance.RunHeartbeaterRefusesAnOrphanedLeaseOnAClosedIssue(t, ctx, fixture) + }) + t.Run("RefusesAnOrphanedLeaseOnAnIssueSomeoneElseHolds", func(t *testing.T) { + conformance.RunHeartbeaterRefusesAnOrphanedLeaseOnAnIssueSomeoneElseHolds(t, ctx, fixture) + }) +} + +// TestHeartbeaterRearmKeepsAConcurrentWrite is the LatentLabsSpace/NEXUS#92 +// regression for the re-arm's scoped commit: another session commits a change +// to a different issues row while the re-arm's transaction is open, and the +// Dolt commit the re-arm makes must stage issues as committed, with that +// change in it, not as the re-arm's start snapshot. DOLT_ADD stages a whole +// table from the session's transaction root, so staging inside the open +// transaction did the latter: HEAD then disagreed with the rows every reader +// sees, for a write still only in the working set (batch mode, or the window +// before the writer's own Dolt commit). ScopedCommitter commits the SQL +// transaction first. +func TestHeartbeaterRearmKeepsAConcurrentWrite(t *testing.T) { + ctx := t.Context() + const prefix = "hbw" + provider := newUOWRoleFixtureProvider(t, ctx, prefix) + kit := newUOWRoleFixtureKit(provider, prefix) + lifecycle, err := provider.(IssueLifecycleSource).IssueLifecycle() + if err != nil { + t.Fatalf("IssueLifecycle(): %v", err) + } + const holder = "hb-holder" + for _, tc := range []struct { + name string + write func(ctx context.Context, id, title string) error + }{ + {"a write with its own dolt commit", func(ctx context.Context, id, title string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + _, err := uw.RawSQLUseCase().Exec(ctx, "UPDATE issues SET title = ? WHERE id = ?", title, id) + return "bd: retitle " + id, err + }) + }}, + {"a write only in the working set", func(ctx context.Context, id, title string) error { + _, err := RunTxEphemeral(ctx, provider, func(ctx context.Context, uw UnitOfWork) (struct{}, error) { + _, err := uw.RawSQLUseCase().Exec(ctx, "UPDATE issues SET title = ? WHERE id = ?", title, id) + return struct{}{}, err + }) + return err + }}, + } { + t.Run(tc.name, func(t *testing.T) { + suffix := strings.ReplaceAll(tc.name, " ", "-") + doled, bystander := prefix+"-doled-"+suffix, prefix+"-bystander-"+suffix + for _, id := range []string{doled, bystander} { + issue := &types.Issue{ID: id, Title: "seed " + id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := kit.CreateIssue(ctx, issue, "seeder"); err != nil { + t.Fatalf("seed %s: %v", id, err) + } + } + if _, err := lifecycle.Update(ctx, publicops.UpdateRequest{ + Actor: holder, IssueID: doled, + Patch: publicops.IssuePatch{ + Status: publicops.Field[publicops.Status]{Set: true, Value: types.StatusInProgress}, + Assignee: publicops.Field[string]{Set: true, Value: holder}, + }, + }); err != nil { + t.Fatalf("hand-dole %s: %v", doled, err) + } + + const retitled = "retitled while the re-arm was open" + wrote := false + heartbeater, err := NewHeartbeater(&beforeScopedCommitProvider{ + UnitOfWorkProvider: provider, + before: func(ctx context.Context) error { + if wrote { + return nil + } + wrote = true + return tc.write(ctx, bystander, retitled) + }, + }) + if err != nil { + t.Fatalf("NewHeartbeater: %v", err) + } + result, err := heartbeater.Heartbeat(ctx, publicops.HeartbeatRequest{Actor: holder, IssueID: doled}) + if err != nil { + t.Fatalf("Heartbeat: %v", err) + } + if !result.Rearmed || !wrote { + t.Fatalf("result = %+v, concurrent write ran = %v: the case needs a re-arm with a write inside its window", result, wrote) + } + + for _, at := range []string{"the working set", "HEAD"} { + query := "SELECT title FROM issues WHERE id = ?" + if at == "HEAD" { + query = "SELECT title FROM issues AS OF 'HEAD' WHERE id = ?" + } + var title string + if err := kit.QueryScalar(ctx, query, []any{bystander}, &title); err != nil { + t.Fatalf("read %s title at %s: %v", bystander, at, err) + } + if title != retitled { + t.Errorf("%s title at %s = %q, want %q: the re-arm's Dolt commit staged issues from its start snapshot", bystander, at, title, retitled) + } + } + // The re-arm itself is committed: its reminted row_lock is at HEAD + // (events is dolt_ignored, so the issues row is what its commit + // carries). + var working, head int64 + if err := kit.QueryScalar(ctx, "SELECT row_lock FROM issues WHERE id = ?", []any{doled}, &working); err != nil { + t.Fatalf("read %s row_lock: %v", doled, err) + } + if err := kit.QueryScalar(ctx, "SELECT row_lock FROM issues AS OF 'HEAD' WHERE id = ?", []any{doled}, &head); err != nil { + t.Fatalf("read %s row_lock at HEAD: %v", doled, err) + } + var commits int + if err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM dolt_log WHERE message = ?", []any{"bd: re-arm lease " + doled}, &commits); err != nil { + t.Fatalf("count re-arm commits: %v", err) + } + if head != working || commits != 1 { + t.Errorf("%s row_lock at HEAD = %d (working set %d), re-arm commits = %d, want the re-arm in one Dolt commit", doled, head, working, commits) + } + }) + } +} + +// beforeScopedCommitProvider runs before ahead of each scoped commit of the +// units of work it opens: a way into the window between a transaction's +// writes and its commit. +type beforeScopedCommitProvider struct { + UnitOfWorkProvider + before func(context.Context) error +} + +func (p *beforeScopedCommitProvider) NewUOW(ctx context.Context) (UnitOfWork, error) { + uw, err := p.UnitOfWorkProvider.NewUOW(ctx) + if err != nil { + return nil, err + } + return &beforeScopedCommitUOW{UnitOfWork: uw, before: p.before}, nil +} + +type beforeScopedCommitUOW struct { + UnitOfWork + before func(context.Context) error +} + +func (u *beforeScopedCommitUOW) Unwrap() UnitOfWork { return u.UnitOfWork } + +func (u *beforeScopedCommitUOW) CommitScoped(ctx context.Context, tables []string, message string) error { + if err := u.before(ctx); err != nil { + return err + } + return commitScoped(ctx, u.UnitOfWork, tables, message) +} + +// TestHeartbeaterRefusesBeforeOpeningAUOW: a malformed heartbeat is a +// deterministic validation failure and must not cost a database connection to +// discover, as on the dolt and embedded-dolt legs. +func TestHeartbeaterRefusesBeforeOpeningAUOW(t *testing.T) { + for _, tc := range []struct { + name string + request publicops.HeartbeatRequest + }{ + {"no actor", publicops.HeartbeatRequest{IssueID: "x"}}, + {"no id", publicops.HeartbeatRequest{Actor: "worker"}}, + } { + t.Run(tc.name, func(t *testing.T) { + provider := &mockUnitOfWorkProvider{newUOWErr: errors.New("unexpected unit-of-work open")} + heartbeater, err := NewHeartbeater(provider) + if err != nil { + t.Fatalf("NewHeartbeater: %v", err) + } + if _, err := heartbeater.Heartbeat(context.Background(), tc.request); !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("err = %v, want ErrValidation", err) + } + if provider.newUOWCalls != 0 { + t.Errorf("an invalid request opened %d units of work", provider.newUOWCalls) + } + }) + } +} + +// newUOWHeartbeaterFixture takes every role through the provider's own +// capability accessors, and the hooked heartbeater off the notifying provider +// the proxied CLI route wraps around its provider. +func newUOWHeartbeaterFixture(t *testing.T, ctx context.Context, prefix string) conformance.HeartbeaterFixture { + t.Helper() + provider := newUOWRoleFixtureProvider(t, ctx, prefix) + source, ok := provider.(HeartbeaterSource) + if !ok { + t.Fatalf("provider %T does not offer the Heartbeater accessor", provider) + } + heartbeater, err := source.Heartbeater() + if err != nil { + t.Fatalf("Heartbeater(): %v", err) + } + claimer, err := provider.(IssueClaimerSource).IssueClaimer() + if err != nil { + t.Fatalf("IssueClaimer(): %v", err) + } + lifecycle, err := provider.(IssueLifecycleSource).IssueLifecycle() + if err != nil { + t.Fatalf("IssueLifecycle(): %v", err) + } + releaser, err := provider.(ReleaserSource).Releaser() + if err != nil { + t.Fatalf("Releaser(): %v", err) + } + reclaimer, err := provider.(LeaseReclaimerSource).LeaseReclaimer() + if err != nil { + t.Fatalf("LeaseReclaimer(): %v", err) + } + configurer, ok := provider.(storage.EventsJournalConfigurer) + if !ok { + t.Fatalf("provider %T does not implement storage.EventsJournalConfigurer", provider) + } + versionConfigurer, ok := provider.(storage.VersionedHistoryConfigurer) + if !ok { + t.Fatalf("provider %T does not implement storage.VersionedHistoryConfigurer", provider) + } + runner, fired := conformance.NewUpdateHookLog(t) + hooked := heartbeater + if runner != nil { + notifying, ok := NewNotifyingProvider(provider, Sinks{Hook: runner}).(HeartbeaterSource) + if !ok { + t.Fatal("the notifying provider does not offer the Heartbeater accessor") + } + if hooked, err = notifying.Heartbeater(); err != nil { + t.Fatalf("hooked Heartbeater(): %v", err) + } + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.HeartbeaterFixture{ + IssuePrefix: kit.IssuePrefix, + Heartbeater: heartbeater, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + Claimer: claimer, + Lifecycle: lifecycle, + Releaser: releaser, + LeaseReclaimer: reclaimer, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + ExecUncommitted: func(ctx context.Context, statements []conformance.SQLStatement) error { + _, err := RunTxEphemeral(ctx, provider, func(ctx context.Context, uw UnitOfWork) (struct{}, error) { + for _, stmt := range statements { + if _, err := uw.RawSQLUseCase().Exec(ctx, stmt.Query, stmt.Args...); err != nil { + return struct{}{}, fmt.Errorf("%s: %w", stmt.Query, err) + } + } + return struct{}{}, nil + }) + return err + }, + Exec: func(ctx context.Context, statements []conformance.SQLStatement) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + for _, stmt := range statements { + if _, err := uw.RawSQLUseCase().Exec(ctx, stmt.Query, stmt.Args...); err != nil { + return "", fmt.Errorf("%s: %w", stmt.Query, err) + } + } + return "seed heartbeater rows", nil + }) + }, + SetJournalEnabled: configurer.SetEventsJournalEnabled, + SetVersionedHistoryEnabled: versionConfigurer.SetVersionedHistoryEnabled, + HookedHeartbeater: hooked, + FiredUpdates: fired, + } +} diff --git a/internal/storage/uow/history_off_differential_test.go b/internal/storage/uow/history_off_differential_test.go new file mode 100644 index 000000000..aabe0eefe --- /dev/null +++ b/internal/storage/uow/history_off_differential_test.go @@ -0,0 +1,92 @@ +package uow + +import ( + "context" + "testing" + "time" + + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/storage/historyoffequiv" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// TestVersionedHistoryOffMatchesPreStackGolden_UOW is the unit-of-work leg's +// versioned-history flag-off differential (internal/storage/historyoffequiv): +// on a provider whose versioned history was never turned on, the scripted +// mutation set must leave every table as the code before the +// versioned-history stack left it, apart from that stack's new columns and +// table staying NULL and empty. +// +// Beyond the shared role scenario this leg drives the domain create that +// leaves CreateOnly unset (the quick, todo and batch proxied servers' path): +// it is an upsert, and the stack gave it an existence probe that must not run +// while history is off (see TestInsertUpsertWithHistoryOffIssuesThePreStackStatements +// in domain/db). The importer role's upsert of an existing row runs too. +func TestVersionedHistoryOffMatchesPreStackGolden_UOW(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, historyoffequiv.Prefix) + roles, ok := provider.(historyoffequiv.Roles) + if !ok { + t.Fatalf("provider %T does not offer every role the scenario drives", provider) + } + fixedAt := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC) + issue := func(id, title string) *types.Issue { + return &types.Issue{ID: id, Title: title, Description: "about " + id, Status: types.StatusOpen, + Priority: 2, IssueType: types.TypeTask, CreatedAt: fixedAt, UpdatedAt: fixedAt} + } + domainCreate := func(wisp bool, is *types.Issue) func(context.Context) error { + return func(ctx context.Context) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + params := domain.CreateIssueParams{Issue: is, ExplicitID: is.ID} + var err error + if wisp { + _, err = uw.IssueUseCase().CreateWisp(ctx, params, "uma") + } else { + _, err = uw.IssueUseCase().CreateIssue(ctx, params, "uma") + } + return "bd: create " + is.ID, err + }) + } + } + historyoffequiv.Run(t, historyoffequiv.Leg{ + Name: "uow", + Roles: roles, + Wake: func(ctx context.Context) error { + _, err := WakeExpiredDefers(ctx, provider) + return err + }, + Extra: []historyoffequiv.Step{ + {Name: "domain upsert new u1", Run: domainCreate(false, issue("ho-u1", "uniform one"))}, + {Name: "domain upsert existing u1", Run: domainCreate(false, issue("ho-u1", "uniform one again"))}, + {Name: "domain upsert new wisp uw", Run: domainCreate(true, issue("ho-uw", "uniform wisp"))}, + {Name: "domain upsert existing wisp uw", Run: domainCreate(true, issue("ho-uw", "uniform wisp again"))}, + {Name: "import upsert u1 and new u2", Run: func(ctx context.Context) error { + importer, err := provider.(interface { + Importer() (publicops.Importer, error) + }).Importer() + if err != nil { + return err + } + u1 := issue("ho-u1", "uniform one imported") + u1.UpdatedAt = fixedAt.Add(time.Hour) + u2 := issue("ho-u2", "uniform two") + u2.Labels = []string{"imported"} + u2.Dependencies = []*types.Dependency{{IssueID: "ho-u2", DependsOnID: "ho-u1", Type: types.DepBlocks, CreatedAt: fixedAt}} + u2.Comments = []*types.Comment{{ID: "ho-u2-comment", IssueID: "ho-u2", Author: "importer", Text: "imported", CreatedAt: fixedAt}} + _, err = importer.ImportBatch(ctx, publicops.ImportBatchRequest{Actor: "importer", + Issues: []*types.Issue{u1, u2}, SkipPrefixValidation: true}) + return err + }}, + }, + Query: func(ctx context.Context, query string) ([][]*string, error) { + return RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) ([][]*string, error) { + result, err := uw.RawSQLUseCase().Query(ctx, query) + if err != nil { + return nil, err + } + return historyoffequiv.AnyRows(result.Rows), nil + }) + }, + }) +} diff --git a/internal/storage/uow/issue_operations.go b/internal/storage/uow/issue_operations.go index c0f3451d8..18ba064c4 100644 --- a/internal/storage/uow/issue_operations.go +++ b/internal/storage/uow/issue_operations.go @@ -231,6 +231,9 @@ func (o *issueOperations) Update(ctx context.Context, request publicops.UpdateRe // version and status before authorizing, so when one is stale the fence // stands down and ApplyUpdate reports the mismatch instead. if updatePreconditionsHold(attempt, before) { + if err := storageissueops.AuthorizeTemplateUpdate(before, attempt); err != nil { + return publicops.UpdateResult{}, "", err + } if err := authorizeAssigneeTransfer(ctx, uw, before, attempt); err != nil { return publicops.UpdateResult{}, "", err } @@ -310,6 +313,9 @@ func updateSpec(request publicops.UpdateRequest) (domain.UpdateSpec, error) { setField(fields, "acceptance_criteria", patch.AcceptanceCriteria) setField(fields, "spec_id", patch.SpecID) setField(fields, "await_id", patch.AwaitID) + if patch.Waiters.Set { + fields["waiters"] = storageissueops.PatchWaiters(patch.Waiters) + } setField(fields, "status", patch.Status) setField(fields, "priority", patch.Priority) if patch.IssueType.Set { @@ -437,8 +443,15 @@ func (o *issueOperations) Close(ctx context.Context, request publicops.CloseRequ if err != nil { return publicops.CloseResult{}, "", err } - return publicops.CloseResult{Issue: hydrated, Changed: !semanticIssueEqual(before, hydrated), OpenChildren: closed.OpenChildren}, - "close issue", nil + result := publicops.CloseResult{Issue: hydrated, Changed: !semanticIssueEqual(before, hydrated), OpenChildren: closed.OpenChildren} + if attempt.AutoCloseMolecule { + auto, err := CloseCompletedMoleculeInUOW(ctx, uw, attempt.IssueID, attempt.Actor, attempt.Session) + if err != nil { + return publicops.CloseResult{}, "", err + } + result.AutoClosedMolecule, result.MoleculeAutoCloseRefusal = auto.Root, auto.Refusal + } + return result, "close issue", nil }) } diff --git a/internal/storage/uow/issue_operations_claim_contract_test.go b/internal/storage/uow/issue_operations_claim_contract_test.go index c4c84067b..9ecc081a2 100644 --- a/internal/storage/uow/issue_operations_claim_contract_test.go +++ b/internal/storage/uow/issue_operations_claim_contract_test.go @@ -289,7 +289,7 @@ func TestBatchRunUpdateIdempotentClaimAcrossSpellingReportsNoChange(t *testing.T result, err := run.runUpdate(context.Background(), publicops.UpdateRequest{ Actor: "gastown.mayor", IssueID: "bd-1", Claim: true, - }) + }, true) if err != nil { t.Fatalf("runUpdate: %v, want success (same identity, different separator spelling)", err) } @@ -307,7 +307,7 @@ func TestBatchRunUpdateClaimByGenuinelyDifferentIdentityReportsAChange(t *testin result, err := run.runUpdate(context.Background(), publicops.UpdateRequest{ Actor: "gastown.dog-3", IssueID: "bd-1", Claim: true, - }) + }, true) if err != nil { t.Fatalf("runUpdate: %v", err) } diff --git a/internal/storage/uow/issue_reader.go b/internal/storage/uow/issue_reader.go index 5f9bcc147..8c62b8779 100644 --- a/internal/storage/uow/issue_reader.go +++ b/internal/storage/uow/issue_reader.go @@ -122,7 +122,7 @@ func (r *issueReader) List(ctx context.Context, req publicops.ListRequest) (publ if req.ReadyFlag { page, err = uw.IssueUseCase().GetReadyWorkWithCounts(ctx, workapi.ReadyFilterFromIssueFilter(filter)) } else { - page, err = uw.IssueUseCase().SearchIssuesWithCounts(ctx, "", filter) + page, err = uw.IssueUseCase().SearchIssuesWithCounts(ctx, req.Query, filter) } if err != nil { return publicops.IssuePage{}, err diff --git a/internal/storage/uow/lease_reclaimer.go b/internal/storage/uow/lease_reclaimer.go new file mode 100644 index 000000000..1cc522c6b --- /dev/null +++ b/internal/storage/uow/lease_reclaimer.go @@ -0,0 +1,60 @@ +package uow + +import ( + "context" + "fmt" + + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + publicops "github.com/steveyegge/beads/issueops" +) + +// LeaseReclaimerSource is the capability accessor a unit-of-work provider +// offers for the lease-sweep role, the sibling of DeleterSource and +// ReleaserSource. +type LeaseReclaimerSource interface { + LeaseReclaimer() (publicops.LeaseReclaimer, error) +} + +// leaseReclaimer sweeps stale leases through a unit of work. +type leaseReclaimer struct { + provider UnitOfWorkProvider +} + +// LeaseReclaimer returns the guarded lease-sweep surface for this provider. +func (p *doltSQLProvider) LeaseReclaimer() (publicops.LeaseReclaimer, error) { + return NewLeaseReclaimer(p) +} + +// NewLeaseReclaimer constructs a public LeaseReclaimer backed by provider. +func NewLeaseReclaimer(provider UnitOfWorkProvider) (publicops.LeaseReclaimer, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new lease reclaimer: unit-of-work provider must not be nil") + } + return &leaseReclaimer{provider: provider}, nil +} + +var _ publicops.LeaseReclaimer = (*leaseReclaimer)(nil) + +// Reclaim reaches domain.IssueUseCase.Reclaim inside ONE committing unit of +// work, composing the same conditional commit message the dolt and +// embedded-dolt legs use: a sweep that reverts nothing leaves no history +// entry describing a no-op. +// +// VALIDATION HAPPENS BEFORE THE UNIT OF WORK OPENS, as on those two legs and +// for Releaser's reason: a refusal then changes nothing on the connection as +// well as on the rows. The shared body validates again inside the transaction, +// which is what keeps a leg that skipped this from answering a different +// contract. +func (l *leaseReclaimer) Reclaim(ctx context.Context, request publicops.ReclaimRequest) (publicops.ReclaimResult, error) { + if err := storageissueops.ValidateReclaimRequest(request); err != nil { + return publicops.ReclaimResult{}, err + } + return RunTxResult(ctx, l.provider, func(ctx context.Context, uw UnitOfWork) (publicops.ReclaimResult, string, error) { + result, err := uw.IssueUseCase().Reclaim(ctx, request) + if err != nil { + return result, "", err + } + _, msg := storageissueops.ReclaimVersionCommit(result) + return result, msg, nil + }) +} diff --git a/internal/storage/uow/lease_reclaimer_contract_test.go b/internal/storage/uow/lease_reclaimer_contract_test.go new file mode 100644 index 000000000..edcda454a --- /dev/null +++ b/internal/storage/uow/lease_reclaimer_contract_test.go @@ -0,0 +1,146 @@ +package uow + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/steveyegge/beads/backend/conformance" + publicops "github.com/steveyegge/beads/issueops" +) + +// TestLeaseReclaimerContract runs the LeaseReclaimer contract against the +// unit-of-work provider, which reaches internal/storage/issueops. +// ExecuteReclaimInTx through domain.IssueUseCase.Reclaim inside one committing +// unit of work. +func TestLeaseReclaimerContract(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + fixture := newUOWLeaseReclaimerFixture(t, ctx, "lrc") + + t.Run("RevertsAStaleLease", func(t *testing.T) { + conformance.RunLeaseReclaimerRevertsAStaleLease(t, ctx, fixture) + }) + t.Run("MintsARevisionThatFencesTheFormerHolder", func(t *testing.T) { + conformance.RunLeaseReclaimerMintsARevisionThatFencesTheFormerHolder(t, ctx, fixture) + }) + t.Run("LeavesALiveLeaseAlone", func(t *testing.T) { + conformance.RunLeaseReclaimerLeavesALiveLeaseAlone(t, ctx, fixture) + }) + t.Run("HonorsTheGraceWindow", func(t *testing.T) { + conformance.RunLeaseReclaimerHonorsTheGraceWindow(t, ctx, fixture) + }) + t.Run("ScopesToTheNamedIDs", func(t *testing.T) { + conformance.RunLeaseReclaimerScopesToTheNamedIDs(t, ctx, fixture) + }) + t.Run("AnswersAnAbsentIDWithAnEmptyResult", func(t *testing.T) { + conformance.RunLeaseReclaimerAnswersAnAbsentIDWithAnEmptyResult(t, ctx, fixture) + }) + t.Run("ScopesToAssigneesAndLabels", func(t *testing.T) { + conformance.RunLeaseReclaimerScopesToAssigneesAndLabels(t, ctx, fixture) + }) + t.Run("AttributesTheRecoveryEvent", func(t *testing.T) { + conformance.RunLeaseReclaimerAttributesTheRecoveryEvent(t, ctx, fixture) + }) + t.Run("FiresOnUpdateOncePerReclaimedRow", func(t *testing.T) { + conformance.RunLeaseReclaimerFiresOnUpdateOncePerReclaimedRow(t, ctx, fixture) + }) + t.Run("RefusesAMalformedRequest", func(t *testing.T) { + conformance.RunLeaseReclaimerRefusesAMalformedRequest(t, ctx, fixture) + }) + t.Run("RefusesABlankScopeEntry", func(t *testing.T) { + conformance.RunLeaseReclaimerRefusesABlankScopeEntry(t, ctx, fixture) + }) + t.Run("AcceptsExactlyTheCap", func(t *testing.T) { + conformance.RunLeaseReclaimerAcceptsExactlyTheCap(t, ctx, fixture) + }) + t.Run("DoesNotMutateTheCallerRequest", func(t *testing.T) { + conformance.RunLeaseReclaimerDoesNotMutateTheCallerRequest(t, ctx, fixture) + }) +} + +// TestLeaseReclaimerRefusesBeforeOpeningAUOW: a malformed sweep is a +// deterministic validation failure and must not cost a database connection to +// discover, as on the dolt and embedded-dolt legs. The provider fails every +// open, so a refusal that came from inside a unit of work would be counted. +func TestLeaseReclaimerRefusesBeforeOpeningAUOW(t *testing.T) { + for _, tc := range []struct { + name string + request publicops.ReclaimRequest + }{ + {"no actor", publicops.ReclaimRequest{}}, + {"a negative grace window", publicops.ReclaimRequest{Actor: "reaper", OlderThan: -1}}, + {"a blank id", publicops.ReclaimRequest{Actor: "reaper", Filter: publicops.ReclaimFilter{IDs: []string{""}}}}, + } { + t.Run(tc.name, func(t *testing.T) { + provider := &mockUnitOfWorkProvider{newUOWErr: errors.New("unexpected unit-of-work open")} + reclaimer, err := NewLeaseReclaimer(provider) + if err != nil { + t.Fatalf("NewLeaseReclaimer: %v", err) + } + if _, err := reclaimer.Reclaim(context.Background(), tc.request); !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("err = %v, want ErrValidation", err) + } + if provider.newUOWCalls != 0 { + t.Errorf("an invalid request opened %d units of work", provider.newUOWCalls) + } + }) + } +} + +// newUOWLeaseReclaimerFixture takes every role through the provider's own +// capability accessors, and the hooked reclaimer off the notifying provider +// the proxied CLI route wraps around its provider. +func newUOWLeaseReclaimerFixture(t *testing.T, ctx context.Context, prefix string) conformance.LeaseReclaimerFixture { + t.Helper() + provider := newUOWRoleFixtureProvider(t, ctx, prefix) + source, ok := provider.(LeaseReclaimerSource) + if !ok { + t.Fatalf("provider %T does not offer the LeaseReclaimer accessor", provider) + } + reclaimer, err := source.LeaseReclaimer() + if err != nil { + t.Fatalf("LeaseReclaimer(): %v", err) + } + claimer, err := provider.(IssueClaimerSource).IssueClaimer() + if err != nil { + t.Fatalf("IssueClaimer(): %v", err) + } + lifecycle, err := provider.(IssueLifecycleSource).IssueLifecycle() + if err != nil { + t.Fatalf("IssueLifecycle(): %v", err) + } + runner, fired := conformance.NewUpdateHookLog(t) + hooked := reclaimer + if runner != nil { + notifying, ok := NewNotifyingProvider(provider, Sinks{Hook: runner}).(LeaseReclaimerSource) + if !ok { + t.Fatal("the notifying provider does not offer the LeaseReclaimer accessor") + } + if hooked, err = notifying.LeaseReclaimer(); err != nil { + t.Fatalf("hooked LeaseReclaimer(): %v", err) + } + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.LeaseReclaimerFixture{ + IssuePrefix: kit.IssuePrefix, + LeaseReclaimer: reclaimer, + CreateIssue: kit.CreateIssue, + Claimer: claimer, + Lifecycle: lifecycle, + QueryScalar: kit.QueryScalar, + Exec: func(ctx context.Context, statements []conformance.SQLStatement) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + for _, stmt := range statements { + if _, err := uw.RawSQLUseCase().Exec(ctx, stmt.Query, stmt.Args...); err != nil { + return "", fmt.Errorf("%s: %w", stmt.Query, err) + } + } + return "seed lease reclaimer rows", nil + }) + }, + HookedLeaseReclaimer: hooked, + FiredUpdates: fired, + } +} diff --git a/internal/storage/uow/lifecycle_close_reopen_contract_test.go b/internal/storage/uow/lifecycle_close_reopen_contract_test.go index 0282aa3d2..9a77a7f95 100644 --- a/internal/storage/uow/lifecycle_close_reopen_contract_test.go +++ b/internal/storage/uow/lifecycle_close_reopen_contract_test.go @@ -63,6 +63,9 @@ func TestLifecycleCloseReopenContract(t *testing.T) { t.Run("ResultsAreHydratedPostStateSnapshots", func(t *testing.T) { conformance.RunLifecycleResultsAreHydratedPostStateSnapshots(t, ctx, fixture) }) + t.Run("ResultsCarryThePostWriteRowVersion", func(t *testing.T) { + conformance.RunLifecycleResultsCarryThePostWriteRowVersion(t, ctx, fixture) + }) t.Run("CloseAndReopenRequireActorAndIssueID", func(t *testing.T) { conformance.RunLifecycleCloseAndReopenRequireActorAndIssueID(t, ctx, fixture) }) @@ -78,6 +81,9 @@ func TestLifecycleCloseReopenContract(t *testing.T) { t.Run("ReopenReblocksItsDependers", func(t *testing.T) { conformance.RunLifecycleReopenReblocksItsDependers(t, ctx, fixture) }) + t.Run("CloseEnforcesTheCloseGuards", func(t *testing.T) { + conformance.RunLifecycleCloseEnforcesTheCloseGuards(t, ctx, fixture) + }) } func newUOWLifecycleCloseReopenFixture(t *testing.T, ctx context.Context, prefix string) conformance.LifecycleCloseReopenFixture { diff --git a/internal/storage/uow/lifecycle_create_contract_test.go b/internal/storage/uow/lifecycle_create_contract_test.go index 19e1d16b5..c1028dcfd 100644 --- a/internal/storage/uow/lifecycle_create_contract_test.go +++ b/internal/storage/uow/lifecycle_create_contract_test.go @@ -40,6 +40,15 @@ func TestLifecycleCreateContract(t *testing.T) { t.Run("EchoesSubSecondTimestamps", func(t *testing.T) { conformance.RunLifecycleCreateEchoesSubSecondTimestamps(t, ctx, fixture) }) + t.Run("AppliesTheDefaultPriority", func(t *testing.T) { + conformance.RunLifecycleCreateAppliesTheDefaultPriority(t, ctx, fixture) + }) + t.Run("WritesTheGateMembers", func(t *testing.T) { + conformance.RunLifecycleCreateWritesTheGateMembers(t, ctx, fixture) + }) + t.Run("BoundsTheGateMembers", func(t *testing.T) { + conformance.RunLifecycleCreateBoundsTheGateMembers(t, ctx, fixture) + }) } func newUOWLifecycleCreateFixture(t *testing.T, ctx context.Context, prefix string) conformance.LifecycleCreateFixture { diff --git a/internal/storage/uow/lifecycle_update_contract_test.go b/internal/storage/uow/lifecycle_update_contract_test.go index e635e5fbd..1861abb57 100644 --- a/internal/storage/uow/lifecycle_update_contract_test.go +++ b/internal/storage/uow/lifecycle_update_contract_test.go @@ -53,6 +53,18 @@ func TestLifecycleUpdateContract(t *testing.T) { t.Run("ConditionalGuardsGateOrdinaryEdits", func(t *testing.T) { conformance.RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits(t, ctx, fixture) }) + t.Run("ExpectedVersionSingleWinnerUnderConcurrency", func(t *testing.T) { + conformance.RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency(t, ctx, fixture) + }) + t.Run("ExpectedVersionSingleWinnerWithDisjointColumnsUnderConcurrency", func(t *testing.T) { + conformance.RunLifecycleUpdateExpectedVersionSingleWinnerWithDisjointColumnsUnderConcurrency(t, ctx, fixture) + }) + t.Run("CloseExpectedVersionSingleWinnerUnderConcurrency", func(t *testing.T) { + conformance.RunLifecycleCloseExpectedVersionSingleWinnerUnderConcurrency(t, ctx, fixture) + }) + t.Run("ExpectedVersionSingleWinnerAcrossUpdateAndCloseUnderConcurrency", func(t *testing.T) { + conformance.RunLifecycleUpdateExpectedVersionSingleWinnerAcrossUpdateAndCloseUnderConcurrency(t, ctx, fixture) + }) t.Run("ConditionalGuardAcceptsRespelledAssignee", func(t *testing.T) { conformance.RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee(t, ctx, fixture) }) @@ -77,9 +89,27 @@ func TestLifecycleUpdateContract(t *testing.T) { t.Run("PersistentPreservesUnversionedClass", func(t *testing.T) { conformance.RunLifecycleUpdatePersistentPreservesUnversionedClass(t, ctx, fixture) }) + t.Run("WispModesRefuseAnUnversionedRow", func(t *testing.T) { + conformance.RunLifecycleUpdateWispModesRefuseAnUnversionedRow(t, ctx, fixture) + }) + t.Run("PersistentPromotesAWisp", func(t *testing.T) { + conformance.RunLifecycleUpdatePersistentPromotesAWisp(t, ctx, fixture) + }) t.Run("ProvenanceLabelsHistory", func(t *testing.T) { conformance.RunLifecycleUpdateProvenanceLabelsHistory(t, ctx, fixture) }) + t.Run("RefusesATemplate", func(t *testing.T) { + conformance.RunLifecycleUpdateRefusesATemplate(t, ctx, fixture) + }) + t.Run("AllowTemplateEditsATemplate", func(t *testing.T) { + conformance.RunLifecycleUpdateAllowTemplateEditsATemplate(t, ctx, fixture) + }) + t.Run("PatchesTheGateMembers", func(t *testing.T) { + conformance.RunLifecycleUpdatePatchesTheGateMembers(t, ctx, fixture) + }) + t.Run("BoundsTheGateMembers", func(t *testing.T) { + conformance.RunLifecycleUpdateBoundsTheGateMembers(t, ctx, fixture) + }) } func newUOWLifecycleUpdateFixture(t *testing.T, ctx context.Context, prefix string) conformance.LifecycleUpdateFixture { diff --git a/internal/storage/uow/memories.go b/internal/storage/uow/memories.go index fc5040881..3b8120468 100644 --- a/internal/storage/uow/memories.go +++ b/internal/storage/uow/memories.go @@ -88,11 +88,16 @@ func (m *memories) Recall(ctx context.Context, req memoryops.RecallRequest) (mem return memoryops.RecallResult{}, err } return RunTxRead(ctx, m.provider, func(ctx context.Context, uw UnitOfWork) (memoryops.RecallResult, error) { - value, err := uw.ConfigUseCase().GetConfig(ctx, storagememoryops.StorageKey(key)) + // The same whole-table probe as Remember, for the reason given there: + // Found is about the ROW, GetConfig answers "" for a missing row and an + // empty one alike, and the map's key set is the only place the + // difference survives. It is one query on a table of tens of rows. + all, err := uw.ConfigUseCase().GetAllConfig(ctx) if err != nil { return memoryops.RecallResult{}, err } - return memoryops.RecallResult{Key: key, Value: value, Found: value != ""}, nil + value, found := all[storagememoryops.StorageKey(key)] + return memoryops.RecallResult{Key: key, Value: value, Found: found}, nil }) } @@ -111,11 +116,14 @@ func (m *memories) Forget(ctx context.Context, req memoryops.ForgetRequest) (mem storageKey := storagememoryops.StorageKey(key) result, err := RunTxResult(ctx, m.provider, func(ctx context.Context, uw UnitOfWork) (memoryops.ForgetResult, string, error) { cfg := uw.ConfigUseCase() - previous, err := cfg.GetConfig(ctx, storageKey) + // The row probe Remember and Recall use: gating on GetConfig's "" is + // what left a memory stored empty unforgettable. + all, err := cfg.GetAllConfig(ctx) if err != nil { return memoryops.ForgetResult{}, "", err } - if previous == "" { + previous, found := all[storageKey] + if !found { return memoryops.ForgetResult{Key: key}, "", nil } if err := cfg.DeleteConfig(ctx, storageKey); err != nil { diff --git a/internal/storage/uow/memories_contract_test.go b/internal/storage/uow/memories_contract_test.go index 9725f306a..85865a199 100644 --- a/internal/storage/uow/memories_contract_test.go +++ b/internal/storage/uow/memories_contract_test.go @@ -56,8 +56,8 @@ func TestMemoriesContract(t *testing.T) { t.Run("RecallReportsAMissAsNotFoundNotAnError", func(t *testing.T) { conformance.RunMemoriesRecallReportsAMissAsNotFoundNotAnError(t, ctx, fixture) }) - t.Run("RecallConflatesStoredEmptyWithAbsent", func(t *testing.T) { - conformance.RunMemoriesRecallConflatesStoredEmptyWithAbsent(t, ctx, fixture) + t.Run("EmptyRowIsPresentUntilForgotten", func(t *testing.T) { + conformance.RunMemoriesEmptyRowIsPresentUntilForgotten(t, ctx, fixture) }) t.Run("ForgetRemovesExactlyTheNamedRow", func(t *testing.T) { conformance.RunMemoriesForgetRemovesExactlyTheNamedRow(t, ctx, fixture) diff --git a/internal/storage/uow/molecule.go b/internal/storage/uow/molecule.go new file mode 100644 index 000000000..859130e5b --- /dev/null +++ b/internal/storage/uow/molecule.go @@ -0,0 +1,182 @@ +package uow + +import ( + "context" + "fmt" + "strconv" + + "github.com/steveyegge/beads/internal/storage/domain" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + publicops "github.com/steveyegge/beads/issueops" +) + +// MoleculeReaderInUOW binds the molecule rules (issueops.MoleculeReader) to a +// caller's unit of work: the SAME BatchGetter, Relations and EdgeReader bodies +// this backend's roles run (GetManyInUOW, RelatedInUOW, ReadEdgesInUOW), +// against uw, so a close that decides whether it completed a molecule reads +// the state its own writes produced. It is this backend's twin of +// internal/storage/issueops.TxMoleculeReader. +func MoleculeReaderInUOW(uw UnitOfWork) publicops.MoleculeReader { + return publicops.MoleculeReaderOver(uowMoleculeReader{uw: uw}) +} + +type uowMoleculeReader struct{ uw UnitOfWork } + +func (r uowMoleculeReader) GetMany(ctx context.Context, request publicops.GetManyRequest) (publicops.GetManyResult, error) { + return GetManyInUOW(ctx, r.uw, request) +} + +func (r uowMoleculeReader) Related(ctx context.Context, request publicops.RelatedRequest) ([]*publicops.RelatedIssue, error) { + if err := storageissueops.ValidateRelatedRequest(request); err != nil { + return nil, err + } + return RelatedInUOW(ctx, r.uw, request) +} + +func (r uowMoleculeReader) ReadEdges(ctx context.Context, request publicops.EdgeReadRequest) (publicops.EdgeReadResult, error) { + return ReadEdgesInUOW(ctx, r.uw, request) +} + +// CloseCompletedMoleculeInUOW is CloseRequest.AutoCloseMolecule's body for +// this backend: CloseCompletedMoleculesInUOW for one step. +func CloseCompletedMoleculeInUOW(ctx context.Context, uw UnitOfWork, stepID, actor, session string) (storageissueops.MoleculeAutoClose, error) { + autos, err := CloseCompletedMoleculesInUOW(ctx, uw, []string{stepID}, actor, session) + if err != nil { + return storageissueops.MoleculeAutoClose{}, err + } + return autos[0], nil +} + +// CloseCompletedMoleculesInUOW is CloseBatchRequest.AutoCloseMolecule's body +// for this backend, the twin of storageissueops.CloseCompletedMoleculesInTx: +// for every auto-closing molecule root a close of stepIDs could have completed +// (issueops.AutoClosingMoleculeRoots read in uw), it rewrites the root's +// coordination cell (storageissueops.MoleculeCoordinationKey, so two units of +// work deciding the same root conflict at commit and the retry reads the +// other's close; the cost, serialized sibling closes, is +// storageissueops.TouchMoleculeCoordinationInTx's), and when every step under +// the root is now closed (issueops.MoleculeStepsClosed) it closes the root in +// uw — unforced, guarded on the root revision read in the same unit of work, +// recording issueops.MoleculeAutoCloseReason and session. +// +// It answers one MoleculeAutoClose per step id, in order: each root is decided +// once and reported on the first step under it. A refusal of the root +// (issueops.IsMoleculeAutoCloseRefusal) is answered as the Refusal and leaves +// the root untouched; the caller's own closes stand. Any other failure is +// returned and fails the caller's unit of work. +func CloseCompletedMoleculesInUOW(ctx context.Context, uw UnitOfWork, stepIDs []string, actor, session string) ([]storageissueops.MoleculeAutoClose, error) { + reader := MoleculeReaderInUOW(uw) + roots, err := publicops.AutoClosingMoleculeRoots(ctx, reader, stepIDs) + if err != nil { + return nil, err + } + autos := make([]storageissueops.MoleculeAutoClose, len(stepIDs)) + decided := make(map[string]bool, len(roots)) + for i, stepID := range stepIDs { + root := roots[stepID] + if root == nil || decided[root.ID] { + continue + } + decided[root.ID] = true + auto, err := closeCompletedMoleculeRootInUOW(ctx, uw, reader, root, actor, session) + if err != nil { + return nil, err + } + autos[i] = auto + } + return autos, nil +} + +func closeCompletedMoleculeRootInUOW(ctx context.Context, uw UnitOfWork, reader publicops.MoleculeReader, root *publicops.Issue, actor, session string) (storageissueops.MoleculeAutoClose, error) { + // storageissueops.TouchMoleculeCoordinationInTx, through this unit of work. + touch := strconv.FormatInt(storageissueops.FreshRowLock(), 10) + if err := uw.ConfigUseCase().SetLocalMetadata(ctx, storageissueops.MoleculeCoordinationKey(root.ID), touch); err != nil { + return storageissueops.MoleculeAutoClose{}, fmt.Errorf("touch molecule coordination for %s: %w", root.ID, err) + } + complete, err := publicops.MoleculeStepsClosed(ctx, reader, root.ID) + if err != nil || !complete { + return storageissueops.MoleculeAutoClose{}, err + } + req := publicops.MoleculeRootClose(root, actor, session) + // A probe, not a write: an UpdateSpec with no Fields applies nothing. It + // only checks the root's revision against req.ExpectedVersion, the guard + // the close below does not take itself. + if _, err := uw.IssueUseCase().ApplyUpdate(ctx, req.IssueID, domain.UpdateSpec{ExpectedVersion: req.ExpectedVersion}, req.Actor); err != nil { + if publicops.IsMoleculeAutoCloseRefusal(err) { + return storageissueops.RefusedMoleculeAutoClose(err), nil + } + return storageissueops.MoleculeAutoClose{}, fmt.Errorf("auto-closing molecule %s: %w", root.ID, err) + } + params := domain.CloseIssueParams{Reason: req.Reason, Session: req.Session} + var closed domain.CloseIssueResult + if storageissueops.IsWisp(root) { + closed, err = uw.IssueUseCase().CloseWispChecked(ctx, req.IssueID, params, req.Actor, req.Force) + } else { + closed, err = uw.IssueUseCase().CloseIssueChecked(ctx, req.IssueID, params, req.Actor, req.Force) + } + if publicops.IsMoleculeAutoCloseRefusal(err) { + return storageissueops.RefusedMoleculeAutoClose(err), nil + } + if err != nil { + return storageissueops.MoleculeAutoClose{}, fmt.Errorf("auto-closing molecule %s: %w", root.ID, err) + } + if !closed.Closed { + return storageissueops.MoleculeAutoClose{}, nil + } + current := root + if closed.Issue != nil { + current = closed.Issue + } + hydrated, err := hydrateIssueOperation(ctx, uw, current, false, false) + if err != nil { + return storageissueops.MoleculeAutoClose{}, err + } + return storageissueops.MoleculeAutoClose{Root: hydrated}, nil +} + +// MoleculeStepperSource is the capability accessor a unit-of-work provider +// offers for the advance-a-molecule role. +type MoleculeStepperSource interface { + MoleculeStepper() (publicops.MoleculeStepper, error) +} + +// MoleculeStepper returns the advance-a-molecule surface for this provider. +func (p *doltSQLProvider) MoleculeStepper() (publicops.MoleculeStepper, error) { + return NewMoleculeStepper(p) +} + +// NewMoleculeStepper is issueops.NewMoleculeStepper composed over the roles +// THIS provider builds (its batch getter, relations, edge reader, claimer and +// lifecycle), so a wrapper that builds its roles over itself — the notifying +// provider, a policy decorator, the server's timed provider — gets an advance +// whose every read and claim goes through its own layer. +func NewMoleculeStepper(provider UnitOfWorkProvider) (publicops.MoleculeStepper, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new molecule stepper: unit-of-work provider must not be nil") + } + getter, err := NewBatchGetter(provider) + if err != nil { + return nil, err + } + relations, err := NewIssueRelations(provider) + if err != nil { + return nil, err + } + edges, err := NewEdgeReader(provider) + if err != nil { + return nil, err + } + claimer, err := NewIssueClaimer(provider) + if err != nil { + return nil, err + } + lifecycle, err := NewIssueOperations(provider) + if err != nil { + return nil, err + } + return publicops.NewMoleculeStepper(publicops.MoleculeStepperRoles{ + Reader: publicops.MoleculeReader{BatchGetter: getter, Relations: relations, EdgeReader: edges}, + Claimer: claimer, + Lifecycle: lifecycle, + }), nil +} diff --git a/internal/storage/uow/molecule_contract_test.go b/internal/storage/uow/molecule_contract_test.go new file mode 100644 index 000000000..a4ea4c1ff --- /dev/null +++ b/internal/storage/uow/molecule_contract_test.go @@ -0,0 +1,257 @@ +package uow + +import ( + "context" + "fmt" + "sync" + "testing" + + "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// TestMoleculeContract runs the molecule contract against the unit-of-work +// backend, whose auto-close body (CloseCompletedMoleculeInUOW) is its own and +// whose stepper is composed over this provider's roles. One provider for the +// suite; sequential subtests namespaced by prefix. +func TestMoleculeContract(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "mol") + fixture := newUOWMoleculeFixture(t, provider, "mol") + + for _, test := range []struct { + name string + run func(*testing.T, context.Context, conformance.MoleculeFixture) + }{ + {"CloseAutoClosesTheCompletedRoot", conformance.RunMoleculeCloseAutoClosesTheCompletedRoot}, + {"AutoCloseIsOptInAndRuleBound", conformance.RunMoleculeAutoCloseIsOptInAndRuleBound}, + {"RecloseHealsAStrandedRoot", conformance.RunMoleculeRecloseHealsAStrandedRoot}, + {"BatchCloseAutoClosesTheRootOnce", conformance.RunMoleculeBatchCloseAutoClosesTheRootOnce}, + {"RefusedRootKeepsTheStepClose", conformance.RunMoleculeRefusedRootKeepsTheStepClose}, + {"GuardedRootKeepsTheStepClose", conformance.RunMoleculeGuardedRootKeepsTheStepClose}, + {"StepperClaimsTheNextReadyStepForTheActor", conformance.RunMoleculeStepperClaimsTheNextReadyStepForTheActor}, + {"StepperNeverTakesAStepAnotherActorHolds", conformance.RunMoleculeStepperNeverTakesAStepAnotherActorHolds}, + {"StepperAnswersCompleteAndOutsideAMolecule", conformance.RunMoleculeStepperAnswersCompleteAndOutsideAMolecule}, + {"StepperClaimsAWispStep", conformance.RunMoleculeStepperClaimsAWispStep}, + } { + t.Run(test.name, func(t *testing.T) { test.run(t, ctx, fixture) }) + } +} + +func newUOWMoleculeFixture(t *testing.T, provider UnitOfWorkProvider, prefix string) conformance.MoleculeFixture { + t.Helper() + lifecycle, err := NewIssueOperations(provider) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + closer, err := NewBatchCloser(provider) + if err != nil { + t.Fatalf("NewBatchCloser: %v", err) + } + source, ok := provider.(MoleculeStepperSource) + if !ok { + t.Fatalf("provider %T does not offer the MoleculeStepper accessor", provider) + } + stepper, err := source.MoleculeStepper() + if err != nil { + t.Fatalf("MoleculeStepper(): %v", err) + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.MoleculeFixture{ + IssuePrefix: kit.IssuePrefix, + Lifecycle: lifecycle, + BatchCloser: closer, + Stepper: stepper, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + QueryScalar: kit.QueryScalar, + } +} + +// seedRacingMoleculeInUOW seeds an auto-closing molecule root with n open +// steps through kit and answers the steps. +func seedRacingMoleculeInUOW(t *testing.T, ctx context.Context, kit roleFixtureKit, root string, n int) []string { + t.Helper() + if err := kit.CreateIssue(ctx, &types.Issue{ID: root, Title: "molecule " + root, IssueType: types.TypeMolecule, Status: types.StatusOpen, Priority: 2}, "tester"); err != nil { + t.Fatalf("seed %s: %v", root, err) + } + steps := make([]string, n) + for i := range steps { + steps[i] = fmt.Sprintf("%s.%d", root, i+1) + if err := kit.CreateIssue(ctx, &types.Issue{ID: steps[i], Title: "step " + steps[i], IssueType: types.TypeTask, Status: types.StatusOpen, Priority: 2}, "tester"); err != nil { + t.Fatalf("seed %s: %v", steps[i], err) + } + if err := kit.AddDependency(ctx, &types.Dependency{IssueID: steps[i], DependsOnID: root, Type: types.DepParentChild}, "tester"); err != nil { + t.Fatalf("seed edge %s -> %s: %v", steps[i], root, err) + } + } + return steps +} + +func readStatusInUOW(t *testing.T, ctx context.Context, kit roleFixtureKit, id string) string { + t.Helper() + var status string + if err := kit.QueryScalar(ctx, "SELECT status FROM issues WHERE id = ?", []any{id}, &status); err != nil { + t.Fatalf("read %s status: %v", id, err) + } + return status +} + +// closeTwoStepsInRacingUOWs closes steps[0] and steps[1], each followed by +// this backend's auto-close body (CloseCompletedMoleculeInUOW), in two units +// of work that both decide before either commits, so each reads the other's +// step open: the race's interleaving, made deterministic. Neither may +// auto-close the root. It commits both and answers the two commit errors. +func closeTwoStepsInRacingUOWs(t *testing.T, ctx context.Context, provider UnitOfWorkProvider, steps []string) [2]error { + t.Helper() + var uws [2]UnitOfWork + for i := range uws { + uw, err := provider.NewUOW(ctx) + if err != nil { + t.Fatalf("open unit of work %d: %v", i, err) + } + defer uw.Close(ctx) // no-op after Commit; preserves cleanup on early Fatal. + uws[i] = uw + } + for i, uw := range uws { + if _, err := uw.IssueUseCase().CloseIssueChecked(ctx, steps[i], domain.CloseIssueParams{Reason: "done"}, "tester", false); err != nil { + t.Fatalf("close %s: %v", steps[i], err) + } + auto, err := CloseCompletedMoleculeInUOW(ctx, uw, steps[i], "tester", "") + if err != nil { + t.Fatalf("auto-close after %s: %v", steps[i], err) + } + if auto.Root != nil { + t.Fatalf("close %s auto-closed %s, but in its own unit of work %s is still open", steps[i], auto.Root.ID, steps[1-i]) + } + } + return [2]error{uws[0].Commit(ctx, "close "+steps[0]), uws[1].Commit(ctx, "close "+steps[1])} +} + +// TestMoleculeAutoCloseLastStepsCannotBothMissTheRootInUOW is the unit-of-work +// twin of the dolt store's two-transaction regression: two units of work that +// each close one of a molecule's last two open steps and run this backend's +// auto-close body (CloseCompletedMoleculeInUOW) each read the other's step +// open, so neither closes the root. The coordination cell both rewrite must +// make one commit conflict, or the complete molecule's root is stranded open. +func TestMoleculeAutoCloseLastStepsCannotBothMissTheRootInUOW(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "molrace") + kit := newUOWRoleFixtureKit(provider, "molrace") + root := kit.IssuePrefix + "-race" + + commitErrs := closeTwoStepsInRacingUOWs(t, ctx, provider, seedRacingMoleculeInUOW(t, ctx, kit, root, 2)) + t.Logf("last-step commits: %v", commitErrs) + if commitErrs[0] == nil && commitErrs[1] == nil { + t.Fatalf("stranded molecule: both last-step closes committed and %s is %s with every step closed; one unit of work must conflict", + root, readStatusInUOW(t, ctx, kit, root)) + } + for i, err := range commitErrs { + if err != nil && !isSerializationError(err) { + t.Fatalf("commit %d error = %v, want a serialization conflict", i, err) + } + } +} + +// TestMoleculeAutoCloseSiblingClosesConflictBeforeTheLastStepInUOW is the +// unit-of-work twin of the dolt store's pin on the coordination cell's cost: +// two concurrent sibling closes under an open auto-closing root conflict even +// while a third step keeps the molecule from completing. If this stops +// conflicting, the docs that state the cost are stale. +func TestMoleculeAutoCloseSiblingClosesConflictBeforeTheLastStepInUOW(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "molsib") + kit := newUOWRoleFixtureKit(provider, "molsib") + + commitErrs := closeTwoStepsInRacingUOWs(t, ctx, provider, seedRacingMoleculeInUOW(t, ctx, kit, kit.IssuePrefix+"-siblings", 3)) + t.Logf("sibling commits: %v", commitErrs) + if commitErrs[0] == nil && commitErrs[1] == nil { + t.Fatal("two concurrent sibling closes under an open auto-closing root both committed; want one serialization conflict") + } + for i, err := range commitErrs { + if err != nil && !isSerializationError(err) { + t.Fatalf("commit %d error = %v, want a serialization conflict", i, err) + } + } +} + +// raceMoleculeClosesInUOW seeds an auto-closing molecule of n steps under +// root and closes every step at once through lifecycle, whose RunTxResult +// replays each unit of work that loses the coordination conflict. Every close +// must land, and the root must end closed, reported by exactly one of them. +func raceMoleculeClosesInUOW(t *testing.T, ctx context.Context, kit roleFixtureKit, lifecycle publicops.Lifecycle, root string, n int) { + t.Helper() + steps := seedRacingMoleculeInUOW(t, ctx, kit, root, n) + var ( + start = make(chan struct{}) + wg sync.WaitGroup + results = make([]publicops.CloseResult, n) + errs = make([]error, n) + ) + for i, step := range steps { + wg.Add(1) + go func() { + defer wg.Done() + <-start + results[i], errs[i] = lifecycle.Close(ctx, publicops.CloseRequest{ + Actor: "tester", IssueID: step, Reason: "done", AutoCloseMolecule: true, + }) + }() + } + close(start) + wg.Wait() + + reported := 0 + for i, err := range errs { + if err != nil { + t.Fatalf("close %s: %v", steps[i], err) + } + if results[i].AutoClosedMolecule != nil { + reported++ + } + } + if status := readStatusInUOW(t, ctx, kit, root); status != string(types.StatusClosed) { + t.Fatalf("%s is %s after all %d of its steps closed, want closed", root, status, n) + } + if reported != 1 { + t.Errorf("%s was reported by %d closes, want exactly one", root, reported) + } +} + +// TestMoleculeAutoCloseConcurrentLastStepsCloseTheRootInUOW races the closes +// of a molecule's last two steps through this backend's Lifecycle role, whose +// RunTxResult replays the unit of work that loses the coordination conflict: +// in every round the root ends closed, reported by exactly one of the closes. +func TestMoleculeAutoCloseConcurrentLastStepsCloseTheRootInUOW(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "molagg") + kit := newUOWRoleFixtureKit(provider, "molagg") + lifecycle, err := NewIssueOperations(provider) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + + const rounds = 8 + for round := range rounds { + raceMoleculeClosesInUOW(t, ctx, kit, lifecycle, fmt.Sprintf("%s-race-%d", kit.IssuePrefix, round), 2) + } +} + +// TestMoleculeAutoCloseSiblingFanOutClosesTheRootInUOW is the unit-of-work +// twin of the dolt store's fan-out: all the steps of one molecule closed at +// once serialize on the root's coordination cell, and RunTxResult carries +// every one of them to a commit, closing the root exactly once. +func TestMoleculeAutoCloseSiblingFanOutClosesTheRootInUOW(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "molfan") + kit := newUOWRoleFixtureKit(provider, "molfan") + lifecycle, err := NewIssueOperations(provider) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + + raceMoleculeClosesInUOW(t, ctx, kit, lifecycle, kit.IssuePrefix+"-fanout", 6) +} diff --git a/internal/storage/uow/notifying.go b/internal/storage/uow/notifying.go index d61b68529..a2148502d 100644 --- a/internal/storage/uow/notifying.go +++ b/internal/storage/uow/notifying.go @@ -31,8 +31,8 @@ // # Where this plumbing deliberately differs from the DoltStorage one // // Every per-verb firing rule below is matched 1:1 against the decorator that -// implements it (each override cites its twin). These five are the exceptions, -// and they are listed here rather than argued in five places: +// implements it (each override cites its twin). These four are the exceptions, +// and they are listed here rather than argued in four places: // // 1. LABEL MULTIPLICITY ON CREATE. The DoltStorage chain replays a legacy // sequence for a create that carries labels: on_create with the labels @@ -61,16 +61,7 @@ // that writes nothing; the DoltStorage plumbing passes the precondition // into the close. See specWrites. // -// 5. THE PROMOTION COMMENT. `bd promote` records an audit comment on the -// promoted issue, and this plumbing's one comment verb fires on_update for -// it. The DoltStorage route writes that comment through the legacy -// AddComment, which the decorator wraps only INSIDE a transaction -// (hookTrackingTransaction.AddComment) and not at the store level, where -// promote calls it — so an embedded promote fires nothing. One verb cannot -// tell which caller it is serving, and "a comment landed" is the on_update -// this vocabulary has. -// -// A sixth is not a divergence but is worth stating: a unit of work whose commit +// A fifth is not a divergence but is worth stating: a unit of work whose commit // message is empty is ROLLED BACK by RunTxResult, and a rolled-back attempt // fires nothing — so a write that lands nothing reports nothing, on both // plumbings. @@ -238,6 +229,14 @@ func (p *notifyingProvider) GraphCounter() (publicops.GraphCounter, error) { return NewGraphCounter(p) } +func (p *notifyingProvider) BatchGetter() (publicops.BatchGetter, error) { + return NewBatchGetter(p) +} + +func (p *notifyingProvider) MoleculeStepper() (publicops.MoleculeStepper, error) { + return NewMoleculeStepper(p) +} + func (p *notifyingProvider) Counter() (publicops.Counter, error) { return NewCounter(p) } func (p *notifyingProvider) ReadyCounter() (publicops.ReadyCounter, error) { @@ -305,6 +304,24 @@ func (p *notifyingProvider) MetadataCAS() (publicops.MetadataCAS, error) { retur func (p *notifyingProvider) Releaser() (publicops.Releaser, error) { return NewReleaser(p) } +func (p *notifyingProvider) LeaseReclaimer() (publicops.LeaseReclaimer, error) { + return NewLeaseReclaimer(p) +} + +// Heartbeater builds the lease refresh over THIS provider. recordingIssueUC +// declares RenewLease: a refresh records nothing (it writes only the +// ephemeral lease row), and a re-arm records an update, the hook +// storage.HookFiringStore.Heartbeater fires for it on the DoltStorage chain. +func (p *notifyingProvider) Heartbeater() (publicops.Heartbeater, error) { + return NewHeartbeater(p) +} + +// BlockedLister builds the blocked listing over THIS provider. It is a read: +// nothing is recorded and no hook fires. +func (p *notifyingProvider) BlockedLister() (publicops.BlockedLister, error) { + return NewBlockedLister(p) +} + func (p *notifyingProvider) Memories() (memoryops.Memories, error) { return NewMemories(p) } // EventsJournalCursor builds on THIS provider, like every role above it, so a @@ -400,6 +417,8 @@ var ( _ BlockingAnnotatorSource = (*notifyingProvider)(nil) _ TreeWalkerSource = (*notifyingProvider)(nil) _ GraphCounterSource = (*notifyingProvider)(nil) + _ BatchGetterSource = (*notifyingProvider)(nil) + _ MoleculeStepperSource = (*notifyingProvider)(nil) _ CounterSource = (*notifyingProvider)(nil) _ ReadyCounterSource = (*notifyingProvider)(nil) _ ReadyClaimerSource = (*notifyingProvider)(nil) @@ -418,6 +437,9 @@ var ( _ WorkspaceConfigSource = (*notifyingProvider)(nil) _ VersionReconcilerSource = (*notifyingProvider)(nil) _ MemoriesSource = (*notifyingProvider)(nil) + _ LeaseReclaimerSource = (*notifyingProvider)(nil) + _ HeartbeaterSource = (*notifyingProvider)(nil) + _ BlockedListerSource = (*notifyingProvider)(nil) _ EventsJournalCursorSource = (*notifyingProvider)(nil) ) @@ -482,6 +504,22 @@ func (u *notifyingUOW) Commit(ctx context.Context, message string) error { return nil } +// CommitScoped is Commit for a scoped version commit (see ScopedCommitter): +// commit through the chain beneath, then fire the buffered hooks. +func (u *notifyingUOW) CommitScoped(ctx context.Context, tables []string, message string) error { + if err := commitScoped(ctx, u.UnitOfWork, tables, message); err != nil { + return err + } + entries := u.rec.drain() + if u.sinks.Hook == nil { + return nil + } + for _, entry := range entries { + u.sinks.Hook.Run(entry.event, entry.issue) + } + return nil +} + // Close rolls the unit of work back unless it committed, so whatever the // attempt buffered is dropped rather than fired. func (u *notifyingUOW) Close(ctx context.Context) { @@ -1003,6 +1041,39 @@ func (u *recordingIssueUC) ReleaseIssue(ctx context.Context, req publicops.Relea return result, wrote, nil } +// RenewLease records an update for a heartbeat that re-armed a lease (a +// mutation: row_lock, updated_at, event, journal, version) and nothing for a +// refresh, which writes only the ephemeral lease row. It is DECLARED for +// ReleaseIssue's reason: an inherited accessor would compile and record +// nothing, silently dropping the re-arm's hook. +func (u *recordingIssueUC) RenewLease(ctx context.Context, request publicops.HeartbeatRequest) (publicops.HeartbeatResult, error) { + result, err := u.IssueUseCase.RenewLease(ctx, request) + if err != nil || !result.Rearmed { + return result, err + } + u.rec.record(opUpdate, u.snap.issue(ctx, result.IssueID)) + return result, nil +} + +// Reclaim records an update for every lease the sweep reverted. +// +// It is DECLARED for the same reason ReleaseIssue above is: an inherited +// accessor would compile and record nothing, silently dropping the hook the +// DoltStorage chain fires once per reverted row. +// +// A sweep reverts only issues, never wisps, so the snapshot is the issues- +// plane snap.issue rather than anyPlane. +func (u *recordingIssueUC) Reclaim(ctx context.Context, request publicops.ReclaimRequest) (publicops.ReclaimResult, error) { + result, err := u.IssueUseCase.Reclaim(ctx, request) + if err != nil { + return result, err + } + for _, r := range result.Reclaimed { + u.rec.record(opUpdate, u.snap.issue(ctx, r.ID)) + } + return result, nil +} + func (u *recordingIssueUC) UpdateWisp(ctx context.Context, id string, updates map[string]any, actor string) error { if err := u.IssueUseCase.UpdateWisp(ctx, id, updates, actor); err != nil { return err diff --git a/internal/storage/uow/notifying_parity_test.go b/internal/storage/uow/notifying_parity_test.go index 5bccc063e..72faa8e03 100644 --- a/internal/storage/uow/notifying_parity_test.go +++ b/internal/storage/uow/notifying_parity_test.go @@ -130,7 +130,9 @@ func TestRecordingIssueUseCaseCoversItsSurface(t *testing.T) { "has no name for a deletion and the row is gone (hook_deleter.go, hookTrackingTransaction.DeleteIssue)" leases := "lease and claim bookkeeping the DoltStorage plumbing fires no hook for: " + "HookFiringStore overrides neither UnclaimIssue, UnclaimIssueIfAssignee, HeartbeatIssue nor " + - "ReclaimExpiredLeases, so `bd unclaim` and `bd heartbeat` run no script on either plumbing" + "ReclaimExpiredLeases, so `bd unclaim` runs no script on either plumbing, and neither does a " + + "heartbeat through these doors (`bd heartbeat` takes the Heartbeater role, whose re-arm records " + + "an update through RenewLease)" assertPartition(t, "IssueUseCase", interfaceMethods(reflect.TypeOf((*domain.IssueUseCase)(nil)).Elem()), reflect.TypeOf((*recordingIssueUC)(nil)), map[string]string{ @@ -145,6 +147,7 @@ func TestRecordingIssueUseCaseCoversItsSurface(t *testing.T) { "GetEpicsEligibleForClosure": reads, "GetIssue": reads, "GetIssuesByIDs": reads, + "GetMany": reads, "GetNewlyUnblockedByClose": reads, "GetNewlyUnblockedByCloseWisp": reads, "GetReadyWork": reads, @@ -171,8 +174,9 @@ func TestRecordingIssueUseCaseCoversItsSurface(t *testing.T) { "ReclaimExpiredLeases": leases, "WakeExpiredDefers": "the deferred-work sweep is a clock crossing rather than a user's " + "mutation, and the DoltStorage plumbing fires nothing for it", - "PromoteWisp": "moves a row between planes without changing the bead; the DoltStorage " + - "plumbing has no promote hook either", + "PromoteWisp": "no route calls it: bd promote moves the row with ApplyUpdate's " + + "persistence spec, which records the update, and its DoltStorage twin, " + + "PromoteFromEphemeral, fires no hook either", }) } @@ -201,6 +205,7 @@ func TestRecordingDependencyUseCaseCoversItsSurface(t *testing.T) { "GetIssueDependencyRecords": reads, "GetWispDependencyRecords": reads, "IsBlocked": reads, + "IsBlockedBatch": reads, "IsWispBlocked": reads, "IterWispWithIssueMetadata": reads, "IterWithIssueMetadata": reads, diff --git a/internal/storage/uow/preview_provider_test.go b/internal/storage/uow/preview_provider_test.go index 6f815c55e..034df323c 100644 --- a/internal/storage/uow/preview_provider_test.go +++ b/internal/storage/uow/preview_provider_test.go @@ -62,12 +62,22 @@ func TestInitSchemaPreviewMissingDatabaseFailsClosed(t *testing.T) { } // TestApplyProviderOptions keeps the option plumbing honest: the ordinary -// callers pass nothing and must stay on the mutating open. +// callers pass nothing and must stay on the mutating open, and only an open +// that asks for it is treated as proxied-server mode. func TestApplyProviderOptions(t *testing.T) { - if got := applyProviderOptions(nil); got.preview { + got := applyProviderOptions(nil) + if got.preview { t.Fatal("applyProviderOptions(nil).preview = true, want false") } + if got.proxiedServerMode { + t.Fatal("applyProviderOptions(nil).proxiedServerMode = true, want false") + } if got := applyProviderOptions([]ProviderOption{WithPreview()}); !got.preview { t.Fatal("applyProviderOptions(WithPreview()).preview = false, want true") } + // The proxied marker changes what a refusal says, not how the open + // behaves, so it must not switch on either open posture as well. + if got := applyProviderOptions([]ProviderOption{WithProxiedServerMode()}); !got.proxiedServerMode || got.preview || got.readOnly { + t.Fatalf("applyProviderOptions(WithProxiedServerMode()) = %+v, want only proxiedServerMode set", got) + } } diff --git a/internal/storage/uow/reader_contract_test.go b/internal/storage/uow/reader_contract_test.go index 427219c4e..54bab3aa0 100644 --- a/internal/storage/uow/reader_contract_test.go +++ b/internal/storage/uow/reader_contract_test.go @@ -92,6 +92,9 @@ func TestReaderContract(t *testing.T) { t.Run("ListEmptyPageIsWellFormed", func(t *testing.T) { conformance.RunReaderListEmptyPageIsWellFormed(t, ctx, fixture) }) + t.Run("ListQueryMatchesTheTitleOrTheID", func(t *testing.T) { + conformance.RunReaderListQueryMatchesTheTitleOrTheID(t, ctx, fixture) + }) t.Run("GetResolvesTheExactIDAcrossBothPlanes", func(t *testing.T) { conformance.RunReaderGetResolvesTheExactIDAcrossBothPlanes(t, ctx, fixture) }) @@ -164,6 +167,12 @@ func TestReaderContract(t *testing.T) { t.Run("ListWispTypeNarrowsTheAdmittedPlaneRatherThanAdmittingIt", func(t *testing.T) { conformance.RunReaderListWispTypeNarrowsTheAdmittedPlaneRatherThanAdmittingIt(t, ctx, fixture) }) + t.Run("ListTimeBoundsAreStrictAndWholeSecond", func(t *testing.T) { + conformance.RunReaderListTimeBoundsAreStrictAndWholeSecond(t, ctx, fixture) + }) + t.Run("ListFilterFamiliesNarrowToTheirRows", func(t *testing.T) { + conformance.RunReaderListFilterFamiliesNarrowToTheirRows(t, ctx, fixture) + }) t.Run("ListBriefDropsTheFreeFormTextAndNothingElse", func(t *testing.T) { conformance.RunReaderListBriefDropsTheFreeFormTextAndNothingElse(t, ctx, fixture) }) @@ -207,5 +216,10 @@ func newUOWReaderFixture(t *testing.T, provider UnitOfWorkProvider, prefix strin return "bd: comment " + issueID, err }) }, + PromoteWisp: func(ctx context.Context, id, actor string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + return "bd: promote " + id, uw.IssueUseCase().PromoteWisp(ctx, id, actor) + }) + }, } } diff --git a/internal/storage/uow/relations.go b/internal/storage/uow/relations.go index 9db1a0815..8e090dc99 100644 --- a/internal/storage/uow/relations.go +++ b/internal/storage/uow/relations.go @@ -48,29 +48,35 @@ func (r *issueRelations) Related(ctx context.Context, request publicops.RelatedR if err := storageissueops.ValidateRelatedRequest(request); err != nil { return nil, err } + return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) ([]*publicops.RelatedIssue, error) { + return RelatedInUOW(ctx, uw, request) + }) +} + +// RelatedInUOW is the Relations body, run inside the caller's unit of work. +// The request must already be validated. +func RelatedInUOW(ctx context.Context, uw UnitOfWork, request publicops.RelatedRequest) ([]*publicops.RelatedIssue, error) { direction := domain.DepDirectionOut if request.Direction == publicops.RelationIn { direction = domain.DepDirectionIn } - return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) ([]*publicops.RelatedIssue, error) { - issue, isWisp, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), request.ID) - if err != nil { - return nil, err - } - filter := domain.DepListFilter{Direction: direction} - var items []*publicops.RelatedIssue - if isWisp { - items, err = uw.DependencyUseCase().ListWispWithIssueMetadata(ctx, issue.ID, filter) - } else { - items, err = uw.DependencyUseCase().ListWithIssueMetadata(ctx, issue.ID, filter) - } - if err != nil { - return nil, err - } - // The filter runs HERE rather than in the use-case call above so both - // implementations narrow and order through one function; passing - // filter.Types down would put the narrowing in the query on one side - // and in Go on the other. - return storageissueops.FinishRelatedPage(items, request.Types), nil - }) + issue, isWisp, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), request.ID) + if err != nil { + return nil, err + } + filter := domain.DepListFilter{Direction: direction} + var items []*publicops.RelatedIssue + if isWisp { + items, err = uw.DependencyUseCase().ListWispWithIssueMetadata(ctx, issue.ID, filter) + } else { + items, err = uw.DependencyUseCase().ListWithIssueMetadata(ctx, issue.ID, filter) + } + if err != nil { + return nil, err + } + // The filter runs HERE rather than in the use-case call above so both + // implementations narrow and order through one function; passing + // filter.Types down would put the narrowing in the query on one side + // and in Go on the other. + return storageissueops.FinishRelatedPage(items, request.Types), nil } diff --git a/internal/storage/uow/retention_epoch_contract_test.go b/internal/storage/uow/retention_epoch_contract_test.go index a2d8bcf00..91d3a5324 100644 --- a/internal/storage/uow/retention_epoch_contract_test.go +++ b/internal/storage/uow/retention_epoch_contract_test.go @@ -2,9 +2,11 @@ package uow import ( "context" + "fmt" "testing" "github.com/steveyegge/beads/backend/conformance" + storeops "github.com/steveyegge/beads/internal/storage/issueops" ) // TestRetentionContract wires this leg into the R20 retention contract. @@ -57,11 +59,28 @@ func TestRetentionContract(t *testing.T) { }) } -// TestEpochContract wires this leg into the R20 epoch contract. Same Phase 0 -// all-nil state as TestRetentionContract above. +// TestEpochContract runs the R20 epoch contract (gastownhall/beads#5898 +// revision 9, #6136) against the unit-of-work +// provider, which reaches the same internal/storage/issueops's epoch Tx +// functions the two store backends wrap — directly against the unit of +// work's own runner (the *baseUOW/base.tx.Runner() pattern +// expected_revision_contract_test.go's expectedRevisionUOWMutateOutside and +// commenter_contract_test.go's SeedCommentAt both use), NOT through the +// domain issue repository: EpochFixture's seven hooks are store-singleton/ +// administrative operations with no natural correspondence to +// IssueUseCase's per-issue CRUD/notification semantics, so unlike +// CompareAndSetVersion there is no domain/use-case method to route through +// in the first place — every hook below needs the escape hatch, not just +// one. +// +// One provider for the whole suite (each newUOWRoleFixtureProvider boots a +// real Dolt sql-server) and NO t.Parallel: this backend has no per-test +// copy-on-write branch, so store_epoch/epoch_minted_addresses are +// database-global and a parallel subtest would corrupt another subtest's +// row — same reasoning as TestExpectedRevisionContract's. func TestEpochContract(t *testing.T) { ctx := context.Background() - fixture := conformance.EpochFixture{IssuePrefix: "epch"} + fixture := newUOWEpochFixture(t, ctx, "epch") t.Run("AnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange", func(t *testing.T) { conformance.RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange(t, ctx, fixture) @@ -69,4 +88,184 @@ func TestEpochContract(t *testing.T) { t.Run("EpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed", func(t *testing.T) { conformance.RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t, ctx, fixture) }) + t.Run("TokenSchemeChangeCarriesLiveAddressesAndOnlyThose", func(t *testing.T) { + conformance.RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose(t, ctx, fixture) + }) + t.Run("ACarriedAddressKeepsResolvingAcrossLaterBumps", func(t *testing.T) { + conformance.RunACarriedAddressKeepsResolvingAcrossLaterBumps(t, ctx, fixture) + }) + t.Run("ALostAddressStaysGoneAcrossASchemeChange", func(t *testing.T) { + conformance.RunALostAddressStaysGoneAcrossASchemeChange(t, ctx, fixture) + }) +} + +// newUOWEpochFixture wires this leg's UnitOfWorkProvider into the R20 epoch +// contract. Like newUOWExpectedRevisionFixture, this fixture needs none of +// roleFixtureKit's CreateIssue/CreateWisp/QueryScalar/CountHistory hooks — +// it has no fields for them — so it does not route through +// newUOWRoleFixtureKit at all. +func newUOWEpochFixture(t *testing.T, ctx context.Context, prefix string) conformance.EpochFixture { + t.Helper() + provider := newUOWRoleFixtureProvider(t, ctx, prefix) + return conformance.EpochFixture{ + IssuePrefix: prefix, + CurrentEpoch: epochUOWCurrentEpoch(provider), + BumpEpoch: epochUOWBumpEpoch(provider), + MintUnderEpoch: epochUOWMintUnderEpoch(provider), + StillServes: epochUOWStillServes(provider), + Resolve: epochUOWResolve(provider), + CurrentAddressFor: epochUOWCurrentAddressFor(provider), + LoseVersion: epochUOWLoseVersion(provider), + } +} + +// epochUOWRunner recovers the *baseUOW a given attempt's UnitOfWork actually +// is, the same type assertion expectedRevisionUOWMutateOutside makes: Tx. +// Runner() is unexported outside this package and none of the seven epoch +// operations has a domain/use-case method to reach it through instead. +func epochUOWRunner(uw UnitOfWork) (storeops.DBTX, error) { + base, ok := uw.(*baseUOW) + if !ok { + return nil, fmt.Errorf("epoch CAS: unit of work %T does not expose the runner the epoch Tx functions need", uw) + } + return base.tx.Runner(), nil +} + +func epochUOWCurrentEpoch(provider UnitOfWorkProvider) func(ctx context.Context, storeID string) (int, error) { + return func(ctx context.Context, storeID string) (int, error) { + return RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (int, error) { + runner, err := epochUOWRunner(uw) + if err != nil { + return 0, err + } + return storeops.CurrentEpochInTx(ctx, runner, storeID) + }) + } +} + +// epochUOWBumpEpoch chooses the bump by the typed trigger: only a +// token-scheme-change bump carries live addresses to the new epoch, and the +// other two triggers move the counter alone. The choice lives here, in the +// contract-test translation layer, because the shared body has no switch on +// the reason string. +func epochUOWBumpEpoch(provider UnitOfWorkProvider) func(ctx context.Context, storeID string, trigger conformance.EpochBumpTrigger) (int, error) { + return func(ctx context.Context, storeID string, trigger conformance.EpochBumpTrigger) (int, error) { + return RunTxResult(ctx, provider, func(ctx context.Context, uw UnitOfWork) (int, string, error) { + runner, err := epochUOWRunner(uw) + if err != nil { + return 0, "", err + } + bump := storeops.BumpEpochInTx + if trigger == conformance.EpochBumpTriggerTokenSchemeChange { + bump = storeops.BumpEpochCarryingInTx + } + epoch, err := bump(ctx, runner, storeID, trigger.String()) + if err != nil { + return 0, "", err + } + return epoch, fmt.Sprintf("bd: bump epoch for %s (%s)", storeID, trigger.String()), nil + }) + } +} + +func epochUOWMintUnderEpoch(provider UnitOfWorkProvider) func(ctx context.Context, storeID, id string) (conformance.Address, error) { + return func(ctx context.Context, storeID, id string) (conformance.Address, error) { + address, err := RunTxResult(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, string, error) { + runner, err := epochUOWRunner(uw) + if err != nil { + return "", "", err + } + address, err := storeops.MintUnderEpochInTx(ctx, runner, storeID, id) + if err != nil { + return "", "", err + } + return address, fmt.Sprintf("bd: mint %s under epoch for %s", id, storeID), nil + }) + if err != nil { + return "", err + } + return conformance.Address(address), nil + } +} + +func epochUOWStillServes(provider UnitOfWorkProvider) func(ctx context.Context, storeID string, address conformance.Address) (bool, error) { + return func(ctx context.Context, storeID string, address conformance.Address) (bool, error) { + return RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (bool, error) { + runner, err := epochUOWRunner(uw) + if err != nil { + return false, err + } + return storeops.StillServesInTx(ctx, runner, storeID, string(address)) + }) + } +} + +func epochUOWResolve(provider UnitOfWorkProvider) func(ctx context.Context, storeID string, address conformance.Address) (conformance.RetentionAnswer, error) { + return func(ctx context.Context, storeID string, address conformance.Address) (conformance.RetentionAnswer, error) { + result, err := RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (storeops.EpochResolveResult, error) { + runner, err := epochUOWRunner(uw) + if err != nil { + return storeops.EpochResolveResult{}, err + } + return storeops.ResolveEpochInTx(ctx, runner, storeID, string(address)) + }) + if err != nil { + return conformance.RetentionAnswer{}, err + } + return epochResolveResultToConformance(result), nil + } +} + +func epochUOWCurrentAddressFor(provider UnitOfWorkProvider) func(ctx context.Context, storeID string, oldAddress conformance.Address) (conformance.Address, error) { + return func(ctx context.Context, storeID string, oldAddress conformance.Address) (conformance.Address, error) { + address, err := RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + runner, err := epochUOWRunner(uw) + if err != nil { + return "", err + } + return storeops.CurrentAddressForInTx(ctx, runner, storeID, string(oldAddress)) + }) + if err != nil { + return "", err + } + return conformance.Address(address), nil + } +} + +func epochUOWLoseVersion(provider UnitOfWorkProvider) func(ctx context.Context, storeID string, address conformance.Address) error { + return func(ctx context.Context, storeID string, address conformance.Address) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + runner, err := epochUOWRunner(uw) + if err != nil { + return "", err + } + if err := storeops.LoseVersionInTx(ctx, runner, storeID, string(address)); err != nil { + return "", err + } + return fmt.Sprintf("bd: lose version %s for %s", address, storeID), nil + }) + } +} + +// epochRestrictionToConformance translates this leg's local +// storeops.EpochRestriction into backend/conformance's own Restriction +// vocabulary — the contract-test file is the translation boundary, per +// epoch_cas.go's package doc. +func epochRestrictionToConformance(r storeops.EpochRestriction) conformance.Restriction { + switch r { + case storeops.EpochRestrictionLive: + return conformance.RestrictionLive + case storeops.EpochRestrictionGoneReorganization: + return conformance.RestrictionGoneReorganization + default: + return conformance.RestrictionUnknown + } +} + +func epochResolveResultToConformance(r storeops.EpochResolveResult) conformance.RetentionAnswer { + return conformance.RetentionAnswer{ + Restriction: epochRestrictionToConformance(r.Restriction), + ProducingStore: r.ProducingStore, + Epoch: r.Epoch, + } } diff --git a/internal/storage/uow/sweeper_contract_test.go b/internal/storage/uow/sweeper_contract_test.go index e054b5226..1f43b50eb 100644 --- a/internal/storage/uow/sweeper_contract_test.go +++ b/internal/storage/uow/sweeper_contract_test.go @@ -44,6 +44,9 @@ func TestSweeperContract(t *testing.T) { t.Run("ProtectsLiveDependents", func(t *testing.T) { conformance.RunSweeperProtectsLiveDependents(t, ctx, fixture) }) + t.Run("ProtectsTransitiveLiveDependents", func(t *testing.T) { + conformance.RunSweeperProtectsTransitiveLiveDependents(t, ctx, fixture) + }) t.Run("ProtectsLiveDependentsAcrossPlanes", func(t *testing.T) { conformance.RunSweeperProtectsLiveDependentsAcrossPlanes(t, ctx, fixture) }) diff --git a/internal/storage/uow/team_server_integration_test.go b/internal/storage/uow/team_server_integration_test.go index 2f1df42fc..20615be64 100644 --- a/internal/storage/uow/team_server_integration_test.go +++ b/internal/storage/uow/team_server_integration_test.go @@ -241,7 +241,7 @@ func TestTeamServerMode_Integration(t *testing.T) { require.Error(t, err) assert.Nil(t, p) assert.Contains(t, err.Error(), "bts migrate") - assert.NotContains(t, err.Error(), "run any bd write command", + assert.NotContains(t, err.Error(), "bd migrate schema", "must not suggest bd-driven migration on a bts-owned schema") assert.Equal(t, rolledBack, snapshotMigrations(t, ctx, direct), diff --git a/internal/storage/uow/team_server_schema.go b/internal/storage/uow/team_server_schema.go index d83aca3e1..f91ca3b0d 100644 --- a/internal/storage/uow/team_server_schema.go +++ b/internal/storage/uow/team_server_schema.go @@ -26,7 +26,7 @@ func checkTeamServerSchema(ctx context.Context, conn schema.DBConn, database str case current < latest: // No BD_IGNORE_SCHEMA_SKEW hatch here: it would let a newer bd write // against an older bts schema. Not SchemaBehindError either: its "run - // any bd write command to migrate" advice is wrong for a bts-owned schema. + // `bd migrate schema`" advice is wrong for a bts-owned schema. return fmt.Errorf( "uow: database %q is at schema v%d, this bd expects v%d; the schema is managed by beads-team-server — ask your operator to run 'bts migrate', or use a bd built against schema v%d", database, current, latest, current) diff --git a/internal/storage/uow/team_server_schema_test.go b/internal/storage/uow/team_server_schema_test.go index fb35bcb56..9c45f9dad 100644 --- a/internal/storage/uow/team_server_schema_test.go +++ b/internal/storage/uow/team_server_schema_test.go @@ -6,6 +6,7 @@ import ( "errors" "io" "os" + "regexp" "strings" "testing" @@ -19,13 +20,13 @@ import ( // table. The probe was added by be-bv7x so a not-yet-created cursor table // never poisons the pooled Dolt session with a failing statement. func expectCursorProbe(mock sqlmock.Sqlmock, table string, exists bool) { - present := 0 + mock.ExpectQuery(regexp.QuoteMeta("SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = DATABASE()")). + WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + rows := sqlmock.NewRows([]string{"Tables_in_beads"}).AddRow("issues") if exists { - present = 1 + rows.AddRow(table) } - mock.ExpectQuery(`SELECT COUNT\(\*\) FROM information_schema\.tables`). - WithArgs(table). - WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(present)) + mock.ExpectQuery("^SHOW TABLES$").WillReturnRows(rows) } func expectVersionQuery(mock sqlmock.Sqlmock, version int) { @@ -108,7 +109,7 @@ func TestCheckTeamServerSchema_Behind_RefusesWithBtsMigrate(t *testing.T) { if !strings.Contains(err.Error(), "bts migrate") { t.Errorf("error %q should point at 'bts migrate'", err) } - if strings.Contains(err.Error(), "run any bd write command") { + if strings.Contains(err.Error(), "bd migrate schema") { t.Errorf("error %q must not suggest bd-driven migration on a bts-owned schema", err) } } diff --git a/internal/storage/uow/testmain_test.go b/internal/storage/uow/testmain_test.go index 165b8b644..880451b46 100644 --- a/internal/storage/uow/testmain_test.go +++ b/internal/storage/uow/testmain_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/steveyegge/beads/internal/doltserver" + "github.com/steveyegge/beads/internal/storage/schema" "github.com/steveyegge/beads/internal/testutil" ) @@ -33,6 +34,12 @@ func TestMain(m *testing.M) { } func testMainInner(m *testing.M) int { + // Package-wide migration consent: these tests exercise the + // provider/bootstrap machinery that runs BELOW the consent gate + // (schema/migrate_consent.go), exactly as production does once an operator + // has consented. + schema.SetLocalMigrateConsent(true) + // Clear out the roots of earlier runs of this suite whose process is // gone, before claiming one of our own. Roots with no owner marker, and // roots whose owner is still running (a parallel package under diff --git a/internal/storage/uow/tx.go b/internal/storage/uow/tx.go index 35cb0a94c..ba5b21b36 100644 --- a/internal/storage/uow/tx.go +++ b/internal/storage/uow/tx.go @@ -181,19 +181,20 @@ func RunTxResultWithin[T any](ctx context.Context, p UnitOfWorkProvider, maxElap } // RunTxEphemeral is RunTxResult for work whose writes touch ONLY ephemeral -// (dolt_ignored) state — today the leases table, whose writes must mint no -// Dolt commit and no history (bd-lrgn1; ported to proxied mode by bd-aq0ql). -// On success the attempt is committed with the SQL-only form (Tx.Commit with -// an empty message ⇒ plain COMMIT, no DOLT_COMMIT), which persists the -// working set but records nothing in dolt_log — the proxied analog of the -// classic DoltStore.withRetryTx commit discipline that HeartbeatIssue relies -// on. A serialization loser (heartbeat and reclaim/close contend on the same -// lease row by design) is replayed against a fresh unit of work, exactly like -// RunTxResult. +// (dolt_ignored) state, which must mint no Dolt commit and no history +// (bd-aq0ql) — today local metadata and the events-journal prune. On success +// the attempt is committed with the SQL-only form (Tx.Commit with an empty +// message ⇒ plain COMMIT, no DOLT_COMMIT), which persists the working set but +// records nothing in dolt_log. A serialization loser is replayed against a +// fresh unit of work, exactly like RunTxResult. // // Do NOT use this for work that writes versioned tables: those writes would // persist while silently bypassing Dolt history. Every versioned write goes -// through RunTx/RunTxResult with a real commit message. +// through RunTx/RunTxResult with a real commit message. A heartbeat is NOT +// ephemeral work: a lease refresh writes only the dolt_ignored leases table +// (bd-lrgn1), but a re-arm writes versioned rows, so the Heartbeater commits +// through RunTxScoped, whose attempt that names no tables takes this same +// plain COMMIT. func RunTxEphemeral[T any](ctx context.Context, p UnitOfWorkProvider, work TxReadFunc[T]) (T, error) { var result T bo := backoff.NewExponentialBackOff() @@ -232,6 +233,99 @@ func RunTxEphemeral[T any](ctx context.Context, p UnitOfWorkProvider, work TxRea return result, err } +// ScopedCommitter is the optional commit a unit of work offers for a write +// whose versioned tables are KNOWN: it commits the SQL transaction, then +// stages exactly tables (plus the versioned-history tables when the +// transaction could have minted) and makes a Dolt commit named message from +// that staged set alone, leaving another writer's uncommitted change to any +// other table in the working set where it was. A staged table is committed +// whole, so another writer's uncommitted change to one of those tables rides +// in this commit, as it does in the DoltStore funnel. With nothing staged, or +// under a deferred version commit, there is no Dolt commit. It is the uow +// twin of the DoltStore funnel's post-transaction DOLT_ADD-per-table commit, +// in the same order — the Dolt commit after the SQL COMMIT, never inside the +// transaction, where it would be built from the transaction's start snapshot +// (LatentLabsSpace/NEXUS#92) — and what a mutation that mostly touches +// dolt_ignored state (a heartbeat re-arm) commits through instead of +// DOLT_COMMIT('-Am'). An error means the SQL transaction did not commit; a +// Dolt commit that fails after it is logged, never returned. +type ScopedCommitter interface { + CommitScoped(ctx context.Context, tables []string, message string) error +} + +// commitScoped commits uw through the first ScopedCommitter on its decorator +// chain. A backend whose unit of work has none (a non-Dolt engine) gets the +// plain SQL COMMIT: there is no version control to scope. +func commitScoped(ctx context.Context, uw UnitOfWork, tables []string, message string) error { + for u := uw; u != nil; { + if scoped, ok := u.(ScopedCommitter); ok { + return scoped.CommitScoped(ctx, tables, message) + } + unwrapper, ok := u.(unitOfWorkUnwrapper) + if !ok { + break + } + u = unwrapper.Unwrap() + } + return uw.Commit(ctx, "") +} + +// TxScopedFunc is the work RunTxScoped runs: its result, and the versioned +// tables the attempt changed with the commit message naming them. No tables +// means the attempt wrote only dolt_ignored state (or nothing). +type TxScopedFunc[T any] func(ctx context.Context, uw UnitOfWork) (result T, tables []string, commitMsg string, err error) + +// RunTxScoped is RunTxEphemeral for work that is USUALLY ephemeral but +// sometimes writes versioned rows it can name: an attempt that reports no +// tables commits with the plain SQL COMMIT (no working-set scan, no Dolt +// commit, nothing swept); one that reports tables commits through +// ScopedCommitter, staging exactly those. Never DOLT_COMMIT('-Am'): that +// would sweep other writers' uncommitted (batch-mode) changes to other tables +// into this commit (a staged table is committed whole). Serialization losers +// are replayed like RunTxEphemeral's. +func RunTxScoped[T any](ctx context.Context, p UnitOfWorkProvider, work TxScopedFunc[T]) (T, error) { + var result T + bo := backoff.NewExponentialBackOff() + bo.InitialInterval = txRetryInitialInterval + bo.MaxElapsedTime = DefaultTxRetryMaxElapsed + + err := backoff.Retry(func() error { + uw, err := p.NewUOW(ctx) + if err != nil { + if isSerializationError(err) { + return err + } + return backoff.Permanent(err) + } + defer closeAttempt(ctx, uw) + + r, tables, msg, err := work(ctx, uw) + if err != nil { + if isSerializationError(err) { + return err + } + return backoff.Permanent(err) + } + + if len(tables) == 0 || msg == "" { + err = uw.Commit(ctx, "") + } else { + err = commitScoped(ctx, uw, tables, msg) + } + if err != nil { + if isSerializationError(err) { + return err + } + return backoff.Permanent(err) + } + + result = r + return nil + }, backoff.WithContext(bo, ctx)) + + return result, err +} + func RunTxRead[T any](ctx context.Context, p UnitOfWorkProvider, work TxReadFunc[T]) (T, error) { var zero T uw, err := p.NewUOW(ctx) diff --git a/internal/storage/uow/uow.go b/internal/storage/uow/uow.go index a141fa5bb..ab69586c5 100644 --- a/internal/storage/uow/uow.go +++ b/internal/storage/uow/uow.go @@ -55,6 +55,20 @@ func (u *baseUOW) Commit(ctx context.Context, message string) error { return u.tx.Commit(ctx, message) } +// CommitScoped commits through the transaction's scoped commit when it has +// one (the Dolt server transaction), else with the plain SQL COMMIT. +func (u *baseUOW) CommitScoped(ctx context.Context, tables []string, message string) error { + if scoped, ok := u.tx.(scopedCommitTx); ok { + return scoped.CommitScoped(ctx, tables, message) + } + return u.tx.Commit(ctx, "") +} + +// scopedCommitTx is the optional Tx half of ScopedCommitter. +type scopedCommitTx interface { + CommitScoped(ctx context.Context, tables []string, message string) error +} + func (u *baseUOW) Close(ctx context.Context) { u.tx.RollbackUnlessCommitted(ctx) } diff --git a/internal/storage/uow/versioned_read_contract_test.go b/internal/storage/uow/versioned_read_contract_test.go new file mode 100644 index 000000000..947f2997f --- /dev/null +++ b/internal/storage/uow/versioned_read_contract_test.go @@ -0,0 +1,404 @@ +package uow + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/storage/dbproxy/proxy" + "github.com/steveyegge/beads/internal/storage/domain" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/testutil" + "github.com/steveyegge/beads/internal/types" +) + +// asOfReadHarness is this leg's Design D dispatch table (gastownhall/beads#5898 +// revision 9, gastownhall/beads#6136): the conformance suite +// invents storeID values to select among N genuinely isolated stores, and +// isolating them is entirely this harness's job -- AsOfReadInTx itself is +// storeID-oblivious (see the package doc on +// internal/storage/issueops/asof_read.go). Each storeID gets its own fresh +// UnitOfWorkProvider, built lazily on first use (provider) and torn down via +// t.Cleanup on the TestAsOfReadContract-level *testing.T. created tracks +// which (storeID, id) pairs already have a base issues row, since mintAt's +// second and later calls for the same pair must only add a historical +// issue_versions row, never a second base create. +// +// UNLIKE the dolt leg's buildAsOfReadStore (one shared testcontainer, N +// randomly-named databases) or the embeddeddolt leg's buildAsOfReadStore (N +// fully independent on-disk databases, isolation free), this leg spawns one +// real dolt sql-server SUBPROCESS per NewDoltServerUOWProvider call unless +// that call adopts an already-running one. Booting N subprocesses -- one per +// storeID, up to seven across a full TestAsOfReadContract run -- would be +// needlessly heavy, so this harness follows the same "one shared server, many +// databases" shape the dolt leg uses: TestAsOfReadContract does the ONE +// heavyweight, Fatal-permitted setup (dolt/bd binaries, HOME, port, +// storeRootDir, server config, log path) once in its own body, before any +// t.Run, and hands the resulting coordinates to newAsOfReadHarness. provider() +// then calls NewDoltServerUOWProvider -- a pure, Fatal-free function -- against +// those SAME coordinates with a fresh, randomly-named database per storeID. +// proxy.GetCreateDatabaseProxyServerEndpoint's adoption semantics (given the +// same rootDir, a later call dials the already-running server instead of +// spawning a duplicate, regardless of which database name it carries -- see +// TestNewDoltServerUOWProvider_ConcurrentInstantiation) mean only ONE server +// process is ever spawned, no matter how many storeIDs a case invents. +// +// storeID itself is used ONLY as a map key into h.providers here -- never as +// the database name. The conformance suite's storeID strings are built from +// free-form tags (asOfReadStore in backend/conformance/ +// versioned_read_contract.go: fixture.IssuePrefix + "-asof-store-" + tag, +// where tag can itself embed a Restriction's hyphenated String()), so they are +// not assumed to be safe SQL/Dolt identifiers. Generating an independent +// random per-store database name (asOfReadDatabaseName, matching the dolt +// leg's own dbSuffix approach) sidesteps that question entirely rather than +// sanitizing storeID. +// +// provider() cannot use newTestUOWProvider or newUOWRoleFixtureProvider. +// AsOfReadFixture's hook types (Resolve/MintAt/MakeUnanswerable) carry no +// *testing.T of their own, so a provider built lazily inside a hook -- itself +// invoked from inside a t.Run subtest closure, sometimes nested two deep (the +// restriction-loop case) -- has access only to whichever *testing.T this +// harness was constructed with: necessarily the OUTER TestAsOfReadContract's +// t, captured before any t.Run. Both of those helpers call testify's +// require.NoError / t.Fatalf internally, and calling FailNow/SkipNow on a +// *testing.T from a goroutine other than the one running that exact test -- +// which a t.Run subtest's closure always is, relative to the outer test -- +// panics with "subtest may have called FailNow on a parent test" (go's +// testing package requires FailNow/SkipNow to run only on the goroutine +// executing that specific test). provider() is a Fatalf/Skip-free path for +// exactly this reason: its failures come back as a plain error, which flows +// through the calling hook's own (..., error) return to +// conformance.RunAsOfReadXXX, which correctly Fatalfs using the SUBTEST's own +// *testing.T on the SUBTEST's own goroutine. Also unlike +// newUOWRoleFixtureProvider (one provider for a whole role suite, matching +// roleFixtureKit's frozen shape), this harness needs N independently-isolated +// providers -- roleFixtureKit is deliberately not reused here; see this +// file's own note by conformanceToAsOfRestriction on why issueops must stay +// conformance-oblivious, the same boundary that keeps this harness's own +// mapping from living centrally. +// +// See internal/storage/dolt/versioned_read_contract_test.go and +// internal/storage/embeddeddolt/versioned_read_contract_test.go for this +// leg's siblings, which this file mirrors as closely as the three backends' +// construction APIs allow. +type asOfReadHarness struct { + t *testing.T + storeRootDir string + doltBin string + cfgPath string + logPath string + providers map[string]UnitOfWorkProvider + created map[[2]string]bool +} + +func newAsOfReadHarness(t *testing.T, storeRootDir, doltBin, cfgPath, logPath string) *asOfReadHarness { + return &asOfReadHarness{ + t: t, + storeRootDir: storeRootDir, + doltBin: doltBin, + cfgPath: cfgPath, + logPath: logPath, + providers: map[string]UnitOfWorkProvider{}, + created: map[[2]string]bool{}, + } +} + +// provider returns storeID's UnitOfWorkProvider, building it on first use +// against a fresh, randomly-named database on the shared server. See the +// asOfReadHarness doc comment for why this function -- and everything it +// calls -- must never call *testing.T's Fatalf/Skip. +func (h *asOfReadHarness) provider(ctx context.Context, storeID string) (UnitOfWorkProvider, error) { + if p, ok := h.providers[storeID]; ok { + return p, nil + } + database, err := asOfReadDatabaseName() + if err != nil { + return nil, err + } + provider, err := NewDoltServerUOWProvider( + ctx, + h.storeRootDir, + database, + h.logPath, + h.cfgPath, + proxy.BackendLocalServer, + "root", + "", + h.doltBin, + 0, + 0, + false, + "", + ) + if err != nil { + return nil, fmt.Errorf("as-of read fixture: new provider for store %q (database %q): %w", storeID, database, err) + } + // t.Cleanup only appends to a mutex-guarded slice -- unlike Fatalf/Skip it + // never calls runtime.Goexit, so registering it on the outer h.t from + // inside a subtest's goroutine is safe. h.t's own cleanups run only after + // ALL of TestAsOfReadContract's t.Run calls have returned (none of them, + // nor their own nested t.Run calls, ever invoke t.Parallel), so every + // provider this harness builds stays open for the whole test. These + // per-provider Close cleanups are registered AFTER (so, per t.Cleanup's + // LIFO order, run BEFORE) TestAsOfReadContract's own shared + // verifiedShutdownCleanup (proxy.Shutdown) cleanup, so every provider is + // closed while the server they share is still up. + h.t.Cleanup(func() { _ = provider.Close(context.Background()) }) + + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + return "bd: set issue prefix", uw.ConfigUseCase().SetConfig(ctx, "issue_prefix", "asof") + }); err != nil { + return nil, fmt.Errorf("as-of read fixture: set issue_prefix for store %q: %w", storeID, err) + } + + h.providers[storeID] = provider + return provider, nil +} + +// asOfReadDatabaseName mints a fresh, unique database name, independent of +// any storeID's own content -- see the asOfReadHarness doc comment for why +// storeID itself is never used as one. +func asOfReadDatabaseName() (string, error) { + suffix := make([]byte, 6) + if _, err := rand.Read(suffix); err != nil { + return "", fmt.Errorf("as-of read fixture: generate db name: %w", err) + } + return "asof_" + hex.EncodeToString(suffix), nil +} + +// ensureCreated bare-creates id in storeID's store the first time it is +// asked for, giving RecordVersionAtInTx (called from mintAt) a base issues +// row to snapshot -- recordVersionAtInTx starts with GetIssueInTx, so it has +// nothing to read until this has run once. This goes through the real +// IssueUseCase, the same production entry point batch_creator.go and +// issue_operations.go use, unlike resolve/mintAt/makeUnanswerable below, +// which reach the shared issueops body directly (see the package doc on +// internal/storage/issueops/asof_read.go: "ALL THREE LEGS SHARE THIS BODY"). +func (h *asOfReadHarness) ensureCreated(ctx context.Context, storeID, id string) error { + key := [2]string{storeID, id} + if h.created[key] { + return nil + } + provider, err := h.provider(ctx, storeID) + if err != nil { + return err + } + issue := &types.Issue{ + ID: id, + Title: "as-of read fixture issue", + Status: types.StatusOpen, + Priority: 3, + IssueType: types.TypeTask, + } + err = RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + params := domain.CreateIssueParams{ + Issue: issue, + ExplicitID: issue.ID, + CreateOnly: true, + } + _, err := uw.IssueUseCase().CreateIssue(ctx, params, "asof-read-fixture") + return "as-of read fixture: bare-create " + issue.ID, err + }) + if err != nil { + return fmt.Errorf("as-of read fixture: bare-create %s: %w", id, err) + } + h.created[key] = true + return nil +} + +func (h *asOfReadHarness) resolve(ctx context.Context, storeID, id string, selector conformance.AsOfSelector) (conformance.AsOfReadResult, error) { + provider, err := h.provider(ctx, storeID) + if err != nil { + return conformance.AsOfReadResult{}, err + } + result, err := RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) (storageissueops.AsOfReadResult, error) { + runner, err := importStatementRunner(uw) + if err != nil { + return storageissueops.AsOfReadResult{}, err + } + return storageissueops.AsOfReadInTx(ctx, runner, storeID, id, toIssueopsSelector(selector)) + }) + if err != nil { + return conformance.AsOfReadResult{}, err + } + return toConformanceResult(result), nil +} + +// mintAt is the two-phase implementation MintAt's contract needs: phase one +// (ensureCreated) runs only once per (storeID, id); phase two +// (RecordVersionAtInTx) runs every call and always supplies the row mintAt +// reports the address of. RecordVersionAtInTx deliberately does not gate on +// versionedHistoryEnabled (this harness never turns that on for its stores), +// so it always mints, and reading MAX(revision) back inside the same +// transaction (read-your-writes) is how we learn which revision it picked -- +// RecordVersionAtInTx itself reports no revision number. +// +// The commit message returned to RunTxResult is deliberately non-empty: an +// empty commitMsg makes RunTxResultWithin skip calling uw.Commit entirely +// (tx.go), so the write would never persist past this attempt's implicit +// rollback -- exactly the RunTxEphemeral hazard its own doc comment warns +// against for versioned tables. +func (h *asOfReadHarness) mintAt(ctx context.Context, storeID, id string, acceptedAt time.Time) (conformance.Address, error) { + if err := h.ensureCreated(ctx, storeID, id); err != nil { + return "", err + } + provider, err := h.provider(ctx, storeID) + if err != nil { + return "", err + } + revision, err := RunTxResult(ctx, provider, func(ctx context.Context, uw UnitOfWork) (int64, string, error) { + runner, err := importStatementRunner(uw) + if err != nil { + return 0, "", err + } + if err := storageissueops.RecordVersionAtInTx(ctx, runner, id, "asof-read-fixture", acceptedAt); err != nil { + return 0, "", err + } + var rev int64 + if err := runner.QueryRowContext(ctx, + `SELECT MAX(revision) FROM issue_versions WHERE issue_id = ?`, id, + ).Scan(&rev); err != nil { + return 0, "", err + } + return rev, "as-of read fixture: mint version for " + id, nil + }) + if err != nil { + return "", err + } + return conformance.Address(storageissueops.AsOfVersionAddress(id, revision)), nil +} + +func (h *asOfReadHarness) makeUnanswerable(ctx context.Context, storeID, id string, restriction conformance.Restriction) error { + asOfRestriction, ok := conformanceToAsOfRestriction[restriction] + if !ok { + return fmt.Errorf("as-of read fixture: unmapped restriction %v", restriction) + } + provider, err := h.provider(ctx, storeID) + if err != nil { + return err + } + reason := fmt.Sprintf("as-of read fixture: made unanswerable as %s", restriction) + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + runner, err := importStatementRunner(uw) + if err != nil { + return "", err + } + if err := storageissueops.MarkLatestVersionRemovedInTx(ctx, runner, id, asOfRestriction, reason); err != nil { + return "", err + } + return "as-of read fixture: mark " + id + " removed", nil + }) +} + +// conformanceToAsOfRestriction and its inverse are this leg's translation +// boundary between backend/conformance.Restriction (hyphenated String(), +// int-backed) and issueops.AsOfRestriction (underscored, string-backed -- +// its values ARE the removed_restriction column's contents). issueops must +// stay conformance-oblivious and conformance must stay backend-oblivious +// (internal/storage/issueops/asof_read.go's package doc), so this mapping is +// deliberately duplicated per leg rather than shared centrally. +var conformanceToAsOfRestriction = map[conformance.Restriction]storageissueops.AsOfRestriction{ + conformance.RestrictionLive: storageissueops.AsOfRestrictionLive, + conformance.RestrictionGoneRetention: storageissueops.AsOfRestrictionGoneRetention, + conformance.RestrictionGoneErasure: storageissueops.AsOfRestrictionGoneErasure, + conformance.RestrictionGoneReorganization: storageissueops.AsOfRestrictionGoneReorganization, + conformance.RestrictionUnknown: storageissueops.AsOfRestrictionUnknown, +} + +var asOfRestrictionToConformance = map[storageissueops.AsOfRestriction]conformance.Restriction{ + storageissueops.AsOfRestrictionLive: conformance.RestrictionLive, + storageissueops.AsOfRestrictionGoneRetention: conformance.RestrictionGoneRetention, + storageissueops.AsOfRestrictionGoneErasure: conformance.RestrictionGoneErasure, + storageissueops.AsOfRestrictionGoneReorganization: conformance.RestrictionGoneReorganization, + storageissueops.AsOfRestrictionUnknown: conformance.RestrictionUnknown, +} + +func toIssueopsSelector(selector conformance.AsOfSelector) storageissueops.AsOfSelector { + out := storageissueops.AsOfSelector{At: selector.At} + if selector.Version != nil { + out.Address = string(*selector.Version) + } + return out +} + +func toConformanceResult(result storageissueops.AsOfReadResult) conformance.AsOfReadResult { + if result.Refused { + return conformance.AsOfReadResult{ + Refusal: &conformance.AsOfReadRefusal{ + Restriction: asOfRestrictionToConformance[result.Restriction], + Reason: result.Reason, + }, + } + } + return conformance.AsOfReadResult{ + Address: conformance.Address(result.Address), + State: result.State, + } +} + +// TestAsOfReadContract wires this leg into the R7.1 as-of-read contract +// (gastownhall/beads#5898 revision 9, gastownhall/beads#6136) with a real +// Resolve/MintAt/MakeUnanswerable backed by one isolated UnitOfWorkProvider +// per storeID (asOfReadHarness). +func TestAsOfReadContract(t *testing.T) { + // Everything through logPath below is the same one-time, Fatal-permitted + // setup newTestUOWProvider does, run here directly instead of through + // that helper: newTestUOWProvider both sets up AND builds one provider + // bound to a fixed "beads" database, but this harness needs the setup + // coordinates kept separate so provider() can build N providers, one per + // storeID, lazily from inside subtest closures. See the asOfReadHarness + // doc comment for why provider() must stay Fatalf/Skip-free, which is + // exactly why this block -- the one place in this file where Fatalf/Skip + // is safe -- must run here, before any t.Run. + testutil.RequireDoltBinary(t) + bin, err := exec.LookPath("dolt") + require.NoError(t, err) + + bdBin := buildBDBinary(t) + prev := proxy.ResolveExecutable + proxy.ResolveExecutable = func() (string, error) { return bdBin, nil } + t.Cleanup(func() { proxy.ResolveExecutable = prev }) + + t.Setenv("HOME", t.TempDir()) + + port, err := proxy.PickFreePort() + require.NoError(t, err) + storeRootDir := t.TempDir() + shutdownOnInterrupt(t, storeRootDir) + verifiedShutdownCleanup(t, storeRootDir) + cfgPath := writeServerConfig(t, port) + logPath := filepath.Join(t.TempDir(), "server.log") + + ctx := context.Background() + h := newAsOfReadHarness(t, storeRootDir, bin, cfgPath, logPath) + fixture := conformance.AsOfReadFixture{ + IssuePrefix: "asof", + Resolve: h.resolve, + MintAt: h.mintAt, + MakeUnanswerable: h.makeUnanswerable, + } + + t.Run("SelectorAcceptsEitherAnInstantOrAVersionAddress", func(t *testing.T) { + conformance.RunAsOfReadSelectorAcceptsEitherAnInstantOrAVersionAddress(t, ctx, fixture) + }) + t.Run("ReturnsTheLatestVersionAtOrBeforeTStrictlyExcludingLater", func(t *testing.T) { + conformance.RunAsOfReadReturnsTheLatestVersionAtOrBeforeTStrictlyExcludingLater(t, ctx, fixture) + }) + t.Run("ReportsTheAddressItServed", func(t *testing.T) { + conformance.RunAsOfReadReportsTheAddressItServed(t, ctx, fixture) + }) + t.Run("RefusesAsGoneOrUnknownNeverSubstitutingAnotherVersion", func(t *testing.T) { + conformance.RunAsOfReadRefusesAsGoneOrUnknownNeverSubstitutingAnotherVersion(t, ctx, fixture) + }) + t.Run("IsCompleteOnlyForTheAnsweringStoresHoldings", func(t *testing.T) { + conformance.RunAsOfReadIsCompleteOnlyForTheAnsweringStoresHoldings(t, ctx, fixture) + }) +} diff --git a/internal/storage/version_control.go b/internal/storage/version_control.go index baa79dda0..45830306e 100644 --- a/internal/storage/version_control.go +++ b/internal/storage/version_control.go @@ -2,7 +2,11 @@ package storage import ( "context" + "fmt" + "strings" "time" + + "github.com/steveyegge/beads/internal/storage/kvkeys" ) // CommitInfo represents a version control commit. @@ -163,7 +167,9 @@ type VersionControl interface { ListBranches(ctx context.Context) ([]string, error) Commit(ctx context.Context, message string) error // CommitWithConfig is like Commit but includes the config table. - // Use after intentional config writes (bd init, bd config set, bd rename-prefix). + // Use after intentional config writes (bd init, bd rename-prefix). Its '-Am' + // stages every dirty table, so a command committing only its own config + // write should use CommitConfigOnly or CommitConfigUserKVOnly instead. // GH#3216: bootstrap paths must use this to commit issue_prefix. CommitWithConfig(ctx context.Context, message string) error // CommitMergeResolution concludes a merge whose conflicts the operator @@ -190,6 +196,23 @@ type VersionControl interface { // racy HEAD-before/HEAD-after comparison (the interface threading tracked // as bd mybd-z9h7j; CommitPending already had the shape). CommitAll(ctx context.Context, message string) (bool, error) + // CommitConfigOnly commits the config table, with the lookup tables + // SetConfig projects from it (custom_statuses, custom_types) — the scoped + // commit for intentional config writes (bd config set) in server mode. + // There, unlike CommitWithConfig ('-Am'), it never stages other tables, so + // a concurrent operation's dirty working set is not swept (GH#2455). + // Embedded mode has no concurrent writer to sweep and commits the whole + // working set, as its CommitWithConfig does. + // GH#4078: without this, server-mode config writes strand the working + // set dirty — generic Commit() excludes config and silently no-ops. + CommitConfigOnly(ctx context.Context, message string) error + // CommitConfigUserKVOnly is the scoped commit for writes of user kv.* data + // (bd remember, bd forget). In server mode it stages the config table alone + // and refuses, committing nothing, when any dirty config row is outside + // kv.*, the screen the pre-pull auto-commit applies. The refusal is a + // *ConfigCommitRefusedError naming those keys. Embedded mode behaves as + // CommitConfigOnly. + CommitConfigUserKVOnly(ctx context.Context, message string) error CommitPending(ctx context.Context, actor string) (bool, error) CommitExists(ctx context.Context, commitHash string) (bool, error) GetCurrentCommit(ctx context.Context) (string, error) @@ -199,3 +222,21 @@ type VersionControl interface { GetConflicts(ctx context.Context) ([]Conflict, error) ResolveConflicts(ctx context.Context, table string, strategy string) error } + +// ConfigCommitRefusedError is CommitConfigUserKVOnly's refusal. Keys are the +// config rows outside the user kv.* namespace that were dirty, or that a +// concurrent writer dirtied while the commit staged: committing the user write +// would have swept them into it (GH#2455). Nothing was committed, and what the +// commit staged was unstaged again unless the error also reports that the +// unstage failed. The user write itself stays in the working set, so a caller +// whose write already landed reports the refusal rather than failing the write. +type ConfigCommitRefusedError struct { + Keys []string +} + +func (e *ConfigCommitRefusedError) Error() string { + return fmt.Sprintf("refusing to commit %d dirty internal config key(s) with a user %s* write: %s; "+ + "only user %s* rows commit with it (GH#2455). The %s* write itself is saved in the "+ + "working set: `bd dolt commit` publishes it together with those keys, or revert the "+ + "keys first", len(e.Keys), kvkeys.Prefix, strings.Join(e.Keys, ", "), kvkeys.Prefix, kvkeys.Prefix) +} diff --git a/internal/storage/version_lister.go b/internal/storage/version_lister.go new file mode 100644 index 000000000..df0946780 --- /dev/null +++ b/internal/storage/version_lister.go @@ -0,0 +1,76 @@ +package storage + +import ( + "context" + "time" +) + +// IssueVersion is one accepted, immutable durable state of one issue, as +// issue_versions records it. +// +// Revision is a PER-STORE ORDINAL, not a portable address: two disconnected +// clones can both hold revision 8 for the same issue (migration 0067's own +// header says so, and the flag is single-writer-only until the version_id +// primary key lands). Callers must not present it as a citable address. +// +// Its JSON key is "local_revision", NOT "revision", for two reasons that +// compound. types.Issue already ships `json:"revision"` (types.go:1206) and +// that is the row-lock CAS token, an unrelated thing -- and it is a STRING +// there while this is an int64, so a script that learned one shape breaks on +// the other. The name also carries the non-citability with the value, where a +// machine reader sees it, instead of only in a footer no script parses. It +// needs no rename when version_id lands beside it. (bee-ghosttrack, #5898 +// consumer read, 2026-09-20.) +// +// ChangeAgent is read from issue_versions.change_agent (migration 0067) but +// is deliberately NOT part of the JSON shape, which is what `bd versions +// --json` prints. Provenance V2 (gastownhall/beads#7510) replaces the ad hoc +// agent field with an actor chain, so publishing it now would make a public +// contract out of a field that is on its way out. The column and the field +// stay; only the JSON key is withheld. +// +// It lives here rather than in issueops for the same reason HistoryEntry +// does: issueops imports storage, so the shared row type has to sit on this +// side of that edge. +type IssueVersion struct { + IssueID string `json:"issue_id"` + Revision int64 `json:"local_revision"` + Epoch int64 `json:"epoch"` + ChangeActor string `json:"change_actor"` + ChangeAgent string `json:"-"` + ChangeMessage string `json:"change_message"` + ChangeAt time.Time `json:"change_at"` + AttributionStatus string `json:"attribution_status"` + RemovedAt *time.Time `json:"removed_at"` + RemovedReason string `json:"removed_reason"` + RemovedRestriction string `json:"removed_restriction"` + StateBytes int64 `json:"state_bytes"` +} + +// Removed reports whether this version is no longer served -- retention, +// erasure or an epoch reorganization removed it. A removed version keeps its +// row (so the gap is legible) but its durable state is gone, and callers must +// render it as a restriction rather than as an empty version. +func (v IssueVersion) Removed() bool { return v.RemovedAt != nil } + +// VersionLister is implemented by backends that can serve an issue's +// versioned history from the issue_versions table (migration 0067+). +// +// This is a narrow capability rather than a method on Storage on purpose: a +// backend that has no issue_versions table -- a proxied client, a no-db +// workspace, a non-Dolt backend -- should not be forced to implement it, and +// a caller that asserts for it learns the truth instead of receiving a stub +// that answers "no versions" for a store that simply cannot know. Same +// reasoning as ExternalRefHistoryQuerier in history_viewer.go. +// +// Holding this capability says the backend can READ versions. It says nothing +// about whether version recording is switched on -- that is +// VersionedHistoryConfigurer, and a store can legitimately implement both +// while the feature is off, in which case ListVersions truthfully returns +// nothing. +type VersionLister interface { + // ListVersions returns every retained version of issueID, newest first. + // An empty result means no retained versions, never "unsupported" -- + // unsupported is the failed type assertion. + ListVersions(ctx context.Context, issueID string) ([]IssueVersion, error) +} diff --git a/internal/storage/versioncontrolops/BUILD.bazel b/internal/storage/versioncontrolops/BUILD.bazel index d33ea0127..84fcf6342 100644 --- a/internal/storage/versioncontrolops/BUILD.bazel +++ b/internal/storage/versioncontrolops/BUILD.bazel @@ -65,3 +65,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/telemetry/BUILD.bazel b/internal/telemetry/BUILD.bazel index ef62f903a..9ad893f45 100644 --- a/internal/telemetry/BUILD.bazel +++ b/internal/telemetry/BUILD.bazel @@ -6,6 +6,8 @@ go_library( "batch_applier.go", "batch_closer.go", "batch_creator.go", + "batch_getter.go", + "blocked_lister.go", "blockingannotator.go", "bootstrapper.go", "commenter.go", @@ -15,12 +17,15 @@ go_library( "dependency_editor.go", "edgereader.go", "graph_counter.go", + "heartbeater.go", "init_verifier.go", "issue_claimer.go", "issue_operations.go", "issue_reader.go", + "lease_reclaimer.go", "memories.go", "metadata_cas.go", + "molecule_stepper.go", "querier.go", "ready_claimer.go", "ready_counter.go", @@ -72,6 +77,7 @@ go_test( embed = [":telemetry"], deps = [ "//internal/storage", + "//internal/storage/domain", "//internal/storage/externaldeps", "//issueops", "//memoryops", @@ -81,3 +87,64 @@ go_test( "@io_opentelemetry_go_otel_trace//noop", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/telemetry/batch_getter.go b/internal/telemetry/batch_getter.go new file mode 100644 index 000000000..1b4f5cddb --- /dev/null +++ b/internal/telemetry/batch_getter.go @@ -0,0 +1,36 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// BatchGetter returns the inner store's batch-read surface wrapped in this +// layer's instrumentation. It recurses instead of delegating: a blind +// delegation would return the inner getter unspanned and untimed. +func (s *InstrumentedStorage) BatchGetter() (issueops.BatchGetter, error) { + inner, err := s.Unwrap().BatchGetter() + if err != nil { + return nil, err + } + return s.WrapBatchGetter(inner), nil +} + +// WrapBatchGetter instruments guarded batch reads with this storage layer's +// existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapBatchGetter(inner issueops.BatchGetter) issueops.BatchGetter { + return &instrumentedBatchGetter{storage: s, inner: inner} +} + +type instrumentedBatchGetter struct { + storage *InstrumentedStorage + inner issueops.BatchGetter +} + +func (c *instrumentedBatchGetter) GetMany(ctx context.Context, request issueops.GetManyRequest) (result issueops.GetManyResult, err error) { + ctx, span, started := c.storage.op(ctx, "BatchGetter.GetMany") + result, err = c.inner.GetMany(ctx, request) + c.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/blocked_lister.go b/internal/telemetry/blocked_lister.go new file mode 100644 index 000000000..c050e0d6b --- /dev/null +++ b/internal/telemetry/blocked_lister.go @@ -0,0 +1,38 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// BlockedLister returns the inner store's blocked-listing surface wrapped in +// this layer's instrumentation. It recurses instead of delegating: a blind +// delegation would return the inner surface unspanned and untimed. +func (s *InstrumentedStorage) BlockedLister() (issueops.BlockedLister, error) { + inner, err := s.Unwrap().BlockedLister() + if err != nil { + return nil, err + } + return s.WrapBlockedLister(inner), nil +} + +// WrapBlockedLister instruments the blocked listing with this storage layer's +// existing telemetry meter and tracer. The external-dependency decorator +// calls it on the lister it builds over itself, so the span survives that +// override. +func (s *InstrumentedStorage) WrapBlockedLister(inner issueops.BlockedLister) issueops.BlockedLister { + return &instrumentedBlockedLister{storage: s, inner: inner} +} + +type instrumentedBlockedLister struct { + storage *InstrumentedStorage + inner issueops.BlockedLister +} + +func (c *instrumentedBlockedLister) ListBlocked(ctx context.Context, request issueops.BlockedRequest) (result issueops.BlockedResult, err error) { + ctx, span, started := c.storage.op(ctx, "BlockedLister.ListBlocked") + result, err = c.inner.ListBlocked(ctx, request) + c.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/heartbeater.go b/internal/telemetry/heartbeater.go new file mode 100644 index 000000000..e0be3a106 --- /dev/null +++ b/internal/telemetry/heartbeater.go @@ -0,0 +1,36 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// Heartbeater returns the inner store's lease-refresh surface wrapped in this +// layer's instrumentation. It recurses instead of delegating: a blind +// delegation would return the inner surface unspanned and untimed. +func (s *InstrumentedStorage) Heartbeater() (issueops.Heartbeater, error) { + inner, err := s.Unwrap().Heartbeater() + if err != nil { + return nil, err + } + return s.WrapHeartbeater(inner), nil +} + +// WrapHeartbeater instruments the lease refresh with this storage layer's +// existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapHeartbeater(inner issueops.Heartbeater) issueops.Heartbeater { + return &instrumentedHeartbeater{storage: s, inner: inner} +} + +type instrumentedHeartbeater struct { + storage *InstrumentedStorage + inner issueops.Heartbeater +} + +func (c *instrumentedHeartbeater) Heartbeat(ctx context.Context, request issueops.HeartbeatRequest) (result issueops.HeartbeatResult, err error) { + ctx, span, started := c.storage.op(ctx, "Heartbeater.Heartbeat") + result, err = c.inner.Heartbeat(ctx, request) + c.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/lease_reclaimer.go b/internal/telemetry/lease_reclaimer.go new file mode 100644 index 000000000..cf61d8356 --- /dev/null +++ b/internal/telemetry/lease_reclaimer.go @@ -0,0 +1,36 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// LeaseReclaimer returns the inner store's lease-sweep surface wrapped in +// this layer's instrumentation. It recurses instead of delegating: a blind +// delegation would return the inner surface unspanned and untimed. +func (s *InstrumentedStorage) LeaseReclaimer() (issueops.LeaseReclaimer, error) { + inner, err := s.Unwrap().LeaseReclaimer() + if err != nil { + return nil, err + } + return s.WrapLeaseReclaimer(inner), nil +} + +// WrapLeaseReclaimer instruments the lease sweep with this storage layer's +// existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapLeaseReclaimer(inner issueops.LeaseReclaimer) issueops.LeaseReclaimer { + return &instrumentedLeaseReclaimer{storage: s, inner: inner} +} + +type instrumentedLeaseReclaimer struct { + storage *InstrumentedStorage + inner issueops.LeaseReclaimer +} + +func (c *instrumentedLeaseReclaimer) Reclaim(ctx context.Context, request issueops.ReclaimRequest) (result issueops.ReclaimResult, err error) { + ctx, span, started := c.storage.op(ctx, "LeaseReclaimer.Reclaim") + result, err = c.inner.Reclaim(ctx, request) + c.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/molecule_stepper.go b/internal/telemetry/molecule_stepper.go new file mode 100644 index 000000000..50ec721ac --- /dev/null +++ b/internal/telemetry/molecule_stepper.go @@ -0,0 +1,35 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// MoleculeStepper returns the inner store's advance surface wrapped in this +// layer's instrumentation. +func (s *InstrumentedStorage) MoleculeStepper() (issueops.MoleculeStepper, error) { + inner, err := s.Unwrap().MoleculeStepper() + if err != nil { + return nil, err + } + return s.WrapMoleculeStepper(inner), nil +} + +// WrapMoleculeStepper instruments molecule advances with this storage layer's +// existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapMoleculeStepper(inner issueops.MoleculeStepper) issueops.MoleculeStepper { + return &instrumentedMoleculeStepper{storage: s, inner: inner} +} + +type instrumentedMoleculeStepper struct { + storage *InstrumentedStorage + inner issueops.MoleculeStepper +} + +func (m *instrumentedMoleculeStepper) Advance(ctx context.Context, req issueops.AdvanceRequest) (result issueops.AdvanceResult, err error) { + ctx, span, started := m.storage.op(ctx, "MoleculeStepper.Advance") + result, err = m.inner.Advance(ctx, req) + m.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/role_accessor_decorator_test.go b/internal/telemetry/role_accessor_decorator_test.go index 0d7caece4..d1fcdc0ce 100644 --- a/internal/telemetry/role_accessor_decorator_test.go +++ b/internal/telemetry/role_accessor_decorator_test.go @@ -94,7 +94,7 @@ func TestInstrumentedStorageDeclaresEveryRoleAccessor(t *testing.T) { } // roleAccessorStore is a DoltStorage whose only real methods are the -// twenty-eight role accessors, each answering with a distinguishable sentinel +// thirty-one role accessors, each answering with a distinguishable sentinel // so a test can tell an instrumented surface from a passed-through one. // // TWO sentinels rather than one: memoryops.Memories.List and issueops.Reader.List @@ -133,6 +133,9 @@ func (s *roleAccessorStore) TreeWalker() (issueops.TreeWalker, error) { return s func (s *roleAccessorStore) GraphCounter() (issueops.GraphCounter, error) { return s.surface, s.err } +func (s *roleAccessorStore) BatchGetter() (issueops.BatchGetter, error) { + return s.surface, s.err +} func (s *roleAccessorStore) BlockingAnnotator() (issueops.BlockingAnnotator, error) { return s.surface, s.err } @@ -172,8 +175,17 @@ func (s *roleAccessorStore) BatchApplier() (issueops.BatchApplier, error) { func (s *roleAccessorStore) Releaser() (issueops.Releaser, error) { return s.surface, s.err } +func (s *roleAccessorStore) LeaseReclaimer() (issueops.LeaseReclaimer, error) { + return s.surface, s.err +} +func (s *roleAccessorStore) Heartbeater() (issueops.Heartbeater, error) { + return s.surface, s.err +} +func (s *roleAccessorStore) BlockedLister() (issueops.BlockedLister, error) { + return s.surface, s.err +} -// roleAccessorSentinel implements twenty-seven of the twenty-eight roles at +// roleAccessorSentinel implements thirty of the thirty-one roles at // once — every one but memoryops.Memories, whose List collides with // issueops.Reader.List and needs the second sentinel below. // Nothing calls its methods; identity is the whole point. @@ -258,6 +270,9 @@ func (*roleAccessorSentinel) CountReady(context.Context, issueops.ReadyRequest) func (*roleAccessorSentinel) CountEdges(context.Context, issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) { return issueops.EdgeCountResult{}, nil } +func (*roleAccessorSentinel) GetMany(context.Context, issueops.GetManyRequest) (issueops.GetManyResult, error) { + return issueops.GetManyResult{}, nil +} func (*roleAccessorSentinel) Query(context.Context, issueops.QueryRequest) (issueops.IssuePage, error) { return issueops.IssuePage{}, nil @@ -300,6 +315,15 @@ func (*roleAccessorSentinel) CompareAndSetKey(context.Context, issueops.CompareA func (*roleAccessorSentinel) Release(context.Context, issueops.ReleaseRequest) (issueops.ReleaseResult, error) { return issueops.ReleaseResult{}, nil } +func (*roleAccessorSentinel) Reclaim(context.Context, issueops.ReclaimRequest) (issueops.ReclaimResult, error) { + return issueops.ReclaimResult{}, nil +} +func (*roleAccessorSentinel) Heartbeat(context.Context, issueops.HeartbeatRequest) (issueops.HeartbeatResult, error) { + return issueops.HeartbeatResult{}, nil +} +func (*roleAccessorSentinel) ListBlocked(context.Context, issueops.BlockedRequest) (issueops.BlockedResult, error) { + return issueops.BlockedResult{}, nil +} // memoryRoleSentinel is the memory role's sentinel — see // memoryRoleSentinel is the remaining role's sentinel — see @@ -355,6 +379,7 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) { {"BlockingAnnotator", func() (any, error) { return wrapped.BlockingAnnotator() }, sentinel}, {"TreeWalker", func() (any, error) { return wrapped.TreeWalker() }, sentinel}, {"GraphCounter", func() (any, error) { return wrapped.GraphCounter() }, sentinel}, + {"BatchGetter", func() (any, error) { return wrapped.BatchGetter() }, sentinel}, {"Counter", func() (any, error) { return wrapped.Counter() }, sentinel}, {"WorkspaceConfig", func() (any, error) { return wrapped.WorkspaceConfig() }, sentinel}, {"Memories", func() (any, error) { return wrapped.Memories() }, memorySentinel}, @@ -375,6 +400,9 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) { {"MetadataCAS", func() (any, error) { return wrapped.MetadataCAS() }, sentinel}, {"BatchApplier", func() (any, error) { return wrapped.BatchApplier() }, sentinel}, {"Releaser", func() (any, error) { return wrapped.Releaser() }, sentinel}, + {"LeaseReclaimer", func() (any, error) { return wrapped.LeaseReclaimer() }, sentinel}, + {"Heartbeater", func() (any, error) { return wrapped.Heartbeater() }, sentinel}, + {"BlockedLister", func() (any, error) { return wrapped.BlockedLister() }, sentinel}, } { t.Run(test.name, func(t *testing.T) { surface, err := test.got() @@ -398,9 +426,10 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) { // turn, so an externaldeps override that skips it silently drops the // storage.ReadyCounter.CountReady span for every text-mode `bd ready`. // -// This is the only test that wires a real decorator above the instrumented -// store, which is why WrapReadyCounter's sole caller outside this package is -// the thing being pinned here. +// This and its blocked-listing twin below are the only tests that wire a real +// decorator above the instrumented store, which is why WrapReadyCounter's and +// WrapBlockedLister's sole callers outside this package are the things being +// pinned here. func TestExternalDepsReadyCounterSurvivesThisLayer(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") inner := &roleAccessorStore{surface: &roleAccessorSentinel{}} @@ -418,6 +447,29 @@ func TestExternalDepsReadyCounterSurvivesThisLayer(t *testing.T) { } } +// TestExternalDepsBlockedListerSurvivesThisLayer is the same pin for the +// blocked listing. externaldeps builds a local store's lister over its own +// GetBlockedIssues, so the listing carries the external blockers that read +// adds, which leaves handing the finished lister to WrapBlockedLister as this +// layer's only turn: an override that skips it silently drops the +// storage.BlockedLister.ListBlocked span for every local `bd blocked`. +func TestExternalDepsBlockedListerSurvivesThisLayer(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + inner := &roleAccessorStore{surface: &roleAccessorSentinel{}} + instrumented, ok := WrapStorage(inner).(*InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage did not instrument the store; telemetry is disabled in this environment") + } + + lister, err := externaldeps.New(instrumented, nil, nil).BlockedLister() + if err != nil { + t.Fatalf("externaldeps BlockedLister() error = %v", err) + } + if _, ok := lister.(*instrumentedBlockedLister); !ok { + t.Fatalf("externaldeps BlockedLister() = %T, want it wrapped by this layer; the storage.BlockedLister.ListBlocked span stops being emitted for local bd blocked", lister) + } +} + // TestInstrumentedStorageRoleAccessorsPropagateInnerErrors pins the other half // of the recursion: an accessor that recurses must not swallow the inner // store's refusal, nor hand back a wrapper around nothing. @@ -440,6 +492,7 @@ func TestInstrumentedStorageRoleAccessorsPropagateInnerErrors(t *testing.T) { {"BlockingAnnotator", func() (any, error) { return wrapped.BlockingAnnotator() }}, {"TreeWalker", func() (any, error) { return wrapped.TreeWalker() }}, {"GraphCounter", func() (any, error) { return wrapped.GraphCounter() }}, + {"BatchGetter", func() (any, error) { return wrapped.BatchGetter() }}, {"Counter", func() (any, error) { return wrapped.Counter() }}, {"WorkspaceConfig", func() (any, error) { return wrapped.WorkspaceConfig() }}, {"Memories", func() (any, error) { return wrapped.Memories() }}, @@ -460,6 +513,9 @@ func TestInstrumentedStorageRoleAccessorsPropagateInnerErrors(t *testing.T) { {"MetadataCAS", func() (any, error) { return wrapped.MetadataCAS() }}, {"BatchApplier", func() (any, error) { return wrapped.BatchApplier() }}, {"Releaser", func() (any, error) { return wrapped.Releaser() }}, + {"LeaseReclaimer", func() (any, error) { return wrapped.LeaseReclaimer() }}, + {"Heartbeater", func() (any, error) { return wrapped.Heartbeater() }}, + {"BlockedLister", func() (any, error) { return wrapped.BlockedLister() }}, } { t.Run(test.name, func(t *testing.T) { surface, err := test.got() diff --git a/internal/telemetry/storage.go b/internal/telemetry/storage.go index d60574eef..98deca157 100644 --- a/internal/telemetry/storage.go +++ b/internal/telemetry/storage.go @@ -3,6 +3,7 @@ package telemetry import ( "context" "encoding/json" + "strings" "time" "go.opentelemetry.io/otel/attribute" @@ -596,6 +597,41 @@ func (s *InstrumentedStorage) GetAllConfig(ctx context.Context) (map[string]stri return v, err } +// GetConfigByPrefix forwards the domain.ConfigPrefixReader optional fast +// path when the wrapped store provides it, and otherwise falls back to +// instrumented GetAllConfig filtered in-process — so wrapping a store never +// costs it the capability. +// +// cmd/bd discovers that capability with storage.UnwrapStore, the repo's +// standard idiom, which peels all the way to the raw store: on that path the +// inner method is called directly and this span does not fire. The forwarder +// is kept deliberately rather than deleted — it preserves the capability for +// any caller holding the instrumented store, and it is the layer a +// peel-until-implements discovery would stop at if spans on prefix reads ever +// justify that non-standard peel. +func (s *InstrumentedStorage) GetConfigByPrefix(ctx context.Context, prefix string) (map[string]string, error) { + attrs := []attribute.KeyValue{attribute.String("bd.config.prefix", prefix)} + if pr, ok := s.inner.(interface { + GetConfigByPrefix(ctx context.Context, prefix string) (map[string]string, error) + }); ok { + ctx, span, t := s.op(ctx, "GetConfigByPrefix", attrs...) + v, err := pr.GetConfigByPrefix(ctx, prefix) + s.done(ctx, span, t, err, attrs...) + return v, err + } + all, err := s.GetAllConfig(ctx) + if err != nil { + return nil, err + } + out := make(map[string]string) + for k, v := range all { + if strings.HasPrefix(k, prefix) { + out[k] = v + } + } + return out, nil +} + func (s *InstrumentedStorage) SetLocalMetadata(ctx context.Context, key, value string) error { attrs := []attribute.KeyValue{attribute.String("bd.local_metadata.key", key)} ctx, span, t := s.op(ctx, "SetLocalMetadata", attrs...) diff --git a/internal/telemetry/storage_test.go b/internal/telemetry/storage_test.go index c3e6cd616..9cdc2a97a 100644 --- a/internal/telemetry/storage_test.go +++ b/internal/telemetry/storage_test.go @@ -5,8 +5,16 @@ import ( "testing" "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/domain" ) +// InstrumentedStorage forwards the optional prefix-read capability, which +// callers find by type assertion — so a drifting method set would degrade +// them to full scans silently. Pinned from the test build rather than +// storage.go to keep the telemetry package free of a production dependency on +// storage/domain. +var _ domain.ConfigPrefixReader = (*InstrumentedStorage)(nil) + // fakeDoltStore is a stub DoltStorage used to assert wrapper identity and // type chain. The embedded interface is nil; tests must not call any of its // methods (interface-promoted calls would panic). diff --git a/internal/templates/BUILD.bazel b/internal/templates/BUILD.bazel index 486d2d183..799491071 100644 --- a/internal/templates/BUILD.bazel +++ b/internal/templates/BUILD.bazel @@ -10,3 +10,64 @@ go_library( importpath = "github.com/steveyegge/beads/internal/templates", visibility = ["//:__subpackages__"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/templates/agents/BUILD.bazel b/internal/templates/agents/BUILD.bazel index edb3fc13a..8ad3255df 100644 --- a/internal/templates/agents/BUILD.bazel +++ b/internal/templates/agents/BUILD.bazel @@ -20,7 +20,70 @@ go_test( name = "agents_test", srcs = [ "agents_test.go", + "golden_test.go", "render_test.go", ], + data = glob(["testdata/**"]), embed = [":agents"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/templates/agents/agents.go b/internal/templates/agents/agents.go index c0eedc1e4..8978d1914 100644 --- a/internal/templates/agents/agents.go +++ b/internal/templates/agents/agents.go @@ -12,11 +12,27 @@ var defaultTemplate string //go:embed defaults/beads-section.md var beadsSection string +// quickReferencePushLine is the Quick Reference entry in the AGENTS.md +// template that tells agents to push beads data to the Dolt remote. +const quickReferencePushLine = "bd dolt push # Push beads data to remote\n" + // EmbeddedDefault returns the full AGENTS.md template content. func EmbeddedDefault() string { return defaultTemplate } +// EmbeddedDefaultWithOpts returns the AGENTS.md template with the text outside +// its managed section adjusted for opts: under the rule the managed section +// follows, the Quick Reference leaves out "bd dolt push" when no Dolt remote is +// configured or the workspace is declared no-push. The managed section is +// returned as embedded; ReplaceSectionWithOpts renders it for a profile. +func EmbeddedDefaultWithOpts(opts RenderOpts) string { + if !opts.omitsDoltPush() { + return defaultTemplate + } + return strings.ReplaceAll(defaultTemplate, "\n"+quickReferencePushLine, "\n") +} + // EmbeddedBeadsSection returns the beads integration section with markers. // The returned string is trimmed to match the existing agentsBeadsSection behavior // (no trailing newline after the end marker). diff --git a/internal/templates/agents/agents_test.go b/internal/templates/agents/agents_test.go index 0c7e1c6b1..c6438a38e 100644 --- a/internal/templates/agents/agents_test.go +++ b/internal/templates/agents/agents_test.go @@ -139,3 +139,30 @@ func TestGoEmbedDefaultManagedMarkerIsCurrent(t *testing.T) { t.Errorf("marker hash = %q, want %q", meta.Hash, CurrentHash(ProfileFull)) } } + +// TestEmbeddedDefaultWithOptsQuickReferenceFollowsRemote pins that the Quick +// Reference bd init writes above the managed section lists `bd dolt push` +// under the same rule as the managed section itself: only with a Dolt remote +// configured and the workspace not declared no-push. Without it the template +// loses exactly that line and nothing else. +func TestEmbeddedDefaultWithOptsQuickReferenceFollowsRemote(t *testing.T) { + if !strings.Contains(EmbeddedDefault(), "\n"+quickReferencePushLine) { + t.Fatalf("test precondition: the template's Quick Reference no longer holds %q", quickReferencePushLine) + } + for _, opts := range []RenderOpts{ + {HasRemote: true}, + {}, + {HasRemote: true, NoPush: true}, + {NoPush: true}, + } { + got := EmbeddedDefaultWithOpts(opts) + sectionPush := strings.Contains(RenderSectionWithOpts(ProfileMinimal, opts), "bd dolt push") + want := EmbeddedDefault() + if !sectionPush { + want = strings.ReplaceAll(want, "\n"+quickReferencePushLine, "\n") + } + if got != want { + t.Errorf("%+v: Quick Reference lists `bd dolt push` = %v, want %v (as the managed section)", opts, strings.Contains(got, "\n"+quickReferencePushLine), sectionPush) + } + } +} diff --git a/internal/templates/agents/golden_test.go b/internal/templates/agents/golden_test.go new file mode 100644 index 000000000..924753f5b --- /dev/null +++ b/internal/templates/agents/golden_test.go @@ -0,0 +1,138 @@ +package agents + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" +) + +// The tests in this file pin the exact managed sections `bd init` and +// `bd setup ` write between the BEGIN/END BEADS INTEGRATION markers of +// CLAUDE.md, AGENTS.md and the other instruction files. A change to a template +// (new guidance, a reworded rule, an added section) changes the bytes every +// user's instruction file receives and, through the marker hash, marks every +// section already installed as stale: `bd setup claude --check` then fails and +// the next `bd init` or `bd setup` rewrites the user's file. Such a change must +// therefore arrive as a reviewed golden diff, never as a side effect. +// +// Regenerate the golden files with +// +// BD_UPDATE_GOLDEN=1 go test ./internal/templates/agents/ -run TestManagedSectionGolden +// +// and update the literal hashes in TestManagedSectionHashes by hand. + +// managedSectionVariant is one managed section bd can render. +type managedSectionVariant struct { + name string + profile Profile + opts RenderOpts +} + +// managedSectionVariants lists every managed section bd renders: both +// profiles, each with and without the `bd dolt push` lines that depend on a +// configured Dolt remote, and each worded for a user-level file +// (UserLevelRenderOpts). NoPush renders the no-remote bytes +// (TestManagedSectionNoPushMatchesNoRemote), so it needs no variant of its own. +var managedSectionVariants = []managedSectionVariant{ + {name: "minimal", profile: ProfileMinimal, opts: RenderOpts{HasRemote: true}}, + {name: "minimal-no-remote", profile: ProfileMinimal, opts: RenderOpts{}}, + {name: "minimal-user", profile: ProfileMinimal, opts: UserLevelRenderOpts()}, + {name: "full", profile: ProfileFull, opts: RenderOpts{HasRemote: true}}, + {name: "full-no-remote", profile: ProfileFull, opts: RenderOpts{}}, + {name: "full-user", profile: ProfileFull, opts: UserLevelRenderOpts()}, +} + +// TestManagedSectionGolden pins each managed section byte for byte, markers +// included. +func TestManagedSectionGolden(t *testing.T) { + for _, v := range managedSectionVariants { + t.Run(v.name, func(t *testing.T) { + assertGoldenFile(t, filepath.Join("testdata", "managed-section-"+v.name+".md"), RenderSectionWithOpts(v.profile, v.opts)) + }) + } +} + +// TestManagedSectionHashes pins the marker hash of each managed section. The +// hash is what `bd setup --check` compares against an installed +// section, so changing it marks every existing install stale. It is a literal +// that BD_UPDATE_GOLDEN does not rewrite: a template change has to bump it by +// hand. +func TestManagedSectionHashes(t *testing.T) { + want := map[string]string{ + "minimal": "6ffdf896", + "minimal-no-remote": "cdcea925", + "minimal-user": "52c58e00", + "full": "bacef91e", + "full-no-remote": "9c890b20", + "full-user": "0d9cad1f", + } + for _, v := range managedSectionVariants { + got := CurrentHashWithOpts(v.profile, v.opts) + if got != want[v.name] { + t.Errorf("%s managed section hash = %q, want %q: the template changed, so every installed %s section is now stale", v.name, got, want[v.name], v.profile) + } + marker := "\n" + if section := RenderSectionWithOpts(v.profile, v.opts); !strings.HasPrefix(section, marker) { + first, _, _ := strings.Cut(section, "\n") + t.Errorf("%s managed section marker = %q, want %q", v.name, first, strings.TrimSuffix(marker, "\n")) + } + } +} + +// TestManagedSectionNoPushMatchesNoRemote pins that a local-only workspace +// (no-push: true) gets the same managed section as one with no Dolt remote, +// whatever the remote state. +func TestManagedSectionNoPushMatchesNoRemote(t *testing.T) { + for _, profile := range []Profile{ProfileMinimal, ProfileFull} { + want := RenderSectionWithOpts(profile, RenderOpts{}) + for _, hasRemote := range []bool{false, true} { + if got := RenderSectionWithOpts(profile, RenderOpts{HasRemote: hasRemote, NoPush: true}); got != want { + t.Errorf("%s profile with NoPush (HasRemote=%v) differs from the no-remote section", profile, hasRemote) + } + } + } +} + +// assertGoldenFile compares got with the golden file at path, or rewrites the +// file when BD_UPDATE_GOLDEN=1. +func assertGoldenFile(t *testing.T, path, got string) { + t.Helper() + if os.Getenv("BD_UPDATE_GOLDEN") == "1" { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatalf("mkdir %s: %v", filepath.Dir(path), err) + } + if err := os.WriteFile(path, []byte(got), 0o644); err != nil { + t.Fatalf("write golden %s: %v", path, err) + } + t.Logf("updated golden %s", path) + return + } + want, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read golden %s (regenerate with BD_UPDATE_GOLDEN=1): %v", path, err) + } + if got == string(want) { + return + } + t.Errorf("rendered output drifted from %s (regenerate with BD_UPDATE_GOLDEN=1 if intended)\n%s", path, firstGoldenDifference(string(want), got)) +} + +// firstGoldenDifference describes the first line on which want and got differ. +func firstGoldenDifference(want, got string) string { + wantLines := strings.Split(want, "\n") + gotLines := strings.Split(got, "\n") + line := func(lines []string, i int) string { + if i >= len(lines) { + return "(end of output)" + } + return fmt.Sprintf("%q", lines[i]) + } + for i := 0; i < len(wantLines) || i < len(gotLines); i++ { + if i >= len(wantLines) || i >= len(gotLines) || wantLines[i] != gotLines[i] { + return fmt.Sprintf("first difference at line %d:\n want: %s\n got: %s", i+1, line(wantLines, i), line(gotLines, i)) + } + } + return "outputs differ" +} diff --git a/internal/templates/agents/render.go b/internal/templates/agents/render.go index 84c6baa40..108bf9227 100644 --- a/internal/templates/agents/render.go +++ b/internal/templates/agents/render.go @@ -52,6 +52,18 @@ type RenderOpts struct { // NoPush indicates the rig is declared local-only (no-push: true in config). // When true, "bd dolt push" is omitted regardless of HasRemote. NoPush bool + // UserLevel words the section for a user-level instructions file, such as + // ~/.claude/CLAUDE.md, that the agent loads in every repository: instead + // of stating that the current project uses bd, it applies only in + // repositories that do, and so do its task-tracking rules. + UserLevel bool +} + +// omitsDoltPush reports whether rendered instructions leave out "bd dolt push": +// no Dolt remote is configured, or the workspace is declared no-push. The +// managed section and the AGENTS.md template around it share this rule. +func (o RenderOpts) omitsDoltPush() bool { + return !o.HasRemote || o.NoPush } // DefaultRenderOpts returns opts that assume a remote is configured, @@ -60,6 +72,13 @@ func DefaultRenderOpts() RenderOpts { return RenderOpts{HasRemote: true} } +// UserLevelRenderOpts returns the fixed opts for a user-level instructions +// file. No one repository's beads config applies to it, so it assumes a +// remote, as DefaultRenderOpts does. +func UserLevelRenderOpts() RenderOpts { + return RenderOpts{HasRemote: true, UserLevel: true} +} + // RenderSection returns the beads integration section for the given profile, // wrapped in markers that include version, profile, and hash metadata for freshness detection. // Assumes a Dolt remote is configured (backward-compatible). Use RenderSectionWithOpts @@ -214,13 +233,36 @@ func templateBodyWithOpts(profile Profile, opts RenderOpts) string { body = strings.TrimSuffix(body, "\n") } - if !opts.HasRemote || opts.NoPush { + if opts.omitsDoltPush() { body = stripDoltPushReferences(body) } + if opts.UserLevel { + body = userLevelWording.Replace(body) + } return body } +// userLevelScope opens a user-level section: the agent loads that file in +// every repository, including ones that do not use beads. +const userLevelScope = "This Beads block applies only in beads repositories: repositories that use **bd (beads)** for issue tracking, with a `.beads/` directory. Ignore it in any other repository." + +// userLevelWording rewords the lines of both profiles' bodies that state the +// current project uses bd, or that set a task-tracking rule with no condition, +// so they apply only in beads repositories (RenderOpts.UserLevel). +var userLevelWording = strings.NewReplacer( + "This project uses **bd (beads)** for issue tracking. Run `bd prime`", + userLevelScope+" In a beads repository, run `bd prime`", + "- Use `bd` for ALL task tracking", + "- In a beads repository, use `bd` for ALL task tracking", + "- Use `bd remember` for durable project facts", + "- In a beads repository, use `bd remember` for durable project facts", + "**IMPORTANT**: This project uses **bd (beads)** for ALL issue tracking.", + userLevelScope+"\n\n**IMPORTANT**: In a beads repository, use **bd (beads)** for ALL issue tracking.", + "- ✅ Use bd for ALL task tracking", + "- ✅ In a beads repository, use bd for ALL task tracking", +) + func normalizeEmbeddedMarkdown(content string) string { return strings.TrimRight(strings.ReplaceAll(content, "\r\n", "\n"), "\n") } diff --git a/internal/templates/agents/render_test.go b/internal/templates/agents/render_test.go index 6df83564c..c0bd12d4a 100644 --- a/internal/templates/agents/render_test.go +++ b/internal/templates/agents/render_test.go @@ -541,3 +541,37 @@ func TestReplaceSectionWithOptsDetectsRemoteChange(t *testing.T) { t.Error("replaced content should not contain 'bd dolt push' with HasRemote=false") } } + +// A user-level section loads in every repository, so it must not say the +// current one uses bd, and its task-tracking rules hold only in repositories +// that do. The wording is matched against the templates' text, so a template +// edit that the rewording no longer finds fails here. +func TestRenderSectionUserLevelAppliesOnlyInBeadsRepositories(t *testing.T) { + for _, profile := range []Profile{ProfileMinimal, ProfileFull} { + section := RenderSectionWithOpts(profile, UserLevelRenderOpts()) + if strings.Contains(section, "This project uses") { + t.Errorf("%s user-level section says the current project uses bd:\n%s", profile, section) + } + if n := strings.Count(section, userLevelScope); n != 1 { + t.Errorf("%s user-level section states its scope %d times, want 1", profile, n) + } + } + rules := map[Profile][]string{ + ProfileMinimal: { + "- In a beads repository, use `bd` for ALL task tracking — do NOT use TodoWrite", + "- In a beads repository, use `bd remember` for durable project facts", + }, + ProfileFull: { + "**IMPORTANT**: In a beads repository, use **bd (beads)** for ALL issue tracking.", + "- ✅ In a beads repository, use bd for ALL task tracking", + }, + } + for profile, want := range rules { + section := RenderSectionWithOpts(profile, UserLevelRenderOpts()) + for _, rule := range want { + if !strings.Contains(section, rule) { + t.Errorf("%s user-level section lacks the scoped rule %q", profile, rule) + } + } + } +} diff --git a/internal/templates/agents/testdata/managed-section-full-no-remote.md b/internal/templates/agents/testdata/managed-section-full-no-remote.md new file mode 100644 index 000000000..526550030 --- /dev/null +++ b/internal/templates/agents/testdata/managed-section-full-no-remote.md @@ -0,0 +1,129 @@ + +## Issue Tracking with bd (beads) + +**IMPORTANT**: This project uses **bd (beads)** for ALL issue tracking. Do NOT use markdown TODOs, task lists, or other tracking methods. + +### Why bd? + +- Dependency-aware: Track blockers and relationships between issues +- Git-friendly: Dolt-powered version control with native sync +- Agent-optimized: JSON output, ready work detection, discovered-from links +- Prevents duplicate tracking systems and confusion + +### Quick Start + +**Check for ready work:** + +```bash +bd ready --json +``` + +**Create new issues:** + +```bash +bd create "Issue title" --description="Detailed context" -t bug|feature|task -p 0-4 --json +bd create "Issue title" --description="What this issue is about" -p 1 --deps discovered-from:bd-123 --json +``` + +**Claim and update:** + +```bash +bd update --claim --json +bd update bd-42 --priority 1 --json +``` + +**Complete work:** + +```bash +bd close bd-42 --reason "Completed" --json +``` + +### Issue Types + +- `bug` - Something broken +- `feature` - New functionality +- `task` - Work item (tests, docs, refactoring) +- `epic` - Large feature with subtasks +- `chore` - Maintenance (dependencies, tooling) + +### Priorities + +- `0` - Critical (security, data loss, broken builds) +- `1` - High (major features, important bugs) +- `2` - Medium (default, nice-to-have) +- `3` - Low (polish, optimization) +- `4` - Backlog (future ideas) + +### Workflow for AI Agents + +1. **Check ready work**: `bd ready` shows unblocked issues +2. **Claim your task atomically**: `bd update --claim` +3. **Work on it**: Implement, test, document +4. **Discover new work?** Create linked issue: + - `bd create "Found bug" --description="Details about what was found" -p 1 --deps discovered-from:` +5. **Complete**: `bd close --reason "Done"` + +### Quality +- Use `--acceptance` and `--design` fields when creating issues +- Use `--validate` to check description completeness + +### Lifecycle +- `bd defer ` / `bd supersede ` for issue management +- `bd stale` / `bd orphans` / `bd lint` for hygiene +- `bd human ` to flag for human decisions +- `bd formula list` / `bd mol pour ` for structured workflows + +### Sync + +bd stores issue history in Dolt: + +- Each write auto-commits to Dolt history +- Do not treat `.beads/issues.jsonl` as the sync protocol + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. + +### Important Rules + +- ✅ Use bd for ALL task tracking +- ✅ Always use `--json` flag for programmatic use +- ✅ Link discovered work with `discovered-from` dependencies +- ✅ Check `bd ready` before asking "what should I work on?" +- ❌ Do NOT create markdown TODO lists +- ❌ Do NOT use external issue trackers +- ❌ Do NOT duplicate tracking systems + +For more details, see README.md and https://github.com/gastownhall/beads/blob/main/docs/getting-started/quickstart.md. + +## Agent Context Profiles + +The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions. + +- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands. +- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise. +- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins. + +## Session Completion + +This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions. + +1. **File issues for remaining work** - Create beads for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **Handle git/sync by active profile**: + ```bash + # Conservative/minimal/default: report status and proposed commands; wait for approval. + git status + + # Team-maintainer opt-in only, unless current instructions forbid it: + git pull --rebase + git push + git status + ``` +5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step + +**Critical rules:** +- Explicit user or orchestrator instructions override this Beads block. +- Do not commit or push without clear authority from the active profile or the current user request. +- If a required sync or push is blocked, stop and report the exact command and error. + + diff --git a/internal/templates/agents/testdata/managed-section-full-user.md b/internal/templates/agents/testdata/managed-section-full-user.md new file mode 100644 index 000000000..56e8785fc --- /dev/null +++ b/internal/templates/agents/testdata/managed-section-full-user.md @@ -0,0 +1,133 @@ + +## Issue Tracking with bd (beads) + +This Beads block applies only in beads repositories: repositories that use **bd (beads)** for issue tracking, with a `.beads/` directory. Ignore it in any other repository. + +**IMPORTANT**: In a beads repository, use **bd (beads)** for ALL issue tracking. Do NOT use markdown TODOs, task lists, or other tracking methods. + +### Why bd? + +- Dependency-aware: Track blockers and relationships between issues +- Git-friendly: Dolt-powered version control with native sync +- Agent-optimized: JSON output, ready work detection, discovered-from links +- Prevents duplicate tracking systems and confusion + +### Quick Start + +**Check for ready work:** + +```bash +bd ready --json +``` + +**Create new issues:** + +```bash +bd create "Issue title" --description="Detailed context" -t bug|feature|task -p 0-4 --json +bd create "Issue title" --description="What this issue is about" -p 1 --deps discovered-from:bd-123 --json +``` + +**Claim and update:** + +```bash +bd update --claim --json +bd update bd-42 --priority 1 --json +``` + +**Complete work:** + +```bash +bd close bd-42 --reason "Completed" --json +``` + +### Issue Types + +- `bug` - Something broken +- `feature` - New functionality +- `task` - Work item (tests, docs, refactoring) +- `epic` - Large feature with subtasks +- `chore` - Maintenance (dependencies, tooling) + +### Priorities + +- `0` - Critical (security, data loss, broken builds) +- `1` - High (major features, important bugs) +- `2` - Medium (default, nice-to-have) +- `3` - Low (polish, optimization) +- `4` - Backlog (future ideas) + +### Workflow for AI Agents + +1. **Check ready work**: `bd ready` shows unblocked issues +2. **Claim your task atomically**: `bd update --claim` +3. **Work on it**: Implement, test, document +4. **Discover new work?** Create linked issue: + - `bd create "Found bug" --description="Details about what was found" -p 1 --deps discovered-from:` +5. **Complete**: `bd close --reason "Done"` + +### Quality +- Use `--acceptance` and `--design` fields when creating issues +- Use `--validate` to check description completeness + +### Lifecycle +- `bd defer ` / `bd supersede ` for issue management +- `bd stale` / `bd orphans` / `bd lint` for hygiene +- `bd human ` to flag for human decisions +- `bd formula list` / `bd mol pour ` for structured workflows + +### Sync + +bd stores issue history in Dolt: + +- Each write auto-commits to Dolt history +- Use `bd dolt push`/`bd dolt pull` for remote sync +- Do not treat `.beads/issues.jsonl` as the sync protocol + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. + +### Important Rules + +- ✅ In a beads repository, use bd for ALL task tracking +- ✅ Always use `--json` flag for programmatic use +- ✅ Link discovered work with `discovered-from` dependencies +- ✅ Check `bd ready` before asking "what should I work on?" +- ❌ Do NOT create markdown TODO lists +- ❌ Do NOT use external issue trackers +- ❌ Do NOT duplicate tracking systems + +For more details, see README.md and https://github.com/gastownhall/beads/blob/main/docs/getting-started/quickstart.md. + +## Agent Context Profiles + +The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions. + +- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands. +- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise. +- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins. + +## Session Completion + +This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions. + +1. **File issues for remaining work** - Create beads for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **Handle git/sync by active profile**: + ```bash + # Conservative/minimal/default: report status and proposed commands; wait for approval. + git status + + # Team-maintainer opt-in only, unless current instructions forbid it: + git pull --rebase + bd dolt push + git push + git status + ``` +5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step + +**Critical rules:** +- Explicit user or orchestrator instructions override this Beads block. +- Do not commit or push without clear authority from the active profile or the current user request. +- If a required sync or push is blocked, stop and report the exact command and error. + + diff --git a/internal/templates/agents/testdata/managed-section-full.md b/internal/templates/agents/testdata/managed-section-full.md new file mode 100644 index 000000000..831c2b736 --- /dev/null +++ b/internal/templates/agents/testdata/managed-section-full.md @@ -0,0 +1,131 @@ + +## Issue Tracking with bd (beads) + +**IMPORTANT**: This project uses **bd (beads)** for ALL issue tracking. Do NOT use markdown TODOs, task lists, or other tracking methods. + +### Why bd? + +- Dependency-aware: Track blockers and relationships between issues +- Git-friendly: Dolt-powered version control with native sync +- Agent-optimized: JSON output, ready work detection, discovered-from links +- Prevents duplicate tracking systems and confusion + +### Quick Start + +**Check for ready work:** + +```bash +bd ready --json +``` + +**Create new issues:** + +```bash +bd create "Issue title" --description="Detailed context" -t bug|feature|task -p 0-4 --json +bd create "Issue title" --description="What this issue is about" -p 1 --deps discovered-from:bd-123 --json +``` + +**Claim and update:** + +```bash +bd update --claim --json +bd update bd-42 --priority 1 --json +``` + +**Complete work:** + +```bash +bd close bd-42 --reason "Completed" --json +``` + +### Issue Types + +- `bug` - Something broken +- `feature` - New functionality +- `task` - Work item (tests, docs, refactoring) +- `epic` - Large feature with subtasks +- `chore` - Maintenance (dependencies, tooling) + +### Priorities + +- `0` - Critical (security, data loss, broken builds) +- `1` - High (major features, important bugs) +- `2` - Medium (default, nice-to-have) +- `3` - Low (polish, optimization) +- `4` - Backlog (future ideas) + +### Workflow for AI Agents + +1. **Check ready work**: `bd ready` shows unblocked issues +2. **Claim your task atomically**: `bd update --claim` +3. **Work on it**: Implement, test, document +4. **Discover new work?** Create linked issue: + - `bd create "Found bug" --description="Details about what was found" -p 1 --deps discovered-from:` +5. **Complete**: `bd close --reason "Done"` + +### Quality +- Use `--acceptance` and `--design` fields when creating issues +- Use `--validate` to check description completeness + +### Lifecycle +- `bd defer ` / `bd supersede ` for issue management +- `bd stale` / `bd orphans` / `bd lint` for hygiene +- `bd human ` to flag for human decisions +- `bd formula list` / `bd mol pour ` for structured workflows + +### Sync + +bd stores issue history in Dolt: + +- Each write auto-commits to Dolt history +- Use `bd dolt push`/`bd dolt pull` for remote sync +- Do not treat `.beads/issues.jsonl` as the sync protocol + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. + +### Important Rules + +- ✅ Use bd for ALL task tracking +- ✅ Always use `--json` flag for programmatic use +- ✅ Link discovered work with `discovered-from` dependencies +- ✅ Check `bd ready` before asking "what should I work on?" +- ❌ Do NOT create markdown TODO lists +- ❌ Do NOT use external issue trackers +- ❌ Do NOT duplicate tracking systems + +For more details, see README.md and https://github.com/gastownhall/beads/blob/main/docs/getting-started/quickstart.md. + +## Agent Context Profiles + +The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions. + +- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands. +- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise. +- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins. + +## Session Completion + +This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions. + +1. **File issues for remaining work** - Create beads for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **Handle git/sync by active profile**: + ```bash + # Conservative/minimal/default: report status and proposed commands; wait for approval. + git status + + # Team-maintainer opt-in only, unless current instructions forbid it: + git pull --rebase + bd dolt push + git push + git status + ``` +5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step + +**Critical rules:** +- Explicit user or orchestrator instructions override this Beads block. +- Do not commit or push without clear authority from the active profile or the current user request. +- If a required sync or push is blocked, stop and report the exact command and error. + + diff --git a/internal/templates/agents/testdata/managed-section-minimal-no-remote.md b/internal/templates/agents/testdata/managed-section-minimal-no-remote.md new file mode 100644 index 000000000..1ab497bff --- /dev/null +++ b/internal/templates/agents/testdata/managed-section-minimal-no-remote.md @@ -0,0 +1,54 @@ + +## Beads Issue Tracker + +This project uses **bd (beads)** for issue tracking. Run `bd prime` to see full workflow context and commands. + +### Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --claim # Claim work +bd close # Complete work +``` + +### Rules + +- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists +- Run `bd prime` for detailed command reference and session close protocol +- Use `bd remember` for durable project facts — not per-tool memory files, which fragment across accounts; keep per-operator preferences in your harness's own memory + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. + +## Agent Context Profiles + +The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions. + +- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands. +- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise. +- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins. + +## Session Completion + +This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions. + +1. **File issues for remaining work** - Create beads for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **Handle git/sync by active profile**: + ```bash + # Conservative/minimal/default: report status and proposed commands; wait for approval. + git status + + # Team-maintainer opt-in only, unless current instructions forbid it: + git pull --rebase + git push + git status + ``` +5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step + +**Critical rules:** +- Explicit user or orchestrator instructions override this Beads block. +- Do not commit or push without clear authority from the active profile or the current user request. +- If a required sync or push is blocked, stop and report the exact command and error. + diff --git a/internal/templates/agents/testdata/managed-section-minimal-user.md b/internal/templates/agents/testdata/managed-section-minimal-user.md new file mode 100644 index 000000000..5c51e2c14 --- /dev/null +++ b/internal/templates/agents/testdata/managed-section-minimal-user.md @@ -0,0 +1,55 @@ + +## Beads Issue Tracker + +This Beads block applies only in beads repositories: repositories that use **bd (beads)** for issue tracking, with a `.beads/` directory. Ignore it in any other repository. In a beads repository, run `bd prime` to see full workflow context and commands. + +### Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --claim # Claim work +bd close # Complete work +``` + +### Rules + +- In a beads repository, use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists +- Run `bd prime` for detailed command reference and session close protocol +- In a beads repository, use `bd remember` for durable project facts — not per-tool memory files, which fragment across accounts; keep per-operator preferences in your harness's own memory + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. + +## Agent Context Profiles + +The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions. + +- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands. +- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise. +- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins. + +## Session Completion + +This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions. + +1. **File issues for remaining work** - Create beads for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **Handle git/sync by active profile**: + ```bash + # Conservative/minimal/default: report status and proposed commands; wait for approval. + git status + + # Team-maintainer opt-in only, unless current instructions forbid it: + git pull --rebase + bd dolt push + git push + git status + ``` +5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step + +**Critical rules:** +- Explicit user or orchestrator instructions override this Beads block. +- Do not commit or push without clear authority from the active profile or the current user request. +- If a required sync or push is blocked, stop and report the exact command and error. + diff --git a/internal/templates/agents/testdata/managed-section-minimal.md b/internal/templates/agents/testdata/managed-section-minimal.md new file mode 100644 index 000000000..22c48412a --- /dev/null +++ b/internal/templates/agents/testdata/managed-section-minimal.md @@ -0,0 +1,55 @@ + +## Beads Issue Tracker + +This project uses **bd (beads)** for issue tracking. Run `bd prime` to see full workflow context and commands. + +### Quick Reference + +```bash +bd ready # Find available work +bd show # View issue details +bd update --claim # Claim work +bd close # Complete work +``` + +### Rules + +- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists +- Run `bd prime` for detailed command reference and session close protocol +- Use `bd remember` for durable project facts — not per-tool memory files, which fragment across accounts; keep per-operator preferences in your harness's own memory + +**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/core-concepts/sync-concepts.md for details and anti-patterns. + +## Agent Context Profiles + +The managed Beads block is task-tracking guidance, not permission to override repository, user, or orchestrator instructions. + +- **Conservative (default)**: Use `bd` for task tracking. Do not run git commits, git pushes, or Dolt remote sync unless explicitly asked. At handoff, report changed files, validation, and suggested next commands. +- **Minimal**: Keep tool instruction files as pointers to `bd prime`; use the same conservative git policy unless active instructions say otherwise. +- **Team-maintainer**: Only when the repository explicitly opts in, agents may close beads, run quality gates, commit, and push as part of session close. A current "do not commit" or "do not push" instruction still wins. + +## Session Completion + +This protocol applies when ending a Beads implementation workflow. It is subordinate to explicit user, repository, and orchestrator instructions. + +1. **File issues for remaining work** - Create beads for anything that needs follow-up +2. **Run quality gates** (if code changed) - Tests, linters, builds +3. **Update issue status** - Close finished work, update in-progress items +4. **Handle git/sync by active profile**: + ```bash + # Conservative/minimal/default: report status and proposed commands; wait for approval. + git status + + # Team-maintainer opt-in only, unless current instructions forbid it: + git pull --rebase + bd dolt push + git push + git status + ``` +5. **Hand off** - Summarize changes, validation, issue status, and any blocked sync/commit/push step + +**Critical rules:** +- Explicit user or orchestrator instructions override this Beads block. +- Do not commit or push without clear authority from the active profile or the current user request. +- If a required sync or push is blocked, stop and report the exact command and error. + diff --git a/internal/testutil/BUILD.bazel b/internal/testutil/BUILD.bazel index 7e54398e1..28367d0eb 100644 --- a/internal/testutil/BUILD.bazel +++ b/internal/testutil/BUILD.bazel @@ -1,4 +1,5 @@ load("@rules_go//go:def.bzl", "go_library", "go_test") +load("@rules_shell//shell:sh_test.bzl", "sh_test") go_library( name = "testutil", @@ -6,6 +7,7 @@ go_library( "container_provider.go", "container_provider_windows.go", "dockercontext.go", + "git_env.go", "git_test_hooks.go", "localdoltserver.go", "localdoltserver_linux.go", @@ -13,6 +15,7 @@ go_library( "suite_temp.go", "testdoltbranch.go", "testdoltcommon.go", + "testdoltreap.go", "testdoltserver.go", "testdoltserver_windows.go", "tmpfs.go", @@ -20,6 +23,7 @@ go_library( importpath = "github.com/steveyegge/beads/internal/testutil", visibility = ["//:__subpackages__"], deps = [ + "//internal/execenv", "//internal/storage/doltutil", "//internal/testutil/bazeltest", "@com_github_go_sql_driver_mysql//:mysql", @@ -107,12 +111,14 @@ go_test( name = "testutil_test", srcs = [ "dockercontext_test.go", + "git_env_test.go", "gm2g3g5r_failopen_test.go", "gm2g3g5r_failopen_unix_test.go", "gm2g3g5r_failopen_windows_test.go", "localdoltserver_test.go", "suite_temp_test.go", "testdoltbranch_test.go", + "testdoltreap_test.go", "testdoltserver_env_test.go", "testdoltserver_unreachable_test.go", "tmpfs_test.go", @@ -122,11 +128,101 @@ go_test( deps = [ "//internal/storage/doltutil", "@com_github_go_sql_driver_mysql//:mysql", - ], + ] + select({ + "@rules_go//go/platform:aix": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:android": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:darwin": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:dragonfly": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:freebsd": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:illumos": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:ios": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:js": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:linux": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:netbsd": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:openbsd": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:osx": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:plan9": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:qnx": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "@rules_go//go/platform:solaris": [ + "@com_github_testcontainers_testcontainers_go//:testcontainers-go", + "@com_github_testcontainers_testcontainers_go_modules_dolt//:dolt", + ], + "//conditions:default": [], + }), ) -# Dolt image pin read as text by //test/docsync and the dolt pin tests in -# //scripts. +# testutil_test on the dolt-server lane: the package's own tests of the +# test-server backends, with the local backend selected and required, so +# TestDoltServerFingerprint's local half (formerly pr.yml's "Test (Dolt +# server fingerprint)" job, every PR) and the TestLocalDoltServer_* tests run +# against the pinned dolt in the test wrapper's runfiles. Every other +# configuration of testutil_test passes BEADS_TEST_SKIP=dolt and skips them. +# The container half needs docker and the image, so no Bazel target runs it: +# it runs under plain `go test` (the container backend is the default there) +# on a host that has both, and TestPinnedDoltCLIMatchesContainerImage +# (//scripts) keeps the image tag on the pinned release. +# +# Tags: +# dolt-server: starts hermetic dolt sql-servers from the pinned dolt in the +# test wrapper's runfiles (BEADS_TEST_DOLT_SERVER=local); excluded from +# --config=prcore/ci, selected by --config=doltserver. +sh_test( + name = "testutil_dolt_test", + size = "medium", + srcs = ["//tools/bazel:go_test_variant.sh"], + args = ["$(rootpath :testutil_test)"], + data = [":testutil_test"], + env = { + "BEADS_TEST_DOLT_SERVER": "local", + "BEADS_TEST_REQUIRE_DOLT_CONTAINER": "1", + }, + tags = ["dolt-server"], +) + +# The pinned dolt sql-server image, read by //scripts:scripts_test (the CI +# pins agree) and //test/docsync (the docs' pin agrees). exports_files( ["testdoltcommon.go"], visibility = [ @@ -134,3 +230,64 @@ exports_files( "//test/docsync:__pkg__", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/testutil/bazeltest/BUILD.bazel b/internal/testutil/bazeltest/BUILD.bazel index ea4bf0b8c..cdb9d6d9e 100644 --- a/internal/testutil/bazeltest/BUILD.bazel +++ b/internal/testutil/bazeltest/BUILD.bazel @@ -13,3 +13,64 @@ go_test( data = glob(["testdata/**"]), embed = [":bazeltest"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/testutil/container_provider.go b/internal/testutil/container_provider.go index b6573eb41..6f461a776 100644 --- a/internal/testutil/container_provider.go +++ b/internal/testutil/container_provider.go @@ -39,9 +39,11 @@ func NewContainerProvider() (*ContainerProvider, error) { ctx, cancel := context.WithTimeout(context.Background(), serverStartTimeout) defer cancel() + reapStaleDoltContainers() ctr, err := dolt.Run(ctx, DoltDockerImage, dolt.WithDatabase("beads_test"), testcontainers.WithEnv(map[string]string{"DOLT_ROOT_HOST": "%"}), + ownerLabels(), ) if err != nil { return nil, fmt.Errorf("starting Dolt container: %w", err) diff --git a/internal/testutil/credentialcmd/BUILD.bazel b/internal/testutil/credentialcmd/BUILD.bazel index 3ea66fd39..d37bbe4a3 100644 --- a/internal/testutil/credentialcmd/BUILD.bazel +++ b/internal/testutil/credentialcmd/BUILD.bazel @@ -16,3 +16,64 @@ go_test( srcs = ["credentialcmd_test.go"], embed = [":credentialcmd"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/testutil/fixtures/BUILD.bazel b/internal/testutil/fixtures/BUILD.bazel index 4f79f92a7..b8b65f00d 100644 --- a/internal/testutil/fixtures/BUILD.bazel +++ b/internal/testutil/fixtures/BUILD.bazel @@ -25,3 +25,64 @@ go_test( "//internal/types", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/testutil/git_env.go b/internal/testutil/git_env.go new file mode 100644 index 000000000..5823f0b8c --- /dev/null +++ b/internal/testutil/git_env.go @@ -0,0 +1,52 @@ +package testutil + +import ( + "fmt" + "os" + + "github.com/steveyegge/beads/internal/execenv" +) + +// gitRepoLocationKeys are the git environment variables that name a +// repository, work tree, index, object store, ref namespace or config file +// outright. Each one overrides what git would find from cmd.Dir or -C, so a +// value leaked in from the invoking shell or a git hook (git exports GIT_DIR to +// every hook it runs) points a fixture's `git init`/`git config` at a +// repository or file the test does not own: the r880 host .git/config clobber +// (wy-qlvlmf). GIT_CONFIG is the legacy single-file override: `git config` +// reads and writes the file it names instead of the repository's config. +// +// The set is deliberately narrower than internal/gitenv's routing keys. It +// leaves GIT_CEILING_DIRECTORIES, GIT_CONFIG_GLOBAL and GIT_CONFIG_NOSYSTEM +// alone because the Bazel and CI test wrappers set those on purpose: a +// discovery fence, and a hermetic global config that carries the test +// identity. Keys match exactly, so dropping GIT_CONFIG keeps all three. +var gitRepoLocationKeys = []string{ + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_COMMON_DIR", + "GIT_CONFIG", + "GIT_DIR", + "GIT_INDEX_FILE", + "GIT_NAMESPACE", + "GIT_OBJECT_DIRECTORY", + "GIT_WORK_TREE", +} + +// WithoutGitRepoLocationEnv returns a copy of env without the variables that +// name a git repository location, for a fixture command's cmd.Env: the command +// then operates on the repository its cmd.Dir resolves to and nothing else. +func WithoutGitRepoLocationEnv(env []string) []string { + return execenv.Without(env, gitRepoLocationKeys...) +} + +// UnsetGitRepoLocationEnv removes the same variables from the current process. +// Suites call it first in TestMain so no fixture git command inherits a leaked +// location; a test that needs one sets it with t.Setenv. +func UnsetGitRepoLocationEnv() error { + for _, key := range gitRepoLocationKeys { + if err := os.Unsetenv(key); err != nil { + return fmt.Errorf("unset %s: %w", key, err) + } + } + return nil +} diff --git a/internal/testutil/git_env_test.go b/internal/testutil/git_env_test.go new file mode 100644 index 000000000..48c2a846e --- /dev/null +++ b/internal/testutil/git_env_test.go @@ -0,0 +1,114 @@ +package testutil + +import ( + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" +) + +// wrapperGitEnv is what tools/bazel/test_env.sh and scripts/ci/lib/test-env.sh +// export for every test. The location scrub must leave all of it in place. +var wrapperGitEnv = []string{ + "GIT_CEILING_DIRECTORIES=/sandbox/srcdir:/sandbox/tmp", + "GIT_CONFIG_GLOBAL=/sandbox/gitconfig", + "GIT_CONFIG_NOSYSTEM=1", +} + +func TestWithoutGitRepoLocationEnvKeepsWrapperGitControls(t *testing.T) { + env := append([]string{ + "GIT_DIR=/host/.git/worktrees/wt", + "GIT_WORK_TREE=/host", + "GIT_COMMON_DIR=/host/.git", + "GIT_INDEX_FILE=/host/.git/worktrees/wt/index", + "GIT_OBJECT_DIRECTORY=/host/.git/objects", + "GIT_ALTERNATE_OBJECT_DIRECTORIES=/host/.git/objects", + "GIT_NAMESPACE=host", + "GIT_CONFIG=/host/.git/config", + "HOME=/sandbox/home", + }, wrapperGitEnv...) + + got := WithoutGitRepoLocationEnv(env) + want := append([]string{"HOME=/sandbox/home"}, wrapperGitEnv...) + if !slices.Equal(got, want) { + t.Fatalf("WithoutGitRepoLocationEnv:\n got %q\nwant %q", got, want) + } +} + +func TestUnsetGitRepoLocationEnvKeepsWrapperGitControls(t *testing.T) { + for _, key := range gitRepoLocationKeys { + t.Setenv(key, "/host/"+key) + } + for _, entry := range wrapperGitEnv { + key, value, _ := strings.Cut(entry, "=") + t.Setenv(key, value) + } + + if err := UnsetGitRepoLocationEnv(); err != nil { + t.Fatal(err) + } + for _, key := range gitRepoLocationKeys { + if value, ok := os.LookupEnv(key); ok { + t.Errorf("%s=%q survived UnsetGitRepoLocationEnv", key, value) + } + } + for _, entry := range wrapperGitEnv { + key, want, _ := strings.Cut(entry, "=") + if got := os.Getenv(key); got != want { + t.Errorf("%s=%q after UnsetGitRepoLocationEnv, want %q kept", key, got, want) + } + } +} + +// TestForceRepoLocalHooksPathIgnoresLeakedGitDir pins the write target: with +// GIT_DIR and GIT_WORK_TREE naming another repository, or GIT_CONFIG naming +// another config file, the hooksPath write must still land in repoDir and leave +// the other config untouched. +func TestForceRepoLocalHooksPathIgnoresLeakedGitDir(t *testing.T) { + decoy, target := t.TempDir(), t.TempDir() + for _, dir := range []string{decoy, target} { + cmd := exec.Command("git", "init", "--quiet", dir) + cmd.Env = WithoutGitRepoLocationEnv(os.Environ()) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git init %s: %v\n%s", dir, err, out) + } + } + decoyConfig := filepath.Join(decoy, ".git", "config") + before, err := os.ReadFile(decoyConfig) + if err != nil { + t.Fatal(err) + } + decoyFile := filepath.Join(t.TempDir(), "leaked.gitconfig") + const decoyFileBefore = "[user]\n\tname = decoy\n" + if err := os.WriteFile(decoyFile, []byte(decoyFileBefore), 0o600); err != nil { + t.Fatal(err) + } + + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + t.Setenv("GIT_WORK_TREE", decoy) + t.Setenv("GIT_CONFIG", decoyFile) + if err := ForceRepoLocalHooksPath(target); err != nil { + t.Fatal(err) + } + + after, err := os.ReadFile(decoyConfig) + if err != nil { + t.Fatal(err) + } + if string(after) != string(before) { + t.Fatalf("leaked GIT_DIR routed the hooksPath write into %s:\n%s", decoyConfig, after) + } + if got, err := os.ReadFile(decoyFile); err != nil || string(got) != decoyFileBefore { + t.Fatalf("leaked GIT_CONFIG routed the hooksPath write into %s (err %v):\n%s", decoyFile, err, got) + } + get := exec.Command("git", "config", "--file", filepath.Join(target, ".git", "config"), "--get", "core.hooksPath") + out, err := get.CombinedOutput() + if err != nil { + t.Fatalf("read target core.hooksPath: %v\n%s", err, out) + } + if got := strings.TrimSpace(string(out)); got != ".git/hooks" { + t.Fatalf("target core.hooksPath=%q, want %q", got, ".git/hooks") + } +} diff --git a/internal/testutil/git_test_hooks.go b/internal/testutil/git_test_hooks.go index 84f12d983..4e6c17475 100644 --- a/internal/testutil/git_test_hooks.go +++ b/internal/testutil/git_test_hooks.go @@ -2,15 +2,18 @@ package testutil import ( "fmt" + "os" "os/exec" "strings" ) // ForceRepoLocalHooksPath configures a git test repository to use .git/hooks -// regardless of any global core.hooksPath configuration. +// regardless of any global core.hooksPath configuration. The write goes to +// repoDir even when a GIT_DIR or GIT_WORK_TREE leaked into the process. func ForceRepoLocalHooksPath(repoDir string) error { cmd := exec.Command("git", "config", "core.hooksPath", ".git/hooks") cmd.Dir = repoDir + cmd.Env = WithoutGitRepoLocationEnv(os.Environ()) if out, err := cmd.CombinedOutput(); err != nil { trimmed := strings.TrimSpace(string(out)) if trimmed != "" { diff --git a/internal/testutil/integration/BUILD.bazel b/internal/testutil/integration/BUILD.bazel index f34816ff5..40d2017d5 100644 --- a/internal/testutil/integration/BUILD.bazel +++ b/internal/testutil/integration/BUILD.bazel @@ -79,3 +79,64 @@ go_test( env = {"BEADS_TEST_GO_BINARY": "$(rlocationpath @go_sdk//:bin/go)"}, tags = ["integration-only"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/testutil/integration/diagnostics.go b/internal/testutil/integration/diagnostics.go index 136d724ec..0e0b7c73e 100644 --- a/internal/testutil/integration/diagnostics.go +++ b/internal/testutil/integration/diagnostics.go @@ -39,7 +39,7 @@ func (d *Diagnostics) CaptureOnFailure() { func (d *Diagnostics) dumpStateFiles() { for _, name := range []string{"dolt-server.pid", "dolt-server.port", "dolt-server.log"} { path := filepath.Join(d.beadsDir, name) - data, err := os.ReadFile(path) + data, err := os.ReadFile(path) //nolint:gosec // G304: a fixed state-file name under the test's own .beads dir if err != nil { d.t.Logf(" %s: not found", name) continue @@ -69,7 +69,7 @@ func (d *Diagnostics) dumpProcessList() { if pid[0] < '0' || pid[0] > '9' { continue } - cmdline, err := os.ReadFile(filepath.Join("/proc", pid, "cmdline")) + cmdline, err := os.ReadFile(filepath.Join("/proc", pid, "cmdline")) //nolint:gosec // G304: /proc//cmdline if err != nil { continue } diff --git a/internal/testutil/integration/harness.go b/internal/testutil/integration/harness.go index 03fd1607f..f6af935de 100644 --- a/internal/testutil/integration/harness.go +++ b/internal/testutil/integration/harness.go @@ -183,7 +183,7 @@ func (r *SubprocessRunner) Build(t *testing.T) string { r.buildErr = fmt.Errorf("failed to build test binary: %w\nstderr: %s\nstdout: %s", err, stderr.String(), stdout.String()) return } - if err := os.Chmod(r.testBin, 0700); err != nil { + if err := os.Chmod(r.testBin, 0700); err != nil { //nolint:gosec // G302: the test binary must be executable r.buildErr = fmt.Errorf("failed to chmod test binary: %w", err) } }) @@ -349,7 +349,7 @@ func WaitForPort(t *testing.T, host string, port int, timeout time.Duration) { // ReadPIDFile reads and parses a PID file, returning 0 if missing or corrupt. func ReadPIDFile(path string) int { - data, err := os.ReadFile(path) + data, err := os.ReadFile(path) //nolint:gosec // G304: a state file path the harness itself derived if err != nil { return 0 } @@ -362,7 +362,7 @@ func ReadPIDFile(path string) int { // ReadPortFile reads and parses a port file, returning 0 if missing or corrupt. func ReadPortFile(path string) int { - data, err := os.ReadFile(path) + data, err := os.ReadFile(path) //nolint:gosec // G304: a state file path the harness itself derived if err != nil { return 0 } diff --git a/internal/testutil/testdoltreap.go b/internal/testutil/testdoltreap.go new file mode 100644 index 000000000..8cb8cf266 --- /dev/null +++ b/internal/testutil/testdoltreap.go @@ -0,0 +1,209 @@ +//go:build !windows + +package testutil + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "runtime" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "github.com/testcontainers/testcontainers-go" +) + +// Stale-container sweep for the Dolt test containers this package starts. +// +// Every container started here carries three labels naming its owner: the +// test binary's pid, the PID namespace that pid belongs to, and the host it +// runs on. Before the first container of a process starts, +// reapStaleDoltContainers lists the containers labeled for this host and +// removes the ones whose owner ran in this process's PID namespace and no +// longer exists. +// +// Why: in-process cleanup (t.Cleanup, TerminateDoltContainer after m.Run) +// never runs when a test binary is killed, or panics on `go test -timeout`, +// and a box running with TESTCONTAINERS_RYUK_DISABLED=true has no reaper +// either. Each such run stranded one idle dolt-sql-server holding 100-470 MiB +// (23 at once on one loaded box, 2026-09-29). The sweep bounds the pile at +// "runs since the last run" instead of "forever". +// +// Safety under concurrent test processes sharing one Docker daemon: a +// container is removed only when its owner ran in this process's PID +// namespace and kill(pid, 0) reports ESRCH. A live owner, a pid reused by +// another live process, or a pid this user may not signal (EPERM) all keep +// the container. A pid means nothing outside its namespace, and sandboxed +// runners (bwrap --unshare-pid, a container without --pid=host) can share the +// hostname and the daemon while seeing none of each other's processes, so a +// container owned from another namespace is never a candidate: if it leaked, +// only a sweep from its own namespace removes it. The namespace label is the +// /proc/self/ns/pid link on Linux, unique among one machine's live +// namespaces, and "" elsewhere; a new namespace that reuses a dead one's +// inode only sees containers whose owners have all exited. Containers without +// the owner labels (older harnesses, other tools) are never touched, and the +// host label keeps a remote DOCKER_HOST's containers, whose pids mean nothing +// here, out of the sweep. + +const ( + ownerPIDLabel = "com.gastownhall.beads.testutil.owner-pid" + ownerPIDNSLabel = "com.gastownhall.beads.testutil.owner-pidns" + ownerHostLabel = "com.gastownhall.beads.testutil.owner-host" +) + +// sweepTimeout bounds the whole sweep, so a wedged daemon or container delays +// the first container start of a process instead of hanging it. +const sweepTimeout = 30 * time.Second + +var reapStaleOnce sync.Once + +// ownerLabels returns the container option that stamps the owner labels. +func ownerLabels() testcontainers.CustomizeRequestOption { + return testcontainers.WithLabels(ownerLabelValues(os.Getpid())) +} + +// ownerLabelValues returns the owner labels for a container owned by pid, a +// process in this process's PID namespace on this host. A hostname, or a Linux +// PID namespace, that cannot be read is stamped as "", which no sweep on this +// host matches: the container leaks rather than risk removal while pid lives. +func ownerLabelValues(pid int) map[string]string { + host, _ := os.Hostname() + ns, _ := pidNamespace() + return map[string]string{ + ownerPIDLabel: strconv.Itoa(pid), + ownerPIDNSLabel: ns, + ownerHostLabel: host, + } +} + +// pidNamespace identifies the PID namespace that os.Getpid and kill(2) +// resolve pids in: the /proc/self/ns/pid link target on Linux, such as +// "pid:[4026531836]", and "" elsewhere. +func pidNamespace() (string, error) { + if runtime.GOOS != "linux" { + return "", nil + } + return os.Readlink("/proc/self/ns/pid") +} + +// ownedContainer is one `docker ps` row: the container id and the raw values +// of its owner-pid and owner-pidns labels. +type ownedContainer struct { + id string + pid string + pidNS string +} + +// staleContainers returns the ids of the rows owned from PID namespace ns +// whose owner pid is dead according to alive. Rows owned from another +// namespace, and rows whose pid label is missing, non-numeric or +// non-positive, are kept: their owner cannot be checked from here, so nothing +// is done. +func staleContainers(rows []ownedContainer, ns string, alive func(pid int) bool) []string { + var stale []string + for _, r := range rows { + if r.pidNS != ns { + continue + } + pid, err := strconv.Atoi(strings.TrimSpace(r.pid)) + if err != nil || pid <= 0 { + continue + } + if alive(pid) { + continue + } + stale = append(stale, r.id) + } + return stale +} + +// pidAlive reports whether a process with the given pid exists. Only ESRCH +// counts as dead; EPERM means the process exists but belongs to someone else. +func pidAlive(pid int) bool { + err := syscall.Kill(pid, 0) + return !errors.Is(err, syscall.ESRCH) +} + +// dockerCommand returns a docker CLI command bound to ctx. WaitDelay lets it +// return once ctx is done even if a process the docker binary started, such +// as a wrapper script's child, still holds its output pipe open. +func dockerCommand(ctx context.Context, args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, "docker", args...) + cmd.WaitDelay = time.Second + return cmd +} + +// listOwnedContainers returns every container (running or not) that carries +// this package's owner-host label for host. +func listOwnedContainers(ctx context.Context, host string) ([]ownedContainer, error) { + out, err := dockerCommand(ctx, "ps", "-a", "--no-trunc", + "--filter", "label="+ownerHostLabel+"="+host, + "--format", fmt.Sprintf("{{.ID}}\t{{.Label %q}}\t{{.Label %q}}", ownerPIDLabel, ownerPIDNSLabel), + ).Output() + if err != nil { + return nil, fmt.Errorf("docker ps: %w", err) + } + return parseOwnedRows(string(out)), nil +} + +// parseOwnedRows parses listOwnedContainers' `docker ps` output: one +// "idpidpidns" line per container, where a missing label prints as +// an empty field. Lines of any other shape are dropped. +func parseOwnedRows(out string) []ownedContainer { + var rows []ownedContainer + for _, line := range strings.Split(out, "\n") { + f := strings.Split(strings.TrimSuffix(line, "\r"), "\t") + if len(f) != 3 || f[0] == "" { + continue + } + rows = append(rows, ownedContainer{id: f[0], pid: f[1], pidNS: f[2]}) + } + return rows +} + +// sweepStaleDoltContainers removes every container on this host whose owner +// ran in this PID namespace and has exited, and returns the ids it removed. +// It is best effort: a docker failure is reported on stderr and leaves the +// containers alone. +func sweepStaleDoltContainers() []string { + host, err := os.Hostname() + if err != nil || host == "" { + return nil + } + ns, err := pidNamespace() + if err != nil { + fmt.Fprintf(os.Stderr, "testutil: stale Dolt container sweep skipped: %v\n", err) + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), sweepTimeout) + defer cancel() + rows, err := listOwnedContainers(ctx, host) + if err != nil { + fmt.Fprintf(os.Stderr, "testutil: stale Dolt container sweep skipped: %v\n", err) + return nil + } + var removed []string + for _, id := range staleContainers(rows, ns, pidAlive) { + // -v also removes the anonymous volume behind the image's + // VOLUME /var/lib/dolt, as testcontainers' own teardown does. + if err := dockerCommand(ctx, "rm", "-f", "-v", id).Run(); err != nil { + fmt.Fprintf(os.Stderr, "testutil: removing stale Dolt container %s: %v\n", id, err) + continue + } + fmt.Fprintf(os.Stderr, "testutil: removed stale Dolt test container %s (owner process exited)\n", id[:12]) + removed = append(removed, id) + } + return removed +} + +// reapStaleDoltContainers runs sweepStaleDoltContainers once per process. It +// is called before the first Dolt container of a process starts, so the cost +// of one `docker ps` is paid once and only by runs that use Docker at all. +func reapStaleDoltContainers() { + reapStaleOnce.Do(func() { sweepStaleDoltContainers() }) +} diff --git a/internal/testutil/testdoltreap_test.go b/internal/testutil/testdoltreap_test.go new file mode 100644 index 000000000..75a0b1b16 --- /dev/null +++ b/internal/testutil/testdoltreap_test.go @@ -0,0 +1,240 @@ +//go:build !windows + +package testutil + +import ( + "context" + "math" + "os" + "os/exec" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/testcontainers/testcontainers-go" + "github.com/testcontainers/testcontainers-go/modules/dolt" +) + +// testPIDNS stands in for this process's PID namespace in the pure tests. +const testPIDNS = "pid:[4026531836]" + +func TestStaleContainers_OnlyDeadOwnersAreStale(t *testing.T) { + alive := func(pid int) bool { return pid == 100 || pid == 300 } + rows := []ownedContainer{ + {id: "live-a", pid: "100", pidNS: testPIDNS}, + {id: "dead-b", pid: "200", pidNS: testPIDNS}, + {id: "live-c", pid: " 300 ", pidNS: testPIDNS}, + {id: "dead-d", pid: "400", pidNS: testPIDNS}, + {id: "no-label", pid: "", pidNS: testPIDNS}, + {id: "garbage", pid: "abc", pidNS: testPIDNS}, + {id: "zero", pid: "0", pidNS: testPIDNS}, + {id: "negative", pid: "-7", pidNS: testPIDNS}, + } + got := staleContainers(rows, testPIDNS, alive) + want := []string{"dead-b", "dead-d"} + if !slices.Equal(got, want) { + t.Fatalf("staleContainers = %v, want %v", got, want) + } +} + +func TestStaleContainers_NeverCallsAliveForUnownedRows(t *testing.T) { + alive := func(pid int) bool { + t.Fatalf("alive called for pid %d; rows without a valid owner pid must be skipped", pid) + return true + } + rows := []ownedContainer{ + {id: "x", pid: "", pidNS: testPIDNS}, + {id: "y", pid: "nope", pidNS: testPIDNS}, + {id: "z", pid: "0", pidNS: testPIDNS}, + } + if got := staleContainers(rows, testPIDNS, alive); got != nil { + t.Fatalf("staleContainers = %v, want nil", got) + } +} + +// A pid names a process only inside its PID namespace: checked from another +// one, a live owner reads as ESRCH. Rows owned from another namespace must +// never reach alive. +func TestStaleContainers_SkipsOtherPIDNamespaces(t *testing.T) { + alive := func(pid int) bool { + t.Fatalf("alive called for pid %d owned from another PID namespace", pid) + return true + } + rows := []ownedContainer{ + {id: "sibling-sandbox", pid: "200", pidNS: "pid:[4026546206]"}, + {id: "no-pidns-label", pid: "200", pidNS: ""}, + } + if got := staleContainers(rows, testPIDNS, alive); got != nil { + t.Fatalf("staleContainers = %v, want nil", got) + } +} + +func TestParseOwnedRows(t *testing.T) { + for _, tc := range []struct { + name string + out string + want []ownedContainer + }{ + {name: "no containers", out: "", want: nil}, + { + name: "trailing newline", + out: "aaa\t12\tpid:[7]\nbbb\t34\tpid:[7]\n", + want: []ownedContainer{{id: "aaa", pid: "12", pidNS: "pid:[7]"}, {id: "bbb", pid: "34", pidNS: "pid:[7]"}}, + }, + {name: "CRLF", out: "aaa\t12\tpid:[7]\r\n", want: []ownedContainer{{id: "aaa", pid: "12", pidNS: "pid:[7]"}}}, + // A missing label prints as an empty field. An empty pidns is what + // every owner outside Linux stamps, so the row must survive parsing. + {name: "empty pidns label", out: "aaa\t12\t\n", want: []ownedContainer{{id: "aaa", pid: "12"}}}, + {name: "empty labels", out: "aaa\t\t\n", want: []ownedContainer{{id: "aaa"}}}, + {name: "malformed lines", out: "aaa\t12\nbbb\n\t12\tpid:[7]\n", want: nil}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := parseOwnedRows(tc.out); !slices.Equal(got, tc.want) { + t.Errorf("parseOwnedRows(%q) = %+v, want %+v", tc.out, got, tc.want) + } + }) + } +} + +func TestOwnerLabels_StampThisProcess(t *testing.T) { + var req testcontainers.GenericContainerRequest + if err := ownerLabels().Customize(&req); err != nil { + t.Fatalf("ownerLabels: %v", err) + } + if got, want := req.Labels[ownerPIDLabel], strconv.Itoa(os.Getpid()); got != want { + t.Errorf("%s = %q, want %q", ownerPIDLabel, got, want) + } + ns, err := pidNamespace() + if err != nil { + t.Fatalf("pidNamespace: %v", err) + } + if got := req.Labels[ownerPIDNSLabel]; got != ns { + t.Errorf("%s = %q, want %q", ownerPIDNSLabel, got, ns) + } + host, _ := os.Hostname() + if got := req.Labels[ownerHostLabel]; got != host { + t.Errorf("%s = %q, want %q", ownerHostLabel, got, host) + } +} + +func TestPidAlive(t *testing.T) { + if !pidAlive(os.Getpid()) { + t.Fatal("pidAlive(self) = false") + } + // No process can have a pid this large on Linux (pid_max <= 2^22) or + // macOS (PID_MAX 99998): kill(2) reports ESRCH. + if pidAlive(math.MaxInt32) { + t.Fatalf("pidAlive(%d) = true, want false", math.MaxInt32) + } +} + +// TestSweepStaleDoltContainers starts one Dolt container owned by a child +// process and one owned by this process, ends the child, sweeps, and checks +// that only the container whose owner exited and its volume are gone. +func TestSweepStaleDoltContainers(t *testing.T) { + if hasTestSkip("dolt") { + t.Skip("skipping: Dolt tests skipped (BEADS_TEST_SKIP=dolt)") + } + // The sweep acts on containers, so it needs docker whichever backend + // BEADS_TEST_DOLT_SERVER selects; under the local one checkDolt only finds + // the dolt CLI (the dolt-server lane's remote workers have no docker). + if !useLocalDoltServer() { + if state := checkDolt(); state != doltReady { + skipOrFailDoltUnavailable(t, state) + } + } else if !isDockerAvailable() || !isDoltImageCached() { + t.Skipf("container backend not available on this host (docker + %s)", DoltDockerImage) + } + if host, err := os.Hostname(); err != nil || host == "" { + t.Skipf("hostname unavailable: %v", err) + } + + start := func(t *testing.T, ownerPID int) string { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), serverStartTimeout) + defer cancel() + ctr, err := dolt.Run(ctx, DoltDockerImage, + dolt.WithDatabase("beads_test"), + testcontainers.WithEnv(map[string]string{"DOLT_ROOT_HOST": "%"}), + testcontainers.WithLabels(ownerLabelValues(ownerPID)), + ) + if err != nil { + t.Fatalf("starting Dolt container: %v", err) + } + t.Cleanup(func() { + // Best effort: the dead-owned container is expected to be gone. + _ = testcontainers.TerminateContainer(ctr) + }) + return ctr.GetContainerID() + } + + // A sibling test binary's sweep (go test ./... runs them in parallel) + // removes a container as soon as it sees the owner dead, even mid-start. + // So the dead-owned container's owner is a child process that runs until + // the container is up and its volumes are read, and only then exits. + owner := exec.Command("sleep", "600") // outlives both starts + if err := owner.Start(); err != nil { + t.Fatalf("starting the owner process: %v", err) + } + endOwner := sync.OnceFunc(func() { + _ = owner.Process.Kill() + // Reaped, its pid reports ESRCH; a zombie would still read as alive. + _ = owner.Wait() + }) + t.Cleanup(endOwner) + + deadOwned := start(t, owner.Process.Pid) + liveOwned := start(t, os.Getpid()) + deadVolumes := containerVolumes(t, deadOwned) + if len(deadVolumes) == 0 { + t.Fatalf("dead-owned container %s has no volume; %s no longer declares VOLUME /var/lib/dolt?", deadOwned, DoltDockerImage) + } + endOwner() + + removed := sweepStaleDoltContainers() + + // Once its owner has exited, a sibling's sweep may remove the dead-owned + // container first, or still be removing it when ours fails to, so only + // its end state is checked, and given time to settle. + if slices.Contains(removed, liveOwned) { + t.Errorf("sweep removed the live-owned container %s", liveOwned) + } + if !dockerObjectGone("inspect", deadOwned) { + t.Errorf("dead-owned container %s still exists after the sweep", deadOwned) + } + for _, v := range deadVolumes { + if !dockerObjectGone("volume", "inspect", v) { + t.Errorf("volume %s of the dead-owned container survived the sweep", v) + } + } + if err := exec.Command("docker", "inspect", liveOwned).Run(); err != nil { + t.Errorf("live-owned container %s missing after the sweep: %v", liveOwned, err) + } +} + +// dockerObjectGone reports whether `docker args...`, an inspect of one object, +// starts failing within sweepTimeout, which also bounds a sibling's removal. +func dockerObjectGone(args ...string) bool { + deadline := time.Now().Add(sweepTimeout) + for exec.Command("docker", args...).Run() == nil { + if time.Now().After(deadline) { + return false + } + time.Sleep(100 * time.Millisecond) + } + return true +} + +// containerVolumes returns the names of the volumes mounted into container id. +func containerVolumes(t *testing.T, id string) []string { + t.Helper() + out, err := exec.Command("docker", "inspect", "--format", + `{{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}`, id).Output() + if err != nil { + t.Fatalf("docker inspect %s: %v", id, err) + } + return strings.Fields(string(out)) +} diff --git a/internal/testutil/testdoltserver.go b/internal/testutil/testdoltserver.go index ad7ca817e..771ddb1c9 100644 --- a/internal/testutil/testdoltserver.go +++ b/internal/testutil/testdoltserver.go @@ -180,6 +180,7 @@ func startDoltContainer() error { ctx, cancel := context.WithTimeout(context.Background(), serverStartTimeout) defer cancel() + reapStaleDoltContainers() ctr, err := dolt.Run(ctx, DoltDockerImage, dolt.WithDatabase("beads_test"), // Docker port-forwarding makes connections appear as non-localhost @@ -187,6 +188,7 @@ func startDoltContainer() error { // "localhost", so root@localhost won't match external connections. // Set to "%" so root can connect from any host. testcontainers.WithEnv(map[string]string{"DOLT_ROOT_HOST": "%"}), + ownerLabels(), ) if err != nil { return fmt.Errorf("starting Dolt container: %w", err) @@ -434,9 +436,11 @@ func startIsolatedDoltContainer(t *testing.T) *IsolatedDoltContainer { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), serverStartTimeout) defer cancel() + reapStaleDoltContainers() ctr, err := dolt.Run(ctx, DoltDockerImage, dolt.WithDatabase("beads_test"), testcontainers.WithEnv(map[string]string{"DOLT_ROOT_HOST": "%"}), + ownerLabels(), ) if err != nil { t.Fatalf("starting Dolt container: %v", err) diff --git a/internal/timeparsing/BUILD.bazel b/internal/timeparsing/BUILD.bazel index 3455ac0bc..c9d379697 100644 --- a/internal/timeparsing/BUILD.bazel +++ b/internal/timeparsing/BUILD.bazel @@ -20,3 +20,64 @@ go_test( ], embed = [":timeparsing"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/timeparsing/duration_test.go b/internal/timeparsing/duration_test.go index 34e7ff059..1c10d2cfb 100644 --- a/internal/timeparsing/duration_test.go +++ b/internal/timeparsing/duration_test.go @@ -183,6 +183,8 @@ func TestParseCompactDuration(t *testing.T) { } func TestIsCompactDuration(t *testing.T) { + now := time.Date(2025, 6, 15, 12, 0, 0, 0, time.UTC) + tests := []struct { input string want bool @@ -191,9 +193,11 @@ func TestIsCompactDuration(t *testing.T) { {"-1d", true}, {"+2w", true}, {"3m", true}, + {"30m", true}, {"1y", true}, {"+24h", true}, {"+30min", true}, + {"30min", true}, {"+30mins", false}, {"", false}, {"tomorrow", false}, @@ -201,13 +205,29 @@ func TestIsCompactDuration(t *testing.T) { {"6h+", false}, {"++1d", false}, {"1x", false}, + + // Units are lowercase. Folding case would make "30M" mean 30 months, + // the ambiguity "min" exists to avoid, so uppercase spellings are not + // compact durations. + {"30M", false}, + {"+6H", false}, + {"1D", false}, + {"2W", false}, + {"1Y", false}, + {"30MIN", false}, } for _, tt := range tests { t.Run(tt.input, func(t *testing.T) { - got := isCompactDuration(tt.input) + got := IsCompactDuration(tt.input) if got != tt.want { - t.Errorf("isCompactDuration(%q) = %v, want %v", tt.input, got, tt.want) + t.Errorf("IsCompactDuration(%q) = %v, want %v", tt.input, got, tt.want) + } + // Callers classify with IsCompactDuration and then parse, so the + // two must agree on every row here. + _, err := ParseCompactDuration(tt.input, now) + if parsed := err == nil; parsed != got { + t.Errorf("IsCompactDuration(%q) = %v, but ParseCompactDuration error = %v", tt.input, got, err) } }) } diff --git a/internal/timeparsing/parser.go b/internal/timeparsing/parser.go index 8d495385c..7f3552af5 100644 --- a/internal/timeparsing/parser.go +++ b/internal/timeparsing/parser.go @@ -87,8 +87,13 @@ func applyDuration(base time.Time, amount int, unit string) time.Time { } } -// isCompactDuration returns true if the string matches compact duration syntax. -func isCompactDuration(s string) bool { +// IsCompactDuration reports whether s is in the compact duration syntax that +// ParseCompactDuration parses; only an amount too large for an int matches it +// and still fails to parse. Callers that classify a compact duration without +// parsing it (the query lexer) use this instead of keeping their own copy of +// the unit set, so a unit added to compactDurationRe reaches them with no edit +// of theirs. +func IsCompactDuration(s string) bool { return compactDurationRe.MatchString(s) } diff --git a/internal/tracker/BUILD.bazel b/internal/tracker/BUILD.bazel index e0cadf8b6..853720cdd 100644 --- a/internal/tracker/BUILD.bazel +++ b/internal/tracker/BUILD.bazel @@ -60,34 +60,11 @@ go_test( ], ) -# tracker_test as pr.yml's "Test (storage domain + uow)" job runs it: no -# -short and no BEADS_TEST_SKIP=dolt, so TestMain starts the shared dolt -# sql-server container, and BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 turns a missing -# container into a failure instead of a suite of skips. tracker_test itself -# stays untagged: under --config=prcore its Dolt-backed tests skip. -# -# Tags: -# requires-docker: needs a docker daemon; excluded from --config=prcore/ci, -# selected by --config=docker. -# no-remote-exec: the daemon is on the host, not on remote workers. -sh_test( - name = "tracker_docker_test", - size = "large", - srcs = ["//tools/bazel:go_test_variant.sh"], - args = ["$(rootpath :tracker_test)"], - data = [":tracker_test"], - env = {"BEADS_TEST_REQUIRE_DOLT_CONTAINER": "1"}, - tags = [ - "no-remote-exec", - "requires-docker", - ], -) - -# tracker_test as pr.yml's "Test (storage domain + uow)" job runs it (no +# tracker_test as the retired "Test (storage domain + uow)" job ran it (no # -short; TestMain starts the shared server), on the dolt-server lane: the # server is a local `dolt sql-server` child of the test process. # BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 makes TestMain exit 1 if it cannot start, -# instead of WARN-skipping the suite. tracker_docker_test is the A/B control. +# instead of WARN-skipping the suite. # # Tags: # dolt-server: starts hermetic dolt sql-servers from the pinned dolt in the @@ -108,3 +85,64 @@ sh_test( }, tags = ["dolt-server"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/tracker/conformance/BUILD.bazel b/internal/tracker/conformance/BUILD.bazel index 0fa79e36d..87299f0ae 100644 --- a/internal/tracker/conformance/BUILD.bazel +++ b/internal/tracker/conformance/BUILD.bazel @@ -51,3 +51,64 @@ sh_test( }, tags = ["dolt-server"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/types/BUILD.bazel b/internal/types/BUILD.bazel index 82e7ed542..ff7b6c8eb 100644 --- a/internal/types/BUILD.bazel +++ b/internal/types/BUILD.bazel @@ -3,6 +3,7 @@ load("@rules_go//go:def.bzl", "go_library", "go_test") go_library( name = "types", srcs = [ + "gated.go", "id_generator.go", "non_completing_close.go", "orphans.go", @@ -17,6 +18,7 @@ go_test( name = "types_test", srcs = [ "explain_test.go", + "gated_test.go", "id_generator_test.go", "issue_summary_test.go", "non_completing_close_test.go", @@ -38,3 +40,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/types/explain_test.go b/internal/types/explain_test.go index bd8c2b0ee..bf1500bc0 100644 --- a/internal/types/explain_test.go +++ b/internal/types/explain_test.go @@ -62,6 +62,9 @@ func TestBuildReadyExplanation_ReadyWithResolvedBlockers(t *testing.T) { }, } + // A nil blockerMap supplies no statuses: the ready set's verdict is the + // only word, so every blocking edge counts as resolved (the pre-#6066 + // shape, kept for callers that fetch nothing). result := BuildReadyExplanation(issues, nil, depCounts, allDeps, nil, nil) if len(result.Ready) != 1 { @@ -75,6 +78,9 @@ func TestBuildReadyExplanation_ReadyWithResolvedBlockers(t *testing.T) { if len(item.ResolvedBlockers) != 2 { t.Errorf("expected 2 resolved blockers, got %d", len(item.ResolvedBlockers)) } + if len(item.PinnedDependencies) != 0 || len(item.OpenDependencies) != 0 { + t.Errorf("expected no pinned/open dependencies without statuses, got %v / %v", item.PinnedDependencies, item.OpenDependencies) + } if item.DependencyCount != 2 { t.Errorf("expected DependencyCount=2, got %d", item.DependencyCount) } @@ -83,6 +89,103 @@ func TestBuildReadyExplanation_ReadyWithResolvedBlockers(t *testing.T) { } } +// A ready issue's blocking edges are sorted by the target's status: closed is +// a resolved blocker, pinned never blocked (the ready query skips pinned +// targets as it skips closed ones), anything else is an open dependency the +// ready set admitted anyway. Before this every edge printed as "resolved", +// so a dependency wired onto a pinned bead reported itself satisfied. +func TestBuildReadyExplanation_ReadyDependencyStatuses(t *testing.T) { + issues := []*Issue{ + {ID: "bd-1", Title: "Ready", Priority: 1, Status: StatusOpen}, + } + allDeps := map[string][]*Dependency{ + "bd-1": { + {IssueID: "bd-1", DependsOnID: "bd-closed", Type: DepBlocks}, + {IssueID: "bd-1", DependsOnID: "bd-pinned", Type: DepBlocks}, + {IssueID: "bd-1", DependsOnID: "bd-open", Type: DepBlocks}, + {IssueID: "bd-1", DependsOnID: "bd-spawner", Type: DepWaitsFor}, + {IssueID: "bd-1", DependsOnID: "bd-unknown", Type: DepConditionalBlocks}, + {IssueID: "bd-1", DependsOnID: "bd-epic", Type: DepParentChild}, + {IssueID: "bd-1", DependsOnID: "bd-related", Type: DepRelated}, + }, + } + blockerMap := map[string]*Issue{ + "bd-closed": {ID: "bd-closed", Status: StatusClosed}, + "bd-pinned": {ID: "bd-pinned", Status: StatusPinned}, + "bd-open": {ID: "bd-open", Status: StatusOpen}, + "bd-spawner": {ID: "bd-spawner", Status: StatusInProgress}, + "bd-epic": {ID: "bd-epic", Status: StatusOpen}, + } + + result := BuildReadyExplanation(issues, nil, nil, allDeps, blockerMap, nil) + if len(result.Ready) != 1 { + t.Fatalf("expected 1 ready item, got %d", len(result.Ready)) + } + item := result.Ready[0] + + // bd-unknown has no status in the map and so joins the resolved set. + assertIDs(t, "ResolvedBlockers", item.ResolvedBlockers, "bd-closed", "bd-unknown") + assertIDs(t, "PinnedDependencies", item.PinnedDependencies, "bd-pinned") + assertIDs(t, "OpenDependencies", item.OpenDependencies, "bd-open", "bd-spawner") + want := "2 blocker(s) resolved; 1 pinned dependency(ies), never blocking; 2 open dependency(ies), not blocking" + if item.Reason != want { + t.Errorf("reason:\n got %q\nwant %q", item.Reason, want) + } + if item.Parent == nil || *item.Parent != "bd-epic" { + t.Errorf("expected Parent=bd-epic, got %v", item.Parent) + } +} + +// Only pinned edges: the reason must not claim anything was resolved. +func TestBuildReadyExplanation_ReadyWithOnlyPinnedDependency(t *testing.T) { + issues := []*Issue{{ID: "bd-1", Title: "Ready", Priority: 1, Status: StatusOpen}} + allDeps := map[string][]*Dependency{ + "bd-1": {{IssueID: "bd-1", DependsOnID: "bd-pinned", Type: DepBlocks}}, + } + blockerMap := map[string]*Issue{"bd-pinned": {ID: "bd-pinned", Status: StatusPinned}} + + item := BuildReadyExplanation(issues, nil, nil, allDeps, blockerMap, nil).Ready[0] + if item.Reason != "1 pinned dependency(ies), never blocking" { + t.Errorf("unexpected reason %q", item.Reason) + } + if len(item.ResolvedBlockers) != 0 { + t.Errorf("expected no resolved blockers, got %v", item.ResolvedBlockers) + } + assertIDs(t, "PinnedDependencies", item.PinnedDependencies, "bd-pinned") +} + +func TestReadyReason(t *testing.T) { + cases := []struct { + resolved, pinned, open int + want string + }{ + {0, 0, 0, "no blocking dependencies"}, + {2, 0, 0, "2 blocker(s) resolved"}, + {0, 1, 0, "1 pinned dependency(ies), never blocking"}, + {0, 0, 3, "3 open dependency(ies), not blocking"}, + {1, 1, 1, "1 blocker(s) resolved; 1 pinned dependency(ies), never blocking; 1 open dependency(ies), not blocking"}, + } + for _, c := range cases { + if got := readyReason(c.resolved, c.pinned, c.open); got != c.want { + t.Errorf("readyReason(%d,%d,%d) = %q, want %q", c.resolved, c.pinned, c.open, got, c.want) + } + } +} + +func assertIDs(t *testing.T, field string, got []string, want ...string) { + t.Helper() + if len(got) != len(want) { + t.Errorf("%s = %v, want %v", field, got, want) + return + } + for i := range want { + if got[i] != want[i] { + t.Errorf("%s = %v, want %v", field, got, want) + return + } + } +} + func TestBuildReadyExplanation_ReadyWithParent(t *testing.T) { issues := []*Issue{ {ID: "bd-child", Title: "Child task", Priority: 2, Status: StatusOpen}, diff --git a/internal/types/gated.go b/internal/types/gated.go new file mode 100644 index 000000000..d0e2467cd --- /dev/null +++ b/internal/types/gated.go @@ -0,0 +1,185 @@ +package types + +import "strings" + +// This file holds the ONE rule by which an issue counts as GATED, and the +// projection of a gate onto the wire. +// +// GATED IS DERIVED, NEVER STORED. `bd gate create --blocks X` writes a gate +// issue plus an ordinary blocking dependency X -> gate; nothing on X changes. +// `bd ready` then drops X through the denormalized is_blocked column, and the +// rule here is the subset of that column's recompute +// (internal/storage/issueops/blocked_consistency.go) a gate can account for: +// +// - the EDGE clause, from the recompute's first two union legs: the edge is +// 'blocks' or 'conditional-blocks' and the target is neither closed nor +// pinned (IsGateEdge + the status test in GateIsHolding); +// - the SUBJECT clause, from unmarkAllBlockedSQL, which forces is_blocked=0 +// for a closed or pinned subject whatever its edges say (SubjectCanBeGated). +// +// Both halves live here, in one predicate every surface asks, so a glyph, a +// header and a gated_by field cannot disagree with each other or with `bd +// ready` about the same bead. +// +// WAITS-FOR IS DELIBERATELY OUT. The recompute's waits-for leg does not apply +// the closed/pinned status test at all: it goes through waitsForGateBlockedSQL +// (internal/storage/issueops/blocked_state.go), which blocks only when the +// target has an OPEN parent-child child, or metadata.also_blocks names an open +// spawner. A plain `bd dep add X G -t waits-for` onto an open childless gate +// therefore leaves X in `bd ready`, and decorating it would be exactly the +// drift this file exists to prevent. Mirroring that leg in Go would be a +// second implementation of a rule the database already owns; a decoration that +// covers the fanout case is its own bead, not this one. + +// GateRef is a gate projected for a caller: the id to resolve, what kind of +// wait it is, and why. It is what `gated_by` carries on the detail view. +type GateRef struct { + ID string `json:"id"` + // Type is the gate's await condition (human, timer, gh:run, gh:pr, bead); + // "gate" when the issue carries no await type, which is what a gate made + // with a bare `bd create --type gate` looks like. + Type string `json:"type,omitempty"` + // Reason is the free text `bd gate create --reason` recorded, empty when + // the gate was created without one. + Reason string `json:"reason,omitempty"` +} + +// IsGateEdge reports whether a dependency of this type is one whose target's +// status alone decides blockedness — the two legs of the is_blocked recompute +// that carry "target not closed and not pinned". It is NOT +// DependencyType.IsBlockingEdge, which also admits waits-for; see the file +// comment. +func IsGateEdge(depType DependencyType) bool { + return depType == DepBlocks || depType == DepConditionalBlocks +} + +// SubjectCanBeGated reports whether an issue's OWN status admits the gate +// decoration. A closed or pinned issue never does: unmarkAllBlockedSQL clears +// is_blocked for those two statuses unconditionally, so `bd ready` withholds +// them for reasons that have nothing to do with a gate, and a "GATED" marker +// on such a row would claim a causation that is not there. +// +// The listing route asks this without hydrated dependencies, which is why the +// clause is exported rather than buried inside GatesHolding. +func SubjectCanBeGated(subject *Issue) bool { + if subject == nil { + return false + } + return subject.Status != StatusClosed && subject.Status != StatusPinned +} + +// GateIsHolding reports whether target, reached over a dependency of type +// depType, is a gate that is currently holding its dependent back. It is the +// EDGE half of the rule; the caller still owes the subject half, which is what +// GatesHolding exists to keep it from forgetting. +func GateIsHolding(depType DependencyType, target *Issue) bool { + if target == nil || target.IssueType != TypeGate { + return false + } + if !IsGateEdge(depType) { + return false + } + return target.Status != StatusClosed && target.Status != StatusPinned +} + +// GatesHolding selects, from subject's hydrated dependencies, the gates that +// are actively holding subject back, in the order the dependencies arrived. +// +// THE one predicate: every gated decoration — `bd show`'s header and meta +// lines, `bd list`'s glyph, the agent line, the detail view's gated_by — comes +// from this function or from the pair it is built out of, so a nonempty result +// means `bd ready` withholds subject on a gate's account. Not the converse: +// only subject's own edges are read, so a child of a gated parent, withheld +// through the recompute's parent-child leg, selects no gate here. +func GatesHolding(subject *Issue, deps []*IssueWithDependencyMetadata) []*Issue { + if !SubjectCanBeGated(subject) { + return nil + } + var gates []*Issue + for _, dep := range deps { + if dep == nil { + continue + } + issue := dep.Issue + if GateIsHolding(dep.DependencyType, &issue) { + gate := issue + gates = append(gates, &gate) + } + } + return gates +} + +// GateKind names a gate's await condition for display, falling back to the +// issue type when the gate carries none. +func GateKind(gate *Issue) string { + if gate == nil { + return "" + } + if gate.AwaitType != "" { + return gate.AwaitType + } + return string(TypeGate) +} + +// NewGateRef projects one gate issue onto the wire shape. +func NewGateRef(gate *Issue) GateRef { + if gate == nil { + return GateRef{} + } + return GateRef{ + ID: gate.ID, + Type: GateKind(gate), + Reason: GateReason(gate.Description), + } +} + +// GateRefs projects a gate set, returning nil for an empty one so the field +// stays absent rather than serializing an empty array. +func GateRefs(gates []*Issue) []GateRef { + if len(gates) == 0 { + return nil + } + refs := make([]GateRef, 0, len(gates)) + for _, gate := range gates { + refs = append(refs, NewGateRef(gate)) + } + return refs +} + +// ReasonMarker separates a generated description from the free-text reason its +// author gave. The reason has no column of its own, so the description is +// where it lives. +// +// It is SHARED, not gate-private: `bd gate create` writes it through +// GateDescription, and `bd state`'s state-change EVENT descriptions write the +// same marker (cmd/bd/state.go). One exported constant so the spelling cannot +// drift between them — and so the sharing is visible rather than a coincidence +// two files have to keep on purpose. +const ReasonMarker = "\n\nReason: " + +// GateDescription builds an ad-hoc gate's description. `bd gate create` is its +// only writer. +func GateDescription(targetID, reason string) string { + desc := "Ad-hoc gate blocking " + targetID + if reason != "" { + desc += ReasonMarker + reason + } + return desc +} + +// GateReason recovers the reason GateDescription recorded, or "" when the +// description carries no marker. +// +// It is a TEXT read-back, not proof of provenance: ReasonMarker is shared (see +// its doc), so any description containing it yields a reason here — a gate +// written by hand with that spelling included. What the pair does guarantee is +// the round trip: what GateDescription wrote, this returns. `bd gate create` +// (cmd/bd/gate.go) is the only GateDescription caller today, so every gate +// whose reason this reports is one it recorded. +func GateReason(description string) string { + idx := strings.Index(description, ReasonMarker) + if idx < 0 { + return "" + } + return strings.TrimSpace(description[idx+len(ReasonMarker):]) +} diff --git a/internal/types/gated_test.go b/internal/types/gated_test.go new file mode 100644 index 000000000..9e831fcde --- /dev/null +++ b/internal/types/gated_test.go @@ -0,0 +1,163 @@ +package types + +import "testing" + +func gateIssue(id string, status Status) *Issue { + return &Issue{ID: id, IssueType: TypeGate, Status: status, AwaitType: "human"} +} + +func TestGateIsHolding(t *testing.T) { + tests := []struct { + name string + depType DependencyType + target *Issue + want bool + }{ + {"open gate over a blocks edge", DepBlocks, gateIssue("g1", StatusOpen), true}, + {"open gate over conditional-blocks", DepConditionalBlocks, gateIssue("g1", StatusOpen), true}, + // waits-for is NOT the same rule: the is_blocked recompute sends that + // leg through waitsForGateBlockedSQL (fanout over the target's OPEN + // parent-child children, or metadata.also_blocks with an open spawner), + // never the closed/pinned status test. A plain waits-for edge onto an + // open childless gate leaves the dependent IN bd ready, so decorating it + // would make the surfaces disagree with readiness. + {"open gate over waits-for", DepWaitsFor, gateIssue("g1", StatusOpen), false}, + {"closed gate", DepBlocks, gateIssue("g1", StatusClosed), false}, + {"pinned gate", DepBlocks, gateIssue("g1", StatusPinned), false}, + // parent-child is structural: it propagates blockedness through the + // is_blocked recompute, not as a direct blocking edge. Inheritance is + // its own question (wy-raudbw) and must not sneak in here. + {"gate over a parent-child edge", DepParentChild, gateIssue("g1", StatusOpen), false}, + {"gate over a relates-to edge", DepRelatesTo, gateIssue("g1", StatusOpen), false}, + {"open non-gate blocker", DepBlocks, &Issue{ID: "b1", IssueType: TypeTask, Status: StatusOpen}, false}, + {"nil target", DepBlocks, nil, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := GateIsHolding(tt.depType, tt.target); got != tt.want { + t.Errorf("GateIsHolding(%s, %v) = %v, want %v", tt.depType, tt.target, got, tt.want) + } + }) + } +} + +func TestGatesHoldingSelectsOnlyLiveGates(t *testing.T) { + deps := []*IssueWithDependencyMetadata{ + {Issue: *gateIssue("open-gate", StatusOpen), DependencyType: DepBlocks}, + {Issue: *gateIssue("closed-gate", StatusClosed), DependencyType: DepBlocks}, + {Issue: Issue{ID: "plain", IssueType: TypeTask, Status: StatusOpen}, DependencyType: DepBlocks}, + {Issue: *gateIssue("second-gate", StatusOpen), DependencyType: DepConditionalBlocks}, + nil, + } + gates := GatesHolding(&Issue{ID: "subject", Status: StatusOpen}, deps) + if len(gates) != 2 { + t.Fatalf("GatesHolding returned %d gates, want 2: %+v", len(gates), gates) + } + if gates[0].ID != "open-gate" || gates[1].ID != "second-gate" { + t.Errorf("GatesHolding = %s,%s; want open-gate,second-gate in dependency order", gates[0].ID, gates[1].ID) + } +} + +// TestGatesHoldingSubjectStatus pins the SUBJECT-side half of the rule. The +// is_blocked recompute's unmark leg (unmarkAllBlockedSQL) forces is_blocked=0 +// for a closed or pinned subject whatever its dependencies say, so `bd ready` +// never withholds such a bead on a gate's account and no surface may claim it +// is gated. +func TestGatesHoldingSubjectStatus(t *testing.T) { + deps := []*IssueWithDependencyMetadata{ + {Issue: *gateIssue("open-gate", StatusOpen), DependencyType: DepBlocks}, + } + tests := []struct { + name string + subject *Issue + want int + }{ + {"open subject", &Issue{ID: "s1", Status: StatusOpen}, 1}, + {"in_progress subject", &Issue{ID: "s1", Status: StatusInProgress}, 1}, + {"deferred subject", &Issue{ID: "s1", Status: StatusDeferred}, 1}, + {"closed subject", &Issue{ID: "s1", Status: StatusClosed}, 0}, + {"pinned subject", &Issue{ID: "s1", Status: StatusPinned}, 0}, + {"nil subject", nil, 0}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := GatesHolding(tt.subject, deps); len(got) != tt.want { + t.Errorf("GatesHolding(%v) returned %d gates, want %d", tt.subject, len(got), tt.want) + } + }) + } +} + +// SubjectCanBeGated is the clause on its own, because the listing route reaches +// it without hydrated dependencies and must ask the SAME question. +func TestSubjectCanBeGated(t *testing.T) { + for _, tt := range []struct { + status Status + want bool + }{ + {StatusOpen, true}, + {StatusInProgress, true}, + {StatusBlocked, true}, + {StatusDeferred, true}, + {StatusClosed, false}, + {StatusPinned, false}, + } { + if got := SubjectCanBeGated(&Issue{ID: "s1", Status: tt.status}); got != tt.want { + t.Errorf("SubjectCanBeGated(%s) = %v, want %v", tt.status, got, tt.want) + } + } + if SubjectCanBeGated(nil) { + t.Error("SubjectCanBeGated(nil) = true, want false") + } +} + +func TestGatesHoldingEmpty(t *testing.T) { + if got := GatesHolding(&Issue{ID: "subject", Status: StatusOpen}, nil); got != nil { + t.Errorf("GatesHolding(subject, nil) = %v, want nil", got) + } +} + +func TestGateDescriptionRoundTrip(t *testing.T) { + desc := GateDescription("bd-abc", "Need design review") + if got := GateReason(desc); got != "Need design review" { + t.Errorf("GateReason(%q) = %q, want the reason back", desc, got) + } + bare := GateDescription("bd-abc", "") + if got := GateReason(bare); got != "" { + t.Errorf("GateReason(%q) = %q, want empty", bare, got) + } + if got := GateReason("a description written by something else"); got != "" { + t.Errorf("GateReason on a foreign description = %q, want empty", got) + } + // The marker is SHARED (cmd/bd/state.go writes it on state-change events), + // so this is a text read-back and not a provenance check. Pinned so the + // doc comment and the behavior cannot drift: any description carrying the + // marker yields a reason. + if got := GateReason("Changed state from a to b" + ReasonMarker + "because"); got != "because" { + t.Errorf("GateReason on a shared-marker description = %q, want %q", got, "because") + } +} + +func TestGateRefsProjection(t *testing.T) { + if got := GateRefs(nil); got != nil { + t.Errorf("GateRefs(nil) = %v, want nil so the field stays absent", got) + } + gate := &Issue{ + ID: "g1", + IssueType: TypeGate, + Status: StatusOpen, + AwaitType: "gh:pr", + Description: GateDescription("bd-abc", "waiting on review"), + } + refs := GateRefs([]*Issue{gate, {ID: "g2", IssueType: TypeGate, Status: StatusOpen}}) + if len(refs) != 2 { + t.Fatalf("GateRefs returned %d refs, want 2", len(refs)) + } + if refs[0] != (GateRef{ID: "g1", Type: "gh:pr", Reason: "waiting on review"}) { + t.Errorf("refs[0] = %+v", refs[0]) + } + // A gate with no await type still names a kind rather than an empty one. + if refs[1] != (GateRef{ID: "g2", Type: "gate"}) { + t.Errorf("refs[1] = %+v, want the gate fallback kind and no reason", refs[1]) + } +} diff --git a/internal/types/storage_class_test.go b/internal/types/storage_class_test.go index d9d8dabcf..acaf36834 100644 --- a/internal/types/storage_class_test.go +++ b/internal/types/storage_class_test.go @@ -2,6 +2,8 @@ package types import ( "encoding/json" + "errors" + "fmt" "strings" "testing" "time" @@ -277,8 +279,16 @@ func TestNormalizePersistenceModeRejectsPlaneClassIncoherence(t *testing.T) { {"durable with explicit ephemeral", Issue{StorageClass: StorageClassEphemeral}, PersistenceModePersistent}, } for _, tc := range cases { - if _, _, _, err := NormalizePersistenceMode(tc.current, tc.target); err == nil { + _, _, _, err := NormalizePersistenceMode(tc.current, tc.target) + if err == nil { t.Errorf("%s: NormalizePersistenceMode succeeded, want error", tc.name) + continue + } + // A row that breaks its own invariants is not the request's refusal, + // even when its class is unversioned: callers classify only + // ErrUnversionedWispMove as validation. + if errors.Is(err, ErrUnversionedWispMove) { + t.Errorf("%s: NormalizePersistenceMode error %q matches ErrUnversionedWispMove, want the row-invariant error", tc.name, err) } } } @@ -294,8 +304,13 @@ func TestNormalizePersistenceModeRejectsUnsetAndUnknown(t *testing.T) { func TestNormalizePersistenceModeRejectsUnversionedDemotion(t *testing.T) { current := Issue{StorageClass: StorageClassUnversioned} for _, target := range []PersistenceMode{PersistenceModeEphemeral, PersistenceModeNoHistory} { - if _, _, _, err := NormalizePersistenceMode(current, target); err == nil { - t.Errorf("NormalizePersistenceMode(unversioned, %q) succeeded, want error", target) + _, _, _, err := NormalizePersistenceMode(current, target) + if !errors.Is(err, ErrUnversionedWispMove) { + t.Errorf("NormalizePersistenceMode(unversioned, %q) error = %v, want ErrUnversionedWispMove", target, err) + continue + } + if want := fmt.Sprintf("cannot move unversioned record to persistence mode %q", target); err.Error() != want { + t.Errorf("NormalizePersistenceMode(unversioned, %q) error = %q, want %q", target, err, want) } } } diff --git a/internal/types/types.go b/internal/types/types.go index fcba02e45..5091abd86 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -931,6 +931,10 @@ func ValidMolTypeNames() string { return joinNamesWithOr(validMolTypes) } +// ValidMolTypes returns the accepted non-empty mol-type values, in canonical +// order, as a copy the caller may keep. +func ValidMolTypes() []MolType { return slices.Clone(validMolTypes) } + // WispType categorizes ephemeral wisps for TTL-based compaction (gt-9br) type WispType string @@ -970,6 +974,10 @@ func ValidWispTypeNames() string { return joinNamesWithOr(validWispTypes) } +// ValidWispTypes returns the accepted non-empty wisp-type values, in canonical +// order, as a copy the caller may keep. +func ValidWispTypes() []WispType { return slices.Clone(validWispTypes) } + // StorageClass is the create-selected marker for a record's history and // replication contract. Persistence plane transitions preserve the marker // except for normalization required by demotion or promotion. The effective @@ -1017,12 +1025,19 @@ func (m PersistenceMode) IsValid() bool { return slices.Contains(validPersistenceModes, m) } +// ErrUnversionedWispMove is NormalizePersistenceMode's refusal to move an +// unversioned record to a wisp mode. The record is sound and the requested +// move is what is refused, so callers can classify it apart from the +// row-invariant errors the function also returns. +var ErrUnversionedWispMove = errors.New("cannot move unversioned record") + // NormalizePersistenceMode maps a requested mode from current to its exact // persistence fields without mutating an issue. The returned values are // Ephemeral, NoHistory, and StorageClass, respectively. Plane and retention // changes preserve the create-selected class. Promotion clears an explicit // ephemeral class marker to select normalized versioned storage. An -// unversioned record may remain persistent but cannot move to a wisp mode. +// unversioned record may remain persistent but cannot move to a wisp mode +// (ErrUnversionedWispMove). func NormalizePersistenceMode(current Issue, mode PersistenceMode) (bool, bool, StorageClass, error) { if !mode.IsValid() { return false, false, "", fmt.Errorf("invalid persistence mode %q", mode) @@ -1041,7 +1056,7 @@ func NormalizePersistenceMode(current Issue, mode PersistenceMode) (bool, bool, return false, false, "", fmt.Errorf("storage class ephemeral requires ephemeral or no_history") } if current.StorageClass == StorageClassUnversioned && mode != PersistenceModePersistent { - return false, false, "", fmt.Errorf("cannot move unversioned record to persistence mode %q", mode) + return false, false, "", fmt.Errorf("%w to persistence mode %q", ErrUnversionedWispMove, mode) } if persistenceMode(current) == mode { return current.Ephemeral, current.NoHistory, current.StorageClass, nil @@ -1230,7 +1245,8 @@ type IssueWithCounts struct { // WHICH SURFACES SET IT, because this type is shared by more than the // listing and an absent marker means different things on them. It is set // by the page epilogue behind issueops.Reader.List — `bd list --json` on - // both routes, its --ready arm included, and GET /v0/beads/issues. It is + // both routes, its --ready arm included, `bd search --json` on every + // route, and GET /v0/beads/issues. It is // NOT set by Reader.Ready (GET /v0/beads/ready) or by the claim response // that returns this type, so on those an absent marker says nothing about // whether a row's comments exist: read comment_count there. Extending the @@ -1263,6 +1279,19 @@ type IssueDetails struct { // Comments slice or a zero count: a true empty stays plain omission. CommentsOmitted *bool `json:"comments_omitted,omitempty"` + // GatedBy names the gates actively blocking this issue — the derived + // GATED decoration `bd show` renders in its header, as data. ADDITIVE and + // omitted when empty: nothing else on this view changes shape, and the + // stored status stays whatever it is (an open issue an open gate blocks + // still reads "open" here). The rule is types.GatesHolding — the gate + // clause of the readiness query's is_blocked column, subject half + // included — so a nonempty list means `bd ready` withholds the issue on a + // gate's account, and a closed or pinned issue carries no gated_by at all. + // The converse does not hold: only the issue's own edges count, so a child + // of a gated parent, which `bd ready` withholds through the parent-child + // leg, carries no gated_by. + GatedBy []GateRef `json:"gated_by,omitempty"` + // UnresolvableDependencies / UnresolvableDependents count the edges // DependencyCount / DependentCount include that the Dependencies / // Dependents slices could not represent, because the issue on the far @@ -1347,11 +1376,29 @@ func RevisionToken(v int64) string { // ParseRevisionToken reads a wire revision token back to the internal int64. // -// It accepts exactly what RevisionToken emits. A caller must echo the token a -// response carried rather than compose one, so anything else is a client that -// invented a value, and reporting that as a parse failure is more useful than -// guessing at it. +// It accepts exactly what RevisionToken emits — the exact inverse of +// strconv.FormatInt — and nothing strconv.ParseInt alone would additionally +// tolerate: no leading "+" (FormatInt never emits one), no leading zero on +// any digit string longer than one character (FormatInt never pads "7" out +// to "007", positive or negative), and never "-0" (FormatInt(0, 10) is "0", +// never "-0"). A caller must echo the token a response carried rather than +// compose one, so anything else is a client that invented a value, and +// reporting that as a parse failure is more useful than guessing at it. func ParseRevisionToken(s string) (int64, error) { + if strings.HasPrefix(s, "+") { + return 0, fmt.Errorf("revision token %q: leading \"+\" is not a token RevisionToken ever emits", s) + } + digits := s + negative := strings.HasPrefix(s, "-") + if negative { + digits = s[1:] + } + if negative && digits == "0" { + return 0, fmt.Errorf("revision token %q: \"-0\" is not a token RevisionToken ever emits", s) + } + if len(digits) > 1 && digits[0] == '0' { + return 0, fmt.Errorf("revision token %q: a leading zero is not a token RevisionToken ever emits", s) + } return strconv.ParseInt(s, 10, 64) } @@ -1366,6 +1413,27 @@ func NewIssueDetails(issue Issue) *IssueDetails { return &IssueDetails{Issue: issue, Revision: RevisionToken(issue.RowVersion)} } +// BatchGetIssue is one entry of BatchGetIssuesResult.issues: a resolved issue +// plus its current revision token, projected the same way IssueDetails +// projects one off the embedded Issue's RowVersion (RowVersion is json:"-", +// so the Issue body alone cannot carry it). Hydration for a batch-get issue +// is LABELS ONLY — no dependencies, dependents or comments; a caller wanting +// those reads GET /v0/beads/issues/{id} (IssueDetails) instead. +// +// NewBatchGetIssue is the only door, for the same reason NewIssueDetails is: +// a struct literal with an unset Revision serializes a "0" indistinguishable +// from a legacy migration-0054 row. +type BatchGetIssue struct { + Issue + Revision string `json:"revision"` +} + +// NewBatchGetIssue projects issue with its wire-visible revision token, the +// BatchGetIssuesResult.issues counterpart of NewIssueDetails. +func NewBatchGetIssue(issue Issue) BatchGetIssue { + return BatchGetIssue{Issue: issue, Revision: RevisionToken(issue.RowVersion)} +} + // DependencyType categorizes the relationship type DependencyType string @@ -1789,6 +1857,11 @@ const ( // EventLeaseReclaimed records that a stale lease was reverted to ready by // bd reclaim (dead-worker recovery). old_value is the previous owner. EventLeaseReclaimed EventType = "lease_reclaimed" + // EventLeaseRearmed records that a heartbeat re-armed a claim that held no + // lease row (a claim hand-doled through a generic update): the lease was + // granted and row_lock reminted. new_value is the holder. A plain lease + // refresh records no event. + EventLeaseRearmed EventType = "lease_rearmed" ) // ProvenanceEvent is one entry in the append-only provenance log: a typed @@ -1848,13 +1921,26 @@ type ReadyExplanation struct { } // ReadyItem explains why a specific issue is ready for work. +// +// The issue's blocking dependencies (blocks, conditional-blocks, waits-for) +// are sorted by the target's status as the caller supplied it in blockerMap: +// ResolvedBlockers holds closed targets, PinnedDependencies holds pinned ones +// (a pinned bead never blocks, so a dependency on one never fenced this +// issue — it is reported as what it is, not as a blocker that was resolved), +// and OpenDependencies holds targets in any other status — a blocks edge +// here means the ready set and the edge disagree (foreign-prefix ids, #6066); +// a waits-for edge here is the ordinary spawner-still-open case. A target the +// caller did not supply a status for is counted under ResolvedBlockers, the +// ready set's own verdict being the only word available. type ReadyItem struct { *Issue - Reason string `json:"reason"` - ResolvedBlockers []string `json:"resolved_blockers"` - DependencyCount int `json:"dependency_count"` - DependentCount int `json:"dependent_count"` - Parent *string `json:"parent,omitempty"` + Reason string `json:"reason"` + ResolvedBlockers []string `json:"resolved_blockers"` + PinnedDependencies []string `json:"pinned_dependencies,omitempty"` + OpenDependencies []string `json:"open_dependencies,omitempty"` + DependencyCount int `json:"dependency_count"` + DependentCount int `json:"dependent_count"` + Parent *string `json:"parent,omitempty"` } // BlockedItem explains why a specific issue is blocked. @@ -1897,18 +1983,29 @@ func BuildReadyExplanation( counts = &DependencyCounts{} } - // Find resolved blockers (closed issues that this depended on) - var resolvedBlockers []string - reason := "no blocking dependencies" + // Sort the blocking dependencies by the target's status. Before this + // every blocking edge of a ready issue was printed as a resolved + // blocker, which is wrong for a pinned target: the ready query skips + // pinned targets exactly as it skips closed ones, so a dependency on + // a pinned bead never blocked anything and nothing about it was + // resolved. --explain is the one place a reader can see that. + var resolvedBlockers, pinnedDeps, openDeps []string deps := allDeps[issue.ID] for _, dep := range deps { - if dep.Type == DepBlocks || dep.Type == DepConditionalBlocks || dep.Type == DepWaitsFor { + if dep.Type != DepBlocks && dep.Type != DepConditionalBlocks && dep.Type != DepWaitsFor { + continue + } + target, known := blockerMap[dep.DependsOnID] + switch { + case !known || target == nil || target.Status == StatusClosed: resolvedBlockers = append(resolvedBlockers, dep.DependsOnID) + case target.Status == StatusPinned: + pinnedDeps = append(pinnedDeps, dep.DependsOnID) + default: + openDeps = append(openDeps, dep.DependsOnID) } } - if len(resolvedBlockers) > 0 { - reason = fmt.Sprintf("%d blocker(s) resolved", len(resolvedBlockers)) - } + reason := readyReason(len(resolvedBlockers), len(pinnedDeps), len(openDeps)) // Compute parent var parent *string @@ -1920,12 +2017,14 @@ func BuildReadyExplanation( } readyItems = append(readyItems, ReadyItem{ - Issue: issue, - Reason: reason, - ResolvedBlockers: resolvedBlockers, - DependencyCount: counts.DependencyCount, - DependentCount: counts.DependentCount, - Parent: parent, + Issue: issue, + Reason: reason, + ResolvedBlockers: resolvedBlockers, + PinnedDependencies: pinnedDeps, + OpenDependencies: openDeps, + DependencyCount: counts.DependencyCount, + DependentCount: counts.DependentCount, + Parent: parent, }) } @@ -1971,6 +2070,28 @@ func BuildReadyExplanation( } } +// readyReason words a ReadyItem's Reason from the three dependency counts. +// "no blocking dependencies" is kept verbatim for the no-edge case; a resolved +// count keeps the historical "N blocker(s) resolved" lead so scripts that +// match on it still do; pinned and open counts are appended as clauses rather +// than folded into the resolved count. +func readyReason(resolved, pinned, open int) string { + var parts []string + if resolved > 0 { + parts = append(parts, fmt.Sprintf("%d blocker(s) resolved", resolved)) + } + if pinned > 0 { + parts = append(parts, fmt.Sprintf("%d pinned dependency(ies), never blocking", pinned)) + } + if open > 0 { + parts = append(parts, fmt.Sprintf("%d open dependency(ies), not blocking", open)) + } + if len(parts) == 0 { + return "no blocking dependencies" + } + return strings.Join(parts, "; ") +} + // TreeNode represents a node in a dependency tree type TreeNode struct { Issue @@ -2280,6 +2401,13 @@ func (s SortPolicy) IsValid() bool { type ReclaimedLease struct { ID string `json:"id"` PreviousOwner string `json:"previous_owner"` + + // Revision is the fresh RevisionToken minted for this issue's row by the + // same UPDATE that reverted its lease — the one this package's + // RevisionToken/ParseRevisionToken pair encodes, the same wire shape as + // IssueDetails.Revision. A caller that re-fetches after a reclaim sees a + // different token than one that raced it. + Revision string `json:"revision"` } // ReclaimFilter scopes which stale-lease issues bd reclaim may revert. The diff --git a/internal/types/types_test.go b/internal/types/types_test.go index c36ee68bb..9f7bedc4c 100644 --- a/internal/types/types_test.go +++ b/internal/types/types_test.go @@ -1155,6 +1155,35 @@ func TestRevisionTokenSurvivesAJavaScriptRealisticParse(t *testing.T) { } } +// TestParseRevisionTokenRejectsMalformedTokens pins that the string<->int64 +// boundary is strict in both directions: ParseRevisionToken accepts exactly +// the decimal integer spelling RevisionToken emits (plain digits, an optional +// leading "-", no fractional part, no exponent, no surrounding whitespace, no +// value outside int64) and refuses everything else rather than guessing — +// the same "a token it cannot read is a server this client cannot follow" +// posture ParseRevisionToken's own doc comment describes, now pinned against +// the inputs a float-typed or lenient parser would have let through. +// +// "007" and "-0" pin the exact-inverse-of-FormatInt rule specifically: +// FormatInt never pads a digit string with a leading zero (so "007" is not a +// token any revision ever produced, even though strconv.ParseInt alone would +// accept it as 7), and FormatInt(0, 10) is always "0", never "-0". +func TestParseRevisionTokenRejectsMalformedTokens(t *testing.T) { + for _, token := range []string{ + "", "1.0", "1.5", "1e10", "1e0", "+1", " 1", "1 ", "0x1", "abc", + "9223372036854775808", // math.MaxInt64 + 1, one past the boundary + "-9223372036854775809", // math.MinInt64 - 1, one past the boundary + "NaN", "Infinity", "1", // fullwidth digit, not ASCII + "007", // leading zero FormatInt never pads in + "-007", // leading zero on the negative digit run + "-0", // FormatInt(0, 10) is "0", never "-0" + } { + if got, err := ParseRevisionToken(token); err == nil { + t.Errorf("ParseRevisionToken(%q) = %d, nil, want an error", token, got) + } + } +} + func TestReclaimedLeaseJSONSerialization(t *testing.T) { b, err := json.Marshal(ReclaimedLease{ID: "bd-1", PreviousOwner: "worker-a"}) if err != nil { diff --git a/internal/ui/BUILD.bazel b/internal/ui/BUILD.bazel index b28b57666..78e070e78 100644 --- a/internal/ui/BUILD.bazel +++ b/internal/ui/BUILD.bazel @@ -31,3 +31,64 @@ go_test( "@land_charm_lipgloss_v2//:lipgloss", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/ui/styles.go b/internal/ui/styles.go index d16dfe335..ecaa0b999 100644 --- a/internal/ui/styles.go +++ b/internal/ui/styles.go @@ -303,6 +303,13 @@ const ( StatusIconDeferred = "❄" // scheduled for later (snowflake) StatusIconPinned = "📌" // elevated priority StatusIconCustom = "◇" // custom/uncategorized status (diamond) + // StatusIconGated marks an issue an OPEN gate blocks (bd gate create + // --blocks). It is a DERIVED decoration, not a stored status: the row's + // status is untouched and only the glyph column changes. Circle family, + // like ○ ◐ ●, so it reads as a sibling of the status icons rather than as + // a badge — barred rather than hollow, because the work exists and cannot + // start. + StatusIconGated = "⊘" // blocked by an open gate (barred circle) ) // RenderStatusIcon returns the appropriate icon for a status with semantic coloring. diff --git a/internal/uimd/BUILD.bazel b/internal/uimd/BUILD.bazel index b6bb87ea5..dbbb4fffa 100644 --- a/internal/uimd/BUILD.bazel +++ b/internal/uimd/BUILD.bazel @@ -23,3 +23,64 @@ go_test( "@land_charm_glamour_v2//styles", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/utils/BUILD.bazel b/internal/utils/BUILD.bazel index 97d1a0e58..392b6b537 100644 --- a/internal/utils/BUILD.bazel +++ b/internal/utils/BUILD.bazel @@ -13,6 +13,7 @@ go_library( importpath = "github.com/steveyegge/beads/internal/utils", visibility = ["//:__subpackages__"], deps = [ + "//beadserrors", "//internal/debug", "//internal/types", ] + select({ @@ -29,6 +30,7 @@ go_library( go_test( name = "utils_test", srcs = [ + "id_parser_exact_only_test.go", "id_parser_exact_test.go", "id_parser_fake_test.go", "id_parser_prefix_test.go", @@ -44,8 +46,70 @@ go_test( ], embed = [":utils"], deps = [ + "//beadserrors", "//internal/storage/dolt", "//internal/testutil", "//internal/types", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/utils/id_parser.go b/internal/utils/id_parser.go index 70167c593..8c42c0c95 100644 --- a/internal/utils/id_parser.go +++ b/internal/utils/id_parser.go @@ -9,6 +9,7 @@ import ( "sort" "strings" + "github.com/steveyegge/beads/beadserrors" "github.com/steveyegge/beads/internal/debug" "github.com/steveyegge/beads/internal/types" ) @@ -33,12 +34,46 @@ var ErrAmbiguousID = errors.New("ambiguous issue ID") // id") — see bd comment's resolveAndGetIssueForMutationExact caller. var ErrAbbreviatedIDNotAllowed = errors.New("id is a valid abbreviation, but exact-match resolution is required here") +// AbbreviatedIDError is the error ResolvePartialIDExact returns when Input +// names no issue exactly but is a leading-prefix abbreviation of Matches. It +// wraps ErrAbbreviatedIDNotAllowed, so errors.Is callers see the sentinel +// unchanged; a caller that wants to name the full ids reads Matches through +// errors.As. +type AbbreviatedIDError struct { + Input string + Matches []string // sorted +} + +func (e *AbbreviatedIDError) Error() string { + return fmt.Sprintf("%v: %q (matches %v)", ErrAbbreviatedIDNotAllowed, e.Input, e.Matches) +} + +func (e *AbbreviatedIDError) Unwrap() error { return ErrAbbreviatedIDNotAllowed } + type PartialIDResolverStore interface { SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) SearchIssueIDs(ctx context.Context, query string, filter types.IssueFilter) ([]string, error) GetConfig(ctx context.Context, key string) (string, error) } +// ExactIDLookupStore is an optional PartialIDResolverStore capability: a store +// that can look an issue up only by its EXACT id and has no substring id +// search at all (the http backend: the v0 wire publishes none, design D11). +// +// For such a store the resolver stops at the exact lookups. An input already +// shaped like a prefixed id normalizes to itself, so the first exact probe is +// the whole answer and a miss is a not-found after ONE lookup. A bare hash +// still reads the prefix vocabulary to build its prefixed spelling. A miss +// wraps beadserrors.ErrNotFound — never the substring search's refusal, which +// would report a missing id as a backend fault. +// +// The assertion is made on the store the caller passes, so a decorated chain +// must hand over the store that actually implements it (cmd/bd's routed +// resolution unwraps for this). +type ExactIDLookupStore interface { + ExactIDLookupOnly() bool +} + // parseIssueID ensures an issue ID has the configured prefix. // If the input already has the prefix (e.g., "bd-a3f8e9"), returns it as-is. // If the input lacks the prefix (e.g., "a3f8e9"), adds the configured prefix. @@ -103,6 +138,10 @@ func resolvePartialID(ctx context.Context, store PartialIDResolverStore, input s return "", fmt.Errorf("cannot resolve issue ID %q: storage is nil", input) } + if exact, ok := store.(ExactIDLookupStore); ok && exact.ExactIDLookupOnly() { + return resolveExactIDOnly(ctx, store, input) + } + // Fast path: Use SearchIssues with exact ID filter (GH#942). // This uses the same query path as "bd list --id", ensuring consistency. // Previously we used GetIssue which could fail in cases where SearchIssues @@ -161,10 +200,13 @@ func resolvePartialID(ctx context.Context, store PartialIDResolverStore, input s normalizedID = prefixWithHyphen + input } - // Try exact match on normalized ID using SearchIssues (GH#942) - normalizedFilter := types.IssueFilter{IDs: []string{normalizedID}} - if issues, err := store.SearchIssues(ctx, "", normalizedFilter); err == nil && len(issues) > 0 { - return issues[0].ID, nil + // Try exact match on normalized ID using SearchIssues (GH#942). An input + // that normalized to itself was already asked exactly that above. + if normalizedID != input { + normalizedFilter := types.IssueFilter{IDs: []string{normalizedID}} + if issues, err := store.SearchIssues(ctx, "", normalizedFilter); err == nil && len(issues) > 0 { + return issues[0].ID, nil + } } // If exact match failed, try substring search. @@ -284,7 +326,7 @@ func resolvePartialID(ctx context.Context, store PartialIDResolverStore, input s // resolveAndGetIssueForMutationExact) can surface an accurate, // actionable message rather than claiming the issue is missing. sort.Strings(abbrevOnly) - return "", fmt.Errorf("%w: %q (matches %v)", ErrAbbreviatedIDNotAllowed, input, abbrevOnly) + return "", &AbbreviatedIDError{Input: input, Matches: abbrevOnly} } return "", fmt.Errorf("no issue found matching %q", input) } @@ -308,6 +350,83 @@ func resolvePartialID(ctx context.Context, store PartialIDResolverStore, input s return resolved, nil } +// resolveExactIDOnly is resolvePartialID for an ExactIDLookupStore: the exact +// lookups only, with the same input normalization, and a not-found that says +// why no abbreviation was tried. +func resolveExactIDOnly(ctx context.Context, store PartialIDResolverStore, input string) (string, error) { + issues, err := store.SearchIssues(ctx, "", types.IssueFilter{IDs: []string{input}}) + if err != nil { + return "", err + } + if len(issues) > 0 { + return issues[0].ID, nil + } + if !looksLikePrefixedID(input) { + // A bare hash, or a configured prefix without its hyphen: only the + // prefixed spelling can name an issue, and building it needs the + // workspace's prefix vocabulary. + prefix, allowed := exactOnlyPrefixConfig(ctx, store) + if prefix == "" { + prefix = "bd" + } + prefixWithHyphen := prefix + if !strings.HasSuffix(prefix, "-") { + prefixWithHyphen = prefix + "-" + } + knownPrefixes := []string{strings.TrimSuffix(prefix, "-")} + if allowed != "" { + for _, p := range strings.Split(allowed, ",") { + if p = strings.TrimSuffix(strings.TrimSpace(p), "-"); p != "" { + knownPrefixes = append(knownPrefixes, p) + } + } + } + if !strings.HasPrefix(input, prefixWithHyphen) && !hasKnownPrefix(input, knownPrefixes) { + issues, err = store.SearchIssues(ctx, "", types.IssueFilter{IDs: []string{prefixWithHyphen + input}}) + if err != nil { + return "", err + } + if len(issues) > 0 { + return issues[0].ID, nil + } + } + } + return "", &exactIDNotFoundError{input: input} +} + +// exactIDNotFoundError is resolveExactIDOnly's miss. Its text keeps the general +// resolver's "no issue found matching" lead, which every not-found matcher +// downstream reads (bd's isNotFoundErr, gc's isBdNotFound), and it wraps +// beadserrors.ErrNotFound for errors.Is callers. +type exactIDNotFoundError struct{ input string } + +func (e *exactIDNotFoundError) Error() string { + return fmt.Sprintf("no issue found matching %q (this backend resolves exact ids only; partial-id search is not available)", e.input) +} + +func (e *exactIDNotFoundError) Unwrap() error { return beadserrors.ErrNotFound } + +// exactOnlyPrefixConfig reads issue_prefix and allowed_prefixes, in one +// settings read when the store can enumerate them (a remote store pays a round +// trip per read) and with two point reads otherwise. A failed read is an unset +// key, as it is on the general path. +func exactOnlyPrefixConfig(ctx context.Context, store PartialIDResolverStore) (prefix, allowed string) { + if all, ok := store.(interface { + GetAllConfig(ctx context.Context) (map[string]string, error) + }); ok { + if values, err := all.GetAllConfig(ctx); err == nil { + return values["issue_prefix"], values["allowed_prefixes"] + } + } + if v, err := store.GetConfig(ctx, "issue_prefix"); err == nil { + prefix = v + } + if v, err := store.GetConfig(ctx, "allowed_prefixes"); err == nil { + allowed = v + } + return prefix, allowed +} + // shouldNotifyPartialResolution is the testable predicate behind the // partial-resolution notice. It takes the quiet flag and the suppression env // value as parameters so tests can cover every combination, the same shape as diff --git a/internal/utils/id_parser_exact_only_test.go b/internal/utils/id_parser_exact_only_test.go new file mode 100644 index 000000000..eebd662ba --- /dev/null +++ b/internal/utils/id_parser_exact_only_test.go @@ -0,0 +1,133 @@ +package utils_test + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/steveyegge/beads/beadserrors" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/utils" +) + +// exactOnlyStore is fakeResolverStore as an exact-lookup-only backend (the +// http client's shape, S6b): it counts every call, and its substring search +// fails the test outright, because the resolver must never reach it. +type exactOnlyStore struct { + t *testing.T + inner fakeResolverStore + lookups []string + configs int + allReads int +} + +func (s *exactOnlyStore) ExactIDLookupOnly() bool { return true } + +func (s *exactOnlyStore) SearchIssues(ctx context.Context, q string, f types.IssueFilter) ([]*types.Issue, error) { + s.lookups = append(s.lookups, strings.Join(f.IDs, ",")) + return s.inner.SearchIssues(ctx, q, f) +} + +func (s *exactOnlyStore) SearchIssueIDs(context.Context, string, types.IssueFilter) ([]string, error) { + s.t.Error("exact-only resolution reached the substring search") + return nil, errors.New("no substring search") +} + +func (s *exactOnlyStore) GetConfig(ctx context.Context, key string) (string, error) { + s.configs++ + return s.inner.GetConfig(ctx, key) +} + +func (s *exactOnlyStore) GetAllConfig(context.Context) (map[string]string, error) { + s.allReads++ + return s.inner.config, nil +} + +func TestResolvePartialID_ExactOnlyStore(t *testing.T) { + newStore := func(t *testing.T) *exactOnlyStore { + return &exactOnlyStore{t: t, inner: fakeResolverStore{ + issues: []fakeIssue{{id: "mc-abc123"}, {id: "mc-wisp-z9"}}, + config: map[string]string{"issue_prefix": "mc"}, + }} + } + + t.Run("present prefixed id is one lookup", func(t *testing.T) { + s := newStore(t) + got, err := utils.ResolvePartialID(context.Background(), s, "mc-abc123") + if err != nil || got != "mc-abc123" { + t.Fatalf("got %q, %v", got, err) + } + if len(s.lookups) != 1 || s.configs+s.allReads != 0 { + t.Errorf("lookups=%v configs=%d allReads=%d; want one lookup and no settings read", s.lookups, s.configs, s.allReads) + } + }) + + t.Run("missing prefixed id is a not-found after one lookup", func(t *testing.T) { + s := newStore(t) + _, err := utils.ResolvePartialID(context.Background(), s, "mc-nope") + if !errors.Is(err, beadserrors.ErrNotFound) { + t.Fatalf("err = %v, want ErrNotFound", err) + } + if !strings.HasPrefix(err.Error(), `no issue found matching "mc-nope"`) { + t.Errorf("err text %q lost the not-found lead every matcher reads", err) + } + if len(s.lookups) != 1 || s.configs+s.allReads != 0 { + t.Errorf("lookups=%v configs=%d allReads=%d; want exactly one lookup", s.lookups, s.configs, s.allReads) + } + }) + + t.Run("bare hash tries its prefixed spelling with one settings read", func(t *testing.T) { + s := newStore(t) + got, err := utils.ResolvePartialID(context.Background(), s, "abc123") + if err != nil || got != "mc-abc123" { + t.Fatalf("got %q, %v", got, err) + } + if strings.Join(s.lookups, " ") != "abc123 mc-abc123" || s.allReads != 1 || s.configs != 0 { + t.Errorf("lookups=%v configs=%d allReads=%d", s.lookups, s.configs, s.allReads) + } + }) + + t.Run("an abbreviation is not resolved and reads as not found", func(t *testing.T) { + s := newStore(t) + _, err := utils.ResolvePartialID(context.Background(), s, "abc") + if !errors.Is(err, beadserrors.ErrNotFound) { + t.Fatalf("err = %v, want ErrNotFound (no substring search exists)", err) + } + }) + + t.Run("the exact resolver takes the same path", func(t *testing.T) { + s := newStore(t) + if _, err := utils.ResolvePartialIDExact(context.Background(), s, "mc-nope"); !errors.Is(err, beadserrors.ErrNotFound) { + t.Fatalf("err = %v, want ErrNotFound", err) + } + }) +} + +// TestResolvePartialID_SkipsTheRepeatedNormalizedProbe pins the general +// path's one-lookup saving: an input that normalizes to itself is not asked +// for a second time. +func TestResolvePartialID_SkipsTheRepeatedNormalizedProbe(t *testing.T) { + s := &countingResolverStore{fakeResolverStore: fakeResolverStore{ + issues: []fakeIssue{{id: "mc-abc123"}}, + config: map[string]string{"issue_prefix": "mc"}, + }} + if _, err := utils.ResolvePartialID(context.Background(), s, "mc-zzz"); err == nil { + t.Fatal("resolved an id that names nothing") + } + if s.exactProbes != 1 { + t.Errorf("exact probes = %d, want 1 (mc-zzz normalizes to itself)", s.exactProbes) + } +} + +type countingResolverStore struct { + fakeResolverStore + exactProbes int +} + +func (s *countingResolverStore) SearchIssues(ctx context.Context, q string, f types.IssueFilter) ([]*types.Issue, error) { + if len(f.IDs) > 0 { + s.exactProbes++ + } + return s.fakeResolverStore.SearchIssues(ctx, q, f) +} diff --git a/internal/utils/id_parser_fake_test.go b/internal/utils/id_parser_fake_test.go index 22e7e209a..eea8e2f5c 100644 --- a/internal/utils/id_parser_fake_test.go +++ b/internal/utils/id_parser_fake_test.go @@ -10,6 +10,7 @@ package utils_test import ( "context" "errors" + "slices" "strings" "testing" @@ -175,6 +176,48 @@ func TestResolvePartialIDExact_AbbreviationRefusalIsDistinguishableFromNotFound( } } +// TestResolvePartialIDExact_AbbreviationErrorNamesTheMatches pins the typed +// error behind ErrAbbreviatedIDNotAllowed: errors.As yields the input and the +// sorted full ids it abbreviates, so a caller can name them (bd delete does), +// while errors.Is and the error text stay what they were. +func TestResolvePartialIDExact_AbbreviationErrorNamesTheMatches(t *testing.T) { + ctx := context.Background() + store := &fakeResolverStore{ + issues: []fakeIssue{ + {id: "hq-a3f8zz", ephemeral: false}, + {id: "hq-a3f8e9", ephemeral: false}, + }, + config: map[string]string{"issue_prefix": "hq"}, + } + + _, err := utils.ResolvePartialIDExact(ctx, store, "a3f8") + var abbrev *utils.AbbreviatedIDError + if !errors.As(err, &abbrev) { + t.Fatalf(`ResolvePartialIDExact("a3f8") error = %v; want an *AbbreviatedIDError`, err) + } + if abbrev.Input != "a3f8" { + t.Errorf("Input = %q; want %q", abbrev.Input, "a3f8") + } + if want := []string{"hq-a3f8e9", "hq-a3f8zz"}; !slices.Equal(abbrev.Matches, want) { + t.Errorf("Matches = %v; want %v (sorted)", abbrev.Matches, want) + } + if !errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) { + t.Errorf("error %v no longer wraps ErrAbbreviatedIDNotAllowed", err) + } + if want := `id is a valid abbreviation, but exact-match resolution is required here: "a3f8" (matches [hq-a3f8e9 hq-a3f8zz])`; err.Error() != want { + t.Errorf("error text = %q; want %q", err.Error(), want) + } + + // The wisp branch builds the same error. + _, err = utils.ResolvePartialIDExact(ctx, &fakeResolverStore{ + issues: []fakeIssue{{id: "hq-wisp-list3t0", ephemeral: true}}, + config: map[string]string{"issue_prefix": "hq"}, + }, "list") + if !errors.As(err, &abbrev) || !slices.Equal(abbrev.Matches, []string{"hq-wisp-list3t0"}) { + t.Errorf(`ResolvePartialIDExact("list") error = %v; want an *AbbreviatedIDError naming hq-wisp-list3t0`, err) + } +} + // TestResolvePartialIDExact_RefusesSentinelTokens pins where #6215's bare- // sentinel guard has to live once this PR splits the resolver in two. // @@ -231,3 +274,123 @@ func TestResolvePartialIDExact_RefusesSentinelTokens(t *testing.T) { } } } + +// TestResolvePartialID_FakeStore_QualifiedInputsNeverResolveToAnotherBead pins +// the leading-prefix matcher (#4939) against inputs that a looser matcher +// resolves to an unrelated bead. Each input names no issue in its store but +// shares a fragment with the store's only bead (the decoy), so a matcher that +// compares less than the whole hash part — a substring test, or only the text +// after the last dash — hands back the decoy. Each must stay a plain not-found +// on both resolvers: the default one would act on the decoy, and the +// exact-only one would claim the input abbreviates it. +// +// Every case also resolves a genuine leading-prefix abbreviation of its decoy, +// so a not-found cannot pass merely because the fixture answers nothing. +func TestResolvePartialID_FakeStore_QualifiedInputsNeverResolveToAnotherBead(t *testing.T) { + ctx := context.Background() + // The controls are abbreviations, which announce themselves on stderr; + // that notice is pinned in id_parser_unit_test.go. + t.Setenv("BD_NO_PARTIAL_ID_NOTICE", "1") + + cases := []struct { + name string + prefix string + decoy fakeIssue + control string // a leading-prefix abbreviation of decoy + inputs []string // ids that name no issue in the store + }{ + { + // The reported gcy-g4o incident: "oqf" is only a substring of + // the wisp hash "goqfo". + name: "substring of a wisp hash", + prefix: "gcy", + decoy: fakeIssue{id: "gcy-wisp-goqfo", ephemeral: true}, + control: "goq", + inputs: []string{"gcy-oqf", "oqf"}, + }, + { + // A routed command tries prefix routing only after the local + // lookup reports not-found, so a local hit here would act on + // bd-8wnq2 instead of the hr- rig's issue. + name: "foreign prefix", + prefix: "bd", + decoy: fakeIssue{id: "bd-8wnq2"}, + control: "8wnq", + inputs: []string{"hr-8wnq"}, + }, + { + name: "wisp-qualified id against a plain hash", + prefix: "gcy", + decoy: fakeIssue{id: "gcy-g4oab"}, + control: "g4o", + inputs: []string{"gcy-wisp-g4o"}, + }, + { + name: "wisp-qualified id against a mol-qualified hash", + prefix: "bd", + decoy: fakeIssue{id: "bd-mol-t3xyz"}, + control: "bd-mol-t3", + inputs: []string{"bd-wisp-t3"}, + }, + { + name: "fragment after an interior dash", + prefix: "bd", + decoy: fakeIssue{id: "bd-mol-abcde"}, + control: "bd-mol-ab", + inputs: []string{"abc"}, + }, + { + // Nothing follows the last dash, and an empty fragment is a + // prefix of everything. + name: "trailing dash", + prefix: "bd", + decoy: fakeIssue{id: "bd-mol-abcde"}, + control: "bd-mol-ab", + inputs: []string{"bd-ol-", "ol-"}, + }, + { + // A trailing dash is fine after a leading prefix of the hash + // (the control), and nowhere else. + name: "trailing dash against a numeric tail", + prefix: "bd", + decoy: fakeIssue{id: "bd-x-aap-1"}, + control: "bd-x-aap-", + inputs: []string{"aap-", "bd-aap-"}, + }, + { + name: "lone dash", + prefix: "bd", + decoy: fakeIssue{id: "bd-a3f8e9"}, + control: "a3f8", + inputs: []string{"-"}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + store := &fakeResolverStore{ + issues: []fakeIssue{tc.decoy}, + config: map[string]string{"issue_prefix": tc.prefix}, + } + if got, err := utils.ResolvePartialID(ctx, store, tc.control); err != nil || got != tc.decoy.id { + t.Fatalf("fixture sanity check failed: ResolvePartialID(%q) = (%q, %v); want (%q, nil)", tc.control, got, err, tc.decoy.id) + } + + for _, input := range tc.inputs { + got, err := utils.ResolvePartialID(ctx, store, input) + if err == nil { + t.Errorf("ResolvePartialID(%q) = %q; want not found — %q names no issue here", input, got, input) + } else if !strings.Contains(err.Error(), "no issue found matching") { + t.Errorf("ResolvePartialID(%q) error = %v; want a plain not-found", input, err) + } + + got, err = utils.ResolvePartialIDExact(ctx, store, input) + if err == nil { + t.Errorf("ResolvePartialIDExact(%q) = %q; want not found — %q names no issue here", input, got, input) + } else if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) || !strings.Contains(err.Error(), "no issue found matching") { + t.Errorf("ResolvePartialIDExact(%q) error = %v; want a plain not-found — %q abbreviates no issue here", input, err, input) + } + } + }) + } +} diff --git a/internal/utils/id_parser_test.go b/internal/utils/id_parser_test.go index 59cd91b6a..f606c88c8 100644 --- a/internal/utils/id_parser_test.go +++ b/internal/utils/id_parser_test.go @@ -970,4 +970,109 @@ func TestResolvePartialID_TitleFalsePositive(t *testing.T) { } } -// TestLooksLikePrefixedID tests the helper function for detecting prefixed IDs +// TestResolvePartialID_WispSubstringCollision is a regression test for gcy-g4o: +// a real bead (gcy-oqf) and an ephemeral wisp (gcy-wisp-goqfo) coexist, and a +// lookup of gcy-oqf that missed the exact-ID fast path fell through to partial +// matching, where the wisp's hash "wisp-goqfo" contains the substring "oqf". +// Partial matching has been leading-prefix only since #4939 (strings.HasPrefix +// replaced strings.Contains at both call sites), and neither "wisp-goqfo" nor +// the stripped "goqfo" starts with "oqf". With only the wisp stored, nothing +// short-circuits the partial path, so both forms of the id must come back not +// found. Once the real bead exists, the exact-ID fast path returns it before +// partial matching runs. +func TestResolvePartialID_WispSubstringCollision(t *testing.T) { + ctx := context.Background() + store := newTestStore(t) + + real := &types.Issue{ + ID: "gcy-oqf", + Title: "Real bug bead", + Status: types.StatusOpen, + Priority: 1, + IssueType: types.TypeBug, + } + wisp := &types.Issue{ + ID: "gcy-wisp-goqfo", + Title: "Order wisp", + Status: types.StatusClosed, + Priority: 2, + IssueType: types.TypeTask, + Ephemeral: true, + } + + if err := store.CreateIssue(ctx, wisp, "test"); err != nil { + t.Fatal(err) + } + if err := store.SetConfig(ctx, "issue_prefix", "gcy"); err != nil { + t.Fatal(err) + } + + // The wisp alone must not answer for gcy-oqf: this is the lookup gcy-g4o + // silently resolved to the wisp. + for _, input := range []string{"gcy-oqf", "oqf"} { + if got, err := utils.ResolvePartialID(ctx, store, input); err == nil { + t.Errorf("utils.ResolvePartialID(%q) = %q; want not found (wisp substring collision)", input, got) + } + } + + if err := store.CreateIssue(ctx, real, "test"); err != nil { + t.Fatal(err) + } + + // The real bead must still resolve to itself. This lookup is answered by + // the exact-ID fast path, so it passes under any partial matcher; the + // wisp-only loop above is the substring-collision assertion. + result, err := utils.ResolvePartialID(ctx, store, "gcy-oqf") + if err != nil { + t.Fatalf("utils.ResolvePartialID(%q) unexpected error: %v", "gcy-oqf", err) + } + if result != "gcy-oqf" { + t.Errorf("utils.ResolvePartialID(%q) = %q; want %q (the exact ID must resolve to itself)", "gcy-oqf", result, "gcy-oqf") + } +} + +// TestResolvePartialID_WispLastSegment verifies that a bare wisp hash resolves +// to its wisp ("t3st" finds "bd-wisp-t3st") through the wisp fallback's exact +// branch, even beside a longer wisp hash it abbreviates. The Dolt store merges +// wisps into the unfiltered search, so a matcher that let the first loop claim +// "wisp-t3st" as an abbreviation of "t3st" would make this lookup ambiguous +// with bd-wisp-t3stzz instead of exact. +func TestResolvePartialID_WispLastSegment(t *testing.T) { + ctx := context.Background() + store := newTestStore(t) + + wisp := &types.Issue{ + ID: "bd-wisp-t3st", + Title: "Test wisp", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Ephemeral: true, + } + sibling := &types.Issue{ + ID: "bd-wisp-t3stzz", + Title: "Sibling wisp", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Ephemeral: true, + } + if err := store.CreateIssue(ctx, wisp, "test"); err != nil { + t.Fatal(err) + } + if err := store.CreateIssue(ctx, sibling, "test"); err != nil { + t.Fatal(err) + } + if err := store.SetConfig(ctx, "issue_prefix", "bd"); err != nil { + t.Fatal(err) + } + + // "t3st" is exactly the hash of bd-wisp-t3st and must resolve to it. + result, err := utils.ResolvePartialID(ctx, store, "t3st") + if err != nil { + t.Fatalf("utils.ResolvePartialID(%q) unexpected error: %v", "t3st", err) + } + if result != "bd-wisp-t3st" { + t.Errorf("utils.ResolvePartialID(%q) = %q; want %q", "t3st", result, "bd-wisp-t3st") + } +} diff --git a/internal/utils/id_parser_unit_test.go b/internal/utils/id_parser_unit_test.go index 8d251361f..48b035afb 100644 --- a/internal/utils/id_parser_unit_test.go +++ b/internal/utils/id_parser_unit_test.go @@ -252,3 +252,82 @@ func captureStderr(t *testing.T, fn func()) string { _ = w.Close() return <-done } + +// Partial matching is leading-prefix only (#4939): a fragment from the start +// of a hash abbreviates it, while a fragment from its middle or tail names +// nothing. #4376's first revision pinned this table on a helper; driving it +// through the resolver pins the call sites themselves. +func TestResolvePartialIDMatchesLeadingPrefixOnly(t *testing.T) { + store := &fakeResolverStore{ids: []string{"bd-a3f8e9"}, prefix: "bd"} + + for _, input := range []string{"a3", "a3f8"} { + var resolved string + var err error + captureStderr(t, func() { + resolved, err = ResolvePartialID(context.Background(), store, input) + }) + if err != nil || resolved != "bd-a3f8e9" { + t.Errorf("ResolvePartialID(%q) = (%q, %v), want (%q, nil)", input, resolved, err, "bd-a3f8e9") + } + } + for _, input := range []string{"f8e9", "3f8"} { + if resolved, err := ResolvePartialID(context.Background(), store, input); err == nil { + t.Errorf("ResolvePartialID(%q) = %q, want not found: %q is not a leading prefix of a3f8e9", input, resolved, input) + } + } +} + +// A bare wisp hash is an exact reference: "t3st" names bd-wisp-t3st through +// the wisp fallback's exact branch, so it resolves silently, even beside +// bd-wisp-t3stzz, which it also abbreviates. The unfiltered search returns +// wisps (as Dolt's does), so a first-loop matcher that claimed "wisp-t3st" as +// an abbreviation of "t3st" would add a notice, or an ambiguity with the +// sibling. +func TestResolvePartialIDSilentOnExactWispHash(t *testing.T) { + // An ambient opt-out would make the silence assertion vacuous. + t.Setenv("BD_NO_PARTIAL_ID_NOTICE", "") + + for _, ids := range [][]string{ + {"bd-wisp-t3st"}, + {"bd-wisp-t3st", "bd-wisp-t3stzz"}, + } { + store := &fakeResolverStore{ids: ids, prefix: "bd"} + + var resolved string + var err error + out := captureStderr(t, func() { + resolved, err = ResolvePartialID(context.Background(), store, "t3st") + }) + if err != nil { + t.Errorf("ids %v: ResolvePartialID returned error: %v", ids, err) + continue + } + if resolved != "bd-wisp-t3st" { + t.Errorf("ids %v: resolved = %q, want %q", ids, resolved, "bd-wisp-t3st") + } + if out != "" { + t.Errorf("ids %v: expected no notice for an exact wisp hash, got %q", ids, out) + } + } +} + +// A leading fragment of a wisp hash is still an abbreviation: it resolves +// through the wisp fallback and is announced like any other. +func TestResolvePartialIDNotifiesOnWispHashAbbreviation(t *testing.T) { + store := &fakeResolverStore{ids: []string{"bd-wisp-t3st"}, prefix: "bd"} + + var resolved string + var err error + out := captureStderr(t, func() { + resolved, err = ResolvePartialID(context.Background(), store, "t3") + }) + if err != nil { + t.Fatalf("ResolvePartialID returned error: %v", err) + } + if resolved != "bd-wisp-t3st" { + t.Fatalf("resolved = %q, want %q", resolved, "bd-wisp-t3st") + } + if !strings.Contains(out, "bd-wisp-t3st") || !strings.Contains(out, "not an exact issue ID") { + t.Fatalf("expected a partial-resolution notice on stderr, got %q", out) + } +} diff --git a/internal/validation/BUILD.bazel b/internal/validation/BUILD.bazel index 46bf8895d..e9aefda09 100644 --- a/internal/validation/BUILD.bazel +++ b/internal/validation/BUILD.bazel @@ -13,6 +13,7 @@ go_library( "//internal/config", "//internal/types", "//internal/utils", + "//issueops", ], ) @@ -30,3 +31,64 @@ go_test( "//internal/types", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/validation/issue.go b/internal/validation/issue.go index c59f4e4b2..bad1fc61a 100644 --- a/internal/validation/issue.go +++ b/internal/validation/issue.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" ) // IssueValidator validates an issue and returns an error if validation fails. @@ -43,7 +44,7 @@ func NotTemplate() IssueValidator { return nil // Let Exists() handle nil check if needed } if issue.IsTemplate { - return fmt.Errorf("cannot modify template %s: templates are read-only; use 'bd mol pour' to create a work item", id) + return &issueops.TemplateReadOnlyError{IssueID: id} } return nil } @@ -65,7 +66,7 @@ func NotPinned(force bool) IssueValidator { return nil // Let Exists() handle nil check if needed } if !force && (issue.Pinned || issue.Status == types.StatusPinned) { - return fmt.Errorf("cannot modify pinned issue %s (use --force to override)", id) + return &issueops.PinnedError{IssueID: id} } return nil } @@ -170,7 +171,7 @@ func AssigneeMatches(actor string, force bool) IssueValidator { if issue.Assignee == "" || ActorMatches(issue.Assignee, actor) { return nil } - return fmt.Errorf("cannot close %s: assignee is %q, actor is %q; reclaim or use --force to override", id, issue.Assignee, actor) + return &issueops.CloseNotAssigneeError{IssueID: id, Assignee: issue.Assignee, Actor: actor} } } diff --git a/internal/versioncheck/BUILD.bazel b/internal/versioncheck/BUILD.bazel index b439bcb54..0a7962628 100644 --- a/internal/versioncheck/BUILD.bazel +++ b/internal/versioncheck/BUILD.bazel @@ -18,3 +18,64 @@ go_test( embed = [":versioncheck"], deps = ["//internal/testutil/bazeltest"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/versioncheck/check_test.go b/internal/versioncheck/check_test.go index 71c4564ba..29da1ace4 100644 --- a/internal/versioncheck/check_test.go +++ b/internal/versioncheck/check_test.go @@ -12,7 +12,7 @@ import ( func TestRepositoryReleaseVersionsMatch(t *testing.T) { root := bazeltest.RepoRoot(t) report, err := Check(root) - if err != nil && !(bazeltest.IsBazel() && onlyNPMManifestUndeclared(t, root, report)) { + if err != nil { t.Fatalf("repository release metadata is inconsistent: %v", err) } if report.CheckedSources != 12 { @@ -623,28 +623,3 @@ func writeFixtureAt(t *testing.T, root, version string) { func stringPointer(value string) *string { return &value } - -// onlyNPMManifestUndeclared reports, and logs, whether the npm manifest is the -// one failing release surface and it failed because it is absent. npm-package/ -// is in .bazelignore, so no target can declare npm-package/package.json as data -// and a Bazel run never sees it; `go test` checks it against the real checkout. -func onlyNPMManifestUndeclared(t *testing.T, root string, report Report) bool { - t.Helper() - if _, err := os.Stat(filepath.Join(root, "npm-package", "package.json")); !os.IsNotExist(err) { - return false - } - npmMissing := false - for _, source := range report.Sources { - switch { - case source.Problem == "": - case source.Description == "npm package.json": - npmMissing = true - default: - return false - } - } - if npmMissing { - t.Log("npm-package/ is in .bazelignore, so npm-package/package.json cannot be declared as data; checked under go test") - } - return npmMissing -} diff --git a/internal/versionedhistory/BUILD.bazel b/internal/versionedhistory/BUILD.bazel new file mode 100644 index 000000000..250b9fd91 --- /dev/null +++ b/internal/versionedhistory/BUILD.bazel @@ -0,0 +1,92 @@ +load("@rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "versionedhistory", + srcs = ["activation.go"], + importpath = "github.com/steveyegge/beads/internal/versionedhistory", + visibility = ["//:__subpackages__"], + deps = [ + "//internal/config", + "//internal/debug", + "//internal/storage", + "//internal/storage/uow", + "//issueops", + ], +) + +go_test( + name = "versionedhistory_test", + srcs = ["activation_test.go"], + embed = [":versionedhistory"], + deps = [ + "//internal/config", + "//internal/debug", + "//internal/storage", + "//internal/storage/domain", + "//internal/storage/externaldeps", + "//internal/storage/uow", + "//internal/telemetry", + "//issueops", + ], +) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/versionedhistory/activation.go b/internal/versionedhistory/activation.go new file mode 100644 index 000000000..d187b2758 --- /dev/null +++ b/internal/versionedhistory/activation.go @@ -0,0 +1,350 @@ +// Package versionedhistory decides whether dual-write issue-version history is on +// for one store or unit-of-work provider, and applies that decision where the +// thing is constructed. +// +// It is a package rather than helpers inside cmd/bd for the same reason as +// internal/eventsjournal: bd doctor's repair handlers live in their own package +// and cannot import package main, and a repair that mutates issues needs exactly +// the same rule as the command surface. There is ONE implementation of that rule, +// here. +// +// THE SWITCH IS A PROPERTY OF THE STORE. `bd config set versioned-history.enabled +// true` writes a row of the workspace's own config table, and a store answers for +// itself: a write routed into rig B reads rig B's row, never the launching +// workspace's. The environment (BD_VERSIONED_HISTORY_ENABLED) and a hand-edited +// config.yaml value are read through viper, are process-wide, and can only turn +// recording ON for every store the process opens; nothing but the row turns a +// store off. The two are OR'd rather than ranked, deliberately: the hazard is a +// write that fails to record, never one that records when it needn't, so either +// plane saying yes is enough and neither can silently switch the other off. +// +// Activation is applied by the FACTORIES that construct a store or provider +// (ActivateStore, ActivateProvider), never by the commands that use one. Applying +// it at the root pre-run reached only the store a command opens for its own +// workspace, and missed every store a routed update, a routed close, `bd create +// --repo` or the direct-mode open builds for another one -- which then recorded no +// history while the command reported success. See +// cmd/bd/versioned_history_construction_test.go for the structural guard. +package versionedhistory + +import ( + "context" + "fmt" + "os" + "strconv" + "strings" + + "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/debug" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/issueops" +) + +// ConfigKey is the one spelling of the switch, used for the store-config read +// below and for the `bd config set` line the help text and the off-refusal tell +// people to run. They must not drift. +const ConfigKey = "versioned-history.enabled" + +// Enabled reports whether version recording is on for this store, reading BOTH +// planes bd stores configuration in. +// +// This exists because the two disagreed. `bd config set versioned-history.enabled +// true` -- the command the help text and the off-refusal both name -- writes the +// workspace DATABASE, because the key is not a yaml-only key (config.IsYamlOnlyKey, +// and "versioned-history." is not among the prefixes at yaml_config.go). +// config.GetBool reads viper, which is yaml and env only. So the advertised command +// wrote one plane and the reader read the other: the user ran exactly what they +// were told, was told it worked, and the feature stayed off. Configured on, +// actually off -- the GH#536 class, and the precise failure this command was added +// to end. (bee-ghosttrack, #6661 review, finding 1.) +// +// The store plane is authoritative in the sense that matters: it makes the switch +// a property of the STORE rather than of whoever is calling, so two clients of one +// dolt sql-server agree about whether a write records a version. That closes the +// silent-holes case in the same review's finding 2 -- a client with recording off +// advances nothing, and the next enabled write mints a version that absorbs the +// unrecorded change under its own actor, producing contiguous revisions and a +// gapless-LOOKING history that is not one. +// +// The two are OR'd rather than ranked, deliberately. The hazard is a write that +// fails to record, never one that records when it needn't, so either plane saying +// yes is enough and neither can silently switch the other off. That keeps +// BD_VERSIONED_HISTORY_ENABLED=1 working for a one-off run without letting an unset +// (or =0) env var countermand a store that is recording. +// +// A store that cannot answer is not an error: proxied and no-db workspaces have no +// settings plane to read. Those fall back to viper alone rather than failing the +// command, because a store-config read is not worth breaking every bd invocation +// over. +// +// Nothing in production calls Enabled today. `bd versions` reports StoreSetting +// alone, because it only reads: the process-wide planes cannot make a store +// record, so they cannot speak for it. Activation uses EnabledForStore. Enabled +// stays, with its tests, as the ungated form of the combined rule. +func Enabled(ctx context.Context, st storage.DoltStorage) bool { + if config.GetBool(ConfigKey) { + // Already on via env or yaml; skip the store read entirely. This is also + // what keeps the common path cheap when someone is driving the feature from + // the environment. + return true + } + return StoreSetting(ctx, st) +} + +// StoreSetting reads the switch from the store's own settings plane, answering +// false for every reason a read can fail to produce a true. +// +// "EVERY reason" INCLUDES A PANIC, and that is the whole point of the defer below +// rather than an oversight to tidy away. The factories call this on every store +// they hand back, before anything has established that the store at the bottom of +// the chain can answer a config question at all -- so a store that cannot is not a +// hypothetical, it is a store that takes the process down. The shape that found +// it: a test double embedding a nil storage.DoltStorage, whose promoted +// WorkspaceConfig SIGSEGVs on call. The blast radius of letting that through is not +// one command; it is every bd invocation against any store whose settings plane is +// absent or half-built, for a read whose answer only ever decides whether to record +// versions. (bee-ghosttrack, #6661 second review.) +// +// A CAPABILITY ASSERTION ON WorkspaceConfig CANNOT REPLACE THIS, because +// WorkspaceConfig is declared on storage.DoltStorage itself +// (internal/storage/storage.go): every store satisfies an +// interface{ WorkspaceConfig() ... } assertion, including the one that panics when +// the method is actually called. That assertion would pass and the panic would +// happen anyway. +// +// AN ASSERTION ON storage.VersionedHistoryConfigurer IS DIFFERENT, and it is the +// primary guard now -- see EnabledForStore below. SetVersionedHistoryEnabled is NOT +// part of DoltStorage, so a store that embeds a nil DoltStorage does not promote it +// and does not satisfy that interface. (bee-ghosttrack, #6661 third review.) +// +// The recover stays anyway, because the guard does not cover every caller: `bd +// versions` calls StoreSetting directly, where the read is the point and no +// capability gate precedes it, and because a store that DOES implement the +// capability can still have a half-built settings plane. Guard first, recover as +// the backstop. +// +// A typed nil needs no separate guard for the same reason it needs no reflection: +// if its WorkspaceConfig panics, the recover answers false; if it returns (nil, nil) +// instead, the cfg == nil check answers false. Both arms are already here. +// +// The answer when the store cannot be read is false -- recording off, which is what +// the feature ships as. That is a real tradeoff and not a free one: a store that IS +// recording, whose settings read panics, is read as not recording, and a write +// during that window advances nothing. It is still the right side to fail to, +// because the alternative is that bd does not run at all, and a store too broken to +// answer a settings query is not one that was successfully recording versions a +// moment ago. +// +// WHAT IS AND IS NOT DIAGNOSED. An absent row is "" with a nil error by contract +// (WorkspaceConfig.GetSetting) and is the normal state of every workspace that never +// ran `bd config set`: it stays silently off. A read that ERRORS is different -- the +// row may well be there -- and resolving it to off with nothing to say so is the +// "set but silently off" shape this feature exists to end. Those go to debug.Logf, +// not to stderr: this runs on every invocation, and a diagnostic on a path the user +// did not ask about would be noise on all of them. +func StoreSetting(ctx context.Context, st storage.DoltStorage) (enabled bool) { + if st == nil { + return false + } + defer func() { + if r := recover(); r != nil { + // Deliberately swallowed, not re-raised and not logged: this runs on + // every invocation and its answer is a default, so the honest report is + // the false below rather than noise on a path the user did not ask + // about. The named return makes that explicit. + // + // This is the opposite choice from the repo's other non-test recover + // (internal/storage/dolt/transaction.go), which rolls back and then + // re-panics, and the difference is not stylistic: there a caller must + // not proceed over a half-applied transaction, so the panic has to keep + // traveling. Here the caller can proceed perfectly well, because what it + // wanted was a boolean with a documented default. + enabled = false + } + }() + cfg, err := st.WorkspaceConfig() + if err != nil { + debug.Logf("versioned history: %s left off: no settings plane readable on %T: %v\n", ConfigKey, st, err) + return false + } + if cfg == nil { + return false + } + res, err := cfg.GetSetting(ctx, issueops.GetSettingRequest{Key: ConfigKey}) + if err != nil { + debug.Logf("versioned history: %s left off: reading the setting from %T failed: %v\n", ConfigKey, st, err) + return false + } + return parseSettingBool(res.Value) +} + +// parseSettingBool reads the stored string the way `bd config set` writes it. +// Unset is "" and a nil error by contract (WorkspaceConfig.GetSetting), which lands +// here as false -- the correct default for a flag that ships off. +func parseSettingBool(v string) bool { + b, err := strconv.ParseBool(strings.TrimSpace(v)) + return err == nil && b +} + +// ValueEnables reports whether a stored value of the switch turns recording on, +// reading it the way every reader of the row does. `bd config set` uses it to +// decide whether the value it was just given deserves the replication and +// single-writer caveat, so that answer cannot drift from what the stores do with +// the same string. +func ValueEnables(v string) bool { return parseSettingBool(v) } + +// EnabledForStore answers the switch for a freshly constructed store, which is the +// caller that runs on EVERY store bd opens. +// +// It differs from Enabled in one deliberate way: it will not read the store's +// settings plane unless the store could actually act on the answer. Activation's +// whole use for the result is Apply, which needs a storage.VersionedHistoryConfigurer; +// a store that is not one cannot record versions however the question is answered, +// so the read is pure cost and, for a store whose settings plane is absent or +// half-built, pure risk. This is what took CI red at 32d4f966e: the read panicked at +// wiring time on a test double embedding a nil storage.DoltStorage, which is a panic +// in a path whose answer only ever decides whether to record versions. +// +// The ordering matters and is not interchangeable with Apply's own assertion. The +// viper plane is read FIRST and unconditionally, so a store that is +// set-but-unsupported still reaches Apply with enabled=true and still gets the +// warning it prints. Only the STORE-plane read is gated. The one case that loses its +// warning is a store whose own settings plane says true but which lacks the +// capability -- and `bd config set` could not have written that plane on such a +// store in the first place. +// +// (bee-ghosttrack, #6661 third review, blocking finding 1.) +func EnabledForStore(ctx context.Context, st storage.DoltStorage) bool { + if config.GetBool(ConfigKey) { + return true + } + if _, canRecord := st.(storage.VersionedHistoryConfigurer); !canRecord { + return false + } + return StoreSetting(ctx, st) +} + +// ProviderSetting reads the switch from a unit-of-work provider's own database, +// answering false for every reason a read can fail to produce a true. It is the +// provider-path twin of StoreSetting: a provider has no storage.DoltStorage to ask +// for a settings plane, so the row is read the way the rest of the unit-of-work +// layer reads one -- through a unit of work's ConfigUseCase, as +// internal/storage/uow/issue_operations.go does for claim.pools. +// +// The read opens one unit of work, asks for one config row, and rolls it back: a +// pooled connection, START TRANSACTION, a SELECT, a ROLLBACK. It starts no server +// and creates no schema (the provider constructors have already opened the pool and +// run initSchema by the time this is called) and commits nothing. That is the whole +// cost of "each provider answers for its own database", and it is why this is read +// at construction, once, rather than falling back to viper alone: a provider that +// silently ignored the row would record nothing for a workspace that asked, while +// every command reported success. +// +// The same failure policy as StoreSetting applies, including the recover. +func ProviderSetting(ctx context.Context, p uow.UnitOfWorkProvider) (enabled bool) { + if p == nil { + return false + } + defer func() { + if r := recover(); r != nil { + enabled = false + } + }() + unit, err := p.NewUOW(ctx) + if err != nil { + debug.Logf("versioned history: %s left off: opening a unit of work on %T to read it failed: %v\n", ConfigKey, p, err) + return false + } + // Rolled back, never committed: this is a read. + defer unit.Close(ctx) + raw, err := unit.ConfigUseCase().GetConfig(ctx, ConfigKey) + if err != nil { + debug.Logf("versioned history: %s left off: reading the setting through %T failed: %v\n", ConfigKey, p, err) + return false + } + return parseSettingBool(raw) +} + +// EnabledForProvider is EnabledForStore for a provider: viper first, then the +// capability check, then the provider's own row. +func EnabledForProvider(ctx context.Context, p uow.UnitOfWorkProvider) bool { + if config.GetBool(ConfigKey) { + return true + } + if _, canRecord := p.(storage.VersionedHistoryConfigurer); !canRecord { + return false + } + return ProviderSetting(ctx, p) +} + +// ActivateStore applies a freshly opened store's own configured switch to it. It is +// written to be used as a deferred rewrite of a factory's named results: +// +// func newX(ctx context.Context, ...) (s storage.DoltStorage, err error) { +// defer func() { s, err = versionedhistory.ActivateStore(ctx, s, err) }() +// ... open and return ... +// } +// +// The shape is deliberate, and is internal/eventsjournal's. It keeps the open and +// its activation in ONE function body, so "constructs a store" and "activates +// history on it" are the same syntactic unit -- which is what lets the construction +// guard check the property structurally instead of chasing a call graph. +// +// The store is activated RAW: every factory hands back the concrete store, before +// any decorator wraps it. That ordering is load-bearing, because activation is a +// type assertion and none of the decorators (telemetry, externaldeps, hooks) +// forwards SetVersionedHistoryEnabled -- asserting against a wrapper would fail +// silently and leave history off while the config said it was on. It is pinned by +// TestApplyReachesOnlyTheRawStore. +// +// A failed open passes through untouched, so the typed-nil store never reaches the +// activation. A store that cannot version at all is returned as-is without its +// settings plane being read: there is nothing to activate, and the factories run for +// every command that opens a store. +func ActivateStore(ctx context.Context, s storage.DoltStorage, err error) (storage.DoltStorage, error) { + if err != nil || s == nil { + return s, err + } + Apply(s, EnabledForStore(ctx, s)) + return s, nil +} + +// ActivateProvider is ActivateStore for a unit-of-work provider -- bd's second write +// plumbing, with its own transactions and its own activation switch, which +// proxied-server mode and `bd serve` against a server-mode workspace write through +// instead of a DoltStorage. +func ActivateProvider(ctx context.Context, p uow.UnitOfWorkProvider, err error) (uow.UnitOfWorkProvider, error) { + if err != nil || p == nil { + return p, err + } + Apply(p, EnabledForProvider(ctx, p)) + return p, nil +} + +// Apply binds a resolved answer to one plumbing -- a store or a unit-of-work +// provider. Activation is per instance rather than process-global: a process can +// hold several plumbings at once (a routed create holds two), and enabling history +// on one must not enable it on the rest. +// +// It only ever turns recording ON. A false answer touches nothing, so flag-off is +// byte-identical to a build without the feature, which is the contract #6135 ships +// under. +// +// A plumbing that does not implement the capability is not an error: proxied and +// no-db backends legitimately do not. But it is not silently ignored either -- +// asking for history and not getting it is exactly the case a user must be told +// about, so it warns. +func Apply(target any, enabled bool) { + if !enabled { + return + } + configurer, ok := target.(storage.VersionedHistoryConfigurer) + if !ok { + fmt.Fprintf(os.Stderr, + "warning: versioned-history.enabled is set, but this storage backend (%T) does not support version history; it stays off\n", + target) + return + } + configurer.SetVersionedHistoryEnabled(true) +} diff --git a/internal/versionedhistory/activation_test.go b/internal/versionedhistory/activation_test.go new file mode 100644 index 000000000..a043f6b16 --- /dev/null +++ b/internal/versionedhistory/activation_test.go @@ -0,0 +1,776 @@ +package versionedhistory + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/debug" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/storage/externaldeps" + "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/internal/telemetry" + "github.com/steveyegge/beads/issueops" +) + +// The resolver's tests. Most of them moved here from cmd/bd with the code they +// test, assertions unchanged: that is what shows the move preserved #6661's +// behavior. The rest are the new claims -- each store (and each provider) answers +// for itself, the environment is process-wide and can only turn recording on, and +// a read that errors is not the same as a row that is absent. + +const envVar = "BD_VERSIONED_HISTORY_ENABLED" + +// viperEnv sets the switch's environment variable and re-initialises viper, since +// config.GetBool answers false until viper is initialised and so would make every +// env-driven case below pass whatever the code did with the env. +func viperEnv(t *testing.T, value string) { + t.Helper() + t.Setenv(envVar, value) + // Nothing from the machine's own config may decide these cases. + t.Setenv("HOME", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Chdir(t.TempDir()) + if err := config.Initialize(); err != nil { + t.Fatalf("config.Initialize(): %v", err) + } + t.Cleanup(config.ResetForTesting) +} + +// captureStderr runs fn with os.Stderr redirected and returns what it wrote. With +// verbose set, debug.Logf writes too. +func captureStderr(t *testing.T, verbose bool, fn func()) string { + t.Helper() + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + orig := os.Stderr + os.Stderr = w + debug.SetVerbose(verbose) + func() { + defer func() { + debug.SetVerbose(false) + os.Stderr = orig + _ = w.Close() + }() + fn() + }() + out, err := io.ReadAll(r) + if err != nil { + t.Fatal(err) + } + return string(out) +} + +// --- fakes ----------------------------------------------------------------- + +// settingsPlane is a workspace settings plane with one canned answer. +type settingsPlane struct { + issueops.WorkspaceConfig + value string + err error + panicMsg string + reads int +} + +func (p *settingsPlane) GetSetting(_ context.Context, req issueops.GetSettingRequest) (issueops.SettingResult, error) { + p.reads++ + if p.panicMsg != "" { + panic(p.panicMsg) + } + return issueops.SettingResult{Key: req.Key, Value: p.value}, p.err +} + +// configProbeStore is a raw store at the bottom of a decorator chain whose +// settings plane behaves however a case needs: panicking, erroring, absent, or +// answering. It counts the reads so a test can prove it was actually asked, rather +// than passing because the switch short-circuited before reaching it. +// +// Every other method promotes from the embedded nil interface and panics if +// called, which is deliberate: nothing here should be calling them. +type configProbeStore struct { + storage.DoltStorage + cfg issueops.WorkspaceConfig + err error + panicMsg string + calls int + enabled bool + sets int +} + +func (s *configProbeStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) { + s.calls++ + if s.panicMsg != "" { + panic(s.panicMsg) + } + return s.cfg, s.err +} + +// SetVersionedHistoryEnabled makes this store a storage.VersionedHistoryConfigurer, +// which is what earns it the store-plane read at activation time. Without it this +// store would be skipped before WorkspaceConfig was ever called, and every +// calls-count assertion below would pass for the wrong reason. +func (s *configProbeStore) SetVersionedHistoryEnabled(enabled bool) { + s.enabled = enabled + s.sets++ +} + +// nonConfigurerStore is the shape the capability guard exists for, and it is not a +// hypothetical: it is cmd/bd's own fakeProbingDoltStore, which embeds a nil +// storage.DoltStorage and documents that only its own methods may be called. +// SetVersionedHistoryEnabled is not part of DoltStorage, so nothing promotes it and +// this type does not satisfy storage.VersionedHistoryConfigurer -- while +// WorkspaceConfig IS part of DoltStorage, so it promotes, type-checks, and SIGSEGVs +// on call. +type nonConfigurerStore struct { + storage.DoltStorage + calls int +} + +func (s *nonConfigurerStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) { + s.calls++ + panic("WorkspaceConfig on a store with no settings plane") +} + +// planeOnlyStore can answer a settings query but cannot record versions, which is +// what `bd versions` may be pointed at: the read is the point there. +type planeOnlyStore struct { + storage.DoltStorage + cfg issueops.WorkspaceConfig + calls int +} + +func (s *planeOnlyStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) { + s.calls++ + return s.cfg, nil +} + +// nilDerefStore reproduces the exact shape that broke CI: the method body touches +// the receiver, so a TYPED NIL of this type is non-nil as an interface and panics +// when called. +type nilDerefStore struct { + storage.DoltStorage + cfg issueops.WorkspaceConfig +} + +func (s *nilDerefStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) { + return s.cfg, nil +} + +// configUseCaseProbe is a unit of work's config use case with one canned answer. +type configUseCaseProbe struct { + domain.ConfigUseCase + value string + err error + reads int + keys []string +} + +func (c *configUseCaseProbe) GetConfig(_ context.Context, key string) (string, error) { + c.reads++ + c.keys = append(c.keys, key) + return c.value, c.err +} + +// unitProbe is a unit of work that records how it was finished: a settings read +// must be rolled back (Close), never committed. +type unitProbe struct { + uow.UnitOfWork + cfg *configUseCaseProbe + closed int + committed int +} + +func (u *unitProbe) ConfigUseCase() domain.ConfigUseCase { return u.cfg } +func (u *unitProbe) Close(context.Context) { u.closed++ } +func (u *unitProbe) Commit(context.Context, string) error { + u.committed++ + return nil +} + +// providerProbe is a unit-of-work provider that is a VersionedHistoryConfigurer. +type providerProbe struct { + uow.UnitOfWorkProvider + unit *unitProbe + newErr error + panicMsg string + newCalls int + enabled bool + sets int +} + +func (p *providerProbe) NewUOW(context.Context) (uow.UnitOfWork, error) { + p.newCalls++ + if p.panicMsg != "" { + panic(p.panicMsg) + } + if p.newErr != nil { + return nil, p.newErr + } + return p.unit, nil +} + +func (p *providerProbe) SetVersionedHistoryEnabled(enabled bool) { + p.enabled = enabled + p.sets++ +} + +func newProviderProbe(value string, err error) *providerProbe { + return &providerProbe{unit: &unitProbe{cfg: &configUseCaseProbe{value: value, err: err}}} +} + +// nonConfigurerProvider cannot record versions: it does not implement the capability. +type nonConfigurerProvider struct { + uow.UnitOfWorkProvider + newCalls int +} + +func (p *nonConfigurerProvider) NewUOW(context.Context) (uow.UnitOfWork, error) { + p.newCalls++ + panic("NewUOW on a provider that cannot record versions") +} + +// --- the resolver, moved from cmd/bd with its assertions unchanged ---------- + +// TestStoreSettingAnswersFalseForAStoreThatCannotAnswer pins the contract the +// function's own doc states, across every way a store can fail to produce a true +// -- including the two that are panics rather than errors, which is the pair that +// took the process down. +func TestStoreSettingAnswersFalseForAStoreThatCannotAnswer(t *testing.T) { + ctx := context.Background() + var typedNil *nilDerefStore + + for _, tt := range []struct { + name string + store storage.DoltStorage + want bool + }{ + {"nil store", nil, false}, + {"typed nil store", typedNil, false}, + {"WorkspaceConfig panics", &configProbeStore{panicMsg: "no settings plane on this store"}, false}, + {"WorkspaceConfig errors", &configProbeStore{err: fmt.Errorf("server unreachable")}, false}, + {"WorkspaceConfig returns no plane", &configProbeStore{}, false}, + {"GetSetting panics", &configProbeStore{cfg: &settingsPlane{panicMsg: "settings table missing"}}, false}, + {"GetSetting errors", &configProbeStore{cfg: &settingsPlane{err: fmt.Errorf("read failed")}}, false}, + {"unset is off", &configProbeStore{cfg: &settingsPlane{value: ""}}, false}, + {"stored false", &configProbeStore{cfg: &settingsPlane{value: "false"}}, false}, + {"unparseable is off", &configProbeStore{cfg: &settingsPlane{value: "yes please"}}, false}, + {"stored true", &configProbeStore{cfg: &settingsPlane{value: "true"}}, true}, + {"stored 1", &configProbeStore{cfg: &settingsPlane{value: "1"}}, true}, + {"stored true with whitespace", &configProbeStore{cfg: &settingsPlane{value: " true\n"}}, true}, + } { + t.Run(tt.name, func(t *testing.T) { + // No recover here on purpose: a panic escaping the call under test + // must fail this test, not be absorbed by it. + if got := StoreSetting(ctx, tt.store); got != tt.want { + t.Errorf("StoreSetting = %v, want %v", got, tt.want) + } + }) + } +} + +// TestParseSettingBool pins how the stored string is read back. `bd config set` +// stores whatever the user typed, verbatim, so this is the whole translation +// between that and the boolean the factories activate on. +func TestParseSettingBool(t *testing.T) { + for _, tt := range []struct { + in string + want bool + }{ + {"", false}, + {"true", true}, + {"TRUE", true}, + {"True", true}, + {"1", true}, + {"t", true}, + {" true ", true}, + {"false", false}, + {"0", false}, + {"off", false}, + {"on", false}, + {"nonsense", false}, + } { + t.Run(fmt.Sprintf("%q", tt.in), func(t *testing.T) { + if got := parseSettingBool(tt.in); got != tt.want { + t.Errorf("parseSettingBool(%q) = %v, want %v", tt.in, got, tt.want) + } + }) + } +} + +// TestEnabledForStoreSkipsTheStoreReadForANonConfigurer is the capability GUARD's +// test, and the regression test for the CI failure as it actually happened. +// +// The store read is only ever used to decide whether to call +// SetVersionedHistoryEnabled, so a store that cannot record versions has nothing to +// gain from being asked -- and, if its settings plane is absent or half-built, +// everything to lose. That is what took Test (macos-latest) and PR Core (wrapper +// timing) red at 32d4f966e, via cmd/bd's own fakeProbingDoltStore. +// +// The assertion that matters is calls == 0: not "it survived" (the recover would +// deliver that too, which is exactly how this regressed the first time) but "it was +// never asked". +func TestEnabledForStoreSkipsTheStoreReadForANonConfigurer(t *testing.T) { + raw := &nonConfigurerStore{} + if _, isConfigurer := storage.DoltStorage(raw).(storage.VersionedHistoryConfigurer); isConfigurer { + t.Fatal("nonConfigurerStore satisfies VersionedHistoryConfigurer; this test cannot exercise the guard it claims to") + } + if EnabledForStore(context.Background(), raw) { + t.Error("EnabledForStore = true for a store that cannot record versions") + } + if raw.calls != 0 { + t.Fatalf("WorkspaceConfig called %d times on a store that cannot record versions, want 0", raw.calls) + } +} + +// TestEnabledForStoreReadsTheStoreWhenItCanRecord is the other half: the guard must +// not be so eager that it stops reading the plane that finding 1 existed to start +// reading. A store that CAN record still gets asked, and a stored true still turns +// recording on. +func TestEnabledForStoreReadsTheStoreWhenItCanRecord(t *testing.T) { + raw := &configProbeStore{cfg: &settingsPlane{value: "true"}} + if got := EnabledForStore(context.Background(), raw); !got { + t.Fatal("EnabledForStore = false for a configurer whose store plane says true") + } + if raw.calls != 1 { + t.Fatalf("store read %d times, want 1", raw.calls) + } +} + +// TestEnabledReadsTheRowWithoutTheCapabilityGate: `bd versions` is the one caller +// where the read is the point, so it must ask a store that cannot record too. +func TestEnabledReadsTheRowWithoutTheCapabilityGate(t *testing.T) { + raw := &planeOnlyStore{cfg: &settingsPlane{value: "true"}} + if _, isConfigurer := storage.DoltStorage(raw).(storage.VersionedHistoryConfigurer); isConfigurer { + t.Fatal("planeOnlyStore satisfies VersionedHistoryConfigurer; this test cannot exercise what it claims to") + } + if !Enabled(context.Background(), raw) { + t.Error("Enabled = false for a store whose row says true") + } + if raw.calls != 1 { + t.Errorf("store read %d times, want 1", raw.calls) + } +} + +// --- each store answers for itself; the environment only turns recording on -- + +// TestActivateStoreReadsTheStoresOwnRow is D1 at the unit level: two stores opened +// by one process each read ITS OWN row. The one whose row says on records; the one +// with no row does not, and does not inherit the other's answer. +func TestActivateStoreReadsTheStoresOwnRow(t *testing.T) { + ctx := context.Background() + on := &configProbeStore{cfg: &settingsPlane{value: "true"}} + absent := &configProbeStore{cfg: &settingsPlane{value: ""}} + off := &configProbeStore{cfg: &settingsPlane{value: "false"}} + + for name, s := range map[string]*configProbeStore{"on": on, "absent": absent, "off": off} { + got, err := ActivateStore(ctx, s, nil) + if err != nil || got != storage.DoltStorage(s) { + t.Fatalf("%s: ActivateStore = (%v, %v), want the same store and no error", name, got, err) + } + } + if !on.enabled { + t.Error("the store whose row says true was not activated") + } + if absent.enabled || off.enabled { + t.Errorf("a store with no row (%v) or a false row (%v) was activated by another store's answer", absent.enabled, off.enabled) + } +} + +// TestActivateStoreReadsTheRowExactlyOncePerOpen: with the factories activating, +// wireStorageDecorators no longer does, so each store is activated and its row read +// once per open -- not twice. +func TestActivateStoreReadsTheRowExactlyOncePerOpen(t *testing.T) { + plane := &settingsPlane{value: "true"} + raw := &configProbeStore{cfg: plane} + if _, err := ActivateStore(context.Background(), raw, nil); err != nil { + t.Fatal(err) + } + if raw.calls != 1 || plane.reads != 1 { + t.Errorf("settings plane fetched %d time(s) and row read %d time(s), want 1 and 1", raw.calls, plane.reads) + } + if raw.sets != 1 || !raw.enabled { + t.Errorf("SetVersionedHistoryEnabled called %d time(s), enabled=%v; want exactly one call turning it on", raw.sets, raw.enabled) + } +} + +func TestActivateStorePassesAFailedOpenThrough(t *testing.T) { + openErr := errors.New("open failed") + + got, err := ActivateStore(context.Background(), nil, openErr) + if got != nil || !errors.Is(err, openErr) { + t.Errorf("ActivateStore(nil, err) = (%v, %v), want (nil, the open error)", got, err) + } + + // A store handed back alongside an error is not touched or read either. + raw := &configProbeStore{cfg: &settingsPlane{value: "true"}} + got, err = ActivateStore(context.Background(), raw, openErr) + if got != storage.DoltStorage(raw) || !errors.Is(err, openErr) { + t.Errorf("ActivateStore(store, err) = (%v, %v), want the store and the open error unchanged", got, err) + } + if raw.calls != 0 || raw.sets != 0 { + t.Errorf("a failed open still touched the store: %d settings reads, %d activations", raw.calls, raw.sets) + } +} + +// TestActivateStoreSurvivesAStoreThatCannotAnswer is the regression test for the CI +// failure itself, at the layer that now owns it. This is the RECOVER's test: the +// store here IS a configurer, so the capability guard lets it through to the read, +// and only the recover keeps the panic from escaping. +func TestActivateStoreSurvivesAStoreThatCannotAnswer(t *testing.T) { + raw := &configProbeStore{panicMsg: "WorkspaceConfig on a store with no settings plane"} + got, err := ActivateStore(context.Background(), raw, nil) + if err != nil || got != storage.DoltStorage(raw) { + t.Fatalf("ActivateStore = (%v, %v), want the store back and no error", got, err) + } + if raw.calls != 1 { + t.Fatalf("WorkspaceConfig called %d times, want 1; this test is not exercising the read it claims to", raw.calls) + } + if raw.enabled { + t.Error("a store whose settings plane panicked was switched on") + } +} + +func TestActivateStoreLeavesAStoreThatCannotRecordUntouched(t *testing.T) { + raw := &nonConfigurerStore{} + got, err := ActivateStore(context.Background(), raw, nil) + if err != nil || got != storage.DoltStorage(raw) { + t.Fatalf("ActivateStore = (%v, %v), want the store back and no error", got, err) + } + if raw.calls != 0 { + t.Errorf("a store that cannot record was asked for its settings plane %d time(s), want 0", raw.calls) + } +} + +// TestEnvironmentIsProcessWideAndShortCircuitsTheRead is D3 for stores: viper says +// on, so every store the process opens is activated -- including one whose own row +// says nothing -- and the row is not even read. +func TestEnvironmentIsProcessWideAndShortCircuitsTheRead(t *testing.T) { + viperEnv(t, "1") + + absent := &configProbeStore{cfg: &settingsPlane{value: ""}} + if _, err := ActivateStore(context.Background(), absent, nil); err != nil { + t.Fatal(err) + } + if !absent.enabled { + t.Error("the environment said on but a store with no row was not activated") + } + if absent.calls != 0 { + t.Errorf("the settings plane was read %d time(s) although the environment had already answered, want 0", absent.calls) + } +} + +// TestEnvironmentZeroNeverSwitchesOffAStoreWhoseRowIsOn is D3's other half, and +// the rule that OR is never ranked: =0 is not "off". A store whose own row says on +// keeps recording, and a store with no row stays quiet. The only way off is the row. +func TestEnvironmentZeroNeverSwitchesOffAStoreWhoseRowIsOn(t *testing.T) { + viperEnv(t, "0") + ctx := context.Background() + + on := &configProbeStore{cfg: &settingsPlane{value: "true"}} + absent := &configProbeStore{cfg: &settingsPlane{value: ""}} + for _, s := range []*configProbeStore{on, absent} { + if _, err := ActivateStore(ctx, s, nil); err != nil { + t.Fatal(err) + } + } + if !on.enabled { + t.Error("BD_VERSIONED_HISTORY_ENABLED=0 switched off a store whose own row says true") + } + if absent.enabled { + t.Error("BD_VERSIONED_HISTORY_ENABLED=0 switched ON a store with no row") + } +} + +// --- D7: an error is not an absent row -------------------------------------- + +func TestAnAbsentRowIsSilentlyOffButAReadErrorIsDiagnosed(t *testing.T) { + ctx := context.Background() + + t.Run("absent row: off, and nothing to say", func(t *testing.T) { + raw := &configProbeStore{cfg: &settingsPlane{value: ""}} + var got bool + out := captureStderr(t, true, func() { got = StoreSetting(ctx, raw) }) + if got { + t.Error("an absent row resolved to on") + } + if out != "" { + t.Errorf("an absent row is the normal state of every workspace and must not be diagnosed, got: %q", out) + } + }) + + t.Run("GetSetting error: off, and diagnosed at debug level", func(t *testing.T) { + raw := &configProbeStore{cfg: &settingsPlane{err: errors.New("read failed: table config is locked")}} + var got bool + out := captureStderr(t, true, func() { got = StoreSetting(ctx, raw) }) + if got { + t.Error("a failed row read resolved to on") + } + for _, want := range []string{ConfigKey, "table config is locked"} { + if !strings.Contains(out, want) { + t.Errorf("the diagnostic does not mention %q: %q", want, out) + } + } + }) + + t.Run("WorkspaceConfig error: off, and diagnosed at debug level", func(t *testing.T) { + raw := &configProbeStore{err: errors.New("server unreachable")} + var got bool + out := captureStderr(t, true, func() { got = StoreSetting(ctx, raw) }) + if got { + t.Error("an unreadable settings plane resolved to on") + } + if !strings.Contains(out, "server unreachable") { + t.Errorf("the diagnostic does not carry the cause: %q", out) + } + }) + + t.Run("the diagnostic is debug-level, never unconditional stderr", func(t *testing.T) { + raw := &configProbeStore{cfg: &settingsPlane{err: errors.New("read failed")}} + out := captureStderr(t, false, func() { _ = StoreSetting(ctx, raw) }) + if out != "" { + t.Errorf("this runs on every invocation and must be silent unless debugging, got: %q", out) + } + }) +} + +// --- Apply: the raw-store ordering, and the set-but-unsupported warning ----- + +// TestApplyReachesOnlyTheRawStore pins the ORDERING that activation depends on. +// +// The capability is reached by type assertion, and none of the decorators +// (telemetry, externaldeps, hooks) forwards SetVersionedHistoryEnabled. So applying +// the config after any wrap would assert against a wrapper, fail silently, and +// leave versioned history OFF while the operator's config said it was on -- a wrong +// answer rather than an empty one. That is why the factories, which hand back the +// concrete store before anything wraps it, are where activation lives. +// +// The second half of this test is the part that actually guards the ordering: it +// proves the wrapped chain does NOT satisfy the capability, so if a decorator ever +// starts forwarding, the constraint this test exists for has changed. +func TestApplyReachesOnlyTheRawStore(t *testing.T) { + raw := &configProbeStore{} + Apply(raw, true) + if !raw.enabled { + t.Error("Apply(raw, true) did not enable versioned history on the raw store") + } + + wrap := func(s storage.DoltStorage) storage.DoltStorage { + return externaldeps.New( + telemetry.WrapStorage(s), + func(externaldeps.ProjectName) (string, bool) { return "", false }, + func(context.Context, string) (storage.DoltStorage, error) { return nil, errors.New("unused") }, + ) + } + if _, ok := wrap(&configProbeStore{}).(storage.VersionedHistoryConfigurer); ok { + // Fatal, not Skip. A skip here returns BEFORE the assertion below -- the + // half that actually guards the ordering -- so the case would report + // "not applicable" while checking nothing. + t.Fatal("a decorator now forwards SetVersionedHistoryEnabled; the ordering constraint has changed and this test needs rewriting rather than silently passing") + } + + behindWrap := &configProbeStore{} + captureStderr(t, false, func() { Apply(wrap(behindWrap), true) }) + if behindWrap.enabled { + t.Error("the capability was somehow reached through the decorators; this test's premise is stale") + } +} + +// TestApplyOffIsANoop pins that the disabled path touches nothing at all -- +// flag-off must be byte-identical to a build without the feature, which is the +// contract #6135 ships under. +func TestApplyOffIsANoop(t *testing.T) { + raw := &configProbeStore{} + out := captureStderr(t, true, func() { Apply(raw, false) }) + if raw.sets != 0 || raw.enabled { + t.Errorf("Apply(raw, false) called SetVersionedHistoryEnabled %d time(s), enabled=%v; flag-off must be a no-op", raw.sets, raw.enabled) + } + if out != "" { + t.Errorf("Apply(raw, false) wrote %q", out) + } +} + +// TestApplyWarnsWhenTheBackendCannotRecord: asking for history and not getting it is +// exactly the case a user must be told about. The wording is #6661's, unchanged. +func TestApplyWarnsWhenTheBackendCannotRecord(t *testing.T) { + out := captureStderr(t, false, func() { Apply(&nonConfigurerStore{}, true) }) + for _, want := range []string{ + "warning: versioned-history.enabled is set, but this storage backend (", + "does not support version history; it stays off", + } { + if !strings.Contains(out, want) { + t.Errorf("the warning is missing %q: %q", want, out) + } + } +} + +// TestConfigKeyIsNotYamlOnly is D5's pin at the unit level. versioned-history.* must +// NOT become a yaml-only key: `bd config set versioned-history.enabled true` keeps +// writing the database row exactly as #6661 wired it, and a yaml-only key would move +// the switch off the store. +func TestConfigKeyIsNotYamlOnly(t *testing.T) { + if ConfigKey != "versioned-history.enabled" { + t.Errorf("ConfigKey = %q; the key is documented, and read back by `bd versions`, under this exact spelling", ConfigKey) + } + if config.IsYamlOnlyKey(ConfigKey) { + t.Errorf("%s is a yaml-only key, so `bd config set` would write config.yaml and no store would ever read it", ConfigKey) + } +} + +// --- K1: the provider path --------------------------------------------------- + +// TestActivateProviderReadsItsOwnRow is K1's central claim. A unit-of-work provider +// has no storage.DoltStorage to ask, so its flag comes from viper OR its own row -- +// read through a unit of work's ConfigUseCase -- and NOT from viper alone. +func TestActivateProviderReadsItsOwnRow(t *testing.T) { + p := newProviderProbe("true", nil) + got, err := ActivateProvider(context.Background(), p, nil) + if err != nil || got != uow.UnitOfWorkProvider(p) { + t.Fatalf("ActivateProvider = (%v, %v), want the provider back and no error", got, err) + } + if !p.enabled { + t.Fatal("a provider whose database row says true was not activated: the flag was resolved from viper alone") + } + if p.unit.cfg.reads != 1 || len(p.unit.cfg.keys) != 1 || p.unit.cfg.keys[0] != ConfigKey { + t.Errorf("config rows read = %v (%d read(s)), want exactly one read of %q", p.unit.cfg.keys, p.unit.cfg.reads, ConfigKey) + } + // A settings read is a read: rolled back, never committed. + if p.unit.closed != 1 || p.unit.committed != 0 { + t.Errorf("unit of work closed %d time(s) and committed %d time(s), want closed once and never committed", p.unit.closed, p.unit.committed) + } +} + +func TestActivateProviderLeavesAnAbsentOrFalseRowOff(t *testing.T) { + for _, value := range []string{"", "false", "0", "on", "nonsense"} { + t.Run(fmt.Sprintf("%q", value), func(t *testing.T) { + p := newProviderProbe(value, nil) + captureStderr(t, true, func() { _, _ = ActivateProvider(context.Background(), p, nil) }) + if p.enabled { + t.Errorf("a provider whose row is %q was activated", value) + } + if p.unit.closed != 1 { + t.Errorf("unit of work closed %d time(s), want 1", p.unit.closed) + } + }) + } + t.Run("an absent row is silent", func(t *testing.T) { + p := newProviderProbe("", nil) + if out := captureStderr(t, true, func() { _, _ = ActivateProvider(context.Background(), p, nil) }); out != "" { + t.Errorf("an absent row must not be diagnosed, got %q", out) + } + }) +} + +// TestActivateProviderReadFailureIsOffAndDiagnosed is D7 for providers: an error is +// not an absent row. It resolves to off -- but not silently. +func TestActivateProviderReadFailureIsOffAndDiagnosed(t *testing.T) { + t.Run("GetConfig errors", func(t *testing.T) { + p := newProviderProbe("", errors.New("no such table: config")) + out := captureStderr(t, true, func() { _, _ = ActivateProvider(context.Background(), p, nil) }) + if p.enabled { + t.Error("a failed row read activated the provider") + } + for _, want := range []string{ConfigKey, "no such table: config"} { + if !strings.Contains(out, want) { + t.Errorf("the diagnostic does not mention %q: %q", want, out) + } + } + if p.unit.closed != 1 { + t.Errorf("unit of work closed %d time(s) after a failed read, want 1", p.unit.closed) + } + }) + t.Run("NewUOW errors", func(t *testing.T) { + p := &providerProbe{newErr: errors.New("connection refused")} + out := captureStderr(t, true, func() { _, _ = ActivateProvider(context.Background(), p, nil) }) + if p.enabled { + t.Error("a provider that could not open a unit of work was activated") + } + if !strings.Contains(out, "connection refused") { + t.Errorf("the diagnostic does not carry the cause: %q", out) + } + }) + t.Run("silent unless debugging", func(t *testing.T) { + p := newProviderProbe("", errors.New("no such table: config")) + if out := captureStderr(t, false, func() { _, _ = ActivateProvider(context.Background(), p, nil) }); out != "" { + t.Errorf("this runs on every invocation and must be silent unless debugging, got: %q", out) + } + }) +} + +func TestActivateProviderSurvivesAProviderThatPanics(t *testing.T) { + p := &providerProbe{panicMsg: "NewUOW on a half-built provider"} + got, err := ActivateProvider(context.Background(), p, nil) + if err != nil || got != uow.UnitOfWorkProvider(p) { + t.Fatalf("ActivateProvider = (%v, %v), want the provider back and no error", got, err) + } + if p.newCalls != 1 { + t.Fatalf("NewUOW called %d times, want 1; this test is not exercising the read it claims to", p.newCalls) + } + if p.enabled { + t.Error("a provider whose read panicked was activated") + } +} + +func TestActivateProviderSkipsTheReadForANonConfigurer(t *testing.T) { + p := &nonConfigurerProvider{} + if _, ok := uow.UnitOfWorkProvider(p).(storage.VersionedHistoryConfigurer); ok { + t.Fatal("nonConfigurerProvider satisfies VersionedHistoryConfigurer; this test cannot exercise the guard it claims to") + } + got, err := ActivateProvider(context.Background(), p, nil) + if err != nil || got != uow.UnitOfWorkProvider(p) { + t.Fatalf("ActivateProvider = (%v, %v), want the provider back and no error", got, err) + } + if p.newCalls != 0 { + t.Errorf("a provider that cannot record was asked for a unit of work %d time(s), want 0", p.newCalls) + } +} + +func TestActivateProviderPassesAFailedOpenThrough(t *testing.T) { + openErr := errors.New("open failed") + got, err := ActivateProvider(context.Background(), nil, openErr) + if got != nil || !errors.Is(err, openErr) { + t.Errorf("ActivateProvider(nil, err) = (%v, %v), want (nil, the open error)", got, err) + } + p := newProviderProbe("true", nil) + got, err = ActivateProvider(context.Background(), p, openErr) + if got != uow.UnitOfWorkProvider(p) || !errors.Is(err, openErr) { + t.Errorf("ActivateProvider(provider, err) = (%v, %v), want the provider and the open error unchanged", got, err) + } + if p.newCalls != 0 || p.sets != 0 { + t.Errorf("a failed open still touched the provider: %d unit(s) of work opened, %d activation(s)", p.newCalls, p.sets) + } +} + +// TestProviderEnvironmentIsProcessWideAndOnlyTurnsRecordingOn is D3 for providers. +func TestProviderEnvironmentIsProcessWideAndOnlyTurnsRecordingOn(t *testing.T) { + t.Run("=1 activates without reading the row", func(t *testing.T) { + viperEnv(t, "1") + p := newProviderProbe("", nil) + if _, err := ActivateProvider(context.Background(), p, nil); err != nil { + t.Fatal(err) + } + if !p.enabled { + t.Error("the environment said on but the provider was not activated") + } + if p.newCalls != 0 { + t.Errorf("a unit of work was opened %d time(s) although the environment had already answered, want 0", p.newCalls) + } + }) + t.Run("=0 never switches off a provider whose row is on", func(t *testing.T) { + viperEnv(t, "0") + p := newProviderProbe("true", nil) + if _, err := ActivateProvider(context.Background(), p, nil); err != nil { + t.Fatal(err) + } + if !p.enabled { + t.Error("BD_VERSIONED_HISTORY_ENABLED=0 switched off a provider whose own row says true") + } + }) +} diff --git a/internal/workapi/BUILD.bazel b/internal/workapi/BUILD.bazel index 162b4258d..89ecb128a 100644 --- a/internal/workapi/BUILD.bazel +++ b/internal/workapi/BUILD.bazel @@ -73,3 +73,64 @@ go_test( "//issueops", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/workapi/count.go b/internal/workapi/count.go index 2aef4adc4..a39949cd8 100644 --- a/internal/workapi/count.go +++ b/internal/workapi/count.go @@ -43,8 +43,11 @@ func ValidateCountGroup(group issueops.CountGroup) (string, error) { // pinned by a golden-style test comparing this builder's output against // BuildListFilter's for the same request (count_test.go, GH#4387). // -// cfg supplies the workspace's infra vocabulary and is only read under -// IncludeInfra; a zero ListConfig falls back to the default infra set. +// cfg supplies the workspace's infra vocabulary and its custom status names. +// It is read under IncludeInfra AND whenever ExcludeStatus is non-empty (the +// exclusion is validated against the workspace's statuses), so a caller must +// load it in both cases; a zero ListConfig falls back to the default infra set +// and the built-in statuses only. func BuildCountFilter(in issueops.CountRequest, cfg ListConfig) (types.IssueFilter, error) { filter := types.IssueFilter{ TitleSearch: in.TitleSearch, @@ -103,8 +106,52 @@ func BuildCountFilter(in issueops.CountRequest, cfg ListConfig) (types.IssueFilt filter.IDs = ids } + // ParentID and NoParent are refused together, matching `bd list`'s CLI + // refusal of the same combination (cmd/bd/list_input.go) with the same + // wording — the role raises it as ErrValidation so a caller reaching this + // builder from any front door (HTTP, proxied CLI, a future client) gets + // the same refusal the primary CLI's flag parser gives, rather than the + // role silently answering the empty intersection. + if in.ParentID != "" && in.NoParent { + return types.IssueFilter{}, fmt.Errorf("--parent and --no-parent are mutually exclusive%.0w", issueops.ErrValidation) + } + if in.ParentID != "" { + parentID := in.ParentID + filter.ParentID = &parentID + } + if in.NoParent { + filter.NoParent = true + } + + // ExcludeTypes is appended to, not assigned: applyCountIncludeInfra (below) + // contributes its own "gate" exclusion, and the two sets must compose + // rather than one silently discarding the other, exactly as + // BuildListFilter's ExcludeTypes and applyTypeSuppressions compose. + for _, raw := range in.ExcludeTypes { + for _, t := range strings.Split(raw, ",") { + t = strings.TrimSpace(t) + if t != "" { + filter.ExcludeTypes = append(filter.ExcludeTypes, types.IssueType(utils.NormalizeIssueType(t))) + } + } + } + + // ExcludeStatus takes names as written but — unlike Status and IssueType + // above — IS validated against the workspace vocabulary (built-in statuses + // plus cfg's custom ones, the same set ApplyStatusFilter checks in + // list.go). An exclusion list is built by hand from a status name, so a + // misspelled entry here would silently exclude nothing and OVERCOUNT + // rather than undercount, which is a worse failure mode than the + // match-nothing treatment Status and IssueType accept above — so a typo + // is ErrValidation instead. + excluded, err := ParseExcludeStatus(in.ExcludeStatus, cfg.CustomStatusNames()) + if err != nil { + return types.IssueFilter{}, err + } + filter.ExcludeStatus = append(filter.ExcludeStatus, excluded...) + if in.IncludeInfra { - applyCountIncludeInfra(&filter, in.IssueType, cfg) + applyCountIncludeInfra(&filter, in.IssueType, in.IncludeEphemeral, cfg) } else if !in.IncludeEphemeral { filter.SkipWisps = true } @@ -122,12 +169,15 @@ func BuildCountFilter(in issueops.CountRequest, cfg ListConfig) (types.IssueFilt // - template molecules are excluded (list's default); // - gate beads are excluded unless requested via --type gate; // - counting an infra type (agent/role/message, or the store-configured set) -// routes to the ephemeral wisps tier, like list's infra-type listing. +// routes to the ephemeral wisps tier, like list's infra-type listing — +// unless includeEphemeral is also set, which lifts that narrowing on both +// builders, so the durable rows of that type are counted as they are +// listed. // // A count without IncludeInfra never calls this. It keeps its historical // durable-only semantics unless IncludeEphemeral admits the wisps tier: the // first of the changes above, with none of the rest. -func applyCountIncludeInfra(filter *types.IssueFilter, issueType string, cfg ListConfig) { +func applyCountIncludeInfra(filter *types.IssueFilter, issueType string, includeEphemeral bool, cfg ListConfig) { filter.SkipWisps = false isTemplate := false @@ -137,8 +187,33 @@ func applyCountIncludeInfra(filter *types.IssueFilter, issueType string, cfg Lis filter.ExcludeTypes = append(filter.ExcludeTypes, "gate") } - if issueType != "" && cfg.IsInfra(issueType) { + if issueType != "" && cfg.IsInfra(issueType) && !includeEphemeral { ephemeral := true filter.Ephemeral = &ephemeral } } + +// ParseExcludeStatus reads a caller's status exclusion list — the count's and +// the listing's ExcludeStatus, one rule for both — into the statuses it names. +// Entries may be comma-separated and are trimmed; blanks are skipped. Each +// name IS validated against the workspace vocabulary (built-in statuses plus +// customStatusNames): a misspelled exclusion would silently exclude nothing +// and answer a WIDER set, so a typo is ErrValidation instead. +func ParseExcludeStatus(raw []string, customStatusNames []string) ([]types.Status, error) { + var out []types.Status + for _, entry := range raw { + for _, s := range strings.Split(entry, ",") { + s = strings.TrimSpace(s) + if s == "" { + continue + } + status := types.Status(s) + if !status.IsValidWithCustom(customStatusNames) { + return nil, fmt.Errorf("invalid exclude-status %q (valid: %s)%.0w", + s, ValidStatusList(customStatusNames), issueops.ErrValidation) + } + out = append(out, status) + } + } + return out, nil +} diff --git a/internal/workapi/count_test.go b/internal/workapi/count_test.go index 481e035c2..45e7e603a 100644 --- a/internal/workapi/count_test.go +++ b/internal/workapi/count_test.go @@ -16,57 +16,76 @@ import ( // dimensions are the wisps merge (SkipWisps), template exclusion (IsTemplate), // the default gate exclusion (ExcludeTypes), and infra-type routing to the // ephemeral tier (Ephemeral). +// +// Each type runs twice, the second time with --include-ephemeral on both +// sides. That flag lifts the infra-type routing on the list side (an +// infra-typed row can live in the durable table too, and the flag promises +// the durable answer plus the plane), so a count that kept routing would read +// only the wisp tier while the listing it mirrors reads both: the `message` +// arm is the one that fails if the two builders stop moving in lockstep. func TestBuildCountFilterIncludeInfraMirrorsListFilter(t *testing.T) { cfg := ListConfig{} - for _, issueType := range []string{"", "task", "gate", "message"} { - name := issueType - if name == "" { - name = "none" + for _, includeEphemeral := range []bool{false, true} { + for _, issueType := range []string{"", "task", "gate", "message"} { + name := issueType + if name == "" { + name = "none" + } + if includeEphemeral { + name += "_include_ephemeral" + } + t.Run("type_"+name, func(t *testing.T) { + assertCountMirrorsListIncludeInfra(t, cfg, issueType, includeEphemeral) + }) } - t.Run("type_"+name, func(t *testing.T) { - want, err := BuildListFilter(issueops.ListRequest{ - AllFlag: true, IncludeInfra: true, IssueType: issueType, - }, cfg) - if err != nil { - t.Fatalf("BuildListFilter(%q): %v", issueType, err) - } - got, err := BuildCountFilter(issueops.CountRequest{ - IncludeInfra: true, IssueType: issueType, - }, cfg) - if err != nil { - t.Fatalf("BuildCountFilter(%q): %v", issueType, err) - } + } +} - if got.SkipWisps != want.SkipWisps { - t.Errorf("SkipWisps = %v, list --include-infra --all uses %v", got.SkipWisps, want.SkipWisps) - } - if !reflect.DeepEqual(got.IsTemplate, want.IsTemplate) { - t.Errorf("IsTemplate = %v, list --include-infra --all uses %v", countPtrStr(got.IsTemplate), countPtrStr(want.IsTemplate)) - } - if !reflect.DeepEqual(got.ExcludeTypes, want.ExcludeTypes) { - t.Errorf("ExcludeTypes = %v, list --include-infra --all uses %v", got.ExcludeTypes, want.ExcludeTypes) - } - if !reflect.DeepEqual(got.Ephemeral, want.Ephemeral) { - t.Errorf("Ephemeral = %v, list --include-infra --all uses %v", countPtrStr(got.Ephemeral), countPtrStr(want.Ephemeral)) - } - if !reflect.DeepEqual(got.IssueType, want.IssueType) { - t.Errorf("IssueType = %v, list --include-infra --all uses %v", got.IssueType, want.IssueType) - } - // A count defaults to all statuses and all pinned states, which is - // exactly what list's --all flag selects. - if !reflect.DeepEqual(got.Status, want.Status) { - t.Errorf("Status = %v, list --include-infra --all uses %v", got.Status, want.Status) - } - if !reflect.DeepEqual(got.Statuses, want.Statuses) { - t.Errorf("Statuses = %v, list --include-infra --all uses %v", got.Statuses, want.Statuses) - } - if !reflect.DeepEqual(got.ExcludeStatus, want.ExcludeStatus) { - t.Errorf("ExcludeStatus = %v, list --include-infra --all uses %v", got.ExcludeStatus, want.ExcludeStatus) - } - if !reflect.DeepEqual(got.Pinned, want.Pinned) { - t.Errorf("Pinned = %v, list --include-infra --all uses %v", countPtrStr(got.Pinned), countPtrStr(want.Pinned)) - } - }) +// assertCountMirrorsListIncludeInfra compares one `bd count --include-infra` +// filter against the `bd list --include-infra --all` filter it mirrors. +func assertCountMirrorsListIncludeInfra(t *testing.T, cfg ListConfig, issueType string, includeEphemeral bool) { + t.Helper() + want, err := BuildListFilter(issueops.ListRequest{ + AllFlag: true, IncludeInfra: true, IssueType: issueType, IncludeEphemeral: includeEphemeral, + }, cfg) + if err != nil { + t.Fatalf("BuildListFilter(%q): %v", issueType, err) + } + got, err := BuildCountFilter(issueops.CountRequest{ + IncludeInfra: true, IssueType: issueType, IncludeEphemeral: includeEphemeral, + }, cfg) + if err != nil { + t.Fatalf("BuildCountFilter(%q): %v", issueType, err) + } + + if got.SkipWisps != want.SkipWisps { + t.Errorf("SkipWisps = %v, list --include-infra --all uses %v", got.SkipWisps, want.SkipWisps) + } + if !reflect.DeepEqual(got.IsTemplate, want.IsTemplate) { + t.Errorf("IsTemplate = %v, list --include-infra --all uses %v", countPtrStr(got.IsTemplate), countPtrStr(want.IsTemplate)) + } + if !reflect.DeepEqual(got.ExcludeTypes, want.ExcludeTypes) { + t.Errorf("ExcludeTypes = %v, list --include-infra --all uses %v", got.ExcludeTypes, want.ExcludeTypes) + } + if !reflect.DeepEqual(got.Ephemeral, want.Ephemeral) { + t.Errorf("Ephemeral = %v, list --include-infra --all uses %v", countPtrStr(got.Ephemeral), countPtrStr(want.Ephemeral)) + } + if !reflect.DeepEqual(got.IssueType, want.IssueType) { + t.Errorf("IssueType = %v, list --include-infra --all uses %v", got.IssueType, want.IssueType) + } + // A count defaults to all statuses and all pinned states, which is + // exactly what list's --all flag selects. + if !reflect.DeepEqual(got.Status, want.Status) { + t.Errorf("Status = %v, list --include-infra --all uses %v", got.Status, want.Status) + } + if !reflect.DeepEqual(got.Statuses, want.Statuses) { + t.Errorf("Statuses = %v, list --include-infra --all uses %v", got.Statuses, want.Statuses) + } + if !reflect.DeepEqual(got.ExcludeStatus, want.ExcludeStatus) { + t.Errorf("ExcludeStatus = %v, list --include-infra --all uses %v", got.ExcludeStatus, want.ExcludeStatus) + } + if !reflect.DeepEqual(got.Pinned, want.Pinned) { + t.Errorf("Pinned = %v, list --include-infra --all uses %v", countPtrStr(got.Pinned), countPtrStr(want.Pinned)) } } @@ -158,6 +177,204 @@ func TestBuildCountFilterNormalizesLabelsAndIDs(t *testing.T) { } } +// TestBuildCountFilterMapsParentAndNoParent pins ParentID/NoParent's mapping +// into types.IssueFilter, mirroring BuildListFilter's ParentID/NoParent +// mapping (internal/workapi/list.go) field for field. +func TestBuildCountFilterMapsParentAndNoParent(t *testing.T) { + got, err := BuildCountFilter(issueops.CountRequest{ParentID: "bd-1"}, ListConfig{}) + if err != nil { + t.Fatalf("BuildCountFilter: %v", err) + } + if got.ParentID == nil || *got.ParentID != "bd-1" { + t.Errorf("ParentID = %v, want \"bd-1\"", countPtrStr(got.ParentID)) + } + if got.NoParent { + t.Errorf("NoParent = true, want false: request did not set it") + } + + got, err = BuildCountFilter(issueops.CountRequest{NoParent: true}, ListConfig{}) + if err != nil { + t.Fatalf("BuildCountFilter: %v", err) + } + if got.ParentID != nil { + t.Errorf("ParentID = %v, want nil: request did not set it", countPtrStr(got.ParentID)) + } + if !got.NoParent { + t.Error("NoParent = false, want true") + } +} + +// TestBuildCountFilterExcludeTypesSplitsAndNormalizes pins ExcludeTypes' +// mapping: comma-separated entries split, trim and normalize exactly as +// BuildListFilter's ExcludeTypes does, and the result APPENDS to (rather than +// replaces) whatever applyCountIncludeInfra later contributes. +func TestBuildCountFilterExcludeTypesSplitsAndNormalizes(t *testing.T) { + got, err := BuildCountFilter(issueops.CountRequest{ + // "feat" is an alias (-> "feature", internal/utils/strings.go); + // "bug" is not, so it passes through unchanged. + ExcludeTypes: []string{" bug , feat", "", "chore"}, + }, ListConfig{}) + if err != nil { + t.Fatalf("BuildCountFilter: %v", err) + } + want := []types.IssueType{"bug", "feature", "chore"} + if !reflect.DeepEqual(got.ExcludeTypes, want) { + t.Errorf("ExcludeTypes = %v, want %v", got.ExcludeTypes, want) + } + + // Composes with IncludeInfra's own "gate" exclusion rather than + // discarding it. + got, err = BuildCountFilter(issueops.CountRequest{ + ExcludeTypes: []string{"chore"}, + IncludeInfra: true, + }, ListConfig{}) + if err != nil { + t.Fatalf("BuildCountFilter: %v", err) + } + want = []types.IssueType{"chore", "gate"} + if !reflect.DeepEqual(got.ExcludeTypes, want) { + t.Errorf("ExcludeTypes = %v, want %v (explicit exclusions composed with IncludeInfra's)", got.ExcludeTypes, want) + } +} + +// TestBuildCountFilterParentFieldsMatchListFilter extends the GH#4387 +// count/list cardinality-parity pin to the three new Count fields that DO +// have a List counterpart: ParentID, NoParent and ExcludeTypes must produce +// the identical types.IssueFilter contribution BuildListFilter does for the +// same request, since a filter contract test (backend/conformance) can only +// show the two AGREE on one backend's rows — this shows WHY, at the one place +// both builders share. +func TestBuildCountFilterParentFieldsMatchListFilter(t *testing.T) { + cfg := ListConfig{} + + countGot, err := BuildCountFilter(issueops.CountRequest{ParentID: "bd-1"}, cfg) + if err != nil { + t.Fatalf("BuildCountFilter: %v", err) + } + listGot, err := BuildListFilter(issueops.ListRequest{ParentID: "bd-1", AllFlag: true}, cfg) + if err != nil { + t.Fatalf("BuildListFilter: %v", err) + } + if !reflect.DeepEqual(countGot.ParentID, listGot.ParentID) { + t.Errorf("Count ParentID = %v, List ParentID = %v, want equal", countPtrStr(countGot.ParentID), countPtrStr(listGot.ParentID)) + } + + countGot, err = BuildCountFilter(issueops.CountRequest{NoParent: true}, cfg) + if err != nil { + t.Fatalf("BuildCountFilter: %v", err) + } + listGot, err = BuildListFilter(issueops.ListRequest{NoParent: true, AllFlag: true}, cfg) + if err != nil { + t.Fatalf("BuildListFilter: %v", err) + } + if countGot.NoParent != listGot.NoParent { + t.Errorf("Count NoParent = %v, List NoParent = %v, want equal", countGot.NoParent, listGot.NoParent) + } + + countGot, err = BuildCountFilter(issueops.CountRequest{ExcludeTypes: []string{"wisp,feat"}}, cfg) + if err != nil { + t.Fatalf("BuildCountFilter: %v", err) + } + // IncludeAllTypes on the list side skips applyTypeSuppressions' OWN + // exclusions (template/gate/infra defaults), isolating the one thing this + // case compares: the explicit --exclude-type mapping. + listGot, err = BuildListFilter(issueops.ListRequest{ExcludeTypes: []string{"wisp,feat"}, AllFlag: true, IncludeAllTypes: true}, cfg) + if err != nil { + t.Fatalf("BuildListFilter: %v", err) + } + if !reflect.DeepEqual(countGot.ExcludeTypes, listGot.ExcludeTypes) { + t.Errorf("Count ExcludeTypes = %v, List ExcludeTypes = %v, want equal", countGot.ExcludeTypes, listGot.ExcludeTypes) + } +} + +// TestBuildCountFilterExcludeStatusTakesNamesAsWritten pins ExcludeStatus: a +// Count-only field with no List counterpart (ListRequest computes its default +// exclusions internally and exposes no caller-facing knob for them). Entries +// split and trim like ExcludeTypes. UNLIKE Status and ExcludeTypes, each name +// IS validated against the workspace vocabulary (review S8 follow-up #3): a +// built-in name passes as written, and an unrecognized one is ErrValidation +// rather than silently excluding nothing. +func TestBuildCountFilterExcludeStatusTakesNamesAsWritten(t *testing.T) { + got, err := BuildCountFilter(issueops.CountRequest{ + ExcludeStatus: []string{" closed , pinned", ""}, + }, ListConfig{}) + if err != nil { + t.Fatalf("BuildCountFilter: %v", err) + } + want := []types.Status{"closed", "pinned"} + if !reflect.DeepEqual(got.ExcludeStatus, want) { + t.Errorf("ExcludeStatus = %v, want %v", got.ExcludeStatus, want) + } +} + +// TestBuildCountFilterExcludeStatusRejectsAnUnknownName pins the ErrValidation +// refusal (review S8 follow-up #3): a typo'd status name in --exclude-status +// must fail loudly rather than silently excluding nothing and overcounting. +func TestBuildCountFilterExcludeStatusRejectsAnUnknownName(t *testing.T) { + _, err := BuildCountFilter(issueops.CountRequest{ + ExcludeStatus: []string{"no-such-status"}, + }, ListConfig{}) + if err == nil { + t.Fatal("BuildCountFilter accepted an unknown exclude-status name, want ErrValidation") + } + if !errors.Is(err, issueops.ErrValidation) { + t.Errorf("err = %v, want errors.Is(err, issueops.ErrValidation)", err) + } +} + +// TestBuildCountFilterExcludeStatusAllowsAWorkspaceCustomStatus pins the other +// half of #3: a workspace-defined custom status is NOT a typo and must be +// accepted, following ApplyStatusFilter's own IsValidWithCustom precedent in +// list.go. +func TestBuildCountFilterExcludeStatusAllowsAWorkspaceCustomStatus(t *testing.T) { + cfg := ListConfig{CustomStatuses: []types.CustomStatus{{Name: "triaged"}}} + got, err := BuildCountFilter(issueops.CountRequest{ + ExcludeStatus: []string{"triaged"}, + }, cfg) + if err != nil { + t.Fatalf("BuildCountFilter rejected the workspace's own custom status: %v", err) + } + want := []types.Status{"triaged"} + if !reflect.DeepEqual(got.ExcludeStatus, want) { + t.Errorf("ExcludeStatus = %v, want %v", got.ExcludeStatus, want) + } +} + +// TestBuildCountFilterRefusesParentAndNoParentTogether pins review S8 +// follow-up #1: the role refuses the combination as ErrValidation, with the +// same wording `bd list`'s CLI already uses for the same combination +// (cmd/bd/list_input.go), so a caller reaching this role from any front door +// gets the identical refusal. +func TestBuildCountFilterRefusesParentAndNoParentTogether(t *testing.T) { + _, err := BuildCountFilter(issueops.CountRequest{ParentID: "bd-1", NoParent: true}, ListConfig{}) + if err == nil { + t.Fatal("BuildCountFilter accepted --parent with --no-parent, want ErrValidation") + } + if !errors.Is(err, issueops.ErrValidation) { + t.Errorf("err = %v, want errors.Is(err, issueops.ErrValidation)", err) + } + const want = "--parent and --no-parent are mutually exclusive" + if err.Error() != want { + t.Errorf("err = %q, want %q", err.Error(), want) + } +} + +// TestBuildCountFilterStatusAllIsNotValidation pins DESIGN's requirement that +// Status "all" have well-defined semantics: it is the no-filter spelling +// (same as empty), NOT ErrValidation, because BuildListFilter's own "all" +// selector means the same thing and a count must stay able to answer the +// cardinality of `bd list --status all --all` for the shared predicate +// (GH#4387 count/list parity). +func TestBuildCountFilterStatusAllIsNotValidation(t *testing.T) { + got, err := BuildCountFilter(issueops.CountRequest{Status: "all"}, ListConfig{}) + if err != nil { + t.Fatalf(`BuildCountFilter(status="all") returned an error, want nil: %v`, err) + } + if got.Status != nil { + t.Errorf(`status "all" produced Status = %v, want no status predicate`, countPtrStr(got.Status)) + } +} + func TestBuildCountFilterCarriesMetadataFields(t *testing.T) { fields := map[string]string{"team": "platform", "env": "prod"} got, err := BuildCountFilter(issueops.CountRequest{MetadataFields: fields}, ListConfig{}) diff --git a/internal/workapi/detail.go b/internal/workapi/detail.go index acd5cc7e9..172f13cca 100644 --- a/internal/workapi/detail.go +++ b/internal/workapi/detail.go @@ -145,6 +145,16 @@ func BuildIssueDetails(ctx context.Context, src DetailSource, issue *types.Issue deps, depsErr := src.Dependencies(ctx, id, isWisp) details.Dependencies = deps + // The gates blocking this issue are the gate-typed subset of the + // dependencies JUST read (types.GatesHolding, the one predicate the + // readiness query's is_blocked column encodes — subject clause included, + // so a closed or pinned issue publishes no gated_by), which costs no extra + // query. The order is load-bearing twice over: computed AFTER the + // Dependencies read above (an earlier slot sees the nil slice and + // publishes no gate at all) and BEFORE the BriefDeps trim below, which + // rewrites the slice. + details.GatedBy = types.GateRefs(types.GatesHolding(issue, details.Dependencies)) + // The count counts edge ROWS; the slice carries the issues on the far // end, and drops any whose id has no row in this database. The two // therefore disagree by exactly the cross-repo and `external:` edges, diff --git a/internal/workapi/detail_test.go b/internal/workapi/detail_test.go index ecbd0fb38..432d061ca 100644 --- a/internal/workapi/detail_test.go +++ b/internal/workapi/detail_test.go @@ -819,3 +819,58 @@ func deref(t *testing.T, v *int64) int64 { } return *v } + +// TestBuildIssueDetailsGatedByReadsTheDependencies pins the ORDER of the +// build: gated_by is derived from the Dependencies slice, so it must be +// computed after that slice is read and before BriefDeps rewrites it. The +// be-lpi merge moved the read below the counts and silently left gated_by +// computed on a nil slice (wy-j2upyy, PR #6606 CI). +func TestBuildIssueDetailsGatedByReadsTheDependencies(t *testing.T) { + ctx := context.Background() + heavy := strings.Repeat("x", 1024) + + newFixture := func() *detailFixture { + fx := newDetailFixture() + fx.deps["bd-1"] = []*types.IssueWithDependencyMetadata{ + { + Issue: types.Issue{ + ID: "bd-gate", Title: "Gate: human", Status: types.StatusOpen, + IssueType: types.TypeGate, Priority: 2, Description: heavy, + }, + DependencyType: types.DepBlocks, + }, + { + Issue: types.Issue{ID: "bd-blocker", Title: "Blocker", Status: types.StatusOpen, IssueType: types.TypeTask}, + DependencyType: types.DepBlocks, + }, + } + return fx + } + + wantGate := func(t *testing.T, details *types.IssueDetails) { + t.Helper() + if len(details.GatedBy) != 1 { + t.Fatalf("gated_by = %#v, want exactly the one open gate", details.GatedBy) + } + if got := details.GatedBy[0].ID; got != "bd-gate" { + t.Fatalf("gated_by[0].ID = %q, want bd-gate", got) + } + } + + for _, opts := range []DetailOptions{{}, {BriefDeps: true}} { + t.Run(fmt.Sprintf("BriefDeps=%v", opts.BriefDeps), func(t *testing.T) { + fx := newFixture() + store, useCase := fixtureSources(fx) + for name, src := range map[string]DetailSource{"store": store, "usecase": useCase} { + details, err := BuildIssueDetails(ctx, src, fx.issues["bd-1"], false, opts) + if err != nil { + t.Fatalf("%s: BuildIssueDetails: %v", name, err) + } + wantGate(t, details) + if len(details.Dependencies) != 2 { + t.Fatalf("%s: dependencies = %d rows, want 2", name, len(details.Dependencies)) + } + } + }) + } +} diff --git a/internal/workapi/doc.go b/internal/workapi/doc.go index 6df2ee589..bda4b6c15 100644 --- a/internal/workapi/doc.go +++ b/internal/workapi/doc.go @@ -14,5 +14,5 @@ // // The boundary is enforced mechanically, not by review: see the // workapi-frontend-boundary depguard rule in .golangci.yml and the -// banned-accessor check in scripts/ci/pr-policy.sh. +// banned-accessor check in scripts/check-workapi-frontend-boundary.sh. package workapi diff --git a/internal/workapi/list.go b/internal/workapi/list.go index 1798824c1..96a6750a6 100644 --- a/internal/workapi/list.go +++ b/internal/workapi/list.go @@ -194,6 +194,20 @@ func BuildListFilter(in issueops.ListRequest, cfg ListConfig) (types.IssueFilter if err := issueops.ValidateReadyFlagScope(in); err != nil { return types.IssueFilter{}, err } + // The pinned pair is a contradiction, refused here rather than in any one + // frontend so every route agrees: the CLI refuses it at flag parse, and a + // served listing carries both members (issues.list.filters), where the + // branch below used to let PinnedFlag win silently. + if in.PinnedFlag && in.NoPinnedFlag { + return types.IssueFilter{}, fmt.Errorf("--pinned and --no-pinned are mutually exclusive%.0w", issueops.ErrValidation) + } + // The parent pair likewise, in the sentence `bd list` and BuildCountFilter + // refuse it with: a served listing carries no_parent beside parent + // (issues.list.filters), and ANDing the two answered only the edge-less + // rows under the parent's dotted id instead of refusing. + if in.ParentID != "" && in.NoParent { + return types.IssueFilter{}, fmt.Errorf("--parent and --no-parent are mutually exclusive%.0w", issueops.ErrValidation) + } filter := types.IssueFilter{ Limit: SQLLimit(in), @@ -248,6 +262,16 @@ func BuildListFilter(in issueops.ListRequest, cfg ListConfig) (types.IssueFilter } filter.ExcludeStatus = excludeStatuses } + // The caller's own exclusions (ListRequest.ExcludeStatus) are APPENDED to + // the defaults above, never in place of them: excluding `blocked` must not + // re-admit closed rows. They apply on every arm, AllFlag and an explicit + // Status included, which is what lets a caller drop closed history + // (AllFlag with ExcludeStatus "closed") without enumerating every status. + excluded, err := ParseExcludeStatus(in.ExcludeStatus, cfg.CustomStatusNames()) + if err != nil { + return filter, err + } + filter.ExcludeStatus = append(filter.ExcludeStatus, excluded...) if in.Priority != nil { p := *in.Priority @@ -367,11 +391,6 @@ func BuildListFilter(in issueops.ListRequest, cfg ListConfig) (types.IssueFilter } } - if cfg.IsInfra(in.IssueType) { - ephemeral := true - filter.Ephemeral = &ephemeral - } - if in.ParentID != "" { pid := in.ParentID filter.ParentID = &pid @@ -415,7 +434,8 @@ func BuildListFilter(in issueops.ListRequest, cfg ListConfig) (types.IssueFilter // account of WHAT IT IS, so that a "show everything" frontend has exactly one // thing to skip. Two kinds live here: the type-level exclusions that make the // default listing show durable work only (templates, gates, infra types), and -// the plane decision — whether the wisps TABLE is read at all. +// the plane decision — whether the wisps TABLE is read at all, and for a named +// infra type whether only its ephemeral rows are. // // IncludeAllTypes lifts them ALL by skipping this function entirely, which is // what makes it future-proof: a suppression added here is automatically lifted @@ -442,14 +462,28 @@ func applyTypeSuppressions(in issueops.ListRequest, cfg ListConfig, filter *type // The plane bit. Three requests admit the wisp table: an explicit // IncludeEphemeral, IncludeInfra (which admits the plane AND drops the - // infra-type exclusions above), and naming an infra type (which routed to - // the plane alone in BuildListFilter). Everything else is the durable - // listing. IncludeAllTypes is a fourth, via the early return above — it is - // the union of these flags, so it must decide the plane too, not only the - // type exclusions. + // infra-type exclusions above), and naming an infra type (which narrows to + // its ephemeral rows, below). Everything else is the durable listing. + // IncludeAllTypes is a fourth, via the early return above — it is the union + // of these flags, so it must decide the plane too, not only the type + // exclusions. if !in.IncludeEphemeral && !in.IncludeInfra && (in.IssueType == "" || !cfg.IsInfra(in.IssueType)) { filter.SkipWisps = true } + + // Naming an infra type narrows the read to its EPHEMERAL rows alone, which + // is where creating one puts it. IncludeEphemeral lifts that narrowing, + // because it promises the durable answer PLUS the plane, never the plane + // instead: an infra-typed row can still be durable — a promoted wisp, an + // issue retyped after it was created, or one written before its type + // joined types.infra — and while the narrowing held, `bd search --type + // message` (whose scope sets the flag) dropped exactly those rows with exit + // 0. IncludeInfra alone keeps the narrowing, and BuildCountFilter's + // IncludeInfra arm mirrors both halves (GH#4387). + if cfg.IsInfra(in.IssueType) && !in.IncludeEphemeral { + ephemeral := true + filter.Ephemeral = &ephemeral + } } // splitStatusSelector splits a --status selector into its trimmed diff --git a/internal/workapi/list_ephemeral_test.go b/internal/workapi/list_ephemeral_test.go index cb4fb0505..d1b11d49f 100644 --- a/internal/workapi/list_ephemeral_test.go +++ b/internal/workapi/list_ephemeral_test.go @@ -60,6 +60,50 @@ func TestIncludeEphemeralIsThePlaneBitAndNothingElse(t *testing.T) { } } +// TestIncludeEphemeralLiftsTheInfraTypeNarrowing pins the other half of the +// "admits in addition, never narrows" promise, for the one request that DOES +// narrow: naming an infra type reads only that type's ephemeral rows +// (Ephemeral=true), which is where creating one puts it. An infra-typed row can +// still be durable — a promoted wisp, a retyped issue — so IncludeEphemeral has +// to lift the narrowing, or `bd search --type message` (whose scope sets the +// flag) drops those rows with exit 0, as it did while the narrowing held. +// IncludeInfra alone keeps it; IncludeAllTypes, the union of the flags, lifts +// it with them. +func TestIncludeEphemeralLiftsTheInfraTypeNarrowing(t *testing.T) { + searchScope := issueops.SearchListRequest("needle") + searchScope.IssueType = "message" + + for _, tc := range []struct { + name string + req issueops.ListRequest + narrow bool + }{ + {"an infra type alone narrows to its ephemeral rows", issueops.ListRequest{IssueType: "message"}, true}, + {"IncludeInfra alone keeps the narrowing", issueops.ListRequest{IssueType: "message", IncludeInfra: true}, true}, + {"IncludeEphemeral lifts it", issueops.ListRequest{IssueType: "message", IncludeEphemeral: true}, false}, + {"IncludeEphemeral lifts it beside IncludeInfra", issueops.ListRequest{IssueType: "message", IncludeEphemeral: true, IncludeInfra: true}, false}, + {"IncludeAllTypes lifts it", issueops.ListRequest{IssueType: "message", IncludeAllTypes: true}, false}, + {"search's scope lifts it", searchScope, false}, + {"a type that is not infra is never narrowed", issueops.ListRequest{IssueType: "task"}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + filter, err := BuildListFilter(tc.req, ListConfig{}) + if err != nil { + t.Fatalf("BuildListFilter: %v", err) + } + switch { + case tc.narrow && (filter.Ephemeral == nil || !*filter.Ephemeral): + t.Errorf("Ephemeral = %v, want true: the infra type's own wisps are the only rows this request asked for", filter.Ephemeral) + case !tc.narrow && filter.Ephemeral != nil: + t.Errorf("Ephemeral = %v, want nil: the durable rows of the type are part of this answer", *filter.Ephemeral) + } + if tc.req.IssueType == "message" && filter.SkipWisps { + t.Error("SkipWisps is set, but naming an infra type always reads the wisp table") + } + }) + } +} + // TestReadyProjectionCarriesTheEphemeralPlane pins the ReadyFlag arm's half of // the same promise. The projection onto WorkFilter is where a list field is // silently dropped, and a dropped IncludeEphemeral would answer `--ready diff --git a/internal/workapi/list_pinned_test.go b/internal/workapi/list_pinned_test.go index 38e944092..02dd6ad53 100644 --- a/internal/workapi/list_pinned_test.go +++ b/internal/workapi/list_pinned_test.go @@ -1,6 +1,9 @@ package workapi import ( + "errors" + "slices" + "strings" "testing" "github.com/steveyegge/beads/internal/types" @@ -161,3 +164,72 @@ func TestStatusAllCannotBeCombined(t *testing.T) { t.Errorf("error = %q, want %q", err, want) } } + +// TestPinnedPairIsRefusedByTheBuilder pins the library half of the pinned +// pair's refusal. The CLI refuses `--pinned --no-pinned` at flag parse, but the +// builder is the one point every route passes through — a served listing +// carries both members since issues.list.filters — and it used to let +// PinnedFlag win silently. Each member alone still builds. +func TestPinnedPairIsRefusedByTheBuilder(t *testing.T) { + var cfg ListConfig + for _, status := range []string{"", "all", "open"} { + _, err := BuildListFilter(issueops.ListRequest{Status: status, PinnedFlag: true, NoPinnedFlag: true}, cfg) + if !errors.Is(err, issueops.ErrValidation) { + t.Errorf("--status=%q --pinned --no-pinned: err = %v, want ErrValidation", status, err) + } + } + for _, in := range []issueops.ListRequest{{PinnedFlag: true}, {NoPinnedFlag: true}} { + if _, err := BuildListFilter(in, cfg); err != nil { + t.Errorf("BuildListFilter(%+v) = %v, want no error for one member alone", in, err) + } + } +} + +// TestParentPairIsRefusedByTheBuilder is the parent pair's twin of the pinned +// test above: the CLI refuses `--parent X --no-parent` at flag parse, a served +// listing carries both members since issues.list.filters, and the builder used +// to AND them. The sentence is the one the http handler maps to a 400 on +// no_parent, and the one BuildCountFilter refuses the same pair with. +func TestParentPairIsRefusedByTheBuilder(t *testing.T) { + var cfg ListConfig + _, err := BuildListFilter(issueops.ListRequest{ParentID: "bd-1", NoParent: true}, cfg) + if !errors.Is(err, issueops.ErrValidation) { + t.Fatalf("--parent bd-1 --no-parent: err = %v, want ErrValidation", err) + } + if want := "--parent and --no-parent are mutually exclusive"; err.Error() != want { + t.Errorf("--parent bd-1 --no-parent: err = %q, want %q", err, want) + } + for _, in := range []issueops.ListRequest{{ParentID: "bd-1"}, {NoParent: true}} { + if _, err := BuildListFilter(in, cfg); err != nil { + t.Errorf("BuildListFilter(%+v) = %v, want no error for one member alone", in, err) + } + } +} + +// TestListExcludeStatusAppendsAndValidates pins ListRequest.ExcludeStatus in +// the builder: it is appended to the default exclusions (never in their place), +// stands alone under AllFlag, splits commas, and an unknown name is +// ErrValidation with the count's own sentence, which the http handler maps to +// a 400 on exclude_status. +func TestListExcludeStatusAppendsAndValidates(t *testing.T) { + var cfg ListConfig + f, err := BuildListFilter(issueops.ListRequest{ExcludeStatus: []string{"blocked, in_progress"}}, cfg) + if err != nil { + t.Fatalf("BuildListFilter: %v", err) + } + want := []types.Status{types.StatusClosed, types.StatusPinned, types.StatusBlocked, types.StatusInProgress} + if !slices.Equal(f.ExcludeStatus, want) { + t.Errorf("default listing ExcludeStatus = %v, want %v", f.ExcludeStatus, want) + } + f, err = BuildListFilter(issueops.ListRequest{AllFlag: true, ExcludeStatus: []string{"closed"}}, cfg) + if err != nil { + t.Fatalf("BuildListFilter: %v", err) + } + if want := []types.Status{types.StatusClosed}; !slices.Equal(f.ExcludeStatus, want) { + t.Errorf("AllFlag ExcludeStatus = %v, want %v", f.ExcludeStatus, want) + } + _, err = BuildListFilter(issueops.ListRequest{ExcludeStatus: []string{"clsoed"}}, cfg) + if !errors.Is(err, issueops.ErrValidation) || !strings.HasPrefix(err.Error(), "invalid exclude-status ") { + t.Errorf("unknown exclude status: err = %v, want ErrValidation starting \"invalid exclude-status \"", err) + } +} diff --git a/internal/workapi/storecounter/BUILD.bazel b/internal/workapi/storecounter/BUILD.bazel index e200739bd..05bb55bb2 100644 --- a/internal/workapi/storecounter/BUILD.bazel +++ b/internal/workapi/storecounter/BUILD.bazel @@ -12,3 +12,64 @@ go_library( "//issueops", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/workapi/storecounter/counter.go b/internal/workapi/storecounter/counter.go index f873d5900..0c9fa1b29 100644 --- a/internal/workapi/storecounter/counter.go +++ b/internal/workapi/storecounter/counter.go @@ -75,15 +75,18 @@ func (c *storeCounter) CountByGroup(ctx context.Context, req issueops.CountByGro // filter builds the storage filter, loading the workspace configuration only // when the request can read it. // -// TWO THINGS ARE DELIBERATE. The load is SKIPPED unless IncludeInfra is set, -// because that flag is the only thing in a count request the configuration -// reaches. And when it does run it runs PER CALL rather than once at -// construction: the infra vocabulary is workspace state a caller can change -// between two counts, and a counter that cached it would answer for the older -// workspace. +// TWO THINGS ARE DELIBERATE. The load is SKIPPED unless IncludeInfra is set OR +// ExcludeStatus is non-empty — those are the two things in a count request the +// configuration reaches: IncludeInfra needs the infra vocabulary, and +// ExcludeStatus needs the workspace's custom status names so +// BuildCountFilter's validation does not refuse a status the workspace itself +// defines (PR #7199 review). And when it does run it runs PER CALL rather +// than once at construction: the infra vocabulary and custom statuses are +// workspace state a caller can change between two counts, and a counter that +// cached it would answer for the older workspace. func (c *storeCounter) filter(ctx context.Context, req issueops.CountRequest) (types.IssueFilter, error) { var cfg workapi.ListConfig - if req.IncludeInfra { + if req.IncludeInfra || len(req.ExcludeStatus) > 0 { loaded, err := workapi.LoadStoreListConfig(ctx, c.store) if err != nil { return types.IssueFilter{}, err diff --git a/internal/workapi/storequerier/BUILD.bazel b/internal/workapi/storequerier/BUILD.bazel index 72cb226c6..67b7a29b9 100644 --- a/internal/workapi/storequerier/BUILD.bazel +++ b/internal/workapi/storequerier/BUILD.bazel @@ -11,3 +11,64 @@ go_library( "//issueops", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/workapi/storereader/BUILD.bazel b/internal/workapi/storereader/BUILD.bazel index 16a5105dc..5b0c187e6 100644 --- a/internal/workapi/storereader/BUILD.bazel +++ b/internal/workapi/storereader/BUILD.bazel @@ -23,3 +23,64 @@ go_test( "//issueops", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/workapi/storereader/reader.go b/internal/workapi/storereader/reader.go index 8c0c2bae1..006b0deb0 100644 --- a/internal/workapi/storereader/reader.go +++ b/internal/workapi/storereader/reader.go @@ -114,7 +114,7 @@ func (r *storeReader) List(ctx context.Context, req issueops.ListRequest) (issue if req.ReadyFlag { items, err = r.store.GetReadyWorkWithCounts(ctx, workapi.ReadyFilterFromIssueFilter(filter)) } else { - items, err = r.store.SearchIssuesWithCounts(ctx, "", filter) + items, err = r.store.SearchIssuesWithCounts(ctx, req.Query, filter) } if err != nil { return issueops.IssuePage{}, err diff --git a/internal/workapi/storereadycounter/BUILD.bazel b/internal/workapi/storereadycounter/BUILD.bazel index 8ab96877b..29c4998ef 100644 --- a/internal/workapi/storereadycounter/BUILD.bazel +++ b/internal/workapi/storereadycounter/BUILD.bazel @@ -11,3 +11,64 @@ go_library( "//issueops", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/workapi/storestats/BUILD.bazel b/internal/workapi/storestats/BUILD.bazel index f29b27789..d0b08a598 100644 --- a/internal/workapi/storestats/BUILD.bazel +++ b/internal/workapi/storestats/BUILD.bazel @@ -12,3 +12,64 @@ go_library( "//issueops", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/workapi/storeversionreconciler/BUILD.bazel b/internal/workapi/storeversionreconciler/BUILD.bazel index 7d5b03eec..9eac2b29b 100644 --- a/internal/workapi/storeversionreconciler/BUILD.bazel +++ b/internal/workapi/storeversionreconciler/BUILD.bazel @@ -11,3 +11,64 @@ go_library( "//issueops", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/workapi/storeworkspaceconfig/BUILD.bazel b/internal/workapi/storeworkspaceconfig/BUILD.bazel index 33fe08f81..166762ce9 100644 --- a/internal/workapi/storeworkspaceconfig/BUILD.bazel +++ b/internal/workapi/storeworkspaceconfig/BUILD.bazel @@ -11,3 +11,64 @@ go_library( "//issueops", ], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/workapi/sweep.go b/internal/workapi/sweep.go index 24af4ec50..b8a028c57 100644 --- a/internal/workapi/sweep.go +++ b/internal/workapi/sweep.go @@ -332,18 +332,37 @@ func SweepLiveDependentSources(incoming map[string][]*types.Dependency) []string return ids } -// SweepLiveDependentTargets returns the candidates a live row depends on: the -// targets of protecting edges whose source is in live. +// SweepLiveDependentTargets returns the candidates a live row depends on, +// directly or through other candidates. A protected closed candidate must act +// as live for the next edge up the chain; otherwise an open grandchild keeps +// its closed parent while the same sweep deletes the closed grandparent. func SweepLiveDependentTargets(incoming map[string][]*types.Dependency, live map[string]bool) map[string]bool { - protected := make(map[string]bool) + targetsBySource := make(map[string][]string) for target, deps := range incoming { for _, dep := range deps { - if dep != nil && isSweepProtectingEdge(dep.Type) && live[dep.IssueID] { - protected[target] = true - break + if dep != nil && isSweepProtectingEdge(dep.Type) { + targetsBySource[dep.IssueID] = append(targetsBySource[dep.IssueID], target) } } } + + protected := make(map[string]bool) + queue := make([]string, 0, len(live)) + for id, isLive := range live { + if isLive { + queue = append(queue, id) + } + } + for next := 0; next < len(queue); next++ { + source := queue[next] + for _, target := range targetsBySource[source] { + if protected[target] { + continue + } + protected[target] = true + queue = append(queue, target) + } + } return protected } diff --git a/internal/workapi/sweep_test.go b/internal/workapi/sweep_test.go index af26fd9fb..046da4595 100644 --- a/internal/workapi/sweep_test.go +++ b/internal/workapi/sweep_test.go @@ -430,6 +430,30 @@ func TestSweepLiveDependentsCountOnlyProtectingEdgesFromLiveSources(t *testing.T } } +func TestSweepLiveDependentTargetsPropagatesThroughProtectedCandidates(t *testing.T) { + dep := func(source, target string) *types.Dependency { + return &types.Dependency{IssueID: source, DependsOnID: target, Type: types.DepParentChild} + } + incoming := map[string][]*types.Dependency{ + "root": {dep("middle", "root")}, + "middle": {dep("leaf", "middle")}, + "cycle-a": {dep("cycle-b", "cycle-a")}, + "cycle-b": {dep("cycle-a", "cycle-b")}, + } + + protected := SweepLiveDependentTargets(incoming, map[string]bool{"leaf": true}) + for _, id := range []string{"middle", "root"} { + if !protected[id] { + t.Errorf("%s not protected; it is transitively depended on by a live source", id) + } + } + for _, id := range []string{"cycle-a", "cycle-b"} { + if protected[id] { + t.Errorf("%s protected without a live path into its closed cycle", id) + } + } +} + func TestValidateSweepRequestRefusesANegativeLimit(t *testing.T) { err := ValidateSweepRequest(issueops.SweepRequest{Tier: issueops.SweepEphemeral, Limit: -1}) if !errors.Is(err, issueops.ErrValidation) { diff --git a/internal/workspacegate/BUILD.bazel b/internal/workspacegate/BUILD.bazel index 530171afb..4928df002 100644 --- a/internal/workspacegate/BUILD.bazel +++ b/internal/workspacegate/BUILD.bazel @@ -10,7 +10,71 @@ go_library( go_test( name = "workspacegate_test", - srcs = ["gate_test.go"], + srcs = [ + "gate_test.go", + "readonly_wait_test.go", + ], embed = [":workspacegate"], deps = ["//internal/testutil/bazeltest"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/internal/workspacegate/gate.go b/internal/workspacegate/gate.go index 8fc62d18f..d0d27516c 100644 --- a/internal/workspacegate/gate.go +++ b/internal/workspacegate/gate.go @@ -45,6 +45,7 @@ import ( "path/filepath" "runtime" "sort" + "strconv" "strings" "sync" "syscall" @@ -64,20 +65,15 @@ const ( // Shared is held by normal commands for the lifetime of their open // store or UOW provider. Any number of shared holders coexist. // - // Starvation note: a rolling sequence of shared holders (e.g. one bd - // command after another against a busy workspace) can starve an - // Exclusive acquirer indefinitely — acquisition is LOCK_NB polling - // with no intent signal, so a new shared holder has no way to know an - // exclusive attempt is queued and back off. A future extension could - // have Exclusive publish an advisory "waiting" marker (parallel to - // the holder-info sidecar) that new Shared acquisitions check and - // voluntarily defer to, but that does not exist yet: Options.Wait on - // an Exclusive acquisition is not a fairness guarantee. + // Fairness: a waiting Shared acquisition (Options.Wait > 0) defers to a + // queued Exclusive acquirer — see "Writer fairness" on Acquire — so a + // rolling sequence of short shared holders cannot starve maintenance. + // A fail-fast Shared attempt (Wait <= 0) does not consult the queue. Shared Mode = iota // Exclusive is held by maintenance operations. It conflicts with - // every other holder, shared or exclusive. See the starvation note - // on Shared: nothing here prevents shared holders from starving an - // Exclusive acquirer. + // every other holder, shared or exclusive. A waiting Exclusive + // acquisition publishes its intent so new waiting Shared acquisitions + // queue behind it (see Acquire). Exclusive ) @@ -98,14 +94,12 @@ var ErrBusy = errors.New("workspace gate busy") // attempt with no diagnostics callback. type Options struct { // Wait bounds how long Acquire keeps retrying after the first busy - // attempt. Zero or negative means exactly one non-blocking try. - // The underlying blocking lock primitives have no deadline support, - // so waiting is implemented as timed polling of the non-blocking - // primitive. This is not a fairness guarantee: see the starvation - // note on Exclusive — a Wait on an Exclusive acquisition can still - // exhaust its budget against a rolling sequence of Shared holders - // that each individually released before it, none of which had any - // signal that an exclusive acquirer was waiting. + // attempt. Zero or negative means exactly one non-blocking try (which + // also opts out of the writer-fairness queue in both directions: a + // fail-fast Exclusive publishes no intent, and a fail-fast Shared + // ignores published intent). The underlying blocking lock primitives + // have no deadline support, so waiting is implemented as timed polling + // of the non-blocking primitive. Wait time.Duration // PollInterval is the retry cadence while waiting (default 100ms). PollInterval time.Duration @@ -118,6 +112,23 @@ type Options struct { // effort, from the advisory sidecar). AcquireAll fires it at most // once across the whole gate set. OnWait func(holder string) + // ReadOnly makes a SHARED acquisition free of side effects, for commands + // that promise not to mutate the workspace (strict --readonly). The gate + // file is opened O_RDONLY and never created: a gate file that does not + // exist means nothing has ever been gated here (the reading ExclusiveHolder + // uses), so Acquire succeeds holding nothing. An existing file is held + // SHARED as usual, so maintenance still sees the holder and a live + // exclusive holder still turns it away. Ignored for Exclusive: a + // maintenance operation has to be able to create the file it locks. + ReadOnly bool + // IgnoreQueuedExclusive makes a waiting Shared acquisition skip the + // writer-fairness check. Set it only when an ANCESTOR process already + // holds this gate shared (see InheritedSharedHold): the queued + // exclusive acquirer cannot proceed until that ancestor releases, and + // the ancestor may be waiting on this process, so queueing would turn + // a nested bd invocation into a deadlock that only the wait bound + // breaks. Ignored for Exclusive. + IgnoreQueuedExclusive bool } // Gate identifies one gate file. Construct via ForWorkspace or @@ -231,8 +242,19 @@ type Info struct { func (g Gate) infoPath() string { return g.path + ".info" } -func (g Gate) readInfo() *Info { - data, err := os.ReadFile(g.infoPath()) +// intentPath is the writer-fairness lock: a waiting Exclusive acquirer +// holds it exclusively while it polls the gate, and waiting Shared +// acquirers defer while it is held. intentInfoPath is its advisory +// holder-info sidecar (a separate file because Windows LockFileEx locks +// are mandatory byte-range locks: other processes cannot read a locked +// file's contents). Both match the "*.gate.lock*" gitignore pattern. +func (g Gate) intentPath() string { return g.path + ".intent" } +func (g Gate) intentInfoPath() string { return g.path + ".intent.info" } + +func (g Gate) readInfo() *Info { return readInfoAt(g.infoPath()) } + +func readInfoAt(path string) *Info { + data, err := os.ReadFile(path) //nolint:gosec // G304: path derives from the gate location this package computed if err != nil { return nil } @@ -262,16 +284,7 @@ func (g Gate) busyDetail(mode Mode) string { } return "another bd process (no holder info recorded)" } - desc := fmt.Sprintf("pid %d", info.PID) - if info.Hostname != "" { - desc += " on " + info.Hostname - } - if info.Reason != "" { - desc += " (" + info.Reason + ")" - } - if !info.StartedAt.IsZero() { - desc += " since " + info.StartedAt.UTC().Format(time.RFC3339) - } + desc := info.describe() stale := func() bool { host, _ := os.Hostname() return host == info.Hostname && !pidAlive(info.PID) @@ -293,6 +306,42 @@ func (g Gate) busyDetail(mode Mode) string { return "possibly " + desc + ", or shared holders" } +// describe renders a holder record as "pid N on host (reason) since T". +func (info *Info) describe() string { + desc := fmt.Sprintf("pid %d", info.PID) + if info.Hostname != "" { + desc += " on " + info.Hostname + } + if info.Reason != "" { + desc += " (" + info.Reason + ")" + } + if !info.StartedAt.IsZero() { + desc += " since " + info.StartedAt.UTC().Format(time.RFC3339) + } + return desc +} + +// queuedDetail describes the queued exclusive acquirer a waiting Shared +// attempt is deferring to. The intent lock is held whenever this is +// called, so the sidecar (written right after the lock is taken) normally +// names a live process; it is only absent in the brief window before the +// write or when the write failed. +func (g Gate) queuedDetail() string { + info := readInfoAt(g.intentInfoPath()) + if info != nil { + // A sidecar whose removal failed (Windows refuses to delete a file + // another process has open) can outlive its writer; never present + // a dead process as the queued operation. + if host, _ := os.Hostname(); host == info.Hostname && !pidAlive(info.PID) { + info = nil + } + } + if info == nil { + return "a bd maintenance operation queued for exclusive access" + } + return "a bd maintenance operation queued for exclusive access: " + info.describe() +} + // pidAlive reports best-effort process liveness via the zero-signal // probe. Where the probe is unsupported it errs toward alive, which only // makes the diagnostic more cautious (the stale record is then presented @@ -332,6 +381,11 @@ type Handle struct { // Mode reports how this handle was acquired. func (h *Handle) Mode() Mode { return h.mode } +// Empty reports whether the acquisition locked nothing: a ReadOnly shared +// acquisition of a gate file that does not exist (see Options.ReadOnly). An +// empty handle blocks no acquirer. Release does not change the answer. +func (h *Handle) Empty() bool { return h == nil || h.f == nil } + // Release drops the lock and closes the file handle. For exclusive // handles it also best-effort removes the holder-info sidecar. The gate // file itself is intentionally never removed: deleting a lock file that @@ -342,6 +396,11 @@ func (h *Handle) Release() error { return nil } h.once.Do(func() { + if h.f == nil { + // A ReadOnly acquisition of a gate file that does not exist: + // nothing was locked, so there is nothing to drop. + return + } var errs []error if h.mode == Exclusive { // Remove the sidecar BEFORE unlocking: after the unlock a new @@ -367,6 +426,57 @@ func (h *Handle) Release() error { // inherited by spawned children (Go opens files close-on-exec on Unix and // non-inheritable on Windows), so a dolt child outliving its bd parent // does not keep the gate held. +// +// Writer fairness. flock and LockFileEx grant no queueing guarantees, and +// acquisition is non-blocking polling anyway, so without help a steady +// stream of short shared holders — each overlapping the next — would keep +// an Exclusive waiter out until its budget ran dry. A second lock file, +// the intent lock (.intent), fixes that: +// +// - a waiting Exclusive acquisition (Wait > 0) whose first attempt is +// busy takes the intent lock EXCLUSIVELY (non-blocking, retried each +// poll), holds it while it polls the gate, and drops it as soon as it +// owns the gate, gives up, or has held it for maxIntentHold without +// getting in (after which it keeps polling unqueued); +// - a waiting Shared acquisition (Wait > 0) checks the intent lock before +// every attempt but the last (a momentary non-blocking SHARED probe) +// and, while it is held, does not touch the gate — it waits, within its +// own budget, exactly as if the gate were held exclusively. Its final +// attempt tries the gate regardless. +// +// The two bounds keep the queue from ever costing availability. A queue can +// DELAY a shared acquirer but never FAIL it: the final attempt ignores +// intent, so a shared acquisition fails only when the gate itself is held +// exclusively. And a doomed exclusive waiter — one blocked behind a shared +// holder that will not leave soon (a --watch, a tail --follow, an open +// editor, a long-lived embedder) — stops queueing everyone else after +// maxIntentHold instead of for its whole budget. In-flight ordinary commands +// drain far faster than that, so the fairness win is kept. +// +// Queued exclusive operations still run one after another: while they take +// turns on the gate, a waiting shared acquirer waits for all of them (each +// new exclusive waiter re-publishes intent), bounded by its own budget. +// +// Shared holders that are already in keep running; the exclusive waiter +// waits only for them to drain, so its wait is bounded by the longest +// in-flight command rather than by the arrival rate. A shared acquirer that +// probed just before the intent was published can still slip in once, which +// costs at most one more command's duration. +// +// Stale intent cannot outlive its owner: it is an OS advisory lock, released +// by the kernel when the process exits or crashes (on every platform), never +// a marker file whose existence means anything. The intent file and its +// holder-info sidecar may linger; both are ignored whenever the lock itself +// is free. Every intent-lock failure other than "busy" (unsupported +// filesystem, permissions) degrades to the pre-fairness behavior instead of +// failing the acquisition: fairness is advisory, the gate is the authority. +// +// Lock order is unchanged in substance: the intent lock of a gate is taken +// only while acquiring that gate, so it slots directly before the gate in +// AcquireAll's sorted total order and cannot form a cycle. +// +// A Shared acquisition with Options.ReadOnly never creates the gate file: +// see that option for what it holds instead. func (g Gate) Acquire(ctx context.Context, mode Mode, opts Options) (*Handle, error) { if g.path == "" { return nil, errors.New("workspacegate: zero Gate; use ForWorkspace/ForPhysicalRoot") @@ -387,8 +497,20 @@ func (g Gate) Acquire(ctx context.Context, mode Mode, opts Options) (*Handle, er } deadline := time.Now().Add(opts.Wait) - f, err := os.OpenFile(g.path, os.O_CREATE|os.O_RDWR, 0o600) + // An exclusive acquirer always has to create the file it locks, so + // ReadOnly applies to shared acquisition only. + readOnly := opts.ReadOnly && mode == Shared + flag := os.O_CREATE | os.O_RDWR + if readOnly { + flag = os.O_RDONLY + } + f, err := os.OpenFile(g.path, flag, 0o600) if err != nil { + if readOnly && os.IsNotExist(err) { + // No gate file: nothing has ever gated here, so there is no + // holder to see and nothing to hold. + return &Handle{gate: g, mode: mode}, nil + } return nil, fmt.Errorf("workspacegate: open gate %s: %w", g.path, err) } @@ -396,32 +518,77 @@ func (g Gate) Acquire(ctx context.Context, mode Mode, opts Options) (*Handle, er if mode == Exclusive { try = lockfile.FlockExclusiveNonBlock } + waiting := opts.Wait > 0 + defersToIntent := waiting && mode == Shared && !opts.IgnoreQueuedExclusive + publishesIntent := waiting && mode == Exclusive + var intentSince time.Time + + // intent is the writer-fairness lock while this Exclusive acquisition + // holds it. Released on every return path — after writeInfo on success, + // so a shared waiter never sees the gate unqueued-but-unclaimed. + var intent *os.File + defer func() { g.releaseIntent(intent) }() notified := false + // finalAttempt is set once the budget ran out while this acquisition was + // deferring to queued intent: it then gets exactly one more try at the + // gate, ignoring the queue, before it may fail. Deciding finality from + // the clock at the top of an iteration is not enough — the intent probe + // itself takes time (a loaded machine can stall it for milliseconds), so + // "budget not yet spent" before the probe can be "spent" after it, and + // failing there would let a mere queue fail a shared acquirer. + finalAttempt := false for { - err := try(f) - if err == nil { - h := &Handle{gate: g, mode: mode, f: f} - if mode == Exclusive { - g.writeInfo(opts.Reason) + var detail string + deferred := defersToIntent && !finalAttempt && time.Until(deadline) > 0 && g.ExclusiveQueued() + if deferred { + detail = g.queuedDetail() + if testHookAfterIntentDefer != nil { + testHookAfterIntentDefer() } - return h, nil - } - if !errors.Is(err, lockfile.ErrLockBusy) && !lockfile.IsLocked(err) { - _ = f.Close() - return nil, fmt.Errorf("workspacegate: lock %s: %w", g.path, err) + } else { + err := try(f) + if err == nil { + h := &Handle{gate: g, mode: mode, f: f} + if mode == Exclusive { + g.writeInfo(opts.Reason) + } + return h, nil + } + if !errors.Is(err, lockfile.ErrLockBusy) && !lockfile.IsLocked(err) { + _ = f.Close() + return nil, fmt.Errorf("workspacegate: lock %s: %w", g.path, err) + } + detail = g.busyDetail(mode) } if !notified { notified = true if opts.OnWait != nil { - opts.OnWait(g.busyDetail(mode)) + opts.OnWait(detail) } } remaining := time.Until(deadline) - if opts.Wait <= 0 || remaining <= 0 { + if deferred && remaining <= 0 { + // Queued maintenance may delay a shared acquirer, never fail + // it: the budget is spent, so try the gate itself once more. + finalAttempt = true + continue + } + if !waiting || remaining <= 0 { _ = f.Close() return nil, fmt.Errorf("workspacegate: %s (%s mode) held by %s: %w", - g.path, mode, g.busyDetail(mode), ErrBusy) + g.path, mode, detail, ErrBusy) + } + if intent != nil && time.Since(intentSince) >= maxIntentHold { + // Doomed or very slow: stop holding everyone else back. + g.releaseIntent(intent) + intent = nil + publishesIntent = false + } + if publishesIntent && intent == nil { + if intent = g.tryTakeIntent(opts.Reason); intent != nil { + intentSince = time.Now() + } } // Never sleep past the wait budget: a Wait shorter than the poll // interval must still come back within (about) Wait, and the @@ -439,13 +606,76 @@ func (g Gate) Acquire(ctx context.Context, mode Mode, opts Options) (*Handle, er } } -// writeInfo records the advisory exclusive-holder sidecar. Failures are +// testHookAfterIntentDefer, when set (tests only), runs right after a +// waiting shared acquisition decides to defer to queued intent, so tests can +// stall it past its deadline at exactly the point a loaded machine might. +var testHookAfterIntentDefer func() + +// maxIntentHold caps how long one Exclusive acquisition keeps the intent +// lock without getting the gate. It must stay well below the shared wait +// budget callers use (bd: BEADS_GATE_WAIT_TIMEOUT, default 30s) and well +// above how long ordinary in-flight commands take to drain. A var so tests +// can shorten it. +var maxIntentHold = 10 * time.Second + +// ExclusiveQueued reports whether a waiting Exclusive acquirer currently +// holds this gate's intent lock. The probe opens read-only and treats a +// missing file as "no intent", so ordinary shared commands never create +// intent files; any error other than "busy" reads as "not queued" (see the +// degradation rule on Acquire). +func (g Gate) ExclusiveQueued() bool { + f, err := os.OpenFile(g.intentPath(), os.O_RDONLY, 0o600) + if err != nil { + return false + } + defer f.Close() + lerr := lockfile.FlockSharedNonBlock(f) + if lerr == nil { + _ = lockfile.FlockUnlock(f) + return false + } + return errors.Is(lerr, lockfile.ErrLockBusy) || lockfile.IsLocked(lerr) +} + +// tryTakeIntent makes one non-blocking attempt at the intent lock and, on +// success, records the advisory intent sidecar. It returns nil when the +// lock is busy (another exclusive waiter is queued first; this acquirer +// keeps polling the gate and retries the intent next round) or unusable. +func (g Gate) tryTakeIntent(reason string) *os.File { + f, err := os.OpenFile(g.intentPath(), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil + } + if err := lockfile.FlockExclusiveNonBlock(f); err != nil { + _ = f.Close() + return nil + } + writeInfoAt(g.intentInfoPath(), reason) + return f +} + +// releaseIntent drops a held intent lock (nil-safe). As with the gate's own +// sidecar, the intent sidecar is removed BEFORE unlocking so a late removal +// can never delete the next waiter's record. +func (g Gate) releaseIntent(f *os.File) { + if f == nil { + return + } + _ = os.Remove(g.intentInfoPath()) + _ = lockfile.FlockUnlock(f) + _ = f.Close() +} + +// writeInfo records the advisory exclusive-holder sidecar. +func (g Gate) writeInfo(reason string) { writeInfoAt(g.infoPath(), reason) } + +// writeInfoAt writes an advisory holder-info sidecar. Failures are // deliberately swallowed: diagnostics must never block the operation that // already holds the authoritative lock. The write goes to an O_EXCL temp // file renamed into place, which (a) never follows a pre-planted symlink // at either path — plain WriteFile would truncate the symlink's target — // and (b) is atomic, so concurrent readers cannot see torn JSON. -func (g Gate) writeInfo(reason string) { +func writeInfoAt(path, reason string) { host, _ := os.Hostname() data, err := json.Marshal(Info{ PID: os.Getpid(), @@ -456,7 +686,7 @@ func (g Gate) writeInfo(reason string) { if err != nil { return } - tmp := fmt.Sprintf("%s.%d.tmp", g.infoPath(), os.Getpid()) + tmp := fmt.Sprintf("%s.%d.tmp", path, os.Getpid()) _ = os.Remove(tmp) f, err := os.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) //nolint:gosec // G304: path derives from the gate location this package computed, not request input; the preceding os.Remove clears a pre-planted file, and O_EXCL closes the remove-then-open window so a symlink replanted in between is refused rather than followed if err != nil { @@ -469,22 +699,61 @@ func (g Gate) writeInfo(reason string) { return } // Rename replaces a symlink itself rather than following it. - if err := os.Rename(tmp, g.infoPath()); err != nil { + if err := os.Rename(tmp, path); err != nil { // Windows can refuse to replace an existing file; retry once // after removing the destination. Still best effort. - _ = os.Remove(g.infoPath()) - if err := os.Rename(tmp, g.infoPath()); err != nil { + _ = os.Remove(path) + if err := os.Rename(tmp, path); err != nil { _ = os.Remove(tmp) } } } +// InheritedHoldEnv names the environment variable a bd process sets (to its +// PID) while it holds its command's gates SHARED, so that bd processes it +// spawns — `bd orphans` running `bd close`, git hooks under a bd-driven +// commit — can tell that an ancestor already holds the gate. See +// Options.IgnoreQueuedExclusive and InheritedSharedHold. +const InheritedHoldEnv = "BEADS_GATE_SHARED_HOLDER_PID" + +// InheritedSharedHold reports whether InheritedHoldEnv names a live process +// other than this one, i.e. whether this process was (probably) spawned by a +// bd command that still holds its gates shared. A stale or recycled PID only +// costs fairness, never safety: the flag merely skips the writer queue, and +// the gate itself still excludes every exclusive holder. +func InheritedSharedHold() bool { + raw := strings.TrimSpace(os.Getenv(InheritedHoldEnv)) + if raw == "" { + return false + } + pid, err := strconv.Atoi(raw) + if err != nil || pid == os.Getpid() { + return false + } + return pidAlive(pid) +} + // MultiHandle holds several gates acquired by AcquireAll and releases // them in reverse acquisition order. type MultiHandle struct { handles []*Handle } +// Empty reports whether the acquisition locked no gate at all: every gate in +// the set was a ReadOnly acquisition of a gate file that does not exist (see +// Handle.Empty). +func (m *MultiHandle) Empty() bool { + if m == nil { + return true + } + for _, h := range m.handles { + if !h.Empty() { + return false + } + } + return true +} + // Release drops every held gate in reverse order. Idempotent. func (m *MultiHandle) Release() error { if m == nil { @@ -540,6 +809,9 @@ func AcquireAll(ctx context.Context, mode Mode, opts Options, gates ...Gate) (*M m := &MultiHandle{handles: make([]*Handle, 0, len(ordered))} for _, g := range ordered { if opts.Wait > 0 { + // An exhausted budget leaves later gates one non-blocking + // attempt (Wait 0), which ignores the writer-fairness queue — + // the same as the final attempt of a waiting acquisition. perGate.Wait = time.Until(deadline) if perGate.Wait < 0 { perGate.Wait = 0 diff --git a/internal/workspacegate/gate_test.go b/internal/workspacegate/gate_test.go index 4bcdd3ff1..eb5ddd100 100644 --- a/internal/workspacegate/gate_test.go +++ b/internal/workspacegate/gate_test.go @@ -12,6 +12,8 @@ import ( "path/filepath" "runtime" "strings" + "sync" + "sync/atomic" "testing" "time" @@ -34,6 +36,10 @@ func TestMain(m *testing.M) { // // hold — acquire, print ACQUIRED, // hold until stdin closes, release, print RELEASED. +// intent — hold the gate's writer-fairness intent lock +// (as a queued exclusive acquirer does) until stdin closes. +// inherited-acquire — waiting shared acquisition with +// IgnoreQueuedExclusive = InheritedSharedHold(); prints the outcome. // sleep — sleep long without touching any gate (handle-inheritance probe). // exit — exit immediately, so the caller has a real, now-dead PID (used // to fabricate a stale holder-info sidecar in tests). @@ -64,6 +70,43 @@ func helperMain() { os.Exit(1) } fmt.Println("RELEASED") + case "intent": + // Hold the writer-fairness intent lock for /.beads's gate, as + // a queued exclusive acquirer would, until stdin closes. + g, err := ForWorkspace(filepath.Join(os.Args[1], ".beads")) + if err != nil { + fmt.Println("ERR", err) + os.Exit(1) + } + f := g.tryTakeIntent("test-intent-helper") + if f == nil { + fmt.Println("ERR intent lock unavailable") + os.Exit(1) + } + fmt.Println("ACQUIRED") + _, _ = io.Copy(io.Discard, os.Stdin) + g.releaseIntent(f) + fmt.Println("RELEASED") + case "inherited-acquire": + // Waiting shared acquisition the way bd's chokepoint does it, + // honoring an inherited shared hold; reports how long it took. + g, err := ForWorkspace(filepath.Join(os.Args[1], ".beads")) + if err != nil { + fmt.Println("ERR", err) + os.Exit(1) + } + inherited := InheritedSharedHold() + start := time.Now() + h, err := g.Acquire(context.Background(), Shared, Options{ + Wait: 3 * time.Second, PollInterval: 20 * time.Millisecond, + IgnoreQueuedExclusive: inherited, + }) + if err != nil { + fmt.Println("ERR", err) + os.Exit(1) + } + _ = h.Release() + fmt.Printf("inherited=%v waited_ms=%d\n", inherited, time.Since(start).Milliseconds()) case "sleep": time.Sleep(30 * time.Second) } @@ -279,6 +322,184 @@ func TestExclusiveHolderDoesNotDisturbSharedAcquirers(t *testing.T) { <-done } +// A ReadOnly shared acquisition on a workspace that has never been gated must +// succeed and create nothing: an absent gate file means nothing has ever been +// gated here (the reading ExclusiveHolder already uses), so there is no holder +// to observe and nothing to hold. This is what lets a strict --readonly +// command stay mutation-free. +func TestReadOnlySharedAcquireCreatesNothing(t *testing.T) { + g, dir := testGate(t) + + h, err := g.Acquire(context.Background(), Shared, Options{ReadOnly: true}) + if err != nil { + t.Fatalf("ReadOnly shared Acquire on a never-gated workspace: %v, want success (nothing to hold)", err) + } + for i := 1; i <= 2; i++ { + if err := h.Release(); err != nil { + t.Fatalf("Release #%d of the ReadOnly handle: %v", i, err) + } + } + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + var created []string + for _, e := range entries { + created = append(created, e.Name()) + } + if len(created) != 0 { + t.Fatalf("ReadOnly Acquire created %v in %s, want nothing", created, dir) + } +} + +// Against a gate file that already exists, a ReadOnly shared acquisition is a +// real shared hold — it coexists with other shared holders, is refused by a +// live exclusive holder, and keeps an exclusive acquirer out until released. +// Dropping the create must not make strict readonly commands invisible to +// maintenance. +func TestReadOnlySharedAcquireHoldsExistingGate(t *testing.T) { + g, _ := testGate(t) + // Materialize the gate file once, as any workspace that has run bd has. + h0 := mustAcquire(t, g, Shared, Options{}) + _ = h0.Release() + + h := mustAcquire(t, g, Shared, Options{ReadOnly: true}) + other := mustAcquire(t, g, Shared, Options{}) + _ = other.Release() + if _, err := g.Acquire(context.Background(), Exclusive, Options{}); !errors.Is(err, ErrBusy) { + t.Fatalf("exclusive under a ReadOnly shared holder: err = %v, want ErrBusy", err) + } + if err := h.Release(); err != nil { + t.Fatalf("Release: %v", err) + } + + hEx := mustAcquire(t, g, Exclusive, Options{Reason: "after the ReadOnly holder left"}) + defer hEx.Release() + if _, err := g.Acquire(context.Background(), Shared, Options{ReadOnly: true}); !errors.Is(err, ErrBusy) { + t.Fatalf("ReadOnly shared under an exclusive holder: err = %v, want ErrBusy", err) + } +} + +// The gate file is opened O_RDONLY, not merely without O_CREATE: a strict +// readonly command in a sandbox whose gate file it cannot write must still be +// able to hold it (flock does not need a writable descriptor). +func TestReadOnlySharedAcquireNeedsNoWriteAccess(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("POSIX permission bits do not gate opens on Windows") + } + if os.Geteuid() == 0 { + t.Skip("root ignores file permission bits") + } + g, _ := testGate(t) + h0 := mustAcquire(t, g, Shared, Options{}) + _ = h0.Release() + if err := os.Chmod(g.Path(), 0o400); err != nil { + t.Fatal(err) + } + + h, err := g.Acquire(context.Background(), Shared, Options{ReadOnly: true}) + if err != nil { + t.Fatalf("ReadOnly shared Acquire on a read-only gate file: %v, want success", err) + } + _ = h.Release() +} + +// ReadOnly applies to shared acquisition only: an exclusive acquirer has to be +// able to create the gate file it locks, so the option cannot suppress that. +func TestReadOnlyOptionIgnoredForExclusive(t *testing.T) { + g, _ := testGate(t) + + h, err := g.Acquire(context.Background(), Exclusive, Options{ReadOnly: true, Reason: "readonly is ignored"}) + if err != nil { + t.Fatalf("exclusive Acquire with ReadOnly set: %v", err) + } + defer h.Release() + if _, err := os.Stat(g.Path()); err != nil { + t.Fatalf("exclusive Acquire must create the gate file it locks: %v", err) + } + if _, err := g.Acquire(context.Background(), Shared, Options{}); !errors.Is(err, ErrBusy) { + t.Fatalf("shared under that exclusive holder: err = %v, want ErrBusy", err) + } +} + +// AcquireAll passes the option to every gate: gates whose file exists are held +// shared, gates whose file does not are skipped and stay absent — for the +// workspace gate beside .beads and the physical-root gate inside it alike. +func TestAcquireAllReadOnlySkipsAbsentGates(t *testing.T) { + dir := t.TempDir() + beadsDir := filepath.Join(dir, ".beads") + if err := os.MkdirAll(beadsDir, 0o755); err != nil { + t.Fatal(err) + } + ws, err := ForWorkspace(beadsDir) + if err != nil { + t.Fatal(err) + } + root, err := ForPhysicalRoot(filepath.Join(beadsDir, "embeddeddolt")) + if err != nil { + t.Fatal(err) + } + // Only the workspace gate has ever been used. + h0 := mustAcquire(t, ws, Shared, Options{}) + _ = h0.Release() + + m, err := AcquireAll(context.Background(), Shared, Options{ReadOnly: true}, ws, root) + if err != nil { + t.Fatalf("AcquireAll with ReadOnly over an existing and an absent gate: %v", err) + } + if _, err := ws.Acquire(context.Background(), Exclusive, Options{}); !errors.Is(err, ErrBusy) { + t.Fatalf("exclusive on the existing workspace gate under AcquireAll: err = %v, want ErrBusy", err) + } + if err := m.Release(); err != nil { + t.Fatalf("Release: %v", err) + } + if _, err := os.Lstat(root.Path()); !os.IsNotExist(err) { + t.Fatalf("AcquireAll with ReadOnly created the absent physical-root gate %s (stat err: %v)", root.Path(), err) + } +} + +// Empty separates a ReadOnly acquisition that locked nothing from a real +// hold: callers use it to decide whether there is a hold to tell anyone about. +// One gate file that exists makes the whole set a real hold. +func TestEmptyReportsWhetherAnythingIsLocked(t *testing.T) { + never, _ := testGate(t) // never gated: its file stays absent + used, _ := testGate(t) // gated once, below + readOnly := Options{ReadOnly: true} + + if !(*Handle)(nil).Empty() || !(*MultiHandle)(nil).Empty() { + t.Fatal("a nil handle must report Empty") + } + absent, err := AcquireAll(context.Background(), Shared, readOnly, never, used) + if err != nil { + t.Fatalf("ReadOnly AcquireAll over two absent gates: %v", err) + } + if !absent.Empty() { + t.Fatal("ReadOnly AcquireAll over two absent gates reported a hold, want Empty") + } + _ = absent.Release() + + h0 := mustAcquire(t, used, Shared, Options{}) + if h0.Empty() { + t.Fatal("a plain shared acquisition reported Empty") + } + _ = h0.Release() + if h0.Empty() { + t.Fatal("Release changed Empty; it reports the acquisition, not the current state") + } + + partial, err := AcquireAll(context.Background(), Shared, readOnly, never, used) + if err != nil { + t.Fatalf("ReadOnly AcquireAll over an absent and an existing gate: %v", err) + } + defer partial.Release() + if partial.Empty() { + t.Fatal("ReadOnly AcquireAll holding the existing gate reported Empty") + } + if _, err := os.Lstat(never.Path()); !os.IsNotExist(err) { + t.Fatalf("the absent gate %s must stay absent (stat err: %v)", never.Path(), err) + } +} + // A cancelled context must surface as the context error even in // fail-fast mode (Wait == 0), so callers can tell shutdown from // contention. @@ -595,13 +816,20 @@ func (h *holderProc) stop() { // spawnHolder starts this test binary in helper mode and waits until it // reports the lock acquired. func spawnHolder(t *testing.T, dir, mode string) *holderProc { + t.Helper() + return spawnHelperProc(t, "hold", dir, mode) +} + +// spawnHelperProc starts this test binary in the given helper mode and +// waits for it to print ACQUIRED. +func spawnHelperProc(t *testing.T, helperMode string, args ...string) *holderProc { t.Helper() exe, err := os.Executable() if err != nil { t.Fatalf("os.Executable: %v", err) } - cmd := exec.Command(exe, dir, mode) - cmd.Env = append(bazeltest.ShardFreeEnv(os.Environ()), "WORKSPACEGATE_HELPER=hold") + cmd := exec.Command(exe, args...) + cmd.Env = append(bazeltest.ShardFreeEnv(os.Environ()), "WORKSPACEGATE_HELPER="+helperMode) stdin, err := cmd.StdinPipe() if err != nil { t.Fatal(err) @@ -727,3 +955,592 @@ func TestSpawnedChildDoesNotInheritGate(t *testing.T) { } _ = h2.Release() } + +// --- writer fairness (exclusive intent) --- + +// A continuous stream of overlapping shared holders keeps the gate busy +// forever, so without writer fairness a waiting exclusive acquirer would +// exhaust its budget. With it, the exclusive acquirer gets the gate as soon +// as the shared holders that were already in drain, and the stream resumes +// after it releases. +func TestExclusiveWaiterNotStarvedBySharedStream(t *testing.T) { + g, _ := testGate(t) + first := mustAcquire(t, g, Shared, Options{}) + + const ( + workers = 4 + hold = 150 * time.Millisecond + ) + stop := make(chan struct{}) + done := make(chan struct{}) + var acquired, failed atomic.Int64 + go func() { + defer close(done) + var wg sync.WaitGroup + for w := 0; w < workers; w++ { + wg.Add(1) + go func(w int) { + defer wg.Done() + // Stagger so the gate is never free between holders. + time.Sleep(time.Duration(w) * hold / workers) + for { + select { + case <-stop: + return + default: + } + h, err := g.Acquire(context.Background(), Shared, + Options{Wait: 10 * time.Second, PollInterval: 10 * time.Millisecond}) + if err != nil { + failed.Add(1) + continue + } + acquired.Add(1) + time.Sleep(hold) + _ = h.Release() + } + }(w) + } + wg.Wait() + }() + t.Cleanup(func() { close(stop); <-done }) + + // Let the stream get going, then release the original holder: from + // here on the gate is only ever held by overlapping stream members. + time.Sleep(2 * hold) + _ = first.Release() + + start := time.Now() + h, err := g.Acquire(context.Background(), Exclusive, + Options{Wait: 5 * time.Second, PollInterval: 10 * time.Millisecond, Reason: "test exclusive waiter"}) + if err != nil { + t.Fatalf("exclusive acquirer starved by a shared stream: %v", err) + } + waited := time.Since(start) + // Bounded by the in-flight holders draining (one hold), plus slack. + if waited > 2*time.Second { + t.Errorf("exclusive waited %s behind a stream of %s shared holds", waited, hold) + } + if g.ExclusiveQueued() { + t.Error("intent lock still held after the exclusive acquirer got the gate") + } + before := acquired.Load() + time.Sleep(3 * hold) + if got := acquired.Load(); got != before { + t.Errorf("shared stream acquired %d times while the exclusive holder held the gate", got-before) + } + _ = h.Release() + + // The stream resumes once the exclusive holder is gone. + deadline := time.Now().Add(3 * time.Second) + for acquired.Load() == before && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if acquired.Load() == before { + t.Error("shared stream did not resume after the exclusive holder released") + } + if n := failed.Load(); n != 0 { + t.Errorf("%d shared acquisitions failed; with a 10s budget all should wait", n) + } +} + +// A waiting shared acquirer defers to queued intent (and says so), but a +// fail-fast one and one whose ancestor holds the gate do not. +func TestSharedWaitDefersToQueuedExclusive(t *testing.T) { + g, _ := testGate(t) + intent := g.tryTakeIntent("test queued maintenance") + if intent == nil { + t.Fatal("tryTakeIntent on a fresh gate returned nil") + } + t.Cleanup(func() { g.releaseIntent(intent) }) + + // Deferred for its whole budget, then the final attempt ignores the + // queue: delayed, never failed, because nothing holds the gate. + var holder string + start := time.Now() + h, err := g.Acquire(context.Background(), Shared, Options{ + Wait: 300 * time.Millisecond, PollInterval: 20 * time.Millisecond, + OnWait: func(h string) { holder = h }, + }) + if err != nil { + t.Fatalf("waiting shared under queued intent with a free gate: %v, want success on the final attempt", err) + } + _ = h.Release() + if waited := time.Since(start); waited < 250*time.Millisecond { + t.Errorf("shared acquirer did not defer to queued intent (acquired after %s)", waited) + } + if !strings.Contains(holder, "queued for exclusive access") || !strings.Contains(holder, "test queued maintenance") { + t.Errorf("wait notice %q does not name the queued exclusive acquirer", holder) + } + + h = mustAcquire(t, g, Shared, Options{}) // fail-fast: legacy behavior + _ = h.Release() + h = mustAcquire(t, g, Shared, Options{Wait: time.Second, IgnoreQueuedExclusive: true}) + _ = h.Release() + + // Once the intent is withdrawn, a waiting shared acquirer proceeds. + g.releaseIntent(intent) + intent = nil + h = mustAcquire(t, g, Shared, Options{Wait: time.Second}) + _ = h.Release() +} + +// Ordinary shared traffic never creates intent files, and an uncontended +// exclusive acquisition does not either; only a waiting exclusive does, and +// it withdraws its intent when it gives up. +func TestIntentLifecycle(t *testing.T) { + g, _ := testGate(t) + h := mustAcquire(t, g, Shared, Options{Wait: time.Second}) + _ = h.Release() + h = mustAcquire(t, g, Exclusive, Options{Wait: time.Second}) + _ = h.Release() + if _, err := os.Stat(g.intentPath()); !os.IsNotExist(err) { + t.Fatalf("intent file exists without any contended exclusive wait (stat err %v)", err) + } + + sh := mustAcquire(t, g, Shared, Options{}) + _, err := g.Acquire(context.Background(), Exclusive, + Options{Wait: 300 * time.Millisecond, PollInterval: 20 * time.Millisecond, Reason: "test giving up"}) + if !errors.Is(err, ErrBusy) { + t.Fatalf("exclusive under shared holder: %v, want ErrBusy", err) + } + if _, err := os.Stat(g.intentPath()); err != nil { + t.Fatalf("contended exclusive wait did not publish intent: %v", err) + } + if g.ExclusiveQueued() { + t.Error("intent still held after the exclusive acquirer gave up") + } + if _, err := os.Stat(g.intentInfoPath()); !os.IsNotExist(err) { + t.Errorf("intent sidecar left behind by an orderly give-up (stat err %v)", err) + } + _ = sh.Release() +} + +// Intent from a crashed exclusive waiter is released by the OS with the +// process; the leftover intent sidecar must not hold anyone back. +func TestStaleIntentFromCrashedProcess(t *testing.T) { + dir := t.TempDir() + g, err := ForWorkspace(filepath.Join(dir, ".beads")) + if err != nil { + t.Fatal(err) + } + hp := spawnHelperProc(t, "intent", dir) + + var holder string + h0, err := g.Acquire(context.Background(), Shared, Options{ + Wait: 200 * time.Millisecond, PollInterval: 20 * time.Millisecond, + OnWait: func(h string) { holder = h }, + }) + if err != nil { + t.Fatalf("shared wait under another process's intent: %v", err) + } + _ = h0.Release() + if !strings.Contains(holder, fmt.Sprintf("pid %d", hp.cmd.Process.Pid)) { + t.Fatalf("wait notice %q does not name the intent holder pid %d", holder, hp.cmd.Process.Pid) + } + + if err := hp.cmd.Process.Kill(); err != nil { + t.Fatalf("kill helper: %v", err) + } + <-hp.drained + _ = hp.cmd.Wait() + if _, err := os.Stat(g.intentInfoPath()); err != nil { + t.Fatalf("expected the crashed helper's intent sidecar to linger: %v", err) + } + + start := time.Now() + h, err := g.Acquire(context.Background(), Shared, + Options{Wait: 10 * time.Second, PollInterval: 25 * time.Millisecond}) + if err != nil { + t.Fatalf("shared acquisition after intent holder crashed: %v", err) + } + _ = h.Release() + if waited := time.Since(start); waited > 3*time.Second { + t.Errorf("shared acquisition took %s after the intent holder died", waited) + } + // A new exclusive waiter can take the intent over the stale sidecar. + if f := g.tryTakeIntent("test successor"); f == nil { + t.Error("intent lock not reacquirable after its holder crashed") + } else { + g.releaseIntent(f) + } +} + +func TestContextCancelWhileDeferringToIntent(t *testing.T) { + g, _ := testGate(t) + intent := g.tryTakeIntent("test queued maintenance") + if intent == nil { + t.Fatal("tryTakeIntent returned nil") + } + t.Cleanup(func() { g.releaseIntent(intent) }) + + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond) + defer cancel() + start := time.Now() + _, err := g.Acquire(ctx, Shared, Options{Wait: 30 * time.Second}) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("err = %v, want context.DeadlineExceeded", err) + } + if waited := time.Since(start); waited > 3*time.Second { + t.Fatalf("cancellation took %s to stop the wait", waited) + } +} + +func TestInheritedSharedHold(t *testing.T) { + for _, tc := range []struct { + name, val string + want bool + }{ + {"unset", "", false}, + {"garbage", "not-a-pid", false}, + {"self", fmt.Sprint(os.Getpid()), false}, + {"dead", fmt.Sprint(deadPID(t)), false}, + {"live parent", fmt.Sprint(os.Getppid()), true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv(InheritedHoldEnv, tc.val) + if got := InheritedSharedHold(); got != tc.want { + t.Fatalf("InheritedSharedHold() with %s=%q = %v, want %v", InheritedHoldEnv, tc.val, got, tc.want) + } + }) + } +} + +// setMaxIntentHold shortens maxIntentHold for one test. +func setMaxIntentHold(t *testing.T, d time.Duration) { + t.Helper() + old := maxIntentHold + maxIntentHold = d + t.Cleanup(func() { maxIntentHold = old }) +} + +// acquireAsync runs AcquireAll in a goroutine; the result arrives on the +// returned channel and any acquired handle is released at test end. +type acqResult struct { + h *MultiHandle + err error + at time.Time +} + +func acquireAsync(t *testing.T, mode Mode, opts Options, gates ...Gate) <-chan acqResult { + t.Helper() + ch := make(chan acqResult, 1) + go func() { + h, err := AcquireAll(context.Background(), mode, opts, gates...) + ch <- acqResult{h: h, err: err, at: time.Now()} + }() + return ch +} + +func waitQueued(t *testing.T, g Gate) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !g.ExclusiveQueued() { + if time.Now().After(deadline) { + t.Fatal("exclusive waiter never published intent") + } + time.Sleep(5 * time.Millisecond) + } +} + +func recv(t *testing.T, ch <-chan acqResult, what string) acqResult { + t.Helper() + select { + case r := <-ch: + if r.err != nil { + t.Fatalf("%s: %v", what, r.err) + } + t.Cleanup(func() { _ = r.h.Release() }) + return r + case <-time.After(10 * time.Second): + t.Fatalf("%s: no result within 10s (deadlock?)", what) + } + return acqResult{} +} + +// pending fails the test if the acquisition has already completed. +func pending(t *testing.T, ch <-chan acqResult, what string) { + t.Helper() + select { + case r := <-ch: + if r.h != nil { + _ = r.h.Release() + } + t.Fatalf("%s finished early (err %v)", what, r.err) + default: + } +} + +// The availability regression this design must not have: a long-lived +// shared holder (a --watch, an open editor, an embedder) plus an exclusive +// waiter that therefore cannot get in. NEW shared commands must still run — +// before the intent cap they failed for the exclusive waiter's whole budget. +func TestDoomedExclusiveWaiterDoesNotFailNewSharedCommands(t *testing.T) { + t.Run("final attempt ignores queue", func(t *testing.T) { + g, _ := testGate(t) + long := mustAcquire(t, g, Shared, Options{}) + t.Cleanup(func() { _ = long.Release() }) + x := acquireAsync(t, Exclusive, Options{Wait: 3 * time.Second, PollInterval: 20 * time.Millisecond, Reason: "test doomed init"}, g) + waitQueued(t, g) + + h, err := g.Acquire(context.Background(), Shared, Options{Wait: time.Second, PollInterval: 20 * time.Millisecond}) + if err != nil { + t.Fatalf("new shared command failed behind a doomed exclusive waiter: %v", err) + } + _ = h.Release() + if r := <-x; !errors.Is(r.err, ErrBusy) { + t.Fatalf("doomed exclusive waiter: %v, want ErrBusy", r.err) + } + }) + t.Run("intent dropped after maxIntentHold", func(t *testing.T) { + setMaxIntentHold(t, 300*time.Millisecond) + g, _ := testGate(t) + long := mustAcquire(t, g, Shared, Options{}) + t.Cleanup(func() { _ = long.Release() }) + x := acquireAsync(t, Exclusive, Options{Wait: 3 * time.Second, PollInterval: 20 * time.Millisecond}, g) + waitQueued(t, g) + time.Sleep(500 * time.Millisecond) + if g.ExclusiveQueued() { + t.Fatal("exclusive waiter still holds intent past maxIntentHold") + } + start := time.Now() + h, err := g.Acquire(context.Background(), Shared, Options{Wait: time.Second, PollInterval: 20 * time.Millisecond}) + if err != nil { + t.Fatalf("shared after the intent cap: %v", err) + } + _ = h.Release() + if waited := time.Since(start); waited > 200*time.Millisecond { + t.Errorf("shared acquirer still deferred %s after the intent was dropped", waited) + } + pending(t, x, "exclusive waiter") // still waiting, just no longer queueing others + _ = long.Release() + recv(t, x, "exclusive waiter after the long holder left") + }) +} + +// Lock order with intent across a gate set (a < b): a shared AcquireAll that +// holds a and defers on b's intent, while an exclusive waiter on b alone +// drains b. Nobody deadlocks, and the exclusive waiter goes first. +func TestIntentLockOrderSharedHoldsEarlierGate(t *testing.T) { + dir := t.TempDir() + a, _ := ForWorkspace(filepath.Join(dir, "a")) + b, _ := ForPhysicalRoot(filepath.Join(dir, "b")) + if gateKey(a.Path()) >= gateKey(b.Path()) { + t.Fatalf("test assumes %s sorts before %s", a.Path(), b.Path()) + } + hb := mustAcquire(t, b, Shared, Options{}) + x := acquireAsync(t, Exclusive, Options{Wait: 5 * time.Second, PollInterval: 10 * time.Millisecond}, b) + waitQueued(t, b) + s := acquireAsync(t, Shared, Options{Wait: 5 * time.Second, PollInterval: 10 * time.Millisecond}, a, b) + time.Sleep(150 * time.Millisecond) + if held, _, _ := a.ExclusiveHolder(); held { + t.Fatal("unexpected exclusive holder on a") + } + pending(t, s, "shared {a,b}") + pending(t, x, "exclusive {b}") + + _ = hb.Release() + xr := recv(t, x, "exclusive waiter on b") + time.Sleep(100 * time.Millisecond) + pending(t, s, "shared {a,b} while the exclusive holder has b") + xRelease := time.Now() + _ = xr.h.Release() + sr := recv(t, s, "shared {a,b} behind the queued exclusive") + if sr.at.Before(xRelease) { + t.Error("shared acquirer got b while the exclusive holder had it") + } +} + +// ...and the other direction: an exclusive AcquireAll holding a and the +// intent on b, a shared waiter on b alone, and a shared waiter on {a,b} +// blocked on a. All three complete once b's shared holder leaves. +func TestIntentLockOrderExclusiveHoldsEarlierGate(t *testing.T) { + dir := t.TempDir() + a, _ := ForWorkspace(filepath.Join(dir, "a")) + b, _ := ForPhysicalRoot(filepath.Join(dir, "b")) + hb := mustAcquire(t, b, Shared, Options{}) + x := acquireAsync(t, Exclusive, Options{Wait: 5 * time.Second, PollInterval: 10 * time.Millisecond}, a, b) + waitQueued(t, b) + if held, _, _ := a.ExclusiveHolder(); !held { + t.Fatal("exclusive waiter should hold a while queued on b") + } + s1 := acquireAsync(t, Shared, Options{Wait: 5 * time.Second, PollInterval: 10 * time.Millisecond}, b) + s2 := acquireAsync(t, Shared, Options{Wait: 5 * time.Second, PollInterval: 10 * time.Millisecond}, a, b) + time.Sleep(150 * time.Millisecond) + pending(t, s1, "shared {b}") + pending(t, s2, "shared {a,b}") + + _ = hb.Release() + xr := recv(t, x, "exclusive {a,b}") + _ = xr.h.Release() + recv(t, s1, "shared {b}") + recv(t, s2, "shared {a,b}") +} + +// An exhausted AcquireAll budget leaves later gates exactly one attempt, +// and queued intent on such a gate cannot fail the set (the gate is free). +func TestAcquireAllExhaustedBudgetFinalAttemptIgnoresIntent(t *testing.T) { + dir := t.TempDir() + a, _ := ForWorkspace(filepath.Join(dir, "a")) + b, _ := ForPhysicalRoot(filepath.Join(dir, "b")) + intent := b.tryTakeIntent("test queued on b") + if intent == nil { + t.Fatal("tryTakeIntent on b failed") + } + t.Cleanup(func() { b.releaseIntent(intent) }) + + // a held for the whole call (released only after it returns): the set + // fails on a, the gate that is really held, never reaching b. + ha := mustAcquire(t, a, Exclusive, Options{}) + _, err := AcquireAll(context.Background(), Shared, + Options{Wait: 100 * time.Millisecond, PollInterval: 10 * time.Millisecond}, a, b) + _ = ha.Release() + if !errors.Is(err, ErrBusy) || !strings.Contains(err.Error(), a.Path()) { + t.Fatalf("a held past the budget: %v, want ErrBusy on %s", err, a.Path()) + } + + // Both gates free, intent queued on b: b defers for the rest of the + // budget, then its final attempt gets in. + start := time.Now() + m, err := AcquireAll(context.Background(), Shared, + Options{Wait: 200 * time.Millisecond, PollInterval: 10 * time.Millisecond}, a, b) + if err != nil { + t.Fatalf("shared set with free gates and queued intent on b: %v", err) + } + _ = m.Release() + if waited := time.Since(start); waited < 150*time.Millisecond { + t.Errorf("b's queued intent was not honored before the final attempt (took %s)", waited) + } +} + +// The race behind a farm flake of the test above: the budget can run out +// DURING the intent probe (a stalled process), after the iteration already +// decided the attempt was not final. The acquisition must still make its +// final, queue-ignoring attempt instead of failing on the queue alone. The +// hook stalls the acquirer past its deadline at exactly that point, so this +// is deterministic rather than load-dependent. +func TestSharedFinalAttemptSurvivesStallDuringIntentProbe(t *testing.T) { + g, _ := testGate(t) + intent := g.tryTakeIntent("test queued maintenance") + if intent == nil { + t.Fatal("tryTakeIntent failed") + } + t.Cleanup(func() { g.releaseIntent(intent) }) + + // Generous budget: the first probe must happen well inside it even on a + // starved runner, or there is no deferral to stall (asserted below). + const wait = time.Second + var stalls int + testHookAfterIntentDefer = func() { + stalls++ + time.Sleep(wait + 50*time.Millisecond) // budget gone before the deadline check + } + t.Cleanup(func() { testHookAfterIntentDefer = nil }) + + h, err := g.Acquire(context.Background(), Shared, Options{Wait: wait, PollInterval: 10 * time.Millisecond}) + if err != nil { + t.Fatalf("queued intent failed a shared acquisition whose budget ran out mid-probe: %v", err) + } + _ = h.Release() + if stalls != 1 { + t.Fatalf("intent deferrals = %d, want exactly 1 (then the final attempt)", stalls) + } + + // Same through AcquireAll, where later gates get the leftover budget. + stalls = 0 + other, _ := ForPhysicalRoot(filepath.Join(filepath.Dir(g.Path()), "zz")) + m, err := AcquireAll(context.Background(), Shared, Options{Wait: wait, PollInterval: 10 * time.Millisecond}, g, other) + if err != nil { + t.Fatalf("AcquireAll: queued intent failed the set after a mid-probe stall: %v", err) + } + _ = m.Release() + if stalls != 1 { + t.Fatalf("AcquireAll intent deferrals = %d, want exactly 1 (then the final attempt)", stalls) + } +} + +// Two exclusive waiters behind one shared holder: no deadlock, both get the +// gate in turn, and the intent is handed off and finally released. +func TestTwoExclusiveWaiters(t *testing.T) { + g, _ := testGate(t) + sh := mustAcquire(t, g, Shared, Options{}) + opts := Options{Wait: 5 * time.Second, PollInterval: 10 * time.Millisecond} + x1 := acquireAsync(t, Exclusive, opts, g) + x2 := acquireAsync(t, Exclusive, opts, g) + waitQueued(t, g) + time.AfterFunc(200*time.Millisecond, func() { _ = sh.Release() }) + + var second <-chan acqResult + var r acqResult + select { + case r = <-x1: + second = x2 + case r = <-x2: + second = x1 + case <-time.After(5 * time.Second): + t.Fatal("neither exclusive waiter got the gate") + } + if r.err != nil { + t.Fatalf("first exclusive waiter: %v", r.err) + } + time.Sleep(100 * time.Millisecond) + _ = r.h.Release() + r = recv(t, second, "second exclusive waiter") + _ = r.h.Release() + if g.ExclusiveQueued() { + t.Error("intent still held after both exclusive waiters finished") + } +} + +// The nested-bd escape hatch works through a real exec: a child whose +// environment names a live ancestor skips the queue; without it, it defers. +func TestInheritedHoldThroughSubprocess(t *testing.T) { + dir := t.TempDir() + g, err := ForWorkspace(filepath.Join(dir, ".beads")) + if err != nil { + t.Fatal(err) + } + intent := g.tryTakeIntent("test queued maintenance") + if intent == nil { + t.Fatal("tryTakeIntent failed") + } + t.Cleanup(func() { g.releaseIntent(intent) }) + + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + run := func(extra ...string) string { + t.Helper() + cmd := exec.Command(exe, dir) + env := []string{"WORKSPACEGATE_HELPER=inherited-acquire"} + for _, kv := range bazeltest.ShardFreeEnv(os.Environ()) { + if !strings.HasPrefix(kv, InheritedHoldEnv+"=") { + env = append(env, kv) + } + } + cmd.Env = append(env, extra...) + out, err := cmd.Output() + if err != nil { + t.Fatalf("helper: %v (%s)", err, out) + } + return strings.TrimSpace(string(out)) + } + parse := func(out string) (bool, time.Duration) { + var inherited bool + var ms int64 + if _, err := fmt.Sscanf(out, "inherited=%t waited_ms=%d", &inherited, &ms); err != nil { + t.Fatalf("helper output %q: %v", out, err) + } + return inherited, time.Duration(ms) * time.Millisecond + } + + inh, waited := parse(run(fmt.Sprintf("%s=%d", InheritedHoldEnv, os.Getpid()))) + if !inh || waited > time.Second { + t.Errorf("child of a live shared holder: inherited=%v waited=%s, want true and no queueing", inh, waited) + } + inh, waited = parse(run()) + if inh || waited < 2*time.Second { + t.Errorf("unrelated child: inherited=%v waited=%s, want false and a full deferral", inh, waited) + } +} diff --git a/internal/workspacegate/readonly_wait_test.go b/internal/workspacegate/readonly_wait_test.go new file mode 100644 index 000000000..18b623d06 --- /dev/null +++ b/internal/workspacegate/readonly_wait_test.go @@ -0,0 +1,183 @@ +package workspacegate + +import ( + "context" + "errors" + "os" + "slices" + "testing" + "time" +) + +// A strict-readonly SHARED acquisition (Options.ReadOnly) and a waiting one +// (Options.Wait, with its writer-fairness intent queue) meet in exactly one +// place: a ReadOnly acquisition with Wait > 0. The ReadOnly tests in +// gate_test.go are all wait-less, so the tests below pin that seam: waiting +// must not make a ReadOnly acquisition create anything (no gate file, no +// intent file, no holder-info sidecar), and ReadOnly must not change how long +// a shared acquisition waits for an exclusive holder. +// +// None of them touches maxIntentHold or any other package variable a test +// shortens, and none runs in parallel with anything. + +// gateDirEntries lists dir's entries by name (os.ReadDir sorts them), so a +// test can prove an acquisition left the gate's directory as it found it. +func gateDirEntries(t *testing.T, dir string) []string { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + names := make([]string, 0, len(entries)) + for _, e := range entries { + names = append(names, e.Name()) + } + return names +} + +// (i) The gate file exists and no intent file does: a waiting ReadOnly shared +// acquisition takes the gate on its first attempt (OnWait never fires) and +// creates nothing beside it: no .intent, no .intent.info, no .info. +func TestReadOnlyWaitingSharedAcquireOfExistingGateCreatesNothing(t *testing.T) { + g, dir := testGate(t) + // Materialize the gate file the way any ordinary command does. + _ = mustAcquire(t, g, Shared, Options{}).Release() + before := gateDirEntries(t, dir) + if _, err := os.Stat(g.Path()); err != nil { + t.Fatalf("precondition: the gate file must exist: %v", err) + } + if _, err := os.Stat(g.intentPath()); !os.IsNotExist(err) { + t.Fatalf("precondition: no intent file may exist, stat err = %v", err) + } + + const wait = time.Second + var waited []string + start := time.Now() + h, err := g.Acquire(context.Background(), Shared, Options{ + ReadOnly: true, + Wait: wait, + OnWait: func(holder string) { waited = append(waited, holder) }, + }) + elapsed := time.Since(start) + if err != nil { + t.Fatalf("waiting ReadOnly shared Acquire of a free, existing gate: %v", err) + } + defer func() { _ = h.Release() }() + if len(waited) != 0 { + t.Errorf("the first attempt did not take the free gate: OnWait fired with %q", waited) + } + if elapsed >= wait { + t.Errorf("took %s, want far under its %s budget: nothing was holding the gate", elapsed, wait) + } + if h.f == nil { + t.Fatal("handle holds no file: against an existing gate file a ReadOnly acquisition is a real shared hold") + } + if got := gateDirEntries(t, dir); !slices.Equal(got, before) { + t.Errorf("waiting ReadOnly acquisition changed %s\n before: %v\n after: %v", dir, before, got) + } + // It is a real shared hold: a maintenance operation is turned away. + if _, err := g.Acquire(context.Background(), Exclusive, Options{}); !errors.Is(err, ErrBusy) { + t.Fatalf("exclusive Acquire under the ReadOnly shared holder: err = %v, want ErrBusy", err) + } + if err := h.Release(); err != nil { + t.Fatalf("Release: %v", err) + } + if got := gateDirEntries(t, dir); !slices.Equal(got, before) { + t.Errorf("after release %s\n before: %v\n after: %v", dir, before, got) + } +} + +// (ii) No gate file: nothing has ever gated here. A waiting ReadOnly shared +// acquisition returns at once with an empty handle (it holds no file and has +// nothing to wait for) and leaves the directory exactly as it was: it neither +// creates the gate file nor waits for one to appear. +func TestReadOnlyWaitingSharedAcquireOfMissingGateHoldsNothing(t *testing.T) { + g, dir := testGate(t) + before := gateDirEntries(t, dir) + if len(before) != 0 { + t.Fatalf("precondition: %s must start empty, has %v", dir, before) + } + + const wait = time.Second + var waited []string + start := time.Now() + h, err := g.Acquire(context.Background(), Shared, Options{ + ReadOnly: true, + Wait: wait, + OnWait: func(holder string) { waited = append(waited, holder) }, + }) + elapsed := time.Since(start) + if err != nil { + t.Fatalf("waiting ReadOnly shared Acquire with no gate file: %v, want success holding nothing", err) + } + if h == nil || h.f != nil { + t.Fatalf("handle = %+v, want an empty handle (no gate file was opened)", h) + } + if h.Mode() != Shared { + t.Errorf("handle mode = %s, want %s", h.Mode(), Shared) + } + if len(waited) != 0 { + t.Errorf("OnWait fired with %q: with no gate file there is nothing to wait for", waited) + } + if elapsed >= wait { + t.Errorf("took %s, want far under its %s budget: a missing gate file is answered before any retry", elapsed, wait) + } + if got := gateDirEntries(t, dir); !slices.Equal(got, before) { + t.Errorf("waiting ReadOnly acquisition changed %s\n before: %v\n after: %v", dir, before, got) + } + for i := 1; i <= 2; i++ { + if err := h.Release(); err != nil { + t.Fatalf("Release #%d of the empty handle: %v", i, err) + } + } + if got := gateDirEntries(t, dir); !slices.Equal(got, before) { + t.Errorf("after release %s\n before: %v\n after: %v", dir, before, got) + } +} + +// (iii) The gate file exists and is held EXCLUSIVELY: a waiting ReadOnly +// shared acquisition waits out its own budget, exactly like any shared +// acquisition, and then fails with ErrBusy. ReadOnly is not special-cased: +// it neither fails at once nor waits longer (the shared default is 30s, the +// init budget 60s). It also creates nothing while it waits, which is where +// the fairness probe (ExclusiveQueued) meets ReadOnly: the probe opens the +// intent file read-only and treats a missing one as "nothing queued". +func TestReadOnlyWaitingSharedAcquireUnderExclusiveHolderWaitsItsBudget(t *testing.T) { + g, dir := testGate(t) + holder := mustAcquire(t, g, Exclusive, Options{Reason: "test maintenance"}) + defer func() { _ = holder.Release() }() + before := gateDirEntries(t, dir) + + const wait = 300 * time.Millisecond + waited := 0 + start := time.Now() + h, err := g.Acquire(context.Background(), Shared, Options{ + ReadOnly: true, + Wait: wait, + OnWait: func(string) { waited++ }, + }) + elapsed := time.Since(start) + if !errors.Is(err, ErrBusy) { + if h != nil { + _ = h.Release() + } + t.Fatalf("waiting ReadOnly shared Acquire under an exclusive holder: err = %v, want ErrBusy", err) + } + // Acquire's deadline is taken after start, and it reports ErrBusy only + // once that deadline has passed, so this lower bound is exact. + if elapsed < wait { + t.Errorf("gave up after %s, before its %s budget ran out: ReadOnly must wait like any shared acquisition", elapsed, wait) + } + // The loop overshoots by at most one poll interval (100ms by default). + // The ceiling is far more generous than that so a loaded host cannot make + // this flaky; it still catches any special-cased budget. + if limit := wait + 2*time.Second; elapsed > limit { + t.Errorf("gave up after %s, want about its %s budget (at most %s)", elapsed, wait, limit) + } + if waited != 1 { + t.Errorf("OnWait fired %d times, want once (after the first busy attempt)", waited) + } + if got := gateDirEntries(t, dir); !slices.Equal(got, before) { + t.Errorf("waiting ReadOnly acquisition changed %s\n before: %v\n after: %v", dir, before, got) + } +} diff --git a/internal/worktreeremove/BUILD.bazel b/internal/worktreeremove/BUILD.bazel index ea9020fcb..9713ee55b 100644 --- a/internal/worktreeremove/BUILD.bazel +++ b/internal/worktreeremove/BUILD.bazel @@ -12,3 +12,64 @@ go_test( srcs = ["policy_test.go"], embed = [":worktreeremove"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/issue_roles_external_test.go b/issue_roles_external_test.go index f5c70fc34..1a429b5e3 100644 --- a/issue_roles_external_test.go +++ b/issue_roles_external_test.go @@ -238,6 +238,39 @@ func TestReleaserExposesTypedUnsupportedError(t *testing.T) { } } +// TestLeaseReclaimerLayersHooksOutsideTelemetry is the same pin for the +// lease-sweep role. It gives the same answer the release does and for the +// same reason: a reclaim moves assignee and status per reverted row, which +// is on_update — a hook the vocabulary publishes and a row a script can +// still read back — so this decorator wraps rather than recursing the way +// Sweeper and Deleter do. +func TestLeaseReclaimerLayersHooksOutsideTelemetry(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + reclaimer, err := storage.NewHookFiringStore(instrumented, nil).LeaseReclaimer() + if err != nil { + t.Fatalf("LeaseReclaimer() error = %v", err) + } + if got := reflect.TypeOf(reclaimer).String(); got != "*storage.hookLeaseReclaimer" { + t.Fatalf("outer layer = %s, want the hook wrapper", got) + } +} + +func TestLeaseReclaimerExposesTypedUnsupportedError(t *testing.T) { + reclaimer, err := (*dolt.DoltStore)(nil).LeaseReclaimer() + if reclaimer != nil { + t.Fatalf("LeaseReclaimer() reclaimer = %T, want nil", reclaimer) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("LeaseReclaimer() error = %v, want *beads.ErrUnsupported", err) + } +} + // TestIssueRelationsKeepsTelemetryOutermost is the READ role's version of the // pin, and it is deliberately the other answer: the hook decorator adds no // layer to a read, so the outermost thing a caller gets is the instrumented @@ -654,6 +687,35 @@ func TestGraphCounterExposesTypedUnsupportedError(t *testing.T) { } } +// TestBatchGetterKeepsTelemetryOutermost is the READ answer again: reading +// issues by id fires no completion hooks, so the hook decorator adds no layer. +func TestBatchGetterKeepsTelemetryOutermost(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + getter, err := storage.NewHookFiringStore(instrumented, nil).BatchGetter() + if err != nil { + t.Fatalf("BatchGetter() error = %v", err) + } + if got := reflect.TypeOf(getter).String(); got != "*telemetry.instrumentedBatchGetter" { + t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got) + } +} + +func TestBatchGetterExposesTypedUnsupportedError(t *testing.T) { + getter, err := (*dolt.DoltStore)(nil).BatchGetter() + if getter != nil { + t.Fatalf("BatchGetter() getter = %T, want nil", getter) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("BatchGetter() error = %v, want *beads.ErrUnsupported", err) + } +} + func TestCounterExposesTypedUnsupportedError(t *testing.T) { counter, err := (*dolt.DoltStore)(nil).Counter() if counter != nil { @@ -694,6 +756,36 @@ func TestReadyCounterExposesTypedUnsupportedError(t *testing.T) { } } +// TestBlockedListerKeepsTelemetryOutermost is the READ answer again: listing +// the blocked set fires no completion hooks, so the hook decorator adds no +// layer. +func TestBlockedListerKeepsTelemetryOutermost(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + lister, err := storage.NewHookFiringStore(instrumented, nil).BlockedLister() + if err != nil { + t.Fatalf("BlockedLister() error = %v", err) + } + if got := reflect.TypeOf(lister).String(); got != "*telemetry.instrumentedBlockedLister" { + t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got) + } +} + +func TestBlockedListerExposesTypedUnsupportedError(t *testing.T) { + lister, err := (*dolt.DoltStore)(nil).BlockedLister() + if lister != nil { + t.Fatalf("BlockedLister() lister = %T, want nil", lister) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("BlockedLister() error = %v, want *beads.ErrUnsupported", err) + } +} + // TestQuerierKeepsTelemetryOutermost is the READ answer again: a query fires no // completion hooks, so the hook decorator adds no layer. func TestQuerierKeepsTelemetryOutermost(t *testing.T) { @@ -784,3 +876,35 @@ func TestDeleterExposesTypedUnsupportedError(t *testing.T) { t.Fatalf("Deleter() error = %v, want *beads.ErrUnsupported", err) } } + +// TestHeartbeaterLayersHooksOutsideTelemetry is the same pin for the lease +// refresh. It gives the release's answer: a refresh fires nothing, but a +// re-arm is recorded as a mutation and fires on_update +// (internal/storage/hook_heartbeater.go), so this decorator wraps rather than +// recursing the way Sweeper and Deleter do. +func TestHeartbeaterLayersHooksOutsideTelemetry(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + heartbeater, err := storage.NewHookFiringStore(instrumented, nil).Heartbeater() + if err != nil { + t.Fatalf("Heartbeater() error = %v", err) + } + if got := reflect.TypeOf(heartbeater).String(); got != "*storage.hookHeartbeater" { + t.Fatalf("outer layer = %s, want the hook wrapper", got) + } +} + +func TestHeartbeaterExposesTypedUnsupportedError(t *testing.T) { + heartbeater, err := (*dolt.DoltStore)(nil).Heartbeater() + if heartbeater != nil { + t.Fatalf("Heartbeater() heartbeater = %T, want nil", heartbeater) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("Heartbeater() error = %v, want *beads.ErrUnsupported", err) + } +} diff --git a/issueops/BUILD.bazel b/issueops/BUILD.bazel index eb0076988..01800eded 100644 --- a/issueops/BUILD.bazel +++ b/issueops/BUILD.bazel @@ -6,22 +6,33 @@ go_library( "batchapplier.go", "batchcloser.go", "batchcreator.go", + "batchgetter.go", + "blockedlister.go", "blockedstate.go", "blockingannotator.go", "bootstrapper.go", "claimer.go", "commenter.go", "counter.go", + "current.go", "cycledetector.go", "deleter.go", "dependencyeditor.go", "edgereader.go", "errors.go", + "export.go", + "gates.go", "graphcounter.go", + "heartbeater.go", "importer.go", "initverifier.go", "issueops.go", + "leasereclaimer.go", "metadatacas.go", + "molecule.go", + "molecule_active.go", + "moleculestepper.go", + "promote.go", "querier.go", "reader.go", "reader_ready_scope.go", @@ -29,8 +40,10 @@ go_library( "readycounter.go", "relations.go", "releaser.go", + "search.go", "statsreporter.go", "sweeper.go", + "template_errors.go", "treewalker.go", "versionreconciler.go", "workspaceconfig.go", @@ -47,11 +60,21 @@ go_test( name = "issueops_test", srcs = [ "claimer_external_test.go", + "current_test.go", + "export_test.go", + "gates_test.go", + "heartbeater_test.go", "issueops_external_test.go", + "molecule_internal_test.go", + "molecule_test.go", + "promote_test.go", + "search_test.go", ], + embed = [":issueops"], deps = [ - ":issueops", "//:beads", + "//internal/types", + "//internal/workapi", ], ) @@ -67,3 +90,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/issueops/batchapplier.go b/issueops/batchapplier.go index 8eff362fb..71116da50 100644 --- a/issueops/batchapplier.go +++ b/issueops/batchapplier.go @@ -100,11 +100,16 @@ type CreateItem struct { // A caller reading the event stream sees a create and then an update, not // one create carrying values nothing could have known yet. MetadataRefs map[string]Ref + // DefaultPriority is CreateRequest.DefaultPriority for this item: the item + // has no priority, and the create stores DefaultCreatePriority. + DefaultPriority bool } // UpdateItem patches one existing issue, under UpdateRequest's rules. type UpdateItem struct { - // Target names the issue to patch and must resolve BACKWARD — see Ref. + // Target names the issue to patch and must resolve BACKWARD — see Ref. A + // template target refuses with *TemplateReadOnlyError, exactly as + // Lifecycle.Update does: templates are read-only. Target Ref // Patch is the edit, read exactly as UpdateRequest.Patch is — including // that Patch.Labels is the whole LabelPatch, so a label REMOVAL is @@ -165,7 +170,8 @@ type CloseItem struct { // Reason and Session are CloseRequest's, under its first-close-wins rule. Reason string Session string - // Force bypasses blocker and open-child close policy, and nothing else. + // Force is CloseRequest.Force: it bypasses blocker and open-child close + // policy, the pin and the assignee fence, and never the template guard. // // CLOSE POLICY EVALUATES AT THIS ITEM, against the row as this request has // already changed it — the same as-modified rule the update guards take. A @@ -219,6 +225,37 @@ type DepAddItem struct { // members — a spawner, an also-blocks flag — a two-field typed member could // not express. One spelling, and it is this one. Metadata string + // HasSpawner marks a DepWaitsFor edge whose caller explicitly named a + // spawner: a graph plan's edges[].spawner_key/spawner_id, which bd create + // --graph's plan validator forces to equal the edge's own Target. It has + // two producers: bd create --graph itself, which sets it from those + // members on the embedded and proxied legs alike (cmd/bd's + // buildGraphApplyBatchRequest), and an embedder lowering such a plan onto + // this role (gc's ApplyGraphPlan mapping, on BatchApplier below). Only + // when it is set does the role stamp Metadata's spawner_id from the + // resolved Target, once every id in the batch exists (see + // StampWaitsForSpawnerID) — a plan-local spawner key cannot be resolved + // any earlier than that. + // + // AN EDGE WITH NO NAMED SPAWNER MUST KEEP ITS GATE-ONLY METADATA. Stamping + // one in regardless of this flag — the 2026-10 Opus-review HIGH-2 finding + // — produces metadata an unspawnered edge's caller never asked for, which + // is a stored row a later re-apply of the same plan (e.g. by gc) will see + // disagree with what it sent, causing a spurious rewrite and version + // churn the role must not manufacture on its own. Ignored for every other + // Type. + HasSpawner bool + // ThreadID carries conversation-threading metadata (e.g. a replies-to + // edge's originating thread) onto the dependency row. Empty means the edge + // carries none; it is a plain column, not part of Metadata's type-specific + // blob, and one longer than the column holds is ErrValidation. + // + // A RE-ADD OF AN EDGE THAT ALREADY EXISTS WITH THE SAME TYPE CARRIES IT + // TOO. A thread the stored row does not already carry replaces it, and + // versions the source on the same terms as a Metadata change; an empty + // ThreadID keeps the stored thread rather than clearing it, so a re-apply + // that names none cannot erase one. + ThreadID string } // ApplyItem is ONE item of a batch: a kind plus exactly one member matching it. @@ -537,6 +574,29 @@ func HasExtendedRetryBudget(ctx context.Context) bool { // directly. `bd create --file` and `bd dep add --file` remain the file-shaped // front doors for the two homogeneous cases they already serve. // +// TWO EMBEDDER OPERATIONS MAP ONTO THIS ROLE RATHER THAN EARNING THEIR OWN +// (DESIGN §3.8, "Guarded writes: NO NEW ROLES"). Neither needs a new role or a +// new wire member; both are a SHAPE of ApplyBatchRequest, pinned by an +// http-leg conformance case so the shape does not drift under either side +// independently: +// +// - CloseWithMetadataIfMatch is an update item carrying a Metadata patch and +// ExpectedVersion, followed by a close item on the SAME target, in ONE +// request: []ApplyItem{{Kind: ItemUpdate, Update: &UpdateItem{Target: t, +// Patch: IssuePatch{Metadata: ...}, ExpectedVersion: &v}}, {Kind: ItemClose, +// Close: &CloseItem{Target: t}}}. It is atomic because the whole request is: +// a stale ExpectedVersion refuses the update, which refuses the request, and +// the close never runs — zero rows change. CloseItem itself carries no +// metadata member; this composition is the only way to land a metadata +// write and a close as one guarded act. +// - ApplyGraphPlan is a create item per node (Key, the issue's Labels and +// Metadata, Ephemeral, NoHistory, and MetadataRefs for a value only the +// plan's own later ids can supply), dep_add items for every edge the plan +// names — parent-child included, since a parent is a dep_add item of type +// parent-child like any other edge — and trailing update items for an +// AssignAfterCreate step, which patches a just-created row's Assignee by +// its backward Key reference. One request, declaration order, one outcome. +// // Implementations never mutate caller-owned request values, snapshot the // request at method entry, and apply validation and normalization only to // attempt-local clones. Deterministic request-validation failures match diff --git a/issueops/batchcloser.go b/issueops/batchcloser.go index f557a791b..a2c907bdf 100644 --- a/issueops/batchcloser.go +++ b/issueops/batchcloser.go @@ -40,10 +40,11 @@ type CloseBatchRequest struct { Items []BatchCloseItem // Session records the closing session against every item. Session string - // Force bypasses only blocker and open-child close policy, for every item. - // It never bypasses validation, and it never bypasses existence: an id that - // names nothing refuses whether or not force is set. It is request-wide - // because the flag that spells it is. + // Force bypasses blocker and open-child close policy, the pin and the + // assignee fence, for every item — exactly CloseRequest.Force. It never + // bypasses the template guard or validation, and it never bypasses + // existence: an id that names nothing refuses whether or not force is set. + // It is request-wide because the flag that spells it is. // // It would not bypass a per-item LIFECYCLE PRECONDITION either, but no // batch item carries one: there is no counterpart here to the @@ -68,6 +69,15 @@ type CloseBatchRequest struct { // rule, the same nil-means-nothing-eligible outcome. Restating them here // is how the two would come apart. ClaimNext *ReadyRequest + // AutoCloseMolecule is CloseRequest.AutoCloseMolecule for every item + // that closed or was already closed. It runs after all the closes and + // before ClaimNext, inside the same transaction, so a batch that closes + // several steps of one molecule decides its root once, after every close: + // the root it closed, or its refusal, is reported on the outcome of the + // first item under that root whose Err is nil. An auto-closed root is a + // landing: it is named in the batch's history entry. It does not earn + // ClaimNext's claim on its own. + AutoCloseMolecule bool } // CloseOutcome is what happened to ONE requested item. @@ -84,9 +94,14 @@ type CloseOutcome struct { // OpenChildren is the number of open children observed by a forced close // of this item. It is reported even for an idempotent re-close. OpenChildren int + // AutoClosedMolecule and MoleculeAutoCloseRefusal are + // CloseResult's, for this item, under CloseBatchRequest.AutoCloseMolecule. + AutoClosedMolecule *Issue + MoleculeAutoCloseRefusal string // Err is this item's refusal, and NEVER aborts the rest of the batch. It // carries the same typed close vocabulary Lifecycle.Close returns — - // ErrNotFound, ErrCloseBlocked, *CloseOpenChildrenError — so a caller + // ErrNotFound, ErrCloseBlocked, *CloseOpenChildrenError, + // *TemplateReadOnlyError, *PinnedError, *CloseNotAssigneeError — so a caller // classifies it with errors.Is and errors.As rather than by reading prose. Err error } diff --git a/issueops/batchcreator.go b/issueops/batchcreator.go index e75e1fbbc..f3fbe8316 100644 --- a/issueops/batchcreator.go +++ b/issueops/batchcreator.go @@ -43,6 +43,8 @@ type BatchCreateItem struct { // referred to at all, because nothing can name an id that does not exist // yet. Dependencies []CreateDependency + // DefaultPriority is CreateRequest.DefaultPriority for this item. + DefaultPriority bool } // CreateBatchRequest describes one creation of many issues. diff --git a/issueops/batchgetter.go b/issueops/batchgetter.go new file mode 100644 index 000000000..6d6914c41 --- /dev/null +++ b/issueops/batchgetter.go @@ -0,0 +1,149 @@ +package issueops + +import ( + "context" + "fmt" +) + +// MaxGetManyIDs is the largest request this role accepts in one call. It is a +// FLAT bound on the request, not a cost model over what a backend does with +// it: GetMany reads every named id in ONE snapshot, so the bound is really a +// bound on how long one request may hold a single read open. +// +// 1000 is the same number BatchApplier settled on (issueops.MaxApplyBatchItems) +// and the same number DeleteRequest.IDs caps at on the wire +// (openapi.v0.yaml's DeleteIssuesRequest). It is not borrowed for symmetry: a +// caller fanning out gc's ready veto or the CLI's own id-resolution passes +// already walks lists in exactly this range, and a cap an order of magnitude +// smaller would just reintroduce the per-id fan-out this role exists to +// replace. +const MaxGetManyIDs = 1000 + +// TooManyIDsError reports that a GetManyRequest named more ids than this role +// accepts in one call. It wraps ErrValidation, so a caller that only checks +// for a usable request classifies it correctly without knowing this type +// exists, and errors.As gets at Requested and Cap for a caller that wants to +// say how far over the line the request was. +type TooManyIDsError struct { + // Requested is the number of ids the request named, counted BEFORE + // deduplication: a caller that sent 1500 mentions of 3 distinct ids typed + // a request this role still refuses, because the obligation this cap + // bounds is reading the request apart, not reading the rows it resolves + // to. + Requested int + // Cap is MaxGetManyIDs, carried on the error so a caller does not need the + // constant in scope to report what it hit. + Cap int +} + +func (e *TooManyIDsError) Error() string { + return fmt.Sprintf("get many accepts at most %d ids, got %d", e.Cap, e.Requested) +} + +// Unwrap makes TooManyIDsError match ErrValidation. +func (e *TooManyIDsError) Unwrap() error { return ErrValidation } + +// GetManyRequest names the issues to fetch in one read. +// +// Implementations never mutate caller-owned request values: IDs is read, +// never written through, and never sorted in place. +type GetManyRequest struct { + // IDs names the issues to fetch, in either plane, exact ids only. Prefix + // resolution and bd's other id conveniences happen at the front door, + // above this role, the same boundary DeleteRequest.IDs draws. + // + // DUPLICATES COLLAPSE and the surviving order is the caller's first + // mention of each id: a caller that asks for [a, b, a] gets back Issues + // in the order [a, b] (whichever of those resolve) and nothing about a + // twice. + // + // AN ID THAT NAMES NO STORED ROW IS NOT AN ERROR. It is reported in + // GetManyResult.Missing beside whatever else resolved — the same + // result-field answer EdgeCountResult.Anchors and EdgeReadResult give a + // miss, and the reason GetMany does not return ErrNotFound the way + // DeleteRequest's all-or-nothing id check does: a batch GET is a set + // read, not a precondition on every member succeeding. + // + // MORE THAN MaxGetManyIDs IS A REFUSAL: a *TooManyIDsError, counted on + // the request as sent, before deduplication. + // + // An empty slice is not an error. It answers with an empty result, the + // same empty-request answer EdgeCountRequest.IDs documents, because "no + // ids" is a legitimate thing to ask for 0 issues about and a caller that + // built its list by filtering should not have that filter's empty result + // turned into a different kind of failure than the one it already knows + // how to handle. + IDs []string +} + +// GetManyResult answers a GetManyRequest from one snapshot. +type GetManyResult struct { + // Issues holds the hydrated rows for every id that resolved, in the + // REQUEST's order (the caller's first mention of each distinct id), never + // the storage engine's natural order. Each Issue carries its current + // RowVersion, so a caller that goes on to write one back has the + // optimistic-concurrency token a lifecycle write wants without a second + // round trip. + // + // HYDRATION IS LABELS ONLY: no dependencies, dependents or comments. A + // caller that needs those calls Reader.Get instead, one id at a time. + // + // Never nil for a successful call, even when it is empty: a front door + // that marshals this field emits [] rather than null, the same promise + // EdgeCountResult.Anchors makes. + Issues []*Issue + // Missing names every requested id that resolved to no stored row, in the + // same first-mention order as the request. An id that appears in Missing + // does not appear in Issues, and the two slices' lengths sum to the + // number of DISTINCT ids the request named. + // + // Never nil for a successful call: an all-found request answers with an + // empty, non-nil Missing. + Missing []string +} + +// BatchGetter reads many issues by id in one snapshot. +// +// It exists because the obvious way to read N issues — one Get per id — is +// what gc's ready veto and the bd CLI both do today, and it costs N round +// trips (or N transactions, for a backend where each Get opens its own) to +// answer a single question a caller already knows the shape of: "which of +// these ids exist, and what do they look like right now." BatchGetter answers +// that in one call over one snapshot, the same trade EdgeCountRequest.IDs and +// EdgeReadRequest make for the edge-shaped versions of the same question. +// +// IT IS A FACADE-ONLY ROLE, for now: this slice wires every library leg +// (dolt, embedded dolt, the unit-of-work provider) and the +// POST /v0/beads/issues:batchGet HTTP handler, but ships no HTTP CLIENT leg. +// A caller on the wrong side of that door reaches this role through the raw +// HTTP request the handler answers, not through a typed client method, until +// the client generator lands (see the TODO beside the CLI call sites this +// slice did not migrate, and PR #7247). A later slice updates this doc and the +// client-side TODOs together once that leg exists. +// +// It differs from Reader.Get in arity, in hydration and in what a miss means: +// Get answers ONE id with *IssueDetails or ErrNotFound, labels, dependencies, +// dependents and comments included; this answers MANY ids with a result +// whose Missing field is how a caller tells "this one does not exist" from +// "the call failed," and whose Issues are hydrated LABELS ONLY — no +// dependencies, dependents or comments. A caller that needs those calls +// Reader.Get instead, one id at a time. It differs from EdgeReader and +// GraphCounter in what it is reading: those answer questions about the EDGES +// a set of anchors carries; this answers the ISSUES themselves. +type BatchGetter interface { + // GetMany reads every id GetManyRequest.IDs names, in ONE snapshot. The + // existence check and the hydration share that snapshot for the reason + // ExecuteEdgeCount's probe-and-tally share one: a probe in its own + // transaction could report an id missing while a second transaction + // created it, contradicting itself in one response body. + // + // Refuses with: + // - *TooManyIDsError, wrapping ErrValidation, when IDs carries more than + // MaxGetManyIDs entries (counted before deduplication); + // - ErrValidation for an empty-string entry in IDs, the same per-entry + // check EdgeCountRequest.IDs applies. + // + // Never returns ErrNotFound: an id naming no stored row is reported in + // GetManyResult.Missing, not refused. + GetMany(ctx context.Context, request GetManyRequest) (GetManyResult, error) +} diff --git a/issueops/blockedlister.go b/issueops/blockedlister.go new file mode 100644 index 000000000..d02753fb5 --- /dev/null +++ b/issueops/blockedlister.go @@ -0,0 +1,64 @@ +package issueops + +import ( + "context" + + "github.com/steveyegge/beads/internal/types" +) + +// BlockedIssue is one row of the blocked listing: the issue, plus the ids of +// the blockers bd names for it. It is the element type `bd blocked --json` +// emits. +type BlockedIssue = types.BlockedIssue + +// BlockedRequest is the question `bd blocked` asks: which issues are blocked, +// optionally narrowed by parent and labels. +// +// Its fields are the command's flags, one for one. Labels are normalized the +// way every label filter is (trimmed, blanks and repeats dropped) on an +// attempt-local copy; the caller's slices are never written. +type BlockedRequest struct { + // ParentID narrows to the parent's direct children (a parent-child edge) + // and to ids under it in the dotted hierarchy. Empty means no narrowing. + ParentID string + // Labels must all be present (AND). + Labels []string + // LabelsAny needs at least one present (OR). + LabelsAny []string + // ExcludeLabels must all be absent. + ExcludeLabels []string +} + +// BlockedResult is the blocked listing. +type BlockedResult struct { + // Items is ordered by priority ascending, then created_at descending, + // then id. It is never nil: an empty listing is an empty slice, so a + // front door that encodes it prints [] and never null. + Items []*BlockedIssue +} + +// BlockedLister describes listing the blocked issues: what `bd blocked` +// prints. Like Reader and ReadyCounter, it is a role with its own accessor. A +// new capability gets a new role interface and its own accessor; never append +// a method here. +// +// THE SET IS bd's BLOCKED DOOR, NOT THE RAW COLUMN. It is seeded from the +// stored, transitively propagated is_blocked flag on both planes (issues and +// wisps; closed and pinned-status rows excluded; no type exclusions), then +// narrowed to rows bd can NAME a blocker for: an active blocks, waits-for or +// conditional-blocks target resident in this workspace that is neither closed +// nor pinned, else the parent. A row whose flag is set but which has neither +// is not listed. Where the external-dependency policy applies, an unsatisfied +// external: blocker is added to the row's blockers, and a row blocked only by +// such refs is listed too, narrowed by the request's parent and label filters +// like every other row. +// +// IT IS NOT A PAGE. There is no limit and no cursor, like the local command, +// and an answer is never truncated. +// +// LISTING IS A READ. Nothing here records a history entry, fires a completion +// hook or changes a row. Result values are unspecified when error is non-nil. +type BlockedLister interface { + // ListBlocked answers one blocked listing in one read. + ListBlocked(ctx context.Context, req BlockedRequest) (BlockedResult, error) +} 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 +} diff --git a/issueops/counter.go b/issueops/counter.go index 594ec4add..c991f6dda 100644 --- a/issueops/counter.go +++ b/issueops/counter.go @@ -54,6 +54,17 @@ type CountRequest struct { // than quietly tightened, because a scripted caller that counts a status // its workspace has since dropped currently reads 0 and would start reading // an error. + // + // "all" is this field's one well-defined non-literal spelling, and it is + // NOT ErrValidation: it is equivalent to leaving Status empty, and + // BuildListFilter treats its own "all" selector identically (the no-filter + // spelling), so `bd count --status all ` and `bd list --status + // all --all` already agree on cardinality for the shared part + // of the predicate. Rejecting it here would break that count/list parity + // (the whole point of this role, GH#4387) for every caller already + // spelling it, and there is no caller-visible ambiguity it would resolve: + // "no status" is a filter that excludes every row, which "all" has never + // meant on either front door. Status string // IssueType restricts the type, with the same match-nothing-rather-than-fail // treatment Status gets and no alias expansion at all. @@ -66,6 +77,24 @@ type CountRequest struct { // written and answer with the empty intersection. Assignee string + // ParentID restricts to one issue's children, spelled as + // ListRequest.ParentID spells it: a parent-child dependency edge, OR (for + // an issue with no such edge) a dotted-id prefix match. NoParent restricts + // to rows with no parent-child dependency edge. It does not consult the + // dotted-id convention, so an edge-less dotted-id child (X.1) still counts + // as top-level — it is counted by BOTH ParentID X and NoParent, as it is + // listed by both `bd list --parent X --flat` and `bd list --no-parent`. + // + // Setting both IS refused, as ErrValidation, UNLIKE Assignee/NoAssignee + // above: `bd list`'s CLI already refuses `--parent` with `--no-parent` + // (cmd/bd/list_input.go) with this same wording, and a caller reaching + // this role directly — over HTTP, or through a future client that skips + // the primary CLI's flag parser — gets the identical refusal rather than + // a silent empty-intersection answer the primary CLI would never have let + // it ask for. + ParentID string + NoParent bool + // Priority is an exact priority; PriorityMin and PriorityMax bound a range // inclusively. All three are pointers because 0 is a real priority, for the // reason ReadyRequest.Priority gives. @@ -86,6 +115,23 @@ type CountRequest struct { // rather than a slice it had to prepare. IDFilter string + // ExcludeTypes names types to exclude, spelled as ListRequest.ExcludeTypes + // spells it: entries may be comma-separated, splitting and normalization + // happen inside, and an entry is NOT validated against the workspace + // vocabulary — an unrecognized type excludes nothing rather than failing. + // It composes with IncludeInfra's own "gate" exclusion rather than + // replacing it: both contribute to the same exclusion set. + ExcludeTypes []string + // ExcludeStatus names statuses to exclude (behavior token + // `issues.count.scope`; ListRequest.ExcludeStatus is its listing twin, + // validated by the same rule): entries may be comma-separated, and — UNLIKE + // Status and ExcludeTypes above — each name IS validated against the + // workspace vocabulary (built-in statuses plus the workspace's own custom + // ones). An unrecognized name is ErrValidation rather than excluding + // nothing: a caller building an exclusion list by hand gets a loud failure + // on a typo instead of a silently wider, overcounted answer. + ExcludeStatus []string + // TitleContains, DescContains and NotesContains are substring matches on // the three long fields, spelled as ListRequest spells them so the two // requests cannot drift apart in naming while meaning the same thing. @@ -119,7 +165,8 @@ type CountRequest struct { // - template molecules are excluded, which a default count includes; // - gate beads are excluded, unless IssueType asks for gates by name; // - an IssueType the workspace calls infra routes the count to the - // ephemeral tier instead of the durable one. + // ephemeral tier instead of the durable one — unless IncludeEphemeral + // is also set, which lifts that routing, as it does for a listing. // // The infra vocabulary is the WORKSPACE's, read from configuration inside // the implementation. A caller does not supply it and cannot: that is the @@ -150,6 +197,11 @@ type CountRequest struct { // it; only IncludeInfra sets out to reconcile cardinality, and it pays for // that with three changes beyond the plane. // + // Beside IncludeInfra it does one thing more, the same thing it does to a + // listing: it lifts the fourth change's routing of an infra IssueType, so + // the durable rows of that type (a promoted wisp, a retyped issue) are + // counted along with its wisps rather than instead of them. + // // Unset — and with IncludeInfra also unset — the count is durable-plane // only: the historical answer, unchanged. IncludeEphemeral bool diff --git a/issueops/current.go b/issueops/current.go new file mode 100644 index 000000000..30371185e --- /dev/null +++ b/issueops/current.go @@ -0,0 +1,64 @@ +package issueops + +import ( + "context" + "fmt" + "strings" + + "github.com/steveyegge/beads/internal/types" +) + +// CurrentIssueStatuses is the order FindCurrentIssue looks in: the actor's +// in-progress work first, then work hooked to it. +var CurrentIssueStatuses = []types.Status{types.StatusInProgress, types.StatusHooked} + +// FindCurrentIssue answers `bd show --current`'s question — which issue is +// this actor working on — through the Querier role, which every backend +// serves (a remote one as queryIssues). It returns the id of the first issue +// in the actor's in-progress work, else the first hooked to it, in the store's +// default order; "" when both reads answered and found nothing. +// +// A FAILED READ IS AN ERROR, never a miss. A caller falls back (to the +// last-touched issue, say) only on "", which only two reads that answered can +// produce. Treating a refusal as "nothing in progress" is what made the http +// backend print the wrong issue with exit 0. +// +// Each read is exactly the filter `status=`, `assignee=` and nothing +// else, one row. The actor travels as a quoted query value. The query language +// reads `assignee=none` and `assignee=null` (any case) as "no assignee", so an +// actor by one of those names, or an empty actor, cannot be asked about and +// gets "". +func FindCurrentIssue(ctx context.Context, querier Querier, actor string) (string, error) { + if querier == nil || actor == "" || strings.EqualFold(actor, "none") || strings.EqualFold(actor, "null") { + return "", nil + } + for _, status := range CurrentIssueStatuses { + page, err := querier.Query(ctx, currentIssueQuery(status, actor)) + if err != nil { + return "", fmt.Errorf("finding the current issue (%s, assigned to %s): %w", status, actor, err) + } + for _, row := range page.Items { + if row != nil && row.Issue != nil { + return row.ID, nil + } + } + } + return "", nil +} + +// currentIssueQuery is the role request for one status. No display order: +// every backend answers in its default order, and a sort would change which +// row is "current". +func currentIssueQuery(status types.Status, actor string) QueryRequest { + one := 1 + return QueryRequest{ + Expression: fmt.Sprintf("status=%s AND assignee=%s", status, quoteQueryValue(actor)), + Limit: &one, + } +} + +// quoteQueryValue renders v as a double-quoted query-language string, escaping +// the two characters the lexer gives meaning inside one. +func quoteQueryValue(v string) string { + return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(v) + `"` +} diff --git a/issueops/current_test.go b/issueops/current_test.go new file mode 100644 index 000000000..d69170ff9 --- /dev/null +++ b/issueops/current_test.go @@ -0,0 +1,154 @@ +package issueops_test + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" +) + +type currentQueryResponse struct { + ids []string + err error +} + +type currentQueryRecorder struct { + responses []currentQueryResponse + calls []issueops.QueryRequest +} + +func (r *currentQueryRecorder) Query(_ context.Context, req issueops.QueryRequest) (issueops.IssuePage, error) { + r.calls = append(r.calls, req) + response := r.responses[len(r.calls)-1] + if response.err != nil { + return issueops.IssuePage{}, response.err + } + items := make([]*types.IssueWithCounts, 0, len(response.ids)) + for _, id := range response.ids { + items = append(items, &types.IssueWithCounts{Issue: &types.Issue{ID: id}}) + } + return issueops.IssuePage{Items: items}, nil +} + +func wantCurrentQueries(quotedActor string, statuses ...types.Status) []issueops.QueryRequest { + one := 1 + want := make([]issueops.QueryRequest, 0, len(statuses)) + for _, status := range statuses { + want = append(want, issueops.QueryRequest{ + Expression: "status=" + string(status) + " AND assignee=" + quotedActor, + Limit: &one, + }) + } + return want +} + +func TestFindCurrentIssueInProgressShortCircuits(t *testing.T) { + q := ¤tQueryRecorder{responses: []currentQueryResponse{{ids: []string{"in-progress-first", "in-progress-second"}}}} + got, err := issueops.FindCurrentIssue(context.Background(), q, "tester") + if err != nil || got != "in-progress-first" { + t.Fatalf("FindCurrentIssue = (%q, %v), want (in-progress-first, nil)", got, err) + } + if want := wantCurrentQueries(`"tester"`, types.StatusInProgress); !reflect.DeepEqual(q.calls, want) { + t.Fatalf("Query calls = %#v, want %#v", q.calls, want) + } +} + +func TestFindCurrentIssueFindsHookedAfterInProgressMiss(t *testing.T) { + q := ¤tQueryRecorder{responses: []currentQueryResponse{{}, {ids: []string{"hooked"}}}} + got, err := issueops.FindCurrentIssue(context.Background(), q, "tester") + if err != nil || got != "hooked" { + t.Fatalf("FindCurrentIssue = (%q, %v), want (hooked, nil)", got, err) + } + if want := wantCurrentQueries(`"tester"`, types.StatusInProgress, types.StatusHooked); !reflect.DeepEqual(q.calls, want) { + t.Fatalf("Query calls = %#v, want %#v", q.calls, want) + } +} + +func TestFindCurrentIssueAnswersEmptyAfterTwoMisses(t *testing.T) { + q := ¤tQueryRecorder{responses: []currentQueryResponse{{}, {}}} + got, err := issueops.FindCurrentIssue(context.Background(), q, "tester") + if err != nil || got != "" { + t.Fatalf("FindCurrentIssue = (%q, %v), want (\"\", nil)", got, err) + } +} + +// TestFindCurrentIssueNeverTakesAFailureForAMiss is S6e: a refused or failed +// read used to fall through to the next read and then to the last-touched +// issue, so `bd show --current` printed the WRONG issue, exit 0. +func TestFindCurrentIssueNeverTakesAFailureForAMiss(t *testing.T) { + refusal := errors.New("SearchIssues: not supported over HTTP") + for _, tc := range []struct { + name string + responses []currentQueryResponse + calls int + }{ + {"in-progress read fails", []currentQueryResponse{{err: refusal}}, 1}, + {"hooked read fails", []currentQueryResponse{{}, {err: refusal}}, 2}, + } { + t.Run(tc.name, func(t *testing.T) { + q := ¤tQueryRecorder{responses: tc.responses} + got, err := issueops.FindCurrentIssue(context.Background(), q, "tester") + if !errors.Is(err, refusal) || got != "" { + t.Fatalf("FindCurrentIssue = (%q, %v), want (\"\", an error wrapping %v)", got, err, refusal) + } + if len(q.calls) != tc.calls { + t.Fatalf("query calls = %d, want %d", len(q.calls), tc.calls) + } + }) + } +} + +// TestFindCurrentIssueQuotesTheActor pins that an actor is one quoted value, +// whatever it contains, so it can neither break the parse nor splice in a +// clause. +func TestFindCurrentIssueQuotesTheActor(t *testing.T) { + q := ¤tQueryRecorder{responses: []currentQueryResponse{{ids: []string{"x"}}}} + if _, err := issueops.FindCurrentIssue(context.Background(), q, `gastown/polecats/ru"st\ AND status=closed`); err != nil { + t.Fatal(err) + } + if want := wantCurrentQueries(`"gastown/polecats/ru\"st\\ AND status=closed"`, types.StatusInProgress); !reflect.DeepEqual(q.calls, want) { + t.Fatalf("Query calls = %#v, want %#v", q.calls, want) + } +} + +// TestFindCurrentIssueSkipsActorsItCannotAskAbout pins the actors the query +// language cannot express: `assignee=none`/`null` mean "no assignee", which +// would name some unassigned issue as this actor's. +func TestFindCurrentIssueSkipsActorsItCannotAskAbout(t *testing.T) { + for _, actor := range []string{"", "none", "NULL"} { + q := ¤tQueryRecorder{} + got, err := issueops.FindCurrentIssue(context.Background(), q, actor) + if err != nil || got != "" || len(q.calls) != 0 { + t.Fatalf("actor %q: got (%q, %v) after %d queries, want (\"\", nil) after none", actor, got, err, len(q.calls)) + } + } +} + +// TestFindCurrentIssueQueryMeansTheRawFilter pins that each read evaluates to +// exactly `status=`, `assignee=` — no predicate half, no default +// closed exclusion, no sort — so the store answers it with the same rows in +// the same default order the raw read did. +func TestFindCurrentIssueQueryMeansTheRawFilter(t *testing.T) { + for _, actor := range []string{"tester", "gastown/polecats/rust", `we"ird\name`, "has space"} { + q := ¤tQueryRecorder{responses: []currentQueryResponse{{}, {}}} + if _, err := issueops.FindCurrentIssue(context.Background(), q, actor); err != nil { + t.Fatal(err) + } + for i, req := range q.calls { + plan, err := workapi.BuildQueryPlan(req) + if err != nil { + t.Fatalf("actor %q read %d: %v", actor, i, err) + } + f := plan.Filter + status := issueops.CurrentIssueStatuses[i] + if plan.RequiresPredicate() || f.Status == nil || *f.Status != status || f.Assignee == nil || *f.Assignee != actor || + f.NoAssignee || len(f.ExcludeStatus) != 0 || f.Limit != 1 || f.SortBy != "" { + t.Fatalf("actor %q status %s: plan = %+v", actor, status, plan) + } + } + } +} diff --git a/issueops/dependencyeditor.go b/issueops/dependencyeditor.go index f9b0683eb..16cfc1b5b 100644 --- a/issueops/dependencyeditor.go +++ b/issueops/dependencyeditor.go @@ -2,6 +2,8 @@ package issueops import ( "context" + "fmt" + "strings" "github.com/steveyegge/beads/internal/types" ) @@ -147,12 +149,20 @@ type RemoveDependencyResult struct { type DependencyEditor interface { // AddDependencies asserts every edge in the request as ONE durable act: // one transaction, one history entry. Any refused edge refuses the whole - // request and writes nothing — a self-dependency (ErrSelfDependency), a - // scheduling cycle (ErrDependencyCycle), a conflicting type on a pair that - // already has an edge (*DependencyTypeConflictError), a blocking edge that - // would gate an issue on its own ancestor or descendant - // (*DependencyHierarchyConflictError), or a SOURCE that does not exist - // (ErrDependencySourceNotFound). + // request and writes nothing — a self-dependency (ErrSelfDependency), an + // explicit edge from a dotted-id child to its own ancestor + // (*DottedChildDependencyError), a scheduling cycle (ErrDependencyCycle), + // a conflicting type on a pair that already has an edge + // (*DependencyTypeConflictError), a blocking edge that would gate an issue + // on its own ancestor or descendant (*DependencyHierarchyConflictError), + // or a SOURCE that does not exist (ErrDependencySourceNotFound). + // + // The dotted-child refusal is decided from the request alone, before any + // read, so it takes precedence over every refusal that reads stored rows: + // a child whose parent-child edge to that parent is already stored (the + // `bd create --parent` shape) is refused with *DottedChildDependencyError, + // which matches ErrValidation, not with the hierarchy or type conflict the + // stored edge would otherwise raise. // // A target's existence is checked only where the backend can see it. A // target may legitimately be an "external:" reference or an issue in @@ -188,3 +198,72 @@ type DependencyEditor interface { // missing edge is Removed false with a nil error, not ErrNotFound. RemoveDependency(ctx context.Context, req RemoveDependencyRequest) (RemoveDependencyResult, error) } + +// DottedChildDependencyError refuses an explicit edge from a dotted-id child to +// its own ancestor. The id already says "bd-abc.1 is under bd-abc": a child +// inherits its parent's completion through the hierarchy, so a blocking (or any +// other) explicit edge back up the tree either duplicates that structure or, for +// a blocking type, deadlocks it — the parent cannot close before the child, and +// the child would wait on the parent. +// +// The one edge it allows is the hierarchy itself: a parent-child edge to the +// IMMEDIATE dotted parent. A parent-child edge to a higher ancestor is refused +// too, because it would contradict the parent the id names. +// +// It unwraps to ErrValidation: the refusal is decidable from the two ids and +// the type alone, with no read, so it is a property of the request. +// +// The message is the sentence `bd dep add` already printed, kept verbatim, so +// it says "deadlock" whatever the type; Type is carried for callers that +// inspect the refusal and is not rendered. +type DottedChildDependencyError struct { + IssueID string + DependsOnID string + Type DependencyType +} + +func (e *DottedChildDependencyError) Error() string { + return fmt.Sprintf("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", + e.IssueID, e.DependsOnID) +} + +// Unwrap classifies the refusal as request validation. +func (e *DottedChildDependencyError) Unwrap() error { return ErrValidation } + +// IsDottedChildDependency reports whether an edge from issueID to dependsOnID +// of type depType is the dotted-id hierarchy conflict CheckDottedChildDependency +// refuses. It is exported for callers that phrase the refusal themselves (a +// bulk report naming the offending line); every role enforces it through +// CheckDottedChildDependency. +func IsDottedChildDependency(issueID, dependsOnID string, depType DependencyType) bool { + _, immediateParent, depth := types.ParseHierarchicalID(issueID) + if depth == 0 || dependsOnID == "" { + return false + } + if dependsOnID != immediateParent && !strings.HasPrefix(issueID, dependsOnID+".") { + return false + } + return depType != DepParentChild || dependsOnID != immediateParent +} + +// CheckDottedChildDependency is the ONE enforcement of the dotted-id hierarchy +// rule. Every DependencyEditor implementation applies it to each requested edge +// and every BatchApplier applies it to each dep_add item once its refs resolve, +// so `bd dep add`, an HTTP dependencies:add, and a batch apply (including +// `bd create --graph`'s own edges) refuse the same edge the same way. Two CLI +// paths that write an edge through a store verb instead of a role call it +// themselves: `bd link` and `bd batch`'s `dep add`. +// +// Other edge writers do not apply it yet, so they can still store an edge the +// roles refuse. The known ones are `bd relate`; the edges a create writes with +// its issue (`bd create --deps`/`--waits-for`, and Lifecycle.Create's ParentID, +// Dependencies and WaitsFor); `bd duplicate`, `bd supersede` and +// `bd duplicates --auto-merge`'s link and reparenting; and the tracker engine's +// createDependencies. The molecule, template and swarm writers have not been +// audited against it. bd-25s1wh tracks the gap. +func CheckDottedChildDependency(issueID, dependsOnID string, depType DependencyType) error { + if IsDottedChildDependency(issueID, dependsOnID, depType) { + return &DottedChildDependencyError{IssueID: issueID, DependsOnID: dependsOnID, Type: depType} + } + return nil +} diff --git a/issueops/errors.go b/issueops/errors.go index 7dc2dc171..6a1dfe921 100644 --- a/issueops/errors.go +++ b/issueops/errors.go @@ -242,6 +242,51 @@ func (e *CloseOpenChildrenError) Unwrap() error { return ErrCloseOpenChildren } +// ErrPinned is returned when an unforced close names a pinned issue — pinned by +// either of the two spellings bd uses, the Pinned column or the pinned status. +// Force (CloseRequest.Force, CloseBatchRequest.Force, CloseItem.Force) bypasses +// it. +var ErrPinned = errors.New("issue is pinned") + +// PinnedError reports the pinned issue an unforced close was refused for. Its +// message is the sentence `bd close` has always printed for the refusal. +type PinnedError struct { + // IssueID names the pinned issue. + IssueID string +} + +func (e *PinnedError) Error() string { + return fmt.Sprintf("cannot modify pinned issue %s (use --force to override)", e.IssueID) +} + +// Unwrap makes PinnedError match ErrPinned. +func (e *PinnedError) Unwrap() error { return ErrPinned } + +// CloseNotAssigneeError reports an unforced close refused because the issue is +// assigned to someone other than the closing actor (be-035): storage would +// accept the id-only close, so without the guard actor A silently closes the +// bead actor B holds. Authority is identity-by-string under the same +// separator-insensitive comparison every assignee guard uses; an unassigned +// issue is closable by anyone. Force bypasses it. +// +// It matches ErrNotOwner — the ownership refusal a release earns for the same +// situation — and its message is the sentence `bd close` has always printed. +type CloseNotAssigneeError struct { + // IssueID names the issue that refused the close. + IssueID string + // Assignee is the holder observed inside the refusing transaction. + Assignee string + // Actor is the closing actor the request named. + Actor string +} + +func (e *CloseNotAssigneeError) Error() string { + return fmt.Sprintf("cannot close %s: assignee is %q, actor is %q; reclaim or use --force to override", e.IssueID, e.Assignee, e.Actor) +} + +// Unwrap makes CloseNotAssigneeError match ErrNotOwner. +func (e *CloseNotAssigneeError) Unwrap() error { return ErrNotOwner } + // ErrAlreadyExists is returned when a create operation is given an ID that is // already occupied. The issue and wisp tables share one ID space. var ErrAlreadyExists = errors.New("issue already exists") @@ -290,6 +335,32 @@ func (e *AlreadyIdentifiedError) Unwrap() error { return ErrAlreadyIdentified } // precondition from other errors. var ErrVersionMismatch = errors.New("version mismatch") +// VersionMismatchError reports the expected and current row versions that +// refused a guarded write, read inside the same transaction the guard +// checked. It wraps ErrVersionMismatch rather than replacing it — the +// ClaimConflictError arrangement — so errors.Is(err, ErrVersionMismatch) +// still matches and the message stays byte-identical to the historical +// "version mismatch: expected %d, got %d", while a caller that reports the +// refusal elsewhere (a command's --json envelope, the HTTP surface) reads the +// typed pair instead of parsing that prose. +// +// Both fields are the opaque row_lock token: compared for equality only, +// carrying no order. +type VersionMismatchError struct { + // Expected is the version the caller required. + Expected int64 + // Current is the version the guard found instead, read inside the same + // transaction as the check — never a post-rollback re-read. + Current int64 +} + +func (e *VersionMismatchError) Error() string { + return fmt.Sprintf("%v: expected %d, got %d", ErrVersionMismatch, e.Expected, e.Current) +} + +// Unwrap makes VersionMismatchError match ErrVersionMismatch. +func (e *VersionMismatchError) Unwrap() error { return ErrVersionMismatch } + // ErrStatusMismatch is returned by UpdateIssueChecked given an ExpectedStatus // that no longer matches the issue's current status. The caller's view of the // issue was stale; the issue is left untouched. The assignee analog is @@ -373,19 +444,29 @@ func (e *DependencyEndpointNotFoundError) Error() string { func (e *DependencyEndpointNotFoundError) Unwrap() error { return e.Err } // DependencyHierarchyConflictError is returned when a blocking dependency -// would gate an issue on one of its own ancestors or descendants. Either shape -// can never clear under the parent-child close/blocking semantics. +// would gate an issue on one of its own ancestors or descendants. Neither +// shape is how the hierarchy expresses "wait for what is under me". type DependencyHierarchyConflictError struct { IssueID string BlockerID string BlockerIsAncestor bool } +// Error states the DESCENDANT refusal as a modeling refusal, not a +// consequence of the cascade. +// +// It used to read "blocked status cascades to descendants, so would +// inherit the block and never close". That was true until +// gastownhall/beads#6506: a parent-child edge now propagates only the parent's +// EXOGENOUS blockedness, so a parent that blocks on something in its own +// subtree no longer darkens it, and the sentence described a deadlock that no +// longer happens. The refusal itself stands — a blocks edge is not the way to +// say "I close after my children" — so the reason has to say what is. func (e *DependencyHierarchyConflictError) Error() string { if e.BlockerIsAncestor { return fmt.Sprintf("%s cannot be blocked by its ancestor %s: %s cannot close until its descendants finish, so the gate would never clear", e.IssueID, e.BlockerID, e.BlockerID) } - return fmt.Sprintf("%s cannot be blocked by its descendant %s: blocked status cascades to descendants, so %s would inherit the block and never close", - e.IssueID, e.BlockerID, e.BlockerID) + return fmt.Sprintf("%s cannot be blocked by its descendant %s: waiting on your own subtree is a close gate, not a blocks edge — use a waits-for gate over the children (bd gate)", + e.IssueID, e.BlockerID) } diff --git a/issueops/export.go b/issueops/export.go new file mode 100644 index 000000000..242509513 --- /dev/null +++ b/issueops/export.go @@ -0,0 +1,130 @@ +package issueops + +import ( + "context" + "errors" + "fmt" + + "github.com/steveyegge/beads/internal/types" +) + +// ExportRequest describes which issues `bd export` writes. +type ExportRequest struct { + // All exports every row: every status, every type (infra, templates, + // gates), and both planes, wisps included. + All bool + // IncludeInfra admits the workspace's infrastructure types (agents, roles, + // messages by default) without lifting the other default exclusions. + IncludeInfra bool +} + +// ExportRow is one exported issue, fully hydrated: its labels, its stored +// outgoing dependency records and its comment bodies, plus the three +// cardinalities the export line carries. +type ExportRow struct { + Issue *types.Issue + DependencyCount int + DependentCount int + CommentCount int +} + +// ReadExport answers `bd export`'s read set by composing three role reads that +// every backend serves (a remote one as listIssues, listDependencies and +// getIssue): +// +// - Reader.List, unlimited, for the rows, their labels and their counts; +// - EdgeReader.ReadEdges, for every row's stored dependency records; +// - Reader.Get with IncludeComments, for the comment bodies of each row whose +// comment count is nonzero (a row with no comments costs no read). +// +// THE SELECTION IS EXPORT'S, not the listing's. Every status is exported +// (AllFlag), and gates are always exported. Without All, templates and the +// workspace's infra types are excluded (IncludeInfra admits the latter), and +// TRUE wisps are excluded while no-history rows, which live on the wisps plane +// with ephemeral unset, are kept (GH#3649). A listing cannot say "the wisps +// plane minus its ephemeral rows", so the plane is admitted and the ephemeral +// rows are dropped here. That is exact because the listing is unlimited: no +// row is dropped before a limit could have counted it. +// +// A FAILED READ IS AN ERROR. Export is a data-integrity path, so a refusal or +// a missing relation never degrades to a shorter export. An anchor the edge +// read reports missing (a row deleted between the reads) is an error too, and +// so is a listing page marked HasMore: the listing is unlimited, so a +// truncated page means the reader did not honor that. +func ReadExport(ctx context.Context, rd Reader, edges EdgeReader, req ExportRequest) ([]ExportRow, error) { + if rd == nil || edges == nil { + return nil, &ErrUnsupported{Op: "ReadExport", Backend: "nil"} + } + unlimited := 0 + list := ListRequest{ + AllFlag: true, + IncludeGates: true, + IncludeEphemeral: true, + Limit: &unlimited, + } + // --all is EXPORT's scope, spelled as export defines it (infra, + // templates, gates and wisps), not ListRequest.IncludeAllTypes: that + // union is the listing's "hide nothing" contract, which a remote reader + // refuses to restate, and export has always named its own four. + list.IncludeInfra = req.All || req.IncludeInfra + list.IncludeTemplates = req.All + page, err := rd.List(ctx, list) + if err != nil { + return nil, fmt.Errorf("export: listing issues: %w", err) + } + if page.HasMore { + return nil, errors.New("export: listing issues: the listing returned a truncated page; export must never truncate") + } + + rows := make([]ExportRow, 0, len(page.Items)) + ids := make([]string, 0, len(page.Items)) + for _, item := range page.Items { + if item == nil || item.Issue == nil { + continue + } + if !req.All && item.Ephemeral { + continue + } + rows = append(rows, ExportRow{ + Issue: item.Issue, + DependencyCount: item.DependencyCount, + DependentCount: item.DependentCount, + CommentCount: item.CommentCount, + }) + ids = append(ids, item.ID) + } + if len(rows) == 0 { + return rows, nil + } + + edgeResult, err := edges.ReadEdges(ctx, EdgeReadRequest{IDs: ids}) + if err != nil { + return nil, fmt.Errorf("export: reading dependencies: %w", err) + } + deps := make(map[string][]*types.Dependency, len(edgeResult.Anchors)) + for _, anchor := range edgeResult.Anchors { + if anchor.Missing { + return nil, fmt.Errorf("export: reading dependencies: %s is no longer in the store", anchor.ID) + } + if len(anchor.Edges) > 0 { + deps[anchor.ID] = anchor.Edges + } + } + + for i := range rows { + issue := rows[i].Issue + issue.Dependencies = deps[issue.ID] + issue.Comments = nil + if rows[i].CommentCount == 0 { + continue + } + detail, err := rd.Get(ctx, GetRequest{ID: issue.ID, IncludeComments: true}) + if err != nil { + return nil, fmt.Errorf("export: reading comments of %s: %w", issue.ID, err) + } + if detail != nil { + issue.Comments = detail.Comments + } + } + return rows, nil +} diff --git a/issueops/export_test.go b/issueops/export_test.go new file mode 100644 index 000000000..d6024b3ab --- /dev/null +++ b/issueops/export_test.go @@ -0,0 +1,160 @@ +package issueops_test + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +type exportReader struct { + page []*types.IssueWithCounts + hasMore bool + lists []issueops.ListRequest + gets []issueops.GetRequest + err error + getErr error +} + +func (r *exportReader) Ready(context.Context, issueops.ReadyRequest) (issueops.IssuePage, error) { + return issueops.IssuePage{}, errors.New("ready is not export's read") +} + +func (r *exportReader) List(_ context.Context, req issueops.ListRequest) (issueops.IssuePage, error) { + r.lists = append(r.lists, req) + if r.err != nil { + return issueops.IssuePage{}, r.err + } + return issueops.IssuePage{Items: r.page, HasMore: r.hasMore}, nil +} + +func (r *exportReader) Get(_ context.Context, req issueops.GetRequest) (*issueops.IssueDetails, error) { + r.gets = append(r.gets, req) + if r.getErr != nil { + return nil, r.getErr + } + return &issueops.IssueDetails{Comments: []*types.Comment{{IssueID: req.ID, Text: "c of " + req.ID}}}, nil +} + +type exportEdges struct { + calls []issueops.EdgeReadRequest + missing string +} + +func (e *exportEdges) ReadEdges(_ context.Context, req issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) { + e.calls = append(e.calls, req) + out := issueops.EdgeReadResult{Anchors: []issueops.AnchorEdges{}} + for _, id := range req.IDs { + a := issueops.AnchorEdges{ID: id, Edges: []*types.Dependency{}, Missing: id == e.missing} + if id == "x-1" { + a.Edges = []*types.Dependency{{IssueID: "x-1", DependsOnID: "x-2", Type: types.DepBlocks}} + } + out.Anchors = append(out.Anchors, a) + } + return out, nil +} + +func exportPage() []*types.IssueWithCounts { + return []*types.IssueWithCounts{ + {Issue: &types.Issue{ID: "x-1", Labels: []string{"l"}}, DependencyCount: 1, CommentCount: 2}, + {Issue: &types.Issue{ID: "x-2"}, DependentCount: 1}, + {Issue: &types.Issue{ID: "x-wisp", Ephemeral: true}}, + {Issue: &types.Issue{ID: "x-nh", NoHistory: true}}, + nil, + } +} + +// TestReadExportAllExportsEveryRowThroughRoles is S21: `bd export --all` +// composes served role reads, so a remote backend exports without the raw +// search and bulk relation reads it does not serve. +func TestReadExportAllExportsEveryRowThroughRoles(t *testing.T) { + rd := &exportReader{page: exportPage()} + edges := &exportEdges{} + rows, err := issueops.ReadExport(context.Background(), rd, edges, issueops.ExportRequest{All: true}) + if err != nil { + t.Fatalf("ReadExport: %v", err) + } + zero := 0 + wantList := issueops.ListRequest{AllFlag: true, IncludeGates: true, IncludeEphemeral: true, IncludeInfra: true, IncludeTemplates: true, Limit: &zero} + if len(rd.lists) != 1 || !reflect.DeepEqual(rd.lists[0], wantList) { + t.Fatalf("List calls = %#v, want one %#v", rd.lists, wantList) + } + var ids []string + for _, r := range rows { + ids = append(ids, r.Issue.ID) + } + if want := []string{"x-1", "x-2", "x-wisp", "x-nh"}; !reflect.DeepEqual(ids, want) { + t.Fatalf("rows = %v, want %v (every row, in list order)", ids, want) + } + if len(edges.calls) != 1 || !reflect.DeepEqual(edges.calls[0].IDs, ids) { + t.Fatalf("ReadEdges calls = %#v, want one over %v", edges.calls, ids) + } + if got := rows[0].Issue.Dependencies; len(got) != 1 || got[0].DependsOnID != "x-2" { + t.Fatalf("x-1 dependencies = %#v, want the stored edge onto x-2", got) + } + if rows[1].Issue.Dependencies != nil { + t.Fatalf("x-2 dependencies = %#v, want none", rows[1].Issue.Dependencies) + } + // Only the row with comments is read for them. + if want := []issueops.GetRequest{{ID: "x-1", IncludeComments: true}}; !reflect.DeepEqual(rd.gets, want) { + t.Fatalf("Get calls = %#v, want %#v", rd.gets, want) + } + if c := rows[0].Issue.Comments; len(c) != 1 || c[0].Text != "c of x-1" { + t.Fatalf("x-1 comments = %#v", c) + } + if rows[0].CommentCount != 2 || rows[0].DependencyCount != 1 || rows[1].DependentCount != 1 { + t.Fatalf("counts lost: %+v %+v", rows[0], rows[1]) + } + if !reflect.DeepEqual(rows[0].Issue.Labels, []string{"l"}) { + t.Fatalf("labels lost: %v", rows[0].Issue.Labels) + } +} + +// TestReadExportDefaultDropsTrueWispsKeepsNoHistory pins the default scope: +// gates and the wisps plane are read, templates and infra are the listing's to +// exclude, and the true wisps are dropped while no-history rows stay (GH#3649). +func TestReadExportDefaultDropsTrueWispsKeepsNoHistory(t *testing.T) { + for _, infra := range []bool{false, true} { + rd := &exportReader{page: exportPage()} + rows, err := issueops.ReadExport(context.Background(), rd, &exportEdges{}, issueops.ExportRequest{IncludeInfra: infra}) + if err != nil { + t.Fatalf("ReadExport: %v", err) + } + zero := 0 + wantList := issueops.ListRequest{AllFlag: true, IncludeGates: true, IncludeEphemeral: true, IncludeInfra: infra, Limit: &zero} + if !reflect.DeepEqual(rd.lists[0], wantList) { + t.Fatalf("List = %#v, want %#v", rd.lists[0], wantList) + } + var ids []string + for _, r := range rows { + ids = append(ids, r.Issue.ID) + } + if want := []string{"x-1", "x-2", "x-nh"}; !reflect.DeepEqual(ids, want) { + t.Fatalf("rows = %v, want %v", ids, want) + } + } +} + +func TestReadExportNeverShortensOnAFailure(t *testing.T) { + refusal := &issueops.ErrUnsupported{Op: "Reader.List", Backend: "http"} + if rows, err := issueops.ReadExport(context.Background(), &exportReader{err: refusal}, &exportEdges{}, issueops.ExportRequest{All: true}); !errors.Is(err, refusal) || rows != nil { + t.Fatalf("ReadExport = (%v, %v), want (nil, the refusal)", rows, err) + } + if _, err := issueops.ReadExport(context.Background(), &exportReader{page: exportPage()}, &exportEdges{missing: "x-2"}, issueops.ExportRequest{All: true}); err == nil { + t.Fatal("ReadExport with a vanished anchor succeeded, want an error") + } + if rows, err := issueops.ReadExport(context.Background(), &exportReader{page: exportPage(), hasMore: true}, &exportEdges{}, issueops.ExportRequest{All: true}); err == nil || rows != nil { + t.Fatalf("ReadExport over a truncated listing = (%v, %v), want (nil, an error)", rows, err) + } + notFound := errors.New("x-1 not found") + if rows, err := issueops.ReadExport(context.Background(), &exportReader{page: exportPage(), getErr: notFound}, &exportEdges{}, issueops.ExportRequest{All: true}); !errors.Is(err, notFound) || rows != nil { + t.Fatalf("ReadExport with a failed comment read = (%v, %v), want (nil, the failure)", rows, err) + } + var unsupported *issueops.ErrUnsupported + if _, err := issueops.ReadExport(context.Background(), nil, nil, issueops.ExportRequest{}); !errors.As(err, &unsupported) { + t.Fatalf("ReadExport(nil) = %v, want ErrUnsupported", err) + } +} diff --git a/issueops/gates.go b/issueops/gates.go new file mode 100644 index 000000000..5b494232e --- /dev/null +++ b/issueops/gates.go @@ -0,0 +1,107 @@ +package issueops + +import ( + "context" + "fmt" + + "github.com/steveyegge/beads/internal/types" +) + +// GateListExpression is the query `bd gate list` asks: every row of the gate +// type, on both planes, whatever its other fields. It names no status, so the +// Querier's default closed exclusion applies unless GateListRequest.All lifts +// it (QueryRequest.IncludeClosed). +const GateListExpression = "type=gate" + +// GateListRequest describes `bd gate list` over the whole workspace, and the +// listing `bd gate check` evaluates. +type GateListRequest struct { + // All admits closed gates, which the listing otherwise hides. + All bool + // ExcludeTemplates leaves template gates (a persisted proto's, which every + // pour copies) out of the query itself, so none of them takes a row of + // Limit. `bd gate list` leaves it unset and lists them; `bd gate check`, + // which never evaluates a template, sets it. + ExcludeTemplates bool + // Limit bounds the rows returned; 0 means unlimited. A negative limit is + // the Querier's ErrValidation. + Limit int +} + +// ListGates answers `bd gate list` (no issue argument) through the Querier +// role, which every backend serves (a remote one as queryIssues, which every +// deployed server publishes). It is the one library entry for the listing: +// the CLI's direct, proxied and remote routes each call it with their route's +// Querier, so no route builds a storage filter of its own. +// +// The question is exactly the one the raw filter used to ask: the gate type, +// both planes, closed rows excluded unless All is set, no other default +// suppression (templates, pinned rows and ephemeral gates are all listed), +// in the store's default order, cut at Limit. ExcludeTemplates adds +// `template=false` to the expression rather than dropping templates from the +// page, so the cut at Limit counts only the gates that remain. +// +// A failed read is an error, never an empty list. Rows come back in the +// Querier's order; a row carrying no issue is dropped. +func ListGates(ctx context.Context, querier Querier, req GateListRequest) ([]*types.Issue, error) { + if querier == nil { + return nil, &ErrUnsupported{Op: "ListGates", Backend: "nil"} + } + expression := GateListExpression + if req.ExcludeTemplates { + expression += " AND template=false" + } + limit := req.Limit + page, err := querier.Query(ctx, QueryRequest{ + Expression: expression, + IncludeClosed: req.All, + Limit: &limit, + }) + if err != nil { + return nil, fmt.Errorf("listing gates: %w", err) + } + gates := make([]*types.Issue, 0, len(page.Items)) + for _, row := range page.Items { + if row != nil && row.Issue != nil { + gates = append(gates, row.Issue) + } + } + return gates, nil +} + +// The gate members a GateFieldError can name, spelled as the wire and the +// stored columns spell them. +const ( + GateFieldAwaitType = "await_type" + GateFieldAwaitID = "await_id" + GateFieldTimeout = "timeout" + GateFieldWaiters = "waiters" +) + +// GateFieldError reports a gate member a create or an update refused, and the +// one member it is about, so a front door can name that member without parsing +// the message. It wraps ErrValidation. +// +// The widths are the stored columns' and nothing more, so every backend +// refuses the same values a Dolt column always did: await_type at most 32 +// characters, await_id at most 255, and the JSON-encoded waiter list at most +// one TEXT column. The one rule no column enforces is a timeout that is not +// negative (timeout_ns is a BIGINT), which the wire publishes as minimum 0; +// the raw store creates do not run it yet (see ValidateGateFields). There is +// deliberately no await_type vocabulary (formula gate types are free-form), no +// gate-type-only rule (any issue may carry the members, as local updates +// always allowed), and no waiter deduplication. +type GateFieldError struct { + // Field is one of the GateField* constants. + Field string + // Detail is the sentence the error reads as. It is prose, and the HTTP + // client's copy ends with the server's own clause ("; nothing was + // created", "; nothing was written"), so a caller dispatches on Field, + // never on Detail. + Detail string +} + +func (e *GateFieldError) Error() string { return e.Detail } + +// Unwrap makes GateFieldError match ErrValidation. +func (e *GateFieldError) Unwrap() error { return ErrValidation } diff --git a/issueops/gates_test.go b/issueops/gates_test.go new file mode 100644 index 000000000..0e5e4d1ed --- /dev/null +++ b/issueops/gates_test.go @@ -0,0 +1,112 @@ +package issueops_test + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +func gateQuery(all bool, limit int) issueops.QueryRequest { + return issueops.QueryRequest{Expression: "type=gate", IncludeClosed: all, Limit: &limit} +} + +// TestListGatesAsksTheQuerierTheRawQuestion is S20: `bd gate list` used to +// build a raw SearchIssues filter (gate type, closed excluded unless --all), +// which the http backend refuses. The entry asks the Querier role the same +// question, so every route answers it through a role every server serves. +func TestListGatesAsksTheQuerierTheRawQuestion(t *testing.T) { + cases := []struct { + name string + req issueops.GateListRequest + want issueops.QueryRequest + }{ + {"open gates, default limit", issueops.GateListRequest{Limit: 50}, gateQuery(false, 50)}, + {"unlimited", issueops.GateListRequest{Limit: 0}, gateQuery(false, 0)}, + {"all gates", issueops.GateListRequest{All: true, Limit: 7}, gateQuery(true, 7)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + q := ¤tQueryRecorder{responses: []currentQueryResponse{{ids: []string{"g-1", "g-2"}}}} + got, err := issueops.ListGates(context.Background(), q, tc.req) + if err != nil { + t.Fatalf("ListGates: %v", err) + } + if len(q.calls) != 1 || !reflect.DeepEqual(q.calls[0], tc.want) { + t.Fatalf("Query calls = %#v, want one %#v", q.calls, tc.want) + } + ids := make([]string, 0, len(got)) + for _, g := range got { + ids = append(ids, g.ID) + } + if !reflect.DeepEqual(ids, []string{"g-1", "g-2"}) { + t.Fatalf("gates = %v, want [g-1 g-2] in the Querier's order", ids) + } + }) + } +} + +// TestListGatesExcludesTemplatesInTheQuery: ExcludeTemplates (bd gate check's +// listing) puts the template exclusion in the expression the Querier answers, +// so the cut at Limit counts only the gates that remain. Dropping templates +// from the returned page instead let a page of a persisted proto's gates fill +// the limit and hide every live gate behind it. Without it the listing names +// no template field: `bd gate list` lists templates. +func TestListGatesExcludesTemplatesInTheQuery(t *testing.T) { + nonTemplate := func(all bool, limit int) issueops.QueryRequest { + return issueops.QueryRequest{Expression: "type=gate AND template=false", IncludeClosed: all, Limit: &limit} + } + cases := []struct { + name string + req issueops.GateListRequest + want issueops.QueryRequest + }{ + {"open gates, limit 1", issueops.GateListRequest{ExcludeTemplates: true, Limit: 1}, nonTemplate(false, 1)}, + {"unlimited", issueops.GateListRequest{ExcludeTemplates: true}, nonTemplate(false, 0)}, + {"all gates", issueops.GateListRequest{All: true, ExcludeTemplates: true, Limit: 7}, nonTemplate(true, 7)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + q := ¤tQueryRecorder{responses: []currentQueryResponse{{ids: []string{"g-1"}}}} + if _, err := issueops.ListGates(context.Background(), q, tc.req); err != nil { + t.Fatalf("ListGates: %v", err) + } + if len(q.calls) != 1 || !reflect.DeepEqual(q.calls[0], tc.want) { + t.Fatalf("Query calls = %#v, want one %#v", q.calls, tc.want) + } + }) + } +} + +func TestListGatesNeverTakesAFailureForAnEmptyList(t *testing.T) { + refusal := &issueops.ErrUnsupported{Op: "Querier.Query", Backend: "http"} + q := ¤tQueryRecorder{responses: []currentQueryResponse{{err: refusal}}} + got, err := issueops.ListGates(context.Background(), q, issueops.GateListRequest{Limit: 50}) + if !errors.Is(err, refusal) || got != nil { + t.Fatalf("ListGates = (%v, %v), want (nil, the refusal)", got, err) + } +} + +func TestListGatesDropsRowsWithoutAnIssue(t *testing.T) { + q := gateRows{items: []*types.IssueWithCounts{nil, {}, {Issue: &types.Issue{ID: "g-1"}}}} + got, err := issueops.ListGates(context.Background(), q, issueops.GateListRequest{}) + if err != nil || len(got) != 1 || got[0].ID != "g-1" { + t.Fatalf("ListGates = (%v, %v), want ([g-1], nil)", got, err) + } +} + +func TestListGatesRefusesANilQuerier(t *testing.T) { + var unsupported *issueops.ErrUnsupported + if _, err := issueops.ListGates(context.Background(), nil, issueops.GateListRequest{}); !errors.As(err, &unsupported) { + t.Fatalf("ListGates(nil) error = %v, want ErrUnsupported", err) + } +} + +type gateRows struct{ items []*types.IssueWithCounts } + +func (g gateRows) Query(context.Context, issueops.QueryRequest) (issueops.IssuePage, error) { + return issueops.IssuePage{Items: g.items}, nil +} diff --git a/issueops/heartbeater.go b/issueops/heartbeater.go new file mode 100644 index 000000000..7129c1f89 --- /dev/null +++ b/issueops/heartbeater.go @@ -0,0 +1,182 @@ +package issueops + +import ( + "context" + "fmt" + "time" +) + +// ErrLeaseNotHeld is the refusal a heartbeat answers when the caller holds no +// live claim on the issue: it is open, closed, released, reclaimed, moved off +// in_progress, or a wisp (wisps are never leased). +// +// IT ALSO MATCHES ErrNotClaimable, which is what the raw heartbeat has always +// answered for the same states, so a caller written against that sentinel +// keeps working when it moves onto this role. +var ErrLeaseNotHeld = fmt.Errorf("lease not held: %w", ErrNotClaimable) + +// LeaseConflictError reports the state that refused a heartbeat, read inside +// the same transaction that found no lease row for the caller. It wraps the +// refusal rather than replacing it, the way ClaimConflictError does, so the +// sentinel still matches and a front door can classify the conflict from +// typed fields instead of parsing prose. +type LeaseConflictError struct { + // IssueID names the issue the heartbeat was refused on. + IssueID string + // Holder is the foreign assignee that holds the claim. It is empty when + // the refusal is about the status (no live claim) rather than a foreign + // holder. + Holder string + // Status is the status the refusing transaction observed. + Status Status + // Ephemeral is true when the id names a wisp, which is never leased. + // Status is then the wisp's own status, which may well be in_progress. + Ephemeral bool + // Err is the wrapped refusal. It matches ErrAlreadyClaimed (a foreign + // holder) or ErrLeaseNotHeld (no live claim by the caller). + Err error +} + +func (e *LeaseConflictError) Error() string { return e.Err.Error() } + +// Unwrap makes LeaseConflictError match the refusal it carries. +func (e *LeaseConflictError) Unwrap() error { return e.Err } + +// The HeartbeatRequest fields a HeartbeatFieldError can name. +const ( + HeartbeatFieldActor = "actor" + HeartbeatFieldIssueID = "issue_id" +) + +// HeartbeatFieldError reports a HeartbeatRequest refusal and the one field it +// is about, so a front door can name that field without parsing the message. +// It wraps ErrValidation. +type HeartbeatFieldError struct { + // Field is one of the HeartbeatField* constants. + Field string + // Detail is the sentence the error reads as. + Detail string +} + +func (e *HeartbeatFieldError) Error() string { return e.Detail } + +// Unwrap makes HeartbeatFieldError match ErrValidation. +func (e *HeartbeatFieldError) Unwrap() error { return ErrValidation } + +// HeartbeatRequest refreshes the lease on one issue the actor holds — the +// shape behind `bd heartbeat`. +// +// Implementations never mutate caller-owned request values. +type HeartbeatRequest struct { + // Actor is the lease holder refreshing its lease, and the fence's + // subject: only the current holder may heartbeat. It is REQUIRED — a + // blank Actor is ErrValidation — and so is one longer than + // types.MaxFieldLen characters, which no lease row can hold. + // + // THE ROLE DOES NOT TRIM OR CASE-FOLD IT, Releaser.Actor's rule: the + // value is compared with the lease row's holder as sent. A front door may + // normalize before it calls the role: bd serve trims the body's actor by + // the claim's rule (so a served claim and a served heartbeat agree on the + // spelling), and the CLI passes its resolved actor through. A holder + // spelled differently across layers (separator-insensitive, see + // ReleaseRequest.ExpectedAssignee) still heartbeats: it misses the fast + // path, and the slow path refreshes the lease row in place under this + // spelling. + Actor string + // IssueID is the exact canonical id, on either plane, and must not be + // empty. There is no fuzzy or prefix resolution: that is a front-door + // convenience, for the reason GetRequest.ID gives. + IssueID string +} + +// HeartbeatResult reports one refreshed lease. +type HeartbeatResult struct { + // IssueID is the issue whose lease was refreshed. + IssueID string + // Holder is the lease holder after the refresh: the request's Actor, in + // the request's spelling. + Holder string + // HeartbeatAt is the server clock, in UTC and rounded to whole seconds + // as the lease row's column rounds it: the stored value. + HeartbeatAt time.Time + // LeaseExpiresAt is HeartbeatAt plus the store's lease TTL: the deadline + // the next heartbeat must beat before a reclaim may revert the claim. + LeaseExpiresAt time.Time + // Rearmed is true only when the heartbeat CREATED the caller's lease row: + // the caller held a live claim but no lease row the caller holds existed + // (a claim hand-doled through a generic update), so the heartbeat granted + // a fresh one instead of refreshing it. A re-arm is recorded as a + // mutation and remints the issue's revision token (see Heartbeater); + // re-read before a guarded write. A refresh of the caller's own row + // is never a re-arm, including one that changed no value (two heartbeats + // in one second) and one under a differently spelled holder. + // + // false does not prove that nothing reminted the token: a transport that + // resends a heartbeat whose answer was lost (the HTTP client does) reports + // the resend's answer, a refresh of the lease row a committed re-arm + // granted. A guarded write composed on the old revision then fails its + // revision check once and re-reads. + Rearmed bool +} + +// Heartbeater refreshes a held lease — the capability behind `bd heartbeat` — +// and, like every other capability here, a role with its own accessor. +// +// IT IS A DIFFERENT QUESTION FROM Claimer. A claim takes ownership and is +// idempotent for the holder WITHOUT extending the lease (a re-claim returns +// before the lease is touched); a heartbeat proves the holder is alive and +// does nothing else. Folding one into the other would make every keepalive a +// claim attempt, with a claim's refusals and a claim's history. +// +// A REFRESH WRITES ONLY THE LEASE ROW. A heartbeat touches the ephemeral +// leases table and nothing else: it does not remint row_lock (so the holder's +// own revision token survives it and its guarded writes keep working), it +// records no version (current_revision and issue_versions stay put), it does +// not stamp updated_at, it records no event and no events-journal entry, it +// makes no version-control commit, and it fires no hook. It is the hottest +// write in a fleet, and every one of those would make it expensive or noisy. +// +// A RE-ARM IS RECORDED AS A MUTATION; A REFRESH IS NOT. A re-arm (Rearmed: +// the caller held a live claim with no lease row, a claim hand-doled through +// a generic update) is recorded the way every bead mutator records a write: +// it remints row_lock, stamps updated_at, records a lease_rearmed event, an +// events-journal entry and a version, makes a version-control commit, and +// fires on_update. The remint is what makes the grant collide with a release +// or close racing it, instead of committing beside it and leaving a lease on +// an issue that is no longer claimed. Re-arms are rare (a hand-doled claim's +// first heartbeat), so the cost lands once per such claim. +// +// THE LIVE-CLAIM FENCE IS AN INVARIANT AND A PREDICATE. Every path that ends +// or transfers a claim deletes the lease row, and a re-arm racing such a path +// collides with it on row_lock, so a lease row exists only while its claim is +// live. The refresh also matches the lease row by holder AND requires, in the +// same transaction, that the issue is in_progress with that holder as assignee, +// so a lease row orphaned any other way fails the refresh, and the refusal +// deletes it. A refresh that lands is a refresh of a live claim. +// +// EVERY LEG RUNS ONE BODY: dolt, embedded dolt and the unit-of-work provider +// wrap internal/storage/issueops.ExecuteHeartbeatInTx. +// +// Deterministic request-validation failures match ErrValidation. Result +// values are unspecified when error is non-nil. Every refusal below leaves +// persistent state unchanged, with one exception: a *LeaseConflictError +// refusal deletes the caller's own lease row if one survives on an issue the +// caller no longer holds a live claim on (an orphan; never a live holder's +// lease). +type Heartbeater interface { + // Heartbeat refreshes the lease on request.IssueID held by request.Actor. + // + // REFUSALS: + // + // - a blank Actor, one longer than types.MaxFieldLen characters, or an + // empty IssueID: a *HeartbeatFieldError (ErrValidation), before + // anything is read; + // - an IssueID that names no row on either plane: ErrNotFound; + // - an issue another actor holds: a *LeaseConflictError naming the + // Holder, wrapping ErrAlreadyClaimed; + // - a wisp, or an issue the actor holds no live claim on (open, closed, + // released, reclaimed, or any status but in_progress): a + // *LeaseConflictError wrapping ErrLeaseNotHeld, which also matches + // ErrNotClaimable; Ephemeral is set for a wisp. + Heartbeat(ctx context.Context, request HeartbeatRequest) (HeartbeatResult, error) +} diff --git a/issueops/heartbeater_test.go b/issueops/heartbeater_test.go new file mode 100644 index 000000000..c27e86d14 --- /dev/null +++ b/issueops/heartbeater_test.go @@ -0,0 +1,30 @@ +package issueops_test + +import ( + "errors" + "fmt" + "testing" + + "github.com/steveyegge/beads/issueops" +) + +// TestErrLeaseNotHeldStillMatchesErrNotClaimable pins the compatibility +// promise ErrLeaseNotHeld's doc makes: a caller written against the raw +// heartbeat's ErrNotClaimable keeps classifying the role's refusal. +func TestErrLeaseNotHeldStillMatchesErrNotClaimable(t *testing.T) { + err := &issueops.LeaseConflictError{IssueID: "x", Err: fmt.Errorf("%w: x status closed", issueops.ErrLeaseNotHeld)} + if !errors.Is(err, issueops.ErrLeaseNotHeld) || !errors.Is(err, issueops.ErrNotClaimable) { + t.Fatalf("LeaseConflictError(ErrLeaseNotHeld) = %v: want it to match ErrLeaseNotHeld and ErrNotClaimable", err) + } + if errors.Is(err, issueops.ErrAlreadyClaimed) { + t.Fatal("ErrLeaseNotHeld matches ErrAlreadyClaimed; the two refusals must stay distinguishable") + } +} + +// TestHeartbeatFieldErrorMatchesErrValidation pins the field error's sentinel. +func TestHeartbeatFieldErrorMatchesErrValidation(t *testing.T) { + var err error = &issueops.HeartbeatFieldError{Field: issueops.HeartbeatFieldActor, Detail: "validation failed: heartbeat actor is required"} + if !errors.Is(err, issueops.ErrValidation) { + t.Fatalf("HeartbeatFieldError = %v: want it to match ErrValidation", err) + } +} diff --git a/issueops/issueops.go b/issueops/issueops.go index aa2bd2101..c4870ae90 100644 --- a/issueops/issueops.go +++ b/issueops/issueops.go @@ -125,7 +125,15 @@ type IssuePatch struct { // AppendNotes appends to the notes and is mutually exclusive with Notes. AppendNotes Field[string] SpecID Field[string] - AwaitID Field[string] + // AwaitID replaces the gate's condition identifier; the empty string + // clears it. Its bounds are ValidateGateFields' (GateFieldError). + AwaitID Field[string] + // Waiters is a WHOLE-VALUE replacement of the gate's waiter list; a set + // nil or empty Value clears it. The role stores the list as given: + // duplicates are kept, as local storage always has, and deduplication is + // the caller's (bd gate add-waiter dedups before it writes). Its bounds + // are the column's (GateFieldError naming GateFieldWaiters). + Waiters Field[[]string] // Status sets the issue's status. A status that crosses from outside the // configured done category into it answers to close policy: the update // refuses with CloseOpenChildrenError or ErrCloseBlocked unless @@ -195,7 +203,8 @@ type CreateRequest struct { // ignores ContentHash, RowVersion, lease state, compaction state, routing // overrides, hydration flags, and derived fields. Labels are authoritative. // Issue.Comments and Issue.Dependencies must be empty; supply edges through - // the request's own Dependencies field. + // the request's own Dependencies field. An empty Issue.CreatedBy defaults to + // Actor (the same rule for every create shape, batch items included). Issue *Issue // ParentID creates a typed DepParentChild edge. It must not duplicate an // explicit edge in Dependencies. @@ -224,8 +233,23 @@ type CreateRequest struct { // is handed. Without it the two `bd create` routes disagree about which // ids a workspace may mint. IDPrefix string + // DefaultPriority says the caller has no priority for the issue, and the + // create stores DefaultCreatePriority. It exists because Issue.Priority + // cannot say "absent": its zero value is P0, a real and urgent priority, so + // a caller that leaves it unset asks for critical work. The default is + // applied here, once, for every route — the CLI's `bd create` without + // --priority and an HTTP create without `priority` both set this rather + // than spelling the number themselves. + // + // Issue.Priority must be zero when it is set; a request that sets both is + // ErrValidation, because the two would disagree about what was asked for. + DefaultPriority bool } +// DefaultCreatePriority is the priority a create stores when its request sets +// DefaultPriority (CreateRequest, BatchCreateItem, CreateItem): P2, medium. +const DefaultCreatePriority = 2 + // UpdateRequest describes an issue update. type UpdateRequest struct { Actor, IssueID string @@ -273,6 +297,14 @@ type UpdateRequest struct { // It is the update-side spelling of CloseRequest.Force; a command adapter // that maps one flag to both spells both. ForceClosePolicy bool + // AllowTemplate says the caller edits a template deliberately, so the + // template read-only refusal (*TemplateReadOnlyError) stands down for this + // request. bd label and bd set-state set it to keep their pre-guard + // behavior: they have always written to templates. The zero value + // enforces the guard. It bypasses nothing else — validation, the + // preconditions, the assignee and notes fences and close policy still + // apply — and has no effect on an issue that is not a template. + AllowTemplate bool // The three Expected* guards below are this package's FOUNDING spelling of // the compare-and-set family, and the family's rules are stated once, at // length, on DeleteRequest.ExpectedVersion (deleter.go) and @@ -354,8 +386,10 @@ type CloseRequest struct { // and read back on CloseResult.Issue.ClosedBySession, under the same // first-close-wins rule as Reason. Session string - // Force bypasses only blocker and open-child close policy. It never bypasses - // validation, ExpectedVersion, or lifecycle rules. + // Force bypasses blocker and open-child close policy and the two close + // guards a force has always waived in bd: the pin, and the assignee + // authority fence. It never bypasses the template guard, validation, + // ExpectedVersion, or lifecycle rules. Force bool // ExpectedVersion requires the current row version to match, and is checked // BEFORE the idempotent close — so a re-close of an already-closed issue @@ -369,6 +403,47 @@ type CloseRequest struct { // a miss refuses with ErrVersionMismatch having written nothing. Force // bypasses close policy and never this guard. ExpectedVersion *int64 + // AutoCloseMolecule closes the issue's molecule root IN THE SAME + // TRANSACTION when this close completed it: the root closes itself when + // complete (AutoClosesWhenComplete), it is open, and every step under it + // is now closed (CompletedMolecule). The root close is unforced, guarded + // on the root revision read inside that transaction, and records + // MoleculeAutoCloseReason and this request's Session. + // + // It runs for an idempotent re-close too: the rule is state-derived, so a + // replayed close of the last step heals a root a crash left open. + // + // IT IS OPT-IN because an orchestrator may run its own molecule + // lifecycle (gc closes molecule roots itself); the zero value never + // touches a root. A root close its close policy refuses (a live blocker + // on the root, open children) or a close guard refuses (a template root, a + // pinned root, a root assigned to someone other than Actor — the root + // close is unforced, so each guard holds as it does for a direct close) + // leaves the root open and is reported on + // CloseResult.MoleculeAutoCloseRefusal (IsMoleculeAutoCloseRefusal); it + // never fails the step close. + // + // ANY OTHER FAILURE OF THE ROOT CLOSE FAILS THE STEP'S CLOSE. A storage + // error is returned and rolls the step's close back with it, so a retry + // re-runs both. (The CLI used to close the root after the step's close had + // committed and only warned when that failed, leaving a complete + // molecule's root open.) A write to the root that races this close is not + // such a failure: the two conflict at commit, and the backend's retry + // decides the root again (MoleculeRootClose). + // + // Two closes that finish a molecule's last steps concurrently do not + // strand its root: each close that decides a root first rewrites one + // coordination cell for it, so their transactions conflict at commit and + // the one that retries reads the other's close and closes the root. + // + // THE CELL SERIALIZES SIBLING CLOSES. Every close under an open + // auto-closing root rewrites it, whether or not that close completes the + // molecule, so any two concurrent closes of steps under the same root + // conflict and one of them retries. Under heavy fan-out a close can spend + // its whole retry budget conflicting and then fails with the + // serialization error. Closes under different roots contend only when + // their roots hash to the same cell. + AutoCloseMolecule bool } // ReopenRequest describes an issue reopening. @@ -431,6 +506,15 @@ type CloseResult struct { // OpenChildren is the number of open children observed by a forced close. // It is reported even for an idempotent re-close. OpenChildren int + // AutoClosedMolecule is the molecule root CloseRequest.AutoCloseMolecule + // closed in this close's transaction, as a post-close snapshot with + // labels. Nil when nothing was auto-closed. + AutoClosedMolecule *Issue + // MoleculeAutoCloseRefusal says why a completed molecule's root stayed + // open: its close policy or a close guard refused it + // (IsMoleculeAutoCloseRefusal), in that refusal's own message, the same on + // every backend. Empty otherwise. + MoleculeAutoCloseRefusal string } // ReopenResult reports the post-reopen issue as a detached post-state snapshot @@ -478,15 +562,26 @@ type Lifecycle interface { // returns ErrCloseBlocked, both without mutation. ForceClosePolicy bypasses // those two refusals and nothing else. A Claim that loses its // compare-and-set returns *ClaimConflictError carrying the state that beat - // it. A refusal or validation error leaves persistent state unchanged. + // it. An update of a template returns *TemplateReadOnlyError whatever its + // patch and force flags, unless it sets AllowTemplate — templates are + // read-only — checked after the + // compare-and-set preconditions, so a stale guard still reports the + // mismatch. A refusal or validation error leaves persistent state + // unchanged. Update(context.Context, UpdateRequest) (UpdateResult, error) // Close validates guards and commits the complete request as one atomic // mutation. It moves the issue to literal StatusClosed, including from a // configured done status. ExpectedVersion is checked first, including for an - // idempotent close. An unforced close with open children returns - // CloseOpenChildrenError without mutation. Force bypasses blocker and - // open-child policy and reports OpenChildren, including for an idempotent - // re-close. A refusal or validation error leaves persistent state unchanged. + // idempotent close. A close of an issue that is not already closed answers + // to the close guards before close policy: a template returns + // *TemplateReadOnlyError, forced or not; unforced, a pinned issue returns + // *PinnedError and one assigned to someone other than Actor (compared + // separator-insensitively) returns *CloseNotAssigneeError, matching + // ErrNotOwner. An unforced close with open children returns + // CloseOpenChildrenError without mutation. Force bypasses the pin, the + // assignee fence, and blocker and open-child policy, and reports + // OpenChildren, including for an idempotent re-close. A refusal or + // validation error leaves persistent state unchanged. Close(context.Context, CloseRequest) (CloseResult, error) // Reopen validates guards and commits the complete request as one atomic // mutation. It moves literal StatusClosed and configured done statuses to diff --git a/issueops/issueops_external_test.go b/issueops/issueops_external_test.go index 4f12dffbc..fd8f81ce2 100644 --- a/issueops/issueops_external_test.go +++ b/issueops/issueops_external_test.go @@ -340,3 +340,58 @@ func (operationsProbe) Close(context.Context, issueops.CloseRequest) (issueops.C func (operationsProbe) Reopen(context.Context, issueops.ReopenRequest) (issueops.ReopenResult, error) { return issueops.ReopenResult{}, nil } + +// TestCheckDottedChildDependency pins the dotted-id hierarchy rule every +// DependencyEditor and BatchApplier enforces. It absorbs the CLI's former +// isChildOf / isDisallowedHierarchicalDependency tables. +func TestCheckDottedChildDependency(t *testing.T) { + for _, tt := range []struct { + name string + from string + to string + depType issueops.DependencyType + want bool + }{ + {"direct child blocks on parent", "bd-abc.1", "bd-abc", issueops.DepBlocks, true}, + {"grandchild blocks on grandparent", "bd-abc.1.2", "bd-abc", issueops.DepBlocks, true}, + {"grandchild blocks on immediate parent", "bd-abc.1.2", "bd-abc.1", issueops.DepBlocks, true}, + {"deeply nested child blocks on root", "bd-abc.1.2.3", "bd-abc", issueops.DepBlocks, true}, + {"child relates to parent", "bd-abc.1", "bd-abc", issueops.DepRelated, true}, + {"grandchild parent-child to grandparent", "bd-root.1.2", "bd-root", issueops.DepParentChild, true}, + {"immediate parent-child allowed", "bd-root.1.2", "bd-root.1", issueops.DepParentChild, false}, + {"same id", "bd-abc", "bd-abc", issueops.DepBlocks, false}, + {"unrelated ids", "bd-xyz", "bd-abc", issueops.DepBlocks, false}, + {"unrelated target from a dotted child", "bd-root.1.2", "bd-other", issueops.DepBlocks, false}, + {"sibling", "bd-abc.2", "bd-abc.1", issueops.DepBlocks, false}, + {"parent on its child", "bd-abc", "bd-abc.1", issueops.DepBlocks, false}, + {"prefix but not hierarchical", "bd-abcd", "bd-abc", issueops.DepBlocks, false}, + {"textual prefix of a dotted id is not an ancestor", "bd-abc.10", "bd-abc.1", issueops.DepBlocks, false}, + {"external target", "bd-abc.1", "external:bd-abc", issueops.DepBlocks, false}, + } { + t.Run(tt.name, func(t *testing.T) { + if got := issueops.IsDottedChildDependency(tt.from, tt.to, tt.depType); got != tt.want { + t.Fatalf("IsDottedChildDependency(%q, %q, %q) = %v, want %v", tt.from, tt.to, tt.depType, got, tt.want) + } + err := issueops.CheckDottedChildDependency(tt.from, tt.to, tt.depType) + if !tt.want { + if err != nil { + t.Fatalf("CheckDottedChildDependency = %v, want nil", err) + } + return + } + var dotted *issueops.DottedChildDependencyError + if !errors.As(err, &dotted) || !errors.Is(err, issueops.ErrValidation) { + t.Fatalf("CheckDottedChildDependency = %v, want *DottedChildDependencyError matching ErrValidation", err) + } + if dotted.IssueID != tt.from || dotted.DependsOnID != tt.to || dotted.Type != tt.depType { + t.Fatalf("refusal = %#v, want the edge it refused", dotted) + } + // The CLI prints this sentence verbatim, so it is behaviour. + want := "cannot add dependency: " + tt.from + " is already a child of " + tt.to + + ". Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock" + if err.Error() != want { + t.Fatalf("message = %q, want %q", err.Error(), want) + } + }) + } +} diff --git a/issueops/leasereclaimer.go b/issueops/leasereclaimer.go new file mode 100644 index 000000000..4c63f5a42 --- /dev/null +++ b/issueops/leasereclaimer.go @@ -0,0 +1,183 @@ +package issueops + +import ( + "context" + "fmt" + "time" + + "github.com/steveyegge/beads/internal/types" +) + +// ReclaimFilter scopes which stale-lease issues a reclaim may revert. See +// types.ReclaimFilter: this is the same value, aliased into this package the +// way GetManyRequest's sibling roles alias their types.* shapes. +type ReclaimFilter = types.ReclaimFilter + +// ReclaimedLease names one issue whose stale lease a reclaim reverted, plus +// the owner it took the lease from and the fresh revision the revert minted. +// See types.ReclaimedLease. +type ReclaimedLease = types.ReclaimedLease + +// MaxReclaimIDs is the largest ReclaimFilter.IDs this role accepts in one +// call. It is the same number and the same reasoning as MaxGetManyIDs: a flat +// bound on the request rather than a cost model over the sweep it scopes, so +// one call cannot hold the revert transaction open over an unbounded id list. +const MaxReclaimIDs = 1000 + +// TooManyReclaimIDsError reports that a ReclaimRequest's Filter.IDs named more +// ids than this role accepts in one call. It wraps ErrValidation, matching +// TooManyIDsError's shape for the same reason: a caller that only checks for a +// usable request classifies it correctly without knowing this type exists. +type TooManyReclaimIDsError struct { + // Requested is the number of ids Filter.IDs named, counted before + // deduplication. + Requested int + // Cap is MaxReclaimIDs, carried on the error so a caller does not need the + // constant in scope to report what it hit. + Cap int +} + +func (e *TooManyReclaimIDsError) Error() string { + return fmt.Sprintf("reclaim accepts at most %d scoped ids, got %d", e.Cap, e.Requested) +} + +// Unwrap makes TooManyReclaimIDsError match ErrValidation. +func (e *TooManyReclaimIDsError) Unwrap() error { return ErrValidation } + +// The ReclaimRequest fields a ReclaimFieldError can name. +const ( + ReclaimFieldActor = "actor" + ReclaimFieldOlderThan = "older_than" + ReclaimFieldIDs = "ids" + ReclaimFieldAssignees = "assignees" + ReclaimFieldLabels = "labels" + ReclaimFieldLabelsAny = "labels_any" + ReclaimFieldExcludeLabels = "exclude_labels" +) + +// ReclaimFieldError reports a ReclaimRequest refusal and the one field it is +// about, so a front door can name that field without parsing the message. It +// wraps ErrValidation. The id cap is the one refusal that is not one of these: +// it is a *TooManyReclaimIDsError, always about ReclaimFieldIDs. +type ReclaimFieldError struct { + // Field is one of the ReclaimField* constants. + Field string + // Detail is the sentence the error reads as. + Detail string +} + +func (e *ReclaimFieldError) Error() string { return e.Detail } + +// Unwrap makes ReclaimFieldError match ErrValidation. +func (e *ReclaimFieldError) Unwrap() error { return ErrValidation } + +// ReclaimRequest describes one sweep of stale leases — the shape behind +// `bd reclaim`. +// +// Implementations never mutate caller-owned request values: Filter's slices +// are read, never written through. +type ReclaimRequest struct { + // Actor attributes every reverted row's recovery event and its journaled + // update. It is REQUIRED — an empty or all-blank Actor is ErrValidation — + // for the same reason Releaser.Release requires one: a reclaim is the + // moment work stops being owned, and the one question asked of a reverted + // row's history afterwards is who ran the sweep that freed it. It is + // recorded trimmed, and one longer than types.MaxFieldLen characters once + // trimmed is ErrValidation too: the column it is recorded in holds no more. + Actor string + // OlderThan is the grace period past a lease's own TTL: only a lease whose + // lease_expires_at is more than OlderThan in the past is eligible. It must + // not be negative — a negative grace reaches into the future and reclaims + // leases that have not yet expired by their own TTL, which is not a wider + // sweep, it is a different operation this role does not perform. + OlderThan time.Duration + // Filter narrows which stale-lease issues are eligible; the zero value + // reclaims every stale lease workspace-wide. See types.ReclaimFilter for + // the scope fields (ids, assignees, labels) and the AnyReplica escape + // hatch — none of that is restated here, and this role changes none of it. + // + // FILTER.IDS IS NOT AN ERROR WHEN IT NAMES A NON-STALE OR UNKNOWN ISSUE. + // Like GetManyRequest.IDs, an id that is not currently a stale lease + // simply does not appear in ReclaimResult.Reclaimed — scoping by id + // narrows a sweep, it does not assert that every named id was reclaimable. + // + // MORE THAN MaxReclaimIDs ENTRIES IN Filter.IDs IS A REFUSAL: a + // *TooManyReclaimIDsError, counted as sent, before deduplication. + Filter ReclaimFilter +} + +// ReclaimResult reports every issue a reclaim reverted, in the order the sweep +// found them. +type ReclaimResult struct { + // Reclaimed names every issue the sweep reverted, together with the owner + // each lease was taken from and the fresh revision the revert minted on + // each row. Never nil for a successful call, even when it is empty: a + // sweep that finds nothing stale answers with an empty, non-nil slice, the + // same promise GetManyResult.Issues makes. + Reclaimed []ReclaimedLease +} + +// LeaseReclaimer sweeps stale leases back to ready — the capability behind +// `bd reclaim` — and, like every other capability here, a role with its own +// accessor. +// +// IT IS A DIFFERENT QUESTION FROM Releaser. Releaser gives up ONE claim a +// caller names, on the claim's own say-so (Actor, or Force). This sweeps +// MANY leases that have gone stale by a clock, on nobody's say-so but the +// clock's — a reaper calls this, not the agent that held the work. A surface +// carrying both would let a caller that may only report its own abandoned +// work reach into every other holder's, which is the same split Releaser's +// own doc draws against Claimer. +// +// WRITES, AND ITS HOOK IS on_update, once per reverted row. A reclaim clears +// assignee and status on each row it reverts, which is an update and is +// already how the journal classifies it — see Releaser's identical +// reasoning. There is no on_reclaim to fire and inventing one is not this +// role's job. +// +// Reclaim only ever touches the permanent issues table: wisps are ephemeral +// and are never leased work (see internal/storage/issueops. +// ReclaimExpiredLeasesInTx). The replica guard ReclaimFilter.AnyReplica +// documents is unchanged by this role — it is enforced in the shared body +// every library leg calls through. +// +// EVERY LEG RUNS ONE BODY: dolt, embedded dolt and the unit-of-work provider +// wrap internal/storage/issueops.ExecuteReclaimInTx, and the HTTP client leg +// dials POST /v0/beads/issues:reclaim (capability issues.reclaim), behind which +// bd serve runs the same body. `bd reclaim` runs this role on both of its +// routes. Each leg records one version-control entry per sweep that reverted +// anything, and honors a deferred version commit on the context. +// +// Deterministic request-validation failures match ErrValidation. Result +// values are unspecified when error is non-nil, and every refusal below +// leaves persistent state unchanged. +type LeaseReclaimer interface { + // Reclaim sweeps every stale lease ReclaimRequest.Filter admits whose + // lease_expires_at is more than OlderThan in the past, and reports every + // issue it reverted. + // + // IT IS ONE TRANSACTION over the whole sweep: the snapshot that decides + // which leases are stale, every row's revert, and the revision each revert + // mints all see one write. A lease a concurrent heartbeat rescues between + // the snapshot and its row's revert is simply skipped — it never appears + // in Reclaimed, and is not an error. + // + // REFUSALS: + // + // - an empty or all-blank Actor, or one longer than types.MaxFieldLen + // characters once trimmed: ErrValidation, before anything is read; + // - a negative OlderThan: ErrValidation; + // - more than MaxReclaimIDs entries in Filter.IDs, or an empty-string + // entry among them: *TooManyReclaimIDsError or ErrValidation, + // respectively, before anything is read; + // - an empty or all-blank entry in Filter.Assignees, Labels, LabelsAny or + // ExcludeLabels: ErrValidation, because it would match nothing a + // caller meant to name. + // + // Every ErrValidation refusal but the cap is a *ReclaimFieldError naming + // its field. + // + // A sweep that finds no stale leases is not a refusal: it answers an empty, + // non-nil Reclaimed. + Reclaim(ctx context.Context, request ReclaimRequest) (ReclaimResult, error) +} diff --git a/issueops/molecule.go b/issueops/molecule.go new file mode 100644 index 000000000..1b787b748 --- /dev/null +++ b/issueops/molecule.go @@ -0,0 +1,869 @@ +package issueops + +import ( + "context" + "errors" + "fmt" + "sort" + + "github.com/steveyegge/beads/internal/types" +) + +// MoleculeTemplateLabel is the label that marks an epic as a template-driven +// molecule root. `bd mol distill` writes it; a poured molecule's root is +// TypeMolecule instead and carries no label. +const MoleculeTemplateLabel = "template" + +// MoleculeReader is the read surface every molecule operation in this file is +// composed over: three roles every backend serves. +// +// - BatchGetter answers the molecule root and the parent walk's candidate +// roots, labeled, in either plane. +// - Relations answers a node's inbound parent-child steps as FULL rows, in +// either plane. +// - EdgeReader answers the parent walk (a step's outgoing parent-child edge) +// and the blocking edges between a molecule's steps. +// +// THE MOLECULE RULES HAVE ONE IMPLEMENTATION, and it is the functions below. +// A caller that reads committed state binds them to the roles +// (NewMoleculeReader). A close that must decide inside its own +// transaction binds them to the same three role BODIES running against that +// transaction (internal/storage/issueops.TxMoleculeReader, and the unit-of-work +// backend's MoleculeReaderInUOW), so a molecule's membership, completion and +// readiness mean one thing on every backend and every route. +// +// Membership is the parent-child EDGE. A child whose id merely looks +// hierarchical (.) but carries no edge is not a step: no role can +// express an id-pattern scan, and a rule only some routes could apply would +// make the same molecule answer differently per route. +type MoleculeReader struct { + BatchGetter + Relations + EdgeReader +} + +// MoleculeReaderOver binds one value that answers all three role reads — an +// in-transaction binding, a test double — as a MoleculeReader. +func MoleculeReaderOver(r interface { + BatchGetter + Relations + EdgeReader +}) MoleculeReader { + return MoleculeReader{BatchGetter: r, Relations: r, EdgeReader: r} +} + +func (r MoleculeReader) usable() bool { + return r.BatchGetter != nil && r.Relations != nil && r.EdgeReader != nil +} + +// moleculeRoleSource is the accessor set a store or a unit-of-work provider +// offers for the three roles a MoleculeReader composes. +type moleculeRoleSource interface { + BatchGetter() (BatchGetter, error) + IssueRelations() (Relations, error) + EdgeReader() (EdgeReader, error) +} + +// NewMoleculeReader binds a MoleculeReader to src's own role accessors, so +// every decorator src wears (hooks, telemetry, policy) stays in the path. src +// is a storage.DoltStorage or a unit-of-work provider. +func NewMoleculeReader(src moleculeRoleSource) (MoleculeReader, error) { + if src == nil { + return MoleculeReader{}, fmt.Errorf("%w: molecule reader needs a role source", ErrValidation) + } + getter, err := src.BatchGetter() + if err != nil { + return MoleculeReader{}, err + } + relations, err := src.IssueRelations() + if err != nil { + return MoleculeReader{}, err + } + edges, err := src.EdgeReader() + if err != nil { + return MoleculeReader{}, err + } + return MoleculeReader{BatchGetter: getter, Relations: relations, EdgeReader: edges}, nil +} + +// IsMoleculeRoot reports whether issue is the root of a molecule: an epic, a +// TypeMolecule root (`bd mol pour`), or anything carrying the template label. +func IsMoleculeRoot(issue *Issue) bool { + if issue == nil { + return false + } + if issue.IssueType == types.TypeEpic || issue.IssueType == types.TypeMolecule { + return true + } + return hasLabel(issue, MoleculeTemplateLabel) +} + +// AutoClosesWhenComplete reports whether a molecule root closes itself when +// its last step closes. Molecule-typed and ephemeral roots do, and so does a +// template-driven epic; an ordinary epic stays open so it becomes explicit, +// close-eligible work instead of closing as a side effect. +func AutoClosesWhenComplete(root *Issue) bool { + if root == nil { + return false + } + if root.IssueType == types.TypeMolecule || root.Ephemeral { + return true + } + return root.IssueType == types.TypeEpic && hasLabel(root, MoleculeTemplateLabel) +} + +func hasLabel(issue *Issue, label string) bool { + for _, l := range issue.Labels { + if l == label { + return true + } + } + return false +} + +// maxMoleculeDepth bounds the parent walk, so a parent-child cycle ends. +const maxMoleculeDepth = 50 + +// MoleculeRoots walks parent-child edges up from every id and answers, for +// each id that belongs to a molecule, the id of its molecule root. An id whose +// topmost ancestor is not a molecule root (IsMoleculeRoot) is omitted, and so +// is an id that names nothing. A root that is itself a molecule root answers +// itself. +// +// The walk is level by level, one edge read per level for every chain at +// once, so its cost is the depth of the deepest chain, not the number of ids. +// A read the backend fails or refuses is RETURNED: answering "not in a +// molecule" for a read that never happened is how a molecule root gets +// stranded open. +func MoleculeRoots(ctx context.Context, r MoleculeReader, ids []string) (map[string]string, error) { + rows, err := moleculeRootRows(ctx, r, ids) + if err != nil { + return nil, err + } + out := make(map[string]string, len(rows)) + for start, root := range rows { + out[start] = root.ID + } + return out, nil +} + +// moleculeRootRows is MoleculeRoots answering each id's molecule root ROW, as +// the walk read it. +func moleculeRootRows(ctx context.Context, r MoleculeReader, ids []string) (map[string]*Issue, error) { + out := map[string]*Issue{} + if len(ids) == 0 { + return out, nil + } + if !r.usable() { + return nil, fmt.Errorf("%w: molecule reads need a reader", ErrValidation) + } + topOf := make(map[string]string, len(ids)) + current := make(map[string]string, len(ids)) + for _, id := range ids { + current[id] = id + } + for depth := 0; depth < maxMoleculeDepth && len(current) > 0; depth++ { + level := distinctValues(current) + parentOf, err := parentChildParents(ctx, r, level) + if err != nil { + return nil, err + } + next := make(map[string]string, len(current)) + for start, at := range current { + if parent, ok := parentOf[at]; ok { + next[start] = parent + } else { + topOf[start] = at + } + } + current = next + } + for start, at := range current { + topOf[start] = at + } + + tops, err := getIssues(ctx, r, distinctValues(topOf)) + if err != nil { + return nil, fmt.Errorf("loading molecule roots: %w", err) + } + for start, top := range topOf { + if root := tops[top]; IsMoleculeRoot(root) { + out[start] = root + } + } + return out, nil +} + +// MoleculeRoot is MoleculeRoots for one id: the id's molecule root, or "" when +// it belongs to no molecule. +func MoleculeRoot(ctx context.Context, r MoleculeReader, id string) (string, error) { + roots, err := MoleculeRoots(ctx, r, []string{id}) + if err != nil { + return "", err + } + return roots[id], nil +} + +// parentChildParents answers each id's first outgoing parent-child target. +func parentChildParents(ctx context.Context, r MoleculeReader, ids []string) (map[string]string, error) { + res, err := r.ReadEdges(ctx, EdgeReadRequest{IDs: ids, Types: []types.DependencyType{types.DepParentChild}}) + if err != nil { + return nil, fmt.Errorf("walking parent-child edges: %w", err) + } + parentOf := make(map[string]string, len(res.Anchors)) + for _, anchor := range res.Anchors { + for _, edge := range anchor.Edges { + if edge != nil && edge.Type == types.DepParentChild { + parentOf[anchor.ID] = edge.DependsOnID + break + } + } + } + return parentOf, nil +} + +// getIssues reads ids through the BatchGetter in batches the role accepts and +// answers them by id. Missing ids are absent. +func getIssues(ctx context.Context, r MoleculeReader, ids []string) (map[string]*Issue, error) { + out := make(map[string]*Issue, len(ids)) + for start := 0; start < len(ids); start += MaxGetManyIDs { + end := min(start+MaxGetManyIDs, len(ids)) + res, err := r.GetMany(ctx, GetManyRequest{IDs: ids[start:end]}) + if err != nil { + return nil, err + } + for _, issue := range res.Issues { + if issue != nil { + out[issue.ID] = issue + } + } + } + return out, nil +} + +func distinctValues(m map[string]string) []string { + seen := make(map[string]bool, len(m)) + out := make([]string, 0, len(m)) + for _, v := range m { + if !seen[v] { + seen[v] = true + out = append(out, v) + } + } + sort.Strings(out) + return out +} + +// MoleculeGraph is a molecule root, every step under it and the edges between +// them. +type MoleculeGraph struct { + // Root is the molecule root, labeled. + Root *Issue + // Issues holds the root first, then every descendant in depth-first + // pre-order of the parent-child edges. + Issues []*Issue + // Dependencies holds every stored edge whose two ends are both in Issues. + Dependencies []*Dependency + // IssueMap indexes Issues by id. + IssueMap map[string]*Issue +} + +// LoadMolecule reads the molecule rooted at rootID: the root, every +// parent-child descendant as a full row, and the edges between them. A root +// that names nothing is ErrNotFound. A parent-child cycle terminates. +func LoadMolecule(ctx context.Context, r MoleculeReader, rootID string) (*MoleculeGraph, error) { + if !r.usable() { + return nil, fmt.Errorf("%w: molecule reads need a reader", ErrValidation) + } + roots, err := getIssues(ctx, r, []string{rootID}) + if err != nil { + return nil, fmt.Errorf("loading molecule %s: %w", rootID, err) + } + root := roots[rootID] + if root == nil { + return nil, fmt.Errorf("%w: molecule %s", ErrNotFound, rootID) + } + g := &MoleculeGraph{Root: root, Issues: []*Issue{root}, IssueMap: map[string]*Issue{root.ID: root}} + if err := loadMoleculeChildren(ctx, r, g, root.ID); err != nil { + return nil, err + } + + ids := make([]string, len(g.Issues)) + for i, issue := range g.Issues { + ids[i] = issue.ID + } + edges, err := r.ReadEdges(ctx, EdgeReadRequest{IDs: ids}) + if err != nil { + return nil, fmt.Errorf("reading molecule %s edges: %w", rootID, err) + } + for _, anchor := range edges.Anchors { + for _, edge := range anchor.Edges { + if edge == nil { + continue + } + if _, ok := g.IssueMap[edge.DependsOnID]; ok { + g.Dependencies = append(g.Dependencies, edge) + } + } + } + return g, nil +} + +func loadMoleculeChildren(ctx context.Context, r MoleculeReader, g *MoleculeGraph, parentID string) error { + children, err := r.Related(ctx, RelatedRequest{ + ID: parentID, + Direction: RelationIn, + Types: []types.DependencyType{types.DepParentChild}, + }) + if errors.Is(err, ErrNotFound) { + return nil + } + if err != nil { + return fmt.Errorf("reading the steps of %s: %w", parentID, err) + } + for _, child := range children { + if child == nil || child.DependencyType != types.DepParentChild { + continue + } + if _, seen := g.IssueMap[child.ID]; seen { + continue + } + issue := child.Issue + g.Issues = append(g.Issues, &issue) + g.IssueMap[issue.ID] = &issue + if err := loadMoleculeChildren(ctx, r, g, issue.ID); err != nil { + return err + } + } + return nil +} + +// MoleculeStepInfo is one node's readiness inside its molecule. +type MoleculeStepInfo struct { + StepID string `json:"step_id"` + Status string `json:"status"` + IsReady bool `json:"is_ready"` // Can start now (no open blocker) + ParallelGroup string `json:"parallel_group"` // Steps sharing a group can run concurrently + BlockedBy []string `json:"blocked_by"` // Open steps blocking this one + Blocks []string `json:"blocks"` // Steps this one blocks + CanParallel []string `json:"can_parallel"` // Steps that can run in parallel with this one +} + +// MoleculeAnalysis is the readiness and parallelism of every node of a +// molecule, root included. +type MoleculeAnalysis struct { + MoleculeID string `json:"molecule_id"` + TotalSteps int `json:"total_steps"` + ReadySteps int `json:"ready_steps"` + ParallelGroups map[string][]string `json:"parallel_groups"` // group id -> step ids + Steps map[string]*MoleculeStepInfo `json:"steps"` +} + +// AnalyzeMolecule computes readiness from the edges inside the molecule +// rather than from the workspace ready query, which excludes ephemeral rows (a +// wisp molecule's steps are ephemeral by definition). A node is ready when it +// is open or in progress and no open node blocks it through a blocks, +// conditional-blocks or waits-for edge. Nodes at the same blocking depth that +// do not block each other share a parallel group. +func AnalyzeMolecule(g *MoleculeGraph) *MoleculeAnalysis { + analysis := &MoleculeAnalysis{ + MoleculeID: g.Root.ID, + TotalSteps: len(g.Issues), + ParallelGroups: make(map[string][]string), + Steps: make(map[string]*MoleculeStepInfo), + } + + blockedBy := make(map[string]map[string]bool) + blocks := make(map[string]map[string]bool) + parentChildren := make(map[string][]string) + for _, issue := range g.Issues { + blockedBy[issue.ID] = make(map[string]bool) + blocks[issue.ID] = make(map[string]bool) + } + for _, dep := range g.Dependencies { + if dep.Type == types.DepParentChild { + parentChildren[dep.DependsOnID] = append(parentChildren[dep.DependsOnID], dep.IssueID) + } + } + for _, dep := range g.Dependencies { + switch dep.Type { + case types.DepBlocks, types.DepConditionalBlocks: + if _, ok := blockedBy[dep.IssueID]; ok { + blockedBy[dep.IssueID][dep.DependsOnID] = true + } + if _, ok := blocks[dep.DependsOnID]; ok { + blocks[dep.DependsOnID][dep.IssueID] = true + } + case types.DepWaitsFor: + children := parentChildren[dep.DependsOnID] + if len(children) == 0 { + continue + } + if types.ParseWaitsForGateMetadata(dep.Metadata) == types.WaitsForAnyChildren && anyClosed(g, children) { + continue + } + // For all-children (and unresolved any-children) every open child + // blocks the gate. + for _, childID := range children { + child := g.IssueMap[childID] + if child == nil || child.Status == types.StatusClosed { + continue + } + if _, ok := blockedBy[dep.IssueID]; ok { + blockedBy[dep.IssueID][childID] = true + } + if _, ok := blocks[childID]; ok { + blocks[childID][dep.IssueID] = true + } + } + } + } + + for _, issue := range g.Issues { + info := &MoleculeStepInfo{StepID: issue.ID, Status: string(issue.Status), BlockedBy: []string{}, Blocks: []string{}} + for blockerID := range blockedBy[issue.ID] { + if blocker := g.IssueMap[blockerID]; blocker != nil && blocker.Status != types.StatusClosed { + info.BlockedBy = append(info.BlockedBy, blockerID) + } + } + for blockedID := range blocks[issue.ID] { + info.Blocks = append(info.Blocks, blockedID) + } + info.IsReady = (issue.Status == types.StatusOpen || issue.Status == types.StatusInProgress) && len(info.BlockedBy) == 0 + if info.IsReady { + analysis.ReadySteps++ + } + sort.Strings(info.BlockedBy) + sort.Strings(info.Blocks) + analysis.Steps[issue.ID] = info + } + + depths := blockingDepths(g, blockedBy) + depthGroups := make(map[int][]string) + for _, issue := range g.Issues { + depthGroups[depths[issue.ID]] = append(depthGroups[depths[issue.ID]], issue.ID) + } + groupCounter := 0 + for depth := 0; depth <= len(g.Issues); depth++ { + groupCounter = groupParallelSteps(analysis, depthGroups[depth], blocks, blockedBy, groupCounter) + } + return analysis +} + +func anyClosed(g *MoleculeGraph, ids []string) bool { + for _, id := range ids { + if child := g.IssueMap[id]; child != nil && child.Status == types.StatusClosed { + return true + } + } + return false +} + +// groupParallelSteps unions the steps at one blocking depth that do not block +// each other and names every group of two or more. It answers the updated +// group counter. +func groupParallelSteps(analysis *MoleculeAnalysis, steps []string, blocks, blockedBy map[string]map[string]bool, counter int) int { + if len(steps) == 0 { + return counter + } + parent := make(map[string]string, len(steps)) + for _, id := range steps { + parent[id] = id + } + find := func(x string) string { + for parent[x] != x { + parent[x] = parent[parent[x]] + x = parent[x] + } + return x + } + for i, a := range steps { + for _, b := range steps[i+1:] { + if !blocks[a][b] && !blocks[b][a] && !blockedBy[a][b] && !blockedBy[b][a] { + if pa, pb := find(a), find(b); pa != pb { + parent[pa] = pb + } + } + } + } + groups := make(map[string][]string) + var order []string + for _, id := range steps { + root := find(id) + if _, ok := groups[root]; !ok { + order = append(order, root) + } + groups[root] = append(groups[root], id) + } + for _, root := range order { + members := groups[root] + if len(members) < 2 { + continue + } + counter++ + name := fmt.Sprintf("group-%d", counter) + analysis.ParallelGroups[name] = members + for _, id := range members { + info := analysis.Steps[id] + info.ParallelGroup = name + for _, other := range members { + if other != id { + info.CanParallel = append(info.CanParallel, other) + } + } + sort.Strings(info.CanParallel) + } + } + return counter +} + +// blockingDepths answers each node's blocking depth: 0 with no open blocker, +// one more than its deepest open blocker otherwise. A cycle counts as 0. +func blockingDepths(g *MoleculeGraph, blockedBy map[string]map[string]bool) map[string]int { + depths := make(map[string]int) + visiting := make(map[string]bool) + var depthOf func(id string) int + depthOf = func(id string) int { + if d, ok := depths[id]; ok { + return d + } + if visiting[id] { + return 0 + } + visiting[id] = true + deepest := -1 + for blockerID := range blockedBy[id] { + if blocker := g.IssueMap[blockerID]; blocker != nil && blocker.Status != types.StatusClosed { + deepest = max(deepest, depthOf(blockerID)) + } + } + depths[id] = deepest + 1 + return depths[id] + } + for _, issue := range g.Issues { + depthOf(issue.ID) + } + return depths +} + +// Molecule step states, as MoleculeStep.State spells them. +const ( + MoleculeStepDone = "done" + MoleculeStepCurrent = "current" + MoleculeStepReady = "ready" + MoleculeStepBlocked = "blocked" + MoleculeStepPending = "pending" +) + +// MoleculeStep is one step of a MoleculeView. +type MoleculeStep struct { + Issue *Issue + // State is one of the MoleculeStep* constants: done (closed), current (in + // progress), blocked (status blocked), ready (open, no open blocker inside + // the molecule) or pending. + State string + IsCurrent bool +} + +// MoleculeView is where a molecule stands: every step's state, the progress +// counts, the step in progress and the next ready one. +type MoleculeView struct { + Graph *MoleculeGraph + Analysis *MoleculeAnalysis + // Steps holds every step (the root excluded) ordered by how many blocking + // edges inside the molecule each one waits on, fewest first, stable over + // the graph's own order. + Steps []*MoleculeStep + // Completed counts the closed steps and Total every step. + Completed int + Total int + // CurrentStep is the step in progress (the last one in graph order when + // several are); NextStep the first ready step. + CurrentStep *Issue + NextStep *Issue + // Ready holds every node the analysis marks ready (open or in progress + // with no open blocker inside the molecule), root included, in graph + // order: `bd ready --mol`'s list, hydrated rows (assignee and all). + Ready []*Issue +} + +// Complete reports whether every step of the molecule is closed. +func (v *MoleculeView) Complete() bool { return v.Completed >= v.Total } + +// ViewMolecule loads the molecule rooted at rootID and derives its view. +func ViewMolecule(ctx context.Context, r MoleculeReader, rootID string) (*MoleculeView, error) { + g, err := LoadMolecule(ctx, r, rootID) + if err != nil { + return nil, err + } + return MoleculeViewOf(g), nil +} + +// MoleculeViewOf derives the view of an already loaded graph. +func MoleculeViewOf(g *MoleculeGraph) *MoleculeView { + analysis := AnalyzeMolecule(g) + view := &MoleculeView{Graph: g, Analysis: analysis, Total: len(g.Issues) - 1} + for _, issue := range g.Issues { + if info := analysis.Steps[issue.ID]; info != nil && info.IsReady { + view.Ready = append(view.Ready, issue) + } + if issue.ID == g.Root.ID { + continue + } + step := &MoleculeStep{Issue: issue} + switch issue.Status { + case types.StatusClosed: + step.State = MoleculeStepDone + view.Completed++ + case types.StatusInProgress: + step.State = MoleculeStepCurrent + step.IsCurrent = true + view.CurrentStep = issue + case types.StatusBlocked: + step.State = MoleculeStepBlocked + default: + if info := analysis.Steps[issue.ID]; info != nil && info.IsReady { + step.State = MoleculeStepReady + if view.NextStep == nil { + view.NextStep = issue + } + } else { + step.State = MoleculeStepPending + } + } + view.Steps = append(view.Steps, step) + } + sortStepsByBlockers(view.Steps, g) + return view +} + +// ReadySteps answers the steps whose state is ready, in view order. +func (v *MoleculeView) ReadySteps() []*Issue { + var out []*Issue + for _, step := range v.Steps { + if step.State == MoleculeStepReady { + out = append(out, step.Issue) + } + } + return out +} + +func sortStepsByBlockers(steps []*MoleculeStep, g *MoleculeGraph) { + inSteps := make(map[string]bool, len(steps)) + for _, step := range steps { + inSteps[step.Issue.ID] = true + } + waits := make(map[string]int, len(steps)) + for _, dep := range g.Dependencies { + if dep.Type == types.DepBlocks && inSteps[dep.IssueID] && inSteps[dep.DependsOnID] { + waits[dep.IssueID]++ + } + } + sort.SliceStable(steps, func(i, j int) bool { + return waits[steps[i].Issue.ID] < waits[steps[j].Issue.ID] + }) +} + +// MoleculeProgress is a molecule's progress counts over its DIRECT +// parent-child steps. +type MoleculeProgress = types.MoleculeProgressStats + +// ReadMoleculeProgress counts the direct steps of the molecule rooted at +// rootID without loading the whole graph. A root that names nothing is +// ErrNotFound. +func ReadMoleculeProgress(ctx context.Context, r MoleculeReader, rootID string) (*MoleculeProgress, error) { + if !r.usable() { + return nil, fmt.Errorf("%w: molecule reads need a reader", ErrValidation) + } + roots, err := getIssues(ctx, r, []string{rootID}) + if err != nil { + return nil, fmt.Errorf("loading molecule %s: %w", rootID, err) + } + root := roots[rootID] + if root == nil { + return nil, fmt.Errorf("%w: molecule %s", ErrNotFound, rootID) + } + children, err := r.Related(ctx, RelatedRequest{ + ID: rootID, + Direction: RelationIn, + Types: []types.DependencyType{types.DepParentChild}, + }) + if err != nil { + return nil, fmt.Errorf("reading the steps of %s: %w", rootID, err) + } + return MoleculeProgressOf(root, children), nil +} + +// MoleculeProgressOf folds a root's inbound parent-child neighbors into its +// progress counts. CurrentStepID is the first in-progress step in the order +// given. +func MoleculeProgressOf(root *Issue, children []*RelatedIssue) *MoleculeProgress { + stats := &MoleculeProgress{} + if root != nil { + stats.MoleculeID, stats.MoleculeTitle = root.ID, root.Title + } + for _, child := range children { + if child == nil || child.DependencyType != types.DepParentChild { + continue + } + stats.Total++ + switch child.Status { + case types.StatusClosed: + stats.Completed++ + case types.StatusInProgress: + stats.InProgress++ + if stats.CurrentStepID == "" { + stats.CurrentStepID = child.ID + } + } + } + return stats +} + +// CompletedMolecule answers the molecule root that closing stepID completed +// and that closes itself when complete (AutoClosesWhenComplete): the root is +// open and every step under it is closed. It answers nil when stepID belongs +// to no molecule, when the root is already closed or does not auto-close, or +// when a step is still open. It writes nothing; the caller closes the root, +// guarded on the RowVersion of the root it answers. +// +// It is AutoClosingMoleculeRoots then MoleculeStepsClosed, so a step under an +// ordinary epic, or under a root already closed, never reads the steps. +func CompletedMolecule(ctx context.Context, r MoleculeReader, stepID string) (*Issue, error) { + roots, err := AutoClosingMoleculeRoots(ctx, r, []string{stepID}) + if err != nil { + return nil, err + } + root := roots[stepID] + if root == nil { + return nil, nil + } + complete, err := MoleculeStepsClosed(ctx, r, root.ID) + if err != nil || !complete { + return nil, err + } + return root, nil +} + +// AutoClosingMoleculeRoots answers, for each id whose molecule root is open +// and closes itself when complete (AutoClosesWhenComplete), that root's row: +// the roots a close of ids could complete. It is the parent walk and the root +// rows MoleculeRoots reads, and nothing more — it never reads a molecule's +// steps — so a caller deciding several closes reads each root once and walks +// only the molecules that could auto-close. +func AutoClosingMoleculeRoots(ctx context.Context, r MoleculeReader, ids []string) (map[string]*Issue, error) { + rows, err := moleculeRootRows(ctx, r, ids) + if err != nil { + return nil, err + } + for id, root := range rows { + if root.Status == types.StatusClosed || !AutoClosesWhenComplete(root) { + delete(rows, id) + } + } + return rows, nil +} + +// MoleculeStepsClosed reports whether every parent-child descendant of rootID +// is closed — the steps LoadMolecule would load. It reads one level of steps +// at a time and answers false at the first step that is not closed, so an +// incomplete molecule costs the reads up to its first open step, not a load of +// the whole tree. A root with no steps answers true; a parent-child cycle +// terminates. +func MoleculeStepsClosed(ctx context.Context, r MoleculeReader, rootID string) (bool, error) { + if !r.usable() { + return false, fmt.Errorf("%w: molecule reads need a reader", ErrValidation) + } + seen := map[string]bool{rootID: true} + pending := []string{rootID} + for len(pending) > 0 { + parentID := pending[len(pending)-1] + pending = pending[:len(pending)-1] + children, err := r.Related(ctx, RelatedRequest{ + ID: parentID, + Direction: RelationIn, + Types: []types.DependencyType{types.DepParentChild}, + }) + if errors.Is(err, ErrNotFound) { + continue + } + if err != nil { + return false, fmt.Errorf("reading the steps of %s: %w", parentID, err) + } + for _, child := range children { + if child == nil || child.DependencyType != types.DepParentChild || seen[child.ID] { + continue + } + if child.Status != types.StatusClosed { + return false, nil + } + seen[child.ID] = true + pending = append(pending, child.ID) + } + } + return true, nil +} + +// MoleculeAutoCloseReason is the close reason a molecule root's auto-close +// records. +const MoleculeAutoCloseReason = "all steps complete" + +// IsMoleculeAutoCloseRefusal reports whether err is a refusal of a completed +// molecule's root close — an outcome that leaves the root open without failing +// the step close that completed it: the close policy (a live blocker, +// ErrCloseBlocked; open children, *CloseOpenChildrenError) or a close guard (a +// template root, *TemplateReadOnlyError; a pinned root, *PinnedError; a root +// assigned to someone else, *CloseNotAssigneeError). The root close is +// unforced (MoleculeRootClose), so every guard holds for it exactly as it does +// for a direct close of the root. A guard only reads, before the close writes +// anything, and a policy refusal rolls back to the close's savepoint, so a +// refusal leaves the step close's transaction as it found it. +// +// ErrVersionMismatch on the root is NOT a refusal: should a backend's check +// ever see a revision its read did not, it fails the step's close +// (CloseRequest.AutoCloseMolecule). A write to the root that races the close +// does not produce it (MoleculeRootClose). +func IsMoleculeAutoCloseRefusal(err error) bool { + var ( + openChildren *CloseOpenChildrenError + template *TemplateReadOnlyError + pinned *PinnedError + notAssignee *CloseNotAssigneeError + ) + return errors.Is(err, ErrCloseBlocked) || + errors.As(err, &openChildren) || + errors.As(err, &template) || + errors.As(err, &pinned) || + errors.As(err, ¬Assignee) +} + +// MoleculeRootClose is the ONE close request a molecule auto-close sends for a +// root it found complete (AutoClosingMoleculeRoots, then MoleculeStepsClosed, +// read in the transaction that closes it): unforced, recording +// MoleculeAutoCloseReason and the step close's session, and guarded on the +// RowVersion of root as that read answered it. Every backend's +// in-transaction auto-close (CloseRequest.AutoCloseMolecule) builds its root +// close from it. +// +// The guard covers the root row's lifecycle state and nothing else (the +// version family's rule: it guards a row's lifecycle state, not its graph). +// Every backend reads the root and checks its revision in one transaction +// snapshot, so a status, assignee or started_at write that another +// transaction commits to the root after the read does not trip the guard. It +// conflicts with the root close at commit instead, and the backend's retry +// re-reads the root and decides again (a root another actor now holds is a +// refusal, and the step's close stands); only a close still conflicting when +// its retry budget runs out fails, with the serialization error. The guard +// does not cover the steps: reopening a step writes no root row, so a reopen +// that races the auto-close is not detected, and the root can close over the +// reopened step. +func MoleculeRootClose(root *Issue, actor, session string) CloseRequest { + version := root.RowVersion + return CloseRequest{ + Actor: actor, + IssueID: root.ID, + Reason: MoleculeAutoCloseReason, + Session: session, + ExpectedVersion: &version, + } +} diff --git a/issueops/molecule_active.go b/issueops/molecule_active.go new file mode 100644 index 000000000..f8a7b8c98 --- /dev/null +++ b/issueops/molecule_active.go @@ -0,0 +1,141 @@ +package issueops + +import ( + "context" + "fmt" + "sort" + + "github.com/steveyegge/beads/internal/types" +) + +// InProgressMoleculeIDs answers the molecules with a step in progress for +// agent (every agent when agent is empty), each once, in the order the +// listing first reached a step of it. +// +// The listing is Reader.List over every plane and class a step can live in — +// templates, gates, infra and ephemeral rows, the four knobs rather than +// IncludeAllTypes, because the v0 wire publishes each knob and refuses the +// union. A read the backend refuses is returned, never answered as "none". +func InProgressMoleculeIDs(ctx context.Context, reader Reader, r MoleculeReader, agent string) ([]string, error) { + steps, err := listMoleculeCandidates(ctx, reader, types.StatusInProgress, agent) + if err != nil { + return nil, err + } + if len(steps) == 0 { + return nil, nil + } + ids := make([]string, len(steps)) + for i, step := range steps { + ids[i] = step.ID + } + roots, err := MoleculeRoots(ctx, r, ids) + if err != nil { + return nil, err + } + seen := map[string]bool{} + var out []string + for _, id := range ids { + if root := roots[id]; root != "" && !seen[root] { + seen[root] = true + out = append(out, root) + } + } + return out, nil +} + +// ActiveMoleculeIDs answers the molecules agent is working on, sorted: the +// ones with a step in progress or, when there are none, the ones its HOOKED +// work is attached to — a hooked epic itself, or an epic or template the +// hooked issue is blocked by. +func ActiveMoleculeIDs(ctx context.Context, reader Reader, r MoleculeReader, agent string) ([]string, error) { + ids, err := InProgressMoleculeIDs(ctx, reader, r, agent) + if err != nil { + return nil, fmt.Errorf("finding molecules in progress: %w", err) + } + if len(ids) == 0 { + ids, err = hookedMoleculeIDs(ctx, reader, r, agent) + if err != nil { + return nil, fmt.Errorf("finding hooked molecules: %w", err) + } + } + sort.Strings(ids) + return ids, nil +} + +func hookedMoleculeIDs(ctx context.Context, reader Reader, r MoleculeReader, agent string) ([]string, error) { + hooked, err := listMoleculeCandidates(ctx, reader, types.StatusHooked, agent) + if err != nil || len(hooked) == 0 { + return nil, err + } + seen := map[string]bool{} + var out []string + add := func(id string) { + if !seen[id] { + seen[id] = true + out = append(out, id) + } + } + var attached []string + for _, issue := range hooked { + // A hooked epic IS the molecule (a patrol wisp hooked without a + // separate handoff bead). + if issue.IssueType == types.TypeEpic { + add(issue.ID) + continue + } + attached = append(attached, issue.ID) + } + if len(attached) == 0 { + return out, nil + } + edges, err := r.ReadEdges(ctx, EdgeReadRequest{IDs: attached, Types: []types.DependencyType{types.DepBlocks}}) + if err != nil { + return nil, fmt.Errorf("reading the blockers of hooked work: %w", err) + } + var blockers []string + for _, anchor := range edges.Anchors { + for _, edge := range anchor.Edges { + if edge != nil && edge.Type == types.DepBlocks { + blockers = append(blockers, edge.DependsOnID) + } + } + } + candidates, err := getIssues(ctx, r, blockers) + if err != nil { + return nil, err + } + for _, id := range blockers { + // An external or dangling blocker names nothing to load. + if candidate := candidates[id]; candidate != nil && + (candidate.IssueType == types.TypeEpic || hasLabel(candidate, MoleculeTemplateLabel)) { + add(id) + } + } + return out, nil +} + +func listMoleculeCandidates(ctx context.Context, reader Reader, status types.Status, agent string) ([]*Issue, error) { + if reader == nil { + return nil, fmt.Errorf("%w: listing molecule work needs a reader", ErrValidation) + } + unlimited := 0 + page, err := reader.List(ctx, ListRequest{ + Status: string(status), + Assignee: agent, + IncludeTemplates: true, + IncludeGates: true, + IncludeInfra: true, + IncludeEphemeral: true, + Limit: &unlimited, + }) + if err != nil { + return nil, err + } + out := make([]*Issue, 0, len(page.Items)) + for _, row := range page.Items { + if row != nil && row.Issue != nil { + out = append(out, row.Issue) + } + } + return out, nil +} diff --git a/issueops/molecule_internal_test.go b/issueops/molecule_internal_test.go new file mode 100644 index 000000000..0ffda4f16 --- /dev/null +++ b/issueops/molecule_internal_test.go @@ -0,0 +1,40 @@ +package issueops + +import ( + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +// TestBlockingDepths pins the depth rule the parallel grouping keys on: 0 with +// no open blocker, one more than the deepest open blocker otherwise. +func TestBlockingDepths(t *testing.T) { + root := &types.Issue{ID: "root", Status: types.StatusOpen} + step1 := &types.Issue{ID: "step1", Status: types.StatusOpen} + step2 := &types.Issue{ID: "step2", Status: types.StatusOpen} + step3 := &types.Issue{ID: "step3", Status: types.StatusOpen} + g := &MoleculeGraph{ + Root: root, + Issues: []*types.Issue{root, step1, step2, step3}, + IssueMap: map[string]*types.Issue{"root": root, "step1": step1, "step2": step2, "step3": step3}, + } + blockedBy := map[string]map[string]bool{ + "root": {}, + "step1": {"root": true}, + "step2": {"step1": true}, + "step3": {"step2": true}, + } + depths := blockingDepths(g, blockedBy) + for id, want := range map[string]int{"root": 0, "step1": 1, "step2": 2, "step3": 3} { + if depths[id] != want { + t.Errorf("%s depth = %d, want %d", id, depths[id], want) + } + } + + // A closed blocker no longer deepens what it blocked. + step1.Status = types.StatusClosed + depths = blockingDepths(g, blockedBy) + if depths["step2"] != 0 { + t.Errorf("step2 depth with its blocker closed = %d, want 0", depths["step2"]) + } +} diff --git a/issueops/molecule_test.go b/issueops/molecule_test.go new file mode 100644 index 000000000..296f168cc --- /dev/null +++ b/issueops/molecule_test.go @@ -0,0 +1,595 @@ +package issueops_test + +import ( + "context" + "errors" + "fmt" + "slices" + "sort" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// fakeMolecules is an in-memory MoleculeReader, Reader (List), Claimer and +// Lifecycle (Update with Claim, Close) — just enough store for the molecule +// rules, so each rule is pinned without a database. +type fakeMolecules struct { + issueops.Reader + issueops.Lifecycle + issues map[string]*types.Issue + deps []*types.Dependency + + edgeErr error + listErr error + relatedErr error + // related records every Related read, by id, in order. + related []string + // claimErrs answers a claim of the keyed id with that error. + claimErrs map[string]error + claimed []string + updated []string + closes []issueops.CloseRequest + closeErr error +} + +func newFakeMolecules() *fakeMolecules { + return &fakeMolecules{issues: map[string]*types.Issue{}, claimErrs: map[string]error{}} +} + +func (f *fakeMolecules) add(id string, typ types.IssueType, status types.Status, labels ...string) *types.Issue { + issue := &types.Issue{ID: id, Title: "title " + id, IssueType: typ, Status: status, Labels: labels, RowVersion: int64(len(id) * 7)} + f.issues[id] = issue + return issue +} + +func (f *fakeMolecules) edge(from, to string, typ types.DependencyType) { + f.deps = append(f.deps, &types.Dependency{IssueID: from, DependsOnID: to, Type: typ}) +} + +func (f *fakeMolecules) GetMany(_ context.Context, req issueops.GetManyRequest) (issueops.GetManyResult, error) { + out := issueops.GetManyResult{Issues: []*issueops.Issue{}, Missing: []string{}} + for _, id := range req.IDs { + if issue := f.issues[id]; issue != nil { + clone := *issue + out.Issues = append(out.Issues, &clone) + } else { + out.Missing = append(out.Missing, id) + } + } + return out, nil +} + +func (f *fakeMolecules) Related(_ context.Context, req issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) { + f.related = append(f.related, req.ID) + if f.relatedErr != nil { + return nil, f.relatedErr + } + if f.issues[req.ID] == nil { + return nil, fmt.Errorf("%w: %s", issueops.ErrNotFound, req.ID) + } + var out []*issueops.RelatedIssue + for _, dep := range f.deps { + if dep.DependsOnID != req.ID || (len(req.Types) > 0 && !slices.Contains(req.Types, dep.Type)) { + continue + } + if issue := f.issues[dep.IssueID]; issue != nil { + out = append(out, &issueops.RelatedIssue{Issue: *issue, DependencyType: dep.Type}) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) + return out, nil +} + +func (f *fakeMolecules) ReadEdges(_ context.Context, req issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) { + if f.edgeErr != nil { + return issueops.EdgeReadResult{}, f.edgeErr + } + var out issueops.EdgeReadResult + for _, id := range req.IDs { + anchor := issueops.AnchorEdges{ID: id, Missing: f.issues[id] == nil} + for _, dep := range f.deps { + if dep.IssueID == id && (len(req.Types) == 0 || slices.Contains(req.Types, dep.Type)) { + anchor.Edges = append(anchor.Edges, dep) + } + } + out.Anchors = append(out.Anchors, anchor) + } + return out, nil +} + +func (f *fakeMolecules) List(_ context.Context, req issueops.ListRequest) (issueops.IssuePage, error) { + if f.listErr != nil { + return issueops.IssuePage{}, f.listErr + } + var page issueops.IssuePage + for _, issue := range f.issues { + if string(issue.Status) == req.Status && (req.Assignee == "" || issue.Assignee == req.Assignee) { + page.Items = append(page.Items, &types.IssueWithCounts{Issue: issue}) + } + } + sort.Slice(page.Items, func(i, j int) bool { return page.Items[i].ID < page.Items[j].ID }) + return page, nil +} + +func (f *fakeMolecules) take(id, actor string) (*types.Issue, error) { + if err := f.claimErrs[id]; err != nil { + return nil, err + } + issue := f.issues[id] + issue.Status, issue.Assignee = types.StatusInProgress, actor + clone := *issue + clone.Labels = nil + return &clone, nil +} + +func (f *fakeMolecules) Claim(_ context.Context, req issueops.ClaimRequest) (issueops.ClaimResult, error) { + issue, err := f.take(req.IssueID, req.Actor) + if err != nil { + return issueops.ClaimResult{}, err + } + f.claimed = append(f.claimed, req.IssueID) + return issueops.ClaimResult{Issue: issue, Changed: true}, nil +} + +func (f *fakeMolecules) Update(_ context.Context, req issueops.UpdateRequest) (issueops.UpdateResult, error) { + if !req.Claim { + return issueops.UpdateResult{}, errors.New("fake: only claims") + } + issue, err := f.take(req.IssueID, req.Actor) + if err != nil { + return issueops.UpdateResult{}, err + } + f.updated = append(f.updated, req.IssueID) + return issueops.UpdateResult{Issue: issue, Changed: true}, nil +} + +func (f *fakeMolecules) Close(_ context.Context, req issueops.CloseRequest) (issueops.CloseResult, error) { + f.closes = append(f.closes, req) + if f.closeErr != nil { + return issueops.CloseResult{}, f.closeErr + } + issue := f.issues[req.IssueID] + if req.ExpectedVersion != nil && *req.ExpectedVersion != issue.RowVersion { + return issueops.CloseResult{}, issueops.ErrVersionMismatch + } + issue.Status = types.StatusClosed + clone := *issue + return issueops.CloseResult{Issue: &clone, Changed: true}, nil +} + +func (f *fakeMolecules) reader() issueops.MoleculeReader { return issueops.MoleculeReaderOver(f) } + +func (f *fakeMolecules) stepper() issueops.MoleculeStepper { + return issueops.NewMoleculeStepper(issueops.MoleculeStepperRoles{Reader: f.reader(), Claimer: f, Lifecycle: f}) +} + +// A molecule: root (molecule type) <- a, b, c; c blocked by b; b blocked by a. +func seedChain(f *fakeMolecules) { + f.add("m", types.TypeMolecule, types.StatusOpen) + f.add("m.a", types.TypeTask, types.StatusClosed) + f.add("m.b", types.TypeTask, types.StatusOpen) + f.add("m.c", types.TypeTask, types.StatusOpen) + for _, id := range []string{"m.a", "m.b", "m.c"} { + f.edge(id, "m", types.DepParentChild) + } + f.edge("m.b", "m.a", types.DepBlocks) + f.edge("m.c", "m.b", types.DepBlocks) +} + +func TestMoleculeRootsWalksToTheTopmostMoleculeRoot(t *testing.T) { + f := newFakeMolecules() + f.add("root", types.TypeEpic, types.StatusOpen) + f.add("child", types.TypeTask, types.StatusOpen) + f.add("grandchild", types.TypeTask, types.StatusOpen) + f.add("orphan", types.TypeTask, types.StatusOpen) + f.add("plain", types.TypeTask, types.StatusOpen) + f.add("plainkid", types.TypeTask, types.StatusOpen) + f.add("tmpl", types.TypeTask, types.StatusOpen, issueops.MoleculeTemplateLabel) + f.add("tmplkid", types.TypeTask, types.StatusOpen) + f.edge("child", "root", types.DepParentChild) + f.edge("grandchild", "child", types.DepParentChild) + f.edge("plainkid", "plain", types.DepParentChild) + f.edge("tmplkid", "tmpl", types.DepParentChild) + + roots, err := issueops.MoleculeRoots(context.Background(), f.reader(), []string{"grandchild", "child", "root", "orphan", "plainkid", "tmplkid", "absent"}) + if err != nil { + t.Fatalf("MoleculeRoots: %v", err) + } + want := map[string]string{"grandchild": "root", "child": "root", "root": "root", "tmplkid": "tmpl"} + if len(roots) != len(want) { + t.Fatalf("MoleculeRoots = %v, want %v", roots, want) + } + for id, root := range want { + if roots[id] != root { + t.Errorf("MoleculeRoots[%s] = %q, want %q", id, roots[id], root) + } + } +} + +// Every read the rules make RETURNS a refusal. Answering "not in a molecule" +// or "no molecules" for a read that never happened is how `bd mol current` +// went silently empty and a molecule root was stranded open. +func TestMoleculeReadsReturnRefusals(t *testing.T) { + ctx := context.Background() + refusal := errors.New("refused") + + f := newFakeMolecules() + seedChain(f) + f.edgeErr = refusal + if _, err := issueops.MoleculeRoots(ctx, f.reader(), []string{"m.b"}); !errors.Is(err, refusal) { + t.Errorf("MoleculeRoots with a refused edge read = %v, want the refusal", err) + } + if _, err := issueops.CompletedMolecule(ctx, f.reader(), "m.b"); !errors.Is(err, refusal) { + t.Errorf("CompletedMolecule with a refused edge read = %v, want the refusal", err) + } + + f = newFakeMolecules() + seedChain(f) + f.relatedErr = refusal + if _, err := issueops.ViewMolecule(ctx, f.reader(), "m"); !errors.Is(err, refusal) { + t.Errorf("ViewMolecule with a refused relations read = %v, want the refusal", err) + } + if _, err := issueops.ReadMoleculeProgress(ctx, f.reader(), "m"); !errors.Is(err, refusal) { + t.Errorf("ReadMoleculeProgress with a refused relations read = %v, want the refusal", err) + } + + f = newFakeMolecules() + f.listErr = refusal + if _, err := issueops.ActiveMoleculeIDs(ctx, f, f.reader(), "alice"); !errors.Is(err, refusal) { + t.Errorf("ActiveMoleculeIDs with a refused listing = %v, want the refusal", err) + } + if _, err := issueops.InProgressMoleculeIDs(ctx, f, f.reader(), "alice"); !errors.Is(err, refusal) { + t.Errorf("InProgressMoleculeIDs with a refused listing = %v, want the refusal", err) + } +} + +func TestMoleculeViewDerivesStatesProgressAndTheNextStep(t *testing.T) { + f := newFakeMolecules() + seedChain(f) + f.add("m.d", types.TypeTask, types.StatusInProgress) + f.edge("m.d", "m", types.DepParentChild) + f.issues["m.d"].Assignee = "alice" + + view, err := issueops.ViewMolecule(context.Background(), f.reader(), "m") + if err != nil { + t.Fatalf("ViewMolecule: %v", err) + } + if view.Total != 4 || view.Completed != 1 || view.Complete() { + t.Errorf("progress = %d/%d complete=%v, want 1/4 incomplete", view.Completed, view.Total, view.Complete()) + } + states := map[string]string{} + for _, step := range view.Steps { + states[step.Issue.ID] = step.State + } + want := map[string]string{"m.a": "done", "m.b": "ready", "m.c": "pending", "m.d": "current"} + for id, state := range want { + if states[id] != state { + t.Errorf("state[%s] = %q, want %q", id, states[id], state) + } + } + if view.CurrentStep == nil || view.CurrentStep.ID != "m.d" || view.CurrentStep.Assignee != "alice" { + t.Errorf("CurrentStep = %+v, want m.d assigned to alice (the full step row)", view.CurrentStep) + } + if view.NextStep == nil || view.NextStep.ID != "m.b" { + t.Errorf("NextStep = %+v, want m.b", view.NextStep) + } + // Ready is ready --mol's list: every analysis-ready node, hydrated. + ready := map[string]*issueops.Issue{} + for _, issue := range view.Ready { + ready[issue.ID] = issue + } + if ready["m.b"] == nil || ready["m.d"] == nil || ready["m.a"] != nil || ready["m.c"] != nil { + t.Errorf("Ready = %v, want m.b and m.d, never the closed m.a or the blocked m.c", view.Ready) + } + if d := ready["m.d"]; d != nil && d.Assignee != "alice" { + t.Errorf("Ready m.d assignee = %q, want alice (the full step row)", d.Assignee) + } + // Ordered by in-molecule blockers, fewest first: m.c waits on one step. + if last := view.Steps[len(view.Steps)-1].Issue.ID; last != "m.c" && last != "m.b" { + t.Errorf("last step = %s, want a step that waits on a blocker", last) + } + progress, err := issueops.ReadMoleculeProgress(context.Background(), f.reader(), "m") + if err != nil { + t.Fatalf("ReadMoleculeProgress: %v", err) + } + if progress.Total != 4 || progress.Completed != 1 || progress.InProgress != 1 || progress.CurrentStepID != "m.d" { + t.Errorf("progress = %+v, want 4 total, 1 completed, 1 in progress (m.d)", progress) + } +} + +func TestCompletedMoleculeAnswersOnlyAnOpenCompleteAutoClosingRoot(t *testing.T) { + ctx := context.Background() + for _, tc := range []struct { + name string + rootType types.IssueType + labels []string + closeAll bool + want bool + }{ + {"molecule root, all steps closed", types.TypeMolecule, nil, true, true}, + {"template epic, all steps closed", types.TypeEpic, []string{issueops.MoleculeTemplateLabel}, true, true}, + {"plain epic stays open for explicit close", types.TypeEpic, nil, true, false}, + {"a step still open", types.TypeMolecule, nil, false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newFakeMolecules() + f.add("r", tc.rootType, types.StatusOpen, tc.labels...) + f.add("r.1", types.TypeTask, types.StatusClosed) + status := types.StatusOpen + if tc.closeAll { + status = types.StatusClosed + } + f.add("r.2", types.TypeTask, status) + f.edge("r.1", "r", types.DepParentChild) + f.edge("r.2", "r", types.DepParentChild) + root, err := issueops.CompletedMolecule(ctx, f.reader(), "r.1") + if err != nil { + t.Fatalf("CompletedMolecule: %v", err) + } + if (root != nil) != tc.want { + t.Fatalf("CompletedMolecule = %v, want completed=%v", root, tc.want) + } + }) + } + + f := newFakeMolecules() + f.add("orphan", types.TypeTask, types.StatusClosed) + if root, err := issueops.CompletedMolecule(ctx, f.reader(), "orphan"); err != nil || root != nil { + t.Errorf("CompletedMolecule(orphan) = %v, %v, want nil, nil", root, err) + } +} + +// A close under a root that cannot auto-close — an ordinary epic, a root +// already closed — reads no steps at all, and an eligible root's steps are read +// only up to the first open one. +func TestCompletedMoleculeReadsOnlyTheStepsItMust(t *testing.T) { + ctx := context.Background() + for _, tc := range []struct { + name string + rootType types.IssueType + status types.Status + }{ + {"ordinary epic", types.TypeEpic, types.StatusOpen}, + {"closed molecule root", types.TypeMolecule, types.StatusClosed}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newFakeMolecules() + f.add("r", tc.rootType, tc.status) + for _, id := range []string{"r.1", "r.2"} { + f.add(id, types.TypeTask, types.StatusClosed) + f.edge(id, "r", types.DepParentChild) + } + root, err := issueops.CompletedMolecule(ctx, f.reader(), "r.1") + if err != nil || root != nil { + t.Fatalf("CompletedMolecule = %v, %v, want nil, nil", root, err) + } + if len(f.related) != 0 { + t.Errorf("steps read %v, want none: this root never auto-closes", f.related) + } + }) + } + + // r.1 is open; r.2 and r.3 are closed and have steps of their own. The + // walk answers at r.1 without reading below r.2 or r.3. + f := newFakeMolecules() + f.add("r", types.TypeMolecule, types.StatusOpen) + f.add("r.1", types.TypeTask, types.StatusOpen) + f.edge("r.1", "r", types.DepParentChild) + for _, id := range []string{"r.2", "r.3"} { + f.add(id, types.TypeTask, types.StatusClosed) + f.edge(id, "r", types.DepParentChild) + f.add(id+".1", types.TypeTask, types.StatusClosed) + f.edge(id+".1", id, types.DepParentChild) + } + root, err := issueops.CompletedMolecule(ctx, f.reader(), "r.2") + if err != nil || root != nil { + t.Fatalf("CompletedMolecule = %v, %v, want nil, nil (r.1 is open)", root, err) + } + if !slices.Equal(f.related, []string{"r"}) { + t.Errorf("steps read %v, want only r's: r.1 is open, so nothing below r is read", f.related) + } +} + +// MoleculeStepsClosed covers every descendant, not just the direct steps, and a +// parent-child cycle terminates. +func TestMoleculeStepsClosedCoversEveryDescendant(t *testing.T) { + ctx := context.Background() + f := newFakeMolecules() + f.add("r", types.TypeMolecule, types.StatusOpen) + f.add("r.1", types.TypeTask, types.StatusClosed) + f.edge("r.1", "r", types.DepParentChild) + f.add("r.1.1", types.TypeTask, types.StatusOpen) + f.edge("r.1.1", "r.1", types.DepParentChild) + if closed, err := issueops.MoleculeStepsClosed(ctx, f.reader(), "r"); err != nil || closed { + t.Errorf("MoleculeStepsClosed with r.1.1 open = %v, %v, want false", closed, err) + } + + f.issues["r.1.1"].Status = types.StatusClosed + f.edge("r", "r.1.1", types.DepParentChild) // a cycle back to the root + f.related = nil + if closed, err := issueops.MoleculeStepsClosed(ctx, f.reader(), "r"); err != nil || !closed { + t.Errorf("MoleculeStepsClosed with every step closed = %v, %v, want true", closed, err) + } + if len(f.related) != 3 { + t.Errorf("steps read %v, want r, r.1 and r.1.1 once each", f.related) + } + + f.relatedErr = errors.New("refused") + if _, err := issueops.MoleculeStepsClosed(ctx, f.reader(), "r"); !errors.Is(err, f.relatedErr) { + t.Errorf("MoleculeStepsClosed with a refused read = %v, want the refusal", err) + } +} + +// The root close's refusals that leave the step's close standing are the close +// policy and the close guards; a lost race on the root's revision is not one. +func TestIsMoleculeAutoCloseRefusalIsPolicyAndGuardsNeverAVersionRace(t *testing.T) { + for _, tc := range []struct { + name string + err error + want bool + }{ + {"live blocker", &issueops.BlockedError{IssueID: "r", Blockers: []issueops.Blocker{{ID: "b"}}, Err: issueops.ErrCloseBlocked}, true}, + {"open children", &issueops.CloseOpenChildrenError{IssueID: "r", OpenChildren: 1}, true}, + {"template root", &issueops.TemplateReadOnlyError{IssueID: "r"}, true}, + {"pinned root", &issueops.PinnedError{IssueID: "r"}, true}, + {"root assigned to someone else", &issueops.CloseNotAssigneeError{IssueID: "r", Assignee: "bob", Actor: "alice"}, true}, + {"wrapped guard", fmt.Errorf("close r: %w", &issueops.CloseNotAssigneeError{IssueID: "r", Assignee: "bob", Actor: "alice"}), true}, + {"lost race on the root revision", issueops.ErrVersionMismatch, false}, + {"typed lost race", &issueops.VersionMismatchError{Expected: 1, Current: 2}, false}, + {"wrapped lost race", fmt.Errorf("close r: %w", &issueops.VersionMismatchError{Expected: 1, Current: 2}), false}, + {"storage failure", errors.New("connection reset"), false}, + {"no error", nil, false}, + } { + if got := issueops.IsMoleculeAutoCloseRefusal(tc.err); got != tc.want { + t.Errorf("%s: IsMoleculeAutoCloseRefusal(%v) = %v, want %v", tc.name, tc.err, got, tc.want) + } + } +} + +func TestMoleculeRootCloseIsUnforcedAndGuardedOnTheRootRevision(t *testing.T) { + root := &issueops.Issue{ID: "r", RowVersion: 41} + got := issueops.MoleculeRootClose(root, "alice", "sess") + if got.ExpectedVersion == nil || *got.ExpectedVersion != 41 || got.Force { + t.Errorf("root close = %+v, want unforced and guarded on the root revision 41", got) + } + if got.IssueID != "r" || got.Reason != issueops.MoleculeAutoCloseReason || got.Session != "sess" || got.Actor != "alice" { + t.Errorf("root close = %+v, want root r, the auto-close reason, the session and the actor", got) + } + root.RowVersion = 42 + if *got.ExpectedVersion != 41 { + t.Error("the guard aliases the root's revision; it must be the revision read") + } +} + +func TestMoleculeStepperClaimsTheNextReadyStepForTheActor(t *testing.T) { + ctx := context.Background() + f := newFakeMolecules() + seedChain(f) + + // Without AutoClaim nothing is written. + res, err := f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.a"}) + if err != nil { + t.Fatalf("Advance: %v", err) + } + if res.MoleculeID != "m" || res.Claimed || res.NextStep == nil || res.NextStep.ID != "m.b" || len(f.claimed) != 0 { + t.Fatalf("Advance without a claim = %+v (claimed %v), want next m.b and no claim", res, f.claimed) + } + + res, err = f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.a", AutoClaim: true}) + if err != nil { + t.Fatalf("Advance: %v", err) + } + if !res.Claimed || res.NextStep == nil || res.NextStep.ID != "m.b" || res.NextStep.Assignee != "alice" || + res.NextStep.Status != types.StatusInProgress { + t.Fatalf("Advance = %+v, want m.b claimed for alice", res) + } + if !slices.Equal(f.claimed, []string{"m.b"}) || len(f.updated) != 0 { + t.Errorf("claims = %v / updates = %v, want one Claimer claim of m.b", f.claimed, f.updated) + } +} + +// A ready step another actor holds is skipped, never taken; any other claim +// failure is returned rather than read as a lost race. +func TestMoleculeStepperSkipsAHeldStepAndReturnsOtherFailures(t *testing.T) { + ctx := context.Background() + f := newFakeMolecules() + f.add("m", types.TypeMolecule, types.StatusOpen) + for _, id := range []string{"m.1", "m.2"} { + f.add(id, types.TypeTask, types.StatusOpen) + f.edge(id, "m", types.DepParentChild) + } + f.add("m.0", types.TypeTask, types.StatusClosed) + f.edge("m.0", "m", types.DepParentChild) + f.claimErrs["m.1"] = &issueops.ClaimConflictError{Err: issueops.ErrAlreadyClaimed} + + res, err := f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.0", AutoClaim: true}) + if err != nil { + t.Fatalf("Advance: %v", err) + } + if !res.Claimed || res.NextStep.ID != "m.2" { + t.Fatalf("Advance = %+v, want m.1 skipped (held) and m.2 claimed", res) + } + + f.issues["m.2"].Status, f.issues["m.2"].Assignee = types.StatusOpen, "" + boom := errors.New("connection reset") + f.claimErrs["m.1"] = boom + if _, err := f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.0", AutoClaim: true}); !errors.Is(err, boom) { + t.Fatalf("Advance with a failed claim = %v, want the failure", err) + } + + f.claimErrs["m.1"] = issueops.ErrNotClaimable + f.claimErrs["m.2"] = issueops.ErrAlreadyClaimed + res, err = f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.0", AutoClaim: true}) + if err != nil || res.Claimed || res.NextStep == nil || res.NextStep.ID != "m.1" { + t.Fatalf("Advance with every ready step lost = %+v, %v; want no claim and the first ready step named", res, err) + } +} + +func TestMoleculeStepperClaimsAWispStepThroughLifecycle(t *testing.T) { + f := newFakeMolecules() + f.add("w", types.TypeMolecule, types.StatusOpen).Ephemeral = true + f.add("w.1", types.TypeTask, types.StatusClosed).Ephemeral = true + f.add("w.2", types.TypeTask, types.StatusOpen).Ephemeral = true + f.edge("w.1", "w", types.DepParentChild) + f.edge("w.2", "w", types.DepParentChild) + res, err := f.stepper().Advance(context.Background(), issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "w.1", AutoClaim: true}) + if err != nil { + t.Fatalf("Advance: %v", err) + } + if !res.Claimed || !slices.Equal(f.updated, []string{"w.2"}) || len(f.claimed) != 0 { + t.Fatalf("Advance over a wisp = %+v (updates %v, claims %v), want w.2 claimed through Lifecycle", res, f.updated, f.claimed) + } +} + +func TestMoleculeStepperOutsideAMoleculeAndWhenComplete(t *testing.T) { + ctx := context.Background() + f := newFakeMolecules() + f.add("orphan", types.TypeTask, types.StatusClosed) + res, err := f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "orphan", AutoClaim: true}) + if err != nil || res.MoleculeID != "" || res.ClosedStep == nil || res.NextStep != nil { + t.Fatalf("Advance outside a molecule = %+v, %v; want no molecule", res, err) + } + + f.add("m", types.TypeMolecule, types.StatusOpen) + f.add("m.1", types.TypeTask, types.StatusClosed) + f.edge("m.1", "m", types.DepParentChild) + res, err = f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.1", AutoClaim: true}) + if err != nil || !res.Complete || res.NextStep != nil { + t.Fatalf("Advance on a complete molecule = %+v, %v; want complete", res, err) + } + + if _, err := f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "absent"}); !errors.Is(err, issueops.ErrNotFound) { + t.Errorf("Advance on an absent step = %v, want ErrNotFound", err) + } + for _, req := range []issueops.AdvanceRequest{{ClosedStepID: "m.1"}, {Actor: "alice"}} { + if _, err := f.stepper().Advance(ctx, req); !errors.Is(err, issueops.ErrValidation) { + t.Errorf("Advance(%+v) = %v, want ErrValidation", req, err) + } + } +} + +func TestActiveMoleculeIDsFallsBackToHookedWork(t *testing.T) { + ctx := context.Background() + f := newFakeMolecules() + seedChain(f) + f.issues["m.b"].Status, f.issues["m.b"].Assignee = types.StatusInProgress, "alice" + ids, err := issueops.ActiveMoleculeIDs(ctx, f, f.reader(), "alice") + if err != nil || !slices.Equal(ids, []string{"m"}) { + t.Fatalf("ActiveMoleculeIDs = %v, %v, want [m]", ids, err) + } + + g := newFakeMolecules() + g.add("epic", types.TypeEpic, types.StatusOpen) + g.add("handoff", types.TypeTask, types.StatusHooked).Assignee = "bob" + g.edge("handoff", "epic", types.DepBlocks) + ids, err = issueops.ActiveMoleculeIDs(ctx, g, g.reader(), "bob") + if err != nil || !slices.Equal(ids, []string{"epic"}) { + t.Fatalf("ActiveMoleculeIDs (hooked) = %v, %v, want [epic]", ids, err) + } + ids, err = issueops.ActiveMoleculeIDs(ctx, g, g.reader(), "carol") + if err != nil || len(ids) != 0 { + t.Fatalf("ActiveMoleculeIDs (nobody's work) = %v, %v, want none", ids, err) + } +} diff --git a/issueops/moleculestepper.go b/issueops/moleculestepper.go new file mode 100644 index 000000000..d749cae88 --- /dev/null +++ b/issueops/moleculestepper.go @@ -0,0 +1,209 @@ +package issueops + +import ( + "context" + "errors" + "fmt" +) + +// AdvanceRequest describes moving a molecule on after one of its steps +// closed: the operation behind `bd close --continue`. +type AdvanceRequest struct { + // Actor is who advances. With AutoClaim it becomes the claimed step's + // assignee, exactly as ClaimRequest.Actor does. It must not be empty. + Actor string + // ClosedStepID names the step that closed. It must not be empty, and an + // id that names nothing is ErrNotFound. Nothing requires the step to be + // closed: advancing reads where the molecule stands now. + ClosedStepID string + // AutoClaim claims the next ready step for Actor. Without it the advance + // writes nothing and only names the step. + AutoClaim bool +} + +// AdvanceResult reports where a molecule stands after the advance. +type AdvanceResult struct { + // ClosedStep is the step the request named, as read before any claim. + ClosedStep *Issue + // MoleculeID is the step's molecule root, or "" when the step belongs to + // no molecule — in which case nothing else below is set. + MoleculeID string + // Complete reports that every step of the molecule is closed. NextStep is + // then nil. + Complete bool + // NextStep is the step the advance claimed or, without a claim, the first + // ready step (see MoleculeView.ReadySteps). Nil when no step is ready. + NextStep *Issue + // Claimed reports that the advance claimed NextStep for Actor: NextStep is + // then the post-claim row, in progress and assigned to Actor. + Claimed bool +} + +// MoleculeStepper describes advancing a molecule to its next ready step. Like +// Lifecycle and Claimer it is a role with its own accessor; a new capability +// gets a new role interface, so never append a method here. +// +// THE CLAIM IS A REAL CLAIM. A durable step is claimed through the Claimer +// role and a wisp step through Lifecycle.Update's Claim (the Claimer does not +// serve the wisp plane; both run the one claim compare-and-set). Either way +// the step's assignee becomes Actor and a step another actor holds is refused +// rather than taken. A ready step lost that way — held by someone else, or +// moved out of a claimable status since it was read — is skipped for the next +// ready step; when every ready step is lost the advance claims nothing and +// still reports the first one as NextStep. Any other claim failure is +// returned. +// +// Implementations never mutate the caller's request. Validation failures +// match ErrValidation and write nothing. +type MoleculeStepper interface { + Advance(ctx context.Context, req AdvanceRequest) (AdvanceResult, error) +} + +// MoleculeStepperRoles is the role set the shared stepper is composed over. +type MoleculeStepperRoles struct { + Reader MoleculeReader + Claimer Claimer + Lifecycle Lifecycle +} + +// moleculeStepperSource is the accessor set a store or unit-of-work provider +// offers for the roles NewMoleculeStepper composes. +type moleculeStepperSource interface { + BatchGetter() (BatchGetter, error) + IssueRelations() (Relations, error) + EdgeReader() (EdgeReader, error) + IssueClaimer() (Claimer, error) + IssueLifecycle() (Lifecycle, error) +} + +// MoleculeStepperRolesOf binds the stepper's roles to src's own accessors. +func MoleculeStepperRolesOf(src moleculeStepperSource) (MoleculeStepperRoles, error) { + reader, err := NewMoleculeReader(src) + if err != nil { + return MoleculeStepperRoles{}, err + } + claimer, err := src.IssueClaimer() + if err != nil { + return MoleculeStepperRoles{}, err + } + lifecycle, err := src.IssueLifecycle() + if err != nil { + return MoleculeStepperRoles{}, err + } + return MoleculeStepperRoles{Reader: reader, Claimer: claimer, Lifecycle: lifecycle}, nil +} + +// NewMoleculeStepper is THE MoleculeStepper implementation. Every store +// backend's accessor answers it composed over that backend's own roles. The +// http client's accessor dials the server's issues.advanceMolecule instead, +// where the server's library runs this stepper, and refuses before dialing a +// server that does not advertise the operation; it never composes a copy over +// the client's roles. So every route advances a molecule by one rule. +func NewMoleculeStepper(roles MoleculeStepperRoles) MoleculeStepper { + return moleculeStepper{roles: roles} +} + +type moleculeStepper struct{ roles MoleculeStepperRoles } + +// ValidateAdvanceRequest applies the request rules every MoleculeStepper +// shares. +func ValidateAdvanceRequest(req AdvanceRequest) error { + if req.Actor == "" { + return fmt.Errorf("%w: advance requires an actor", ErrValidation) + } + if req.ClosedStepID == "" { + return fmt.Errorf("%w: advance requires the closed step id", ErrValidation) + } + return nil +} + +func (s moleculeStepper) Advance(ctx context.Context, req AdvanceRequest) (AdvanceResult, error) { + if err := ValidateAdvanceRequest(req); err != nil { + return AdvanceResult{}, err + } + r := s.roles.Reader + if !r.usable() || s.roles.Claimer == nil || s.roles.Lifecycle == nil { + return AdvanceResult{}, fmt.Errorf("%w: molecule stepper is missing a role", ErrValidation) + } + steps, err := getIssues(ctx, r, []string{req.ClosedStepID}) + if err != nil { + return AdvanceResult{}, err + } + closed := steps[req.ClosedStepID] + if closed == nil { + return AdvanceResult{}, fmt.Errorf("%w: issue %s", ErrNotFound, req.ClosedStepID) + } + result := AdvanceResult{ClosedStep: closed} + + rootID, err := MoleculeRoot(ctx, r, req.ClosedStepID) + if err != nil { + return AdvanceResult{}, fmt.Errorf("finding the molecule of %s: %w", req.ClosedStepID, err) + } + if rootID == "" { + return result, nil + } + result.MoleculeID = rootID + + view, err := ViewMolecule(ctx, r, rootID) + if err != nil { + return AdvanceResult{}, fmt.Errorf("loading molecule %s: %w", rootID, err) + } + if view.Complete() { + result.Complete = true + return result, nil + } + ready := view.ReadySteps() + if len(ready) == 0 { + return result, nil + } + result.NextStep = ready[0] + if !req.AutoClaim { + return result, nil + } + for _, candidate := range ready { + claimed, err := s.claimStep(ctx, candidate, req.Actor) + if isLostStepClaim(err) { + continue + } + if err != nil { + return AdvanceResult{}, fmt.Errorf("claiming step %s: %w", candidate.ID, err) + } + result.NextStep = claimed + result.Claimed = true + break + } + return result, nil +} + +// claimStep claims one step for actor and answers its post-claim row, labels +// carried over from the row the view read (the claim answers the bare row). +func (s moleculeStepper) claimStep(ctx context.Context, step *Issue, actor string) (*Issue, error) { + var post *Issue + if step.Ephemeral || step.NoHistory { + res, err := s.roles.Lifecycle.Update(ctx, UpdateRequest{Actor: actor, IssueID: step.ID, Claim: true}) + if err != nil { + return nil, err + } + post = res.Issue + } else { + res, err := s.roles.Claimer.Claim(ctx, ClaimRequest{Actor: actor, IssueID: step.ID}) + if err != nil { + return nil, err + } + post = res.Issue + } + if post == nil { + return step, nil + } + if len(post.Labels) == 0 && len(step.Labels) > 0 { + post.Labels = append([]string(nil), step.Labels...) + } + return post, nil +} + +// isLostStepClaim reports whether a step claim failed because the step is no +// longer this actor's to take: held by another actor, or moved out of a +// claimable status since the view read it. +func isLostStepClaim(err error) bool { + return err != nil && (errors.Is(err, ErrAlreadyClaimed) || errors.Is(err, ErrNotClaimable)) +} diff --git a/issueops/promote.go b/issueops/promote.go new file mode 100644 index 000000000..d14d5bae0 --- /dev/null +++ b/issueops/promote.go @@ -0,0 +1,118 @@ +package issueops + +import ( + "context" + "fmt" +) + +// PromoteRequest describes one `bd promote`: move a wisp onto the durable +// issues plane and record why. +type PromoteRequest struct { + // Actor is the principal the move and the comment are attributed to. It + // must not be empty. + Actor string + // IssueID is the exact canonical id of the wisp. It must not be empty; + // fuzzy or prefix resolution is the caller's, for the reason + // GetRequest.ID gives. + IssueID string + // Reason is the optional text appended to the promotion comment. + Reason string + // Provenance labels the version-control history entry of the move, as + // UpdateRequest.Provenance describes. A remote backend labels its own + // entry, so a caller writing through one leaves it empty. + Provenance string +} + +// PromoteResult reports a promotion. +type PromoteResult struct { + // Issue is the promoted row as the move left it. + Issue *Issue + // CommentErr is set when the move succeeded but the promotion comment + // could not be written. The promotion stands: the comment is the audit + // note, not the act, and bd promote has always reported a failed comment + // as a warning rather than undoing the move. + CommentErr error +} + +// PromoteRoles are the three roles Promote composes. Every backend serves +// all three, so a promotion reads and writes the same way on every route. +type PromoteRoles struct { + Reader Reader + Lifecycle Lifecycle + Commenter Commenter +} + +// NotAWispError refuses a promotion of a row that is not an ephemeral wisp: +// it is already durable, or another writer promoted it first. A no-history +// wisp (NoHistory set, Ephemeral not) is refused with the same sentence, +// because the gate reads the Ephemeral flag as `bd promote` always has; +// `bd update --persistent` is the move for that row. +type NotAWispError struct { + ID string +} + +func (e *NotAWispError) Error() string { + return fmt.Sprintf("%s is not a wisp (already persistent)", e.ID) +} + +// PromotionComment is the audit comment a promotion records on the promoted +// row. Every route records exactly this text. +func PromotionComment(reason string) string { + comment := "Promoted from Level 0" + if reason != "" { + comment += ": " + reason + } + return comment +} + +// Promote is the one library entry for `bd promote`. It reads the row, +// refuses one that is not an ephemeral wisp (*NotAWispError), moves it to the +// durable plane with ONE Lifecycle.Update whose patch is the persistence move +// alone (Persistence = persistent: the row keeps its id, and its labels, +// dependencies, events and comments move with it, atomically, in the role's +// own transaction), and then records the promotion comment through the +// Commenter. +// +// A move that changed nothing lost a race to another promoter, and is +// reported as *NotAWispError without a second comment. Every refusal of the +// read or the move is returned unchanged, so a backend that cannot express +// the move (an http server without the issues.update.persistence capability) +// reaches the caller as its own typed refusal, before anything was written. +func Promote(ctx context.Context, roles PromoteRoles, req PromoteRequest) (PromoteResult, error) { + if req.Actor == "" { + return PromoteResult{}, fmt.Errorf("%w: promote: actor is required", ErrValidation) + } + if req.IssueID == "" { + return PromoteResult{}, fmt.Errorf("%w: promote: issue id is required", ErrValidation) + } + current, err := roles.Reader.Get(ctx, GetRequest{ID: req.IssueID}) + if err != nil { + return PromoteResult{}, err + } + if !current.Ephemeral { + return PromoteResult{}, &NotAWispError{ID: req.IssueID} + } + moved, err := roles.Lifecycle.Update(ctx, UpdateRequest{ + Actor: req.Actor, + IssueID: req.IssueID, + Patch: IssuePatch{ + Persistence: Field[PersistenceMode]{Set: true, Value: PersistenceModePersistent}, + }, + Provenance: req.Provenance, + }) + if err != nil { + return PromoteResult{}, err + } + if !moved.Changed { + return PromoteResult{}, &NotAWispError{ID: req.IssueID} + } + result := PromoteResult{Issue: moved.Issue} + if _, err := roles.Commenter.AddComment(ctx, AddCommentRequest{ + Author: req.Actor, + IssueID: req.IssueID, + Text: PromotionComment(req.Reason), + }); err != nil { + result.CommentErr = err + } + return result, nil +} diff --git a/issueops/promote_test.go b/issueops/promote_test.go new file mode 100644 index 000000000..28cb433cb --- /dev/null +++ b/issueops/promote_test.go @@ -0,0 +1,207 @@ +package issueops_test + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads/issueops" +) + +// promoteFakes is the three roles issueops.Promote composes. Each embeds its +// interface so a method the entry must not call panics on the nil. +type promoteFakes struct { + issue *issueops.Issue + getErr error + updateErr error + unchanged bool + commentErr error + + updates []issueops.UpdateRequest + comments []issueops.AddCommentRequest +} + +type promoteReader struct { + issueops.Reader + f *promoteFakes +} + +func (r promoteReader) Get(_ context.Context, req issueops.GetRequest) (*issueops.IssueDetails, error) { + if r.f.getErr != nil { + return nil, r.f.getErr + } + if r.f.issue == nil || r.f.issue.ID != req.ID { + return nil, issueops.ErrNotFound + } + return &issueops.IssueDetails{Issue: *r.f.issue}, nil +} + +type promoteLifecycle struct { + issueops.Lifecycle + f *promoteFakes +} + +func (l promoteLifecycle) Update(_ context.Context, req issueops.UpdateRequest) (issueops.UpdateResult, error) { + l.f.updates = append(l.f.updates, req) + if l.f.updateErr != nil { + return issueops.UpdateResult{}, l.f.updateErr + } + promoted := *l.f.issue + promoted.Ephemeral = false + return issueops.UpdateResult{Issue: &promoted, Changed: !l.f.unchanged}, nil +} + +type promoteCommenter struct { + issueops.Commenter + f *promoteFakes +} + +func (c promoteCommenter) AddComment(_ context.Context, req issueops.AddCommentRequest) (issueops.AddCommentResult, error) { + c.f.comments = append(c.f.comments, req) + if c.f.commentErr != nil { + return issueops.AddCommentResult{}, c.f.commentErr + } + return issueops.AddCommentResult{Comment: &issueops.Comment{IssueID: req.IssueID, Author: req.Author, Text: req.Text}}, nil +} + +func (f *promoteFakes) roles() issueops.PromoteRoles { + return issueops.PromoteRoles{ + Reader: promoteReader{f: f}, + Lifecycle: promoteLifecycle{f: f}, + Commenter: promoteCommenter{f: f}, + } +} + +func wisp(id string) *issueops.Issue { + return &issueops.Issue{ID: id, Title: "a wisp", Ephemeral: true} +} + +func TestPromoteMovesTheWispThroughOnePersistenceUpdateThenComments(t *testing.T) { + f := &promoteFakes{issue: wisp("bd-w1")} + res, err := issueops.Promote(t.Context(), f.roles(), issueops.PromoteRequest{ + Actor: "alice", IssueID: "bd-w1", Reason: "keep it", Provenance: "bd: promote bd-w1", + }) + if err != nil { + t.Fatalf("Promote: %v", err) + } + if len(f.updates) != 1 { + t.Fatalf("updates = %d, want exactly one", len(f.updates)) + } + u := f.updates[0] + if u.Actor != "alice" || u.IssueID != "bd-w1" || u.Provenance != "bd: promote bd-w1" { + t.Errorf("update request = %+v, want actor alice, id bd-w1 and the caller's provenance", u) + } + if !u.Patch.Persistence.Set || u.Patch.Persistence.Value != issueops.PersistenceModePersistent { + t.Errorf("update patch persistence = %+v, want set to persistent", u.Patch.Persistence) + } + // The update is the plane move and nothing else. + only := issueops.IssuePatch{Persistence: u.Patch.Persistence} + if !reflect.DeepEqual(u.Patch, only) { + t.Errorf("update patch carries more than the persistence move: %+v", u.Patch) + } + if len(f.comments) != 1 { + t.Fatalf("comments = %d, want exactly one", len(f.comments)) + } + c := f.comments[0] + if c.Author != "alice" || c.IssueID != "bd-w1" || c.Text != "Promoted from Level 0: keep it" { + t.Errorf("comment = %+v, want alice's promotion comment with the reason", c) + } + if res.Issue == nil || res.Issue.Ephemeral || res.CommentErr != nil { + t.Errorf("result = %+v, want the promoted row and no comment error", res) + } +} + +func TestPromotionCommentWithoutAReason(t *testing.T) { + if got := issueops.PromotionComment(""); got != "Promoted from Level 0" { + t.Errorf("PromotionComment(\"\") = %q", got) + } +} + +func TestPromoteRefusesARowThatIsNotAWispBeforeWriting(t *testing.T) { + f := &promoteFakes{issue: &issueops.Issue{ID: "bd-1", Title: "durable"}} + _, err := issueops.Promote(t.Context(), f.roles(), issueops.PromoteRequest{Actor: "alice", IssueID: "bd-1"}) + var notWisp *issueops.NotAWispError + if !errors.As(err, ¬Wisp) || notWisp.ID != "bd-1" { + t.Fatalf("err = %v, want *NotAWispError for bd-1", err) + } + if err.Error() != "bd-1 is not a wisp (already persistent)" { + t.Errorf("message = %q, want the sentence bd promote always printed", err.Error()) + } + if len(f.updates) != 0 || len(f.comments) != 0 { + t.Errorf("wrote %d updates and %d comments, want none", len(f.updates), len(f.comments)) + } +} + +func TestPromoteReportsALostRaceAsNotAWisp(t *testing.T) { + // Another writer promoted the row between the read and the update: the + // update is a no-op, and no second promotion comment is written. + f := &promoteFakes{issue: wisp("bd-w2"), unchanged: true} + _, err := issueops.Promote(t.Context(), f.roles(), issueops.PromoteRequest{Actor: "alice", IssueID: "bd-w2"}) + var notWisp *issueops.NotAWispError + if !errors.As(err, ¬Wisp) { + t.Fatalf("err = %v, want *NotAWispError", err) + } + if len(f.comments) != 0 { + t.Errorf("wrote %d comments after a no-op promote, want none", len(f.comments)) + } +} + +func TestPromotePassesRefusalsThroughUnchanged(t *testing.T) { + refusal := &issueops.ErrUnsupported{Op: "Lifecycle.Update", Backend: "http", Capability: "issues.update.persistence"} + for name, f := range map[string]*promoteFakes{ + "missing": {}, + "get": {issue: wisp("bd-w3"), getErr: errors.New("boom")}, + "update": {issue: wisp("bd-w3"), updateErr: refusal}, + } { + t.Run(name, func(t *testing.T) { + _, err := issueops.Promote(t.Context(), f.roles(), issueops.PromoteRequest{Actor: "alice", IssueID: "bd-w3"}) + if err == nil { + t.Fatal("no error") + } + switch name { + case "missing": + if !errors.Is(err, issueops.ErrNotFound) { + t.Errorf("err = %v, want ErrNotFound", err) + } + case "update": + var unsup *issueops.ErrUnsupported + if !errors.As(err, &unsup) || unsup.Capability != "issues.update.persistence" { + t.Errorf("err = %v, want the capability refusal unchanged", err) + } + } + if len(f.comments) != 0 { + t.Errorf("commented after a failed promote") + } + }) + } +} + +func TestPromoteKeepsThePromotionWhenTheCommentFails(t *testing.T) { + f := &promoteFakes{issue: wisp("bd-w4"), commentErr: errors.New("comment down")} + res, err := issueops.Promote(t.Context(), f.roles(), issueops.PromoteRequest{Actor: "alice", IssueID: "bd-w4"}) + if err != nil { + t.Fatalf("Promote: %v, want the promotion to stand", err) + } + if res.CommentErr == nil || res.Issue == nil { + t.Errorf("result = %+v, want the promoted row and the comment error", res) + } +} + +func TestPromoteValidatesTheRequest(t *testing.T) { + for name, req := range map[string]issueops.PromoteRequest{ + "no actor": {IssueID: "bd-w5"}, + "no id": {Actor: "alice"}, + } { + t.Run(name, func(t *testing.T) { + f := &promoteFakes{issue: wisp("bd-w5")} + _, err := issueops.Promote(t.Context(), f.roles(), req) + if !errors.Is(err, issueops.ErrValidation) { + t.Errorf("err = %v, want ErrValidation", err) + } + if len(f.updates) != 0 { + t.Errorf("updated on an invalid request") + } + }) + } +} diff --git a/issueops/querier.go b/issueops/querier.go index edd3b22b1..c02bf789b 100644 --- a/issueops/querier.go +++ b/issueops/querier.go @@ -61,16 +61,21 @@ type QueryRequest struct { // than a synonym for unlimited: two spellings of "no bound" is one more // than a caller can check for. // - // NOTHING BACKSTOPS IT. ListRequest pairs its Limit with MaxRows, a - // circuit breaker that refuses an oversized answer outright; this request - // has no twin to it by design, and neither knob that sets that one - // (`--max-rows`, BEADS_MAX_ROWS) is read anywhere on the query path. So an - // unlimited query is unbounded in the plain sense: it reads every row the - // expression matches, however many that is, and a caller who asked for one - // gets it rather than an ErrTooManyRows. The ceiling here is Limit itself. - // This is reachable without asking: a piped `bd query` resolves its - // unflagged limit to 0 before the request, the same policy `bd list` has - // applied to piped output since GH#4094. + // NOTHING BACKSTOPS IT on any backend but http (below). ListRequest pairs + // its Limit with MaxRows, a circuit breaker that refuses an oversized + // answer outright; this request has no twin to it by design, and neither + // knob that sets that one (`--max-rows`, BEADS_MAX_ROWS) is read anywhere + // on the query path. So an unlimited query is unbounded in the plain sense: + // it reads every row the expression matches, however many that is, and a + // caller who asked for one gets it rather than an ErrTooManyRows. The + // ceiling here is Limit itself. This is reachable without asking: a piped + // `bd query` resolves its unflagged limit to 0 before the request, the same + // policy `bd list` has applied to piped output since GH#4094. + // + // The http backend is the one exception, because its whole answer is one + // response: it bounds an unlimited query at BEADS_HTTP_UNLIMITED_READ_CAP + // rows and refuses a larger answer with httpclient.ErrUnlimitedReadCap + // rather than truncating it. Limit *int // Offset skips the first N MATCHING rows, on EVERY implementation and for diff --git a/issueops/reader.go b/issueops/reader.go index 0a0219f52..23cee7bd3 100644 --- a/issueops/reader.go +++ b/issueops/reader.go @@ -54,7 +54,15 @@ type ReadyRequest struct { // the other, and P0 has already been lost that way once. Priority *int - // ParentID restricts to recursive descendants of one issue. + // ParentID restricts to ALL TRANSITIVE DESCENDANTS of one issue, not just + // its direct children: internal/storage/issueops/ready_work.go calls + // GetDescendantIDsInTx(ctx, tx, *filter.ParentID, 0), the recursive walk. + // GH#3396: this used to be a one-hop subquery against the dependency + // table, so grandchildren were silently dropped despite this comment and + // the help text both promising "descendants (recursive)" — do not + // mistake this for ListRequest.ParentID's non-walking clause, which is a + // DIFFERENT query (PR #7199 review: an earlier pass here wrongly copied + // that one-level wording onto this field). ParentID string // MolType restricts to one molecule type. MolType *MolType @@ -85,7 +93,9 @@ type ReadyRequest struct { // Limit bounds the page. Nil means the shared ready default; 0 means // unlimited. It is a pointer so that "unset" and "explicitly unlimited" // stay distinguishable, which is what lets one constant serve both - // surfaces. + // surfaces. Over the http backend an unlimited ready read is one + // response, bounded at BEADS_HTTP_UNLIMITED_READ_CAP rows and refused + // past it with httpclient.ErrUnlimitedReadCap, never truncated. Limit *int // Offset skips the first N matching rows, on EVERY implementation. The // page a caller receives is the rows at positions [Offset, Offset+Limit) @@ -134,6 +144,16 @@ type ListRequest struct { // so `pinned` and `hooked` are the two spellings that also drop that // predicate — every other status narrows to unflagged rows. Status string + // ExcludeStatus names statuses to leave out, on top of whatever Status or + // the default exclusions select (it never re-admits a row they hide). + // Entries may be comma-separated, and each name is validated against the + // workspace vocabulary (built-in plus custom statuses) exactly as + // CountRequest.ExcludeStatus is: an unknown name is ErrValidation rather + // than excluding nothing, because a silently ignored exclusion answers a + // wider set. With AllFlag there are no default exclusions, so the + // listing keeps every status not named here, without the caller + // having to enumerate every status it wants. + ExcludeStatus []string // IssueType is validated against the workspace vocabulary — unlike // ReadyRequest.IssueType, which matches nothing rather than failing. IssueType string @@ -142,6 +162,17 @@ type ListRequest struct { SpecPrefix string // IDFilter is a comma-separated id set. IDFilter string + // Query is `bd search`'s free text, with that command's meaning and not + // TitleSearch's: a row matches when its title contains the text or its id + // does, case-insensitively, and an id-shaped text also matches an exact + // id, an id prefix and the external ref. It is the `query` argument of the + // storage seam's SearchIssues, carried as a member so a backend that + // serves only roles can answer a search. + // + // It narrows; it lifts no default exclusion. A caller that wants search's + // "every status, every kind of row" answer asks for that with AllFlag and + // the Include* members, as for any other listing. + Query string Labels []string LabelsAny []string @@ -263,6 +294,11 @@ type ListRequest struct { // On the ReadyFlag arm neither applies: that set decides pinned for itself, // which is why PinnedFlag is refused there and NoPinnedFlag merely accepted // (see AllFlag). + // + // The two together are a contradiction and are refused with ErrValidation + // on every route, the way `bd list --pinned --no-pinned` refuses: no + // answer is both only-flagged and only-unflagged, and letting one win + // would answer a question the caller did not ask. PinnedFlag bool NoPinnedFlag bool IncludeTemplates bool @@ -301,6 +337,14 @@ type ListRequest struct { // field alone reaches is the ephemeral rows of the types a listing already // shows. // + // AN INFRA IssueType IS THE ONE NARROWING IT LIFTS. Naming a type the + // workspace calls infra reads only that type's EPHEMERAL rows, which is + // where creating one puts it; with this flag set the request reads the + // type's rows on both planes instead, because an infra-typed row can still + // be durable — a promoted wisp, an issue retyped after it was created, or + // one written before its type joined types.infra. That is the superset + // promise above applied to the narrowing; IncludeInfra alone keeps it. + // // THE MERGED ANSWER IS ONE ORDER. Both planes are ordered together by // SortBy as if they were a single table — not the durable rows followed by // the ephemeral ones — so a Limit truncates the merged order rather than @@ -339,6 +383,34 @@ type ListRequest struct { // ExcludeTypes entries may be comma-separated; splitting happens inside. ExcludeTypes []string + // ParentID restricts to one issue's children through one SQL clause, the + // same one CountRequest.ParentID compiles to + // (internal/storage/sqlbuild/filter.go): a parent-child dependency edge + // onto ParentID, OR, for a row with no parent-child edge at all, an id + // under ParentID's dotted prefix ("X.1", "X.1.1"). NEITHER ARM WALKS. The + // edge arm stops at one level, so a grandchild with an edge of its own is + // not in the answer, while the prefix arm reaches every edge-less dotted + // id at any depth (backend/conformance/reader_contract.go pins that arm). + // It is NOT the recursive descendants walk — that is ReadyRequest.ParentID + // above, a DIFFERENT field on a different request, backed by + // GetDescendantIDsInTx (GH#3396); on the ReadyFlag arm this field crosses + // to that query and resolves recursively there. + // The recursive tree that `bd list --parent X` renders by DEFAULT comes + // from cmd/bd/list_show_filter_modes.go's findAllDescendants re-running + // this clause against the store once per level and accumulating the + // results client-side, not from this field answering a deeper question. + // --flat, --json and --format skip that walk and return exactly this + // field's answer, which is why the flat listing is the invocation that + // agrees with `bd count --parent X`'s cardinality. + // + // NoParent restricts to rows with no parent-child dependency edge. It has + // no dotted-id arm, so an edge-less "X.1" matches BOTH ParentID X and + // NoParent. The ReadyFlag arm refuses it; see that field. + // + // Setting both is refused with ErrValidation on every route, as + // CountRequest refuses it and in the sentence `bd list --parent X + // --no-parent` refuses with, rather than answered with only the edge-less + // rows under X's dotted id, which both clauses match. ParentID string NoParent bool MolType *MolType @@ -385,7 +457,7 @@ type ListRequest struct { // fields rather than answering a wider question than was asked. That is // IDFilter, TitleSearch, SpecPrefix, the four *Contains fields, // ExternalRef, every Created/Updated/Closed/Defer/Due bound, DeferredFlag, - // OverdueFlag, EmptyDesc, NoLabels, NoParent, PinnedFlag, PriorityMin, + // OverdueFlag, EmptyDesc, NoLabels, NoParent, PinnedFlag, ExcludeStatus, PriorityMin, // PriorityMax, and the keyset position. There is no fallback: no // combination of the two silently widens the answer. // diff --git a/issueops/reader_ready_scope.go b/issueops/reader_ready_scope.go index bf3ee326c..a62533298 100644 --- a/issueops/reader_ready_scope.go +++ b/issueops/reader_ready_scope.go @@ -64,6 +64,7 @@ type readyScopeField struct { // that can never contain one — it is in the list below. var readyScopeFields = []readyScopeField{ {"IDFilter", "--id", func(r ListRequest) bool { return r.IDFilter != "" }}, + {"Query", "bd search", func(r ListRequest) bool { return r.Query != "" }}, {"TitleSearch", "--title", func(r ListRequest) bool { return r.TitleSearch != "" }}, {"SpecPrefix", "--spec", func(r ListRequest) bool { return r.SpecPrefix != "" }}, @@ -90,6 +91,8 @@ var readyScopeFields = []readyScopeField{ {"NoLabels", "--no-labels", func(r ListRequest) bool { return r.NoLabels }}, {"NoParent", "--no-parent", func(r ListRequest) bool { return r.NoParent }}, {"PinnedFlag", "--pinned", func(r ListRequest) bool { return r.PinnedFlag }}, + // No `bd list` flag sets ExcludeStatus yet, so its wire name stands in. + {"ExcludeStatus", "exclude_status", func(r ListRequest) bool { return len(r.ExcludeStatus) > 0 }}, {"PriorityMin", "--priority-min", func(r ListRequest) bool { return r.PriorityMin != nil }}, {"PriorityMax", "--priority-max", func(r ListRequest) bool { return r.PriorityMax != nil }}, diff --git a/issueops/search.go b/issueops/search.go new file mode 100644 index 000000000..3739a10c7 --- /dev/null +++ b/issueops/search.go @@ -0,0 +1,33 @@ +package issueops + +// SearchListRequest is `bd search`'s request: the listing that answers the +// text query, with search's own scope. Every route of `bd search` — the direct +// store, the proxied server and a remote backend — asks issueops.Reader.List +// with this request (plus the caller's narrowing flags), so the three cannot +// answer the same search differently, and a remote backend serves it through +// the same role the server's listIssues handler calls. +// +// The scope is search's, not a listing's: +// - EVERY STATUS. Closed rows match unless the caller narrows with Status +// (bd-t5yex: "was this already filed or fixed?" must not answer no just +// because the answer is closed). AllFlag lifts the status exclusions and +// the pinned-flag predicate together. +// - EVERY KIND OF ROW. Templates, gates, the workspace's infrastructure types +// and the ephemeral plane all match; the four Include* members lift those +// exclusions. +// - THE STORE'S DEFAULT ORDER, priority then newest then id, so a Limit +// keeps the same rows a raw SearchIssues read kept. A display sort is the +// caller's to apply to the page afterwards. +// +// Limit is left nil (the listing default); a caller sets it. +func SearchListRequest(query string) ListRequest { + return ListRequest{ + Query: query, + AllFlag: true, + IncludeTemplates: true, + IncludeGates: true, + IncludeInfra: true, + IncludeEphemeral: true, + SortBy: "priority", + } +} diff --git a/issueops/search_test.go b/issueops/search_test.go new file mode 100644 index 000000000..9b19e8053 --- /dev/null +++ b/issueops/search_test.go @@ -0,0 +1,22 @@ +package issueops_test + +import ( + "reflect" + "testing" + + "github.com/steveyegge/beads/issueops" +) + +// TestSearchListRequestIsSearchsScope pins the library's search scope: every +// status, every kind of row, the store's default order. +func TestSearchListRequestIsSearchsScope(t *testing.T) { + got := issueops.SearchListRequest("needle") + want := issueops.ListRequest{ + Query: "needle", AllFlag: true, + IncludeTemplates: true, IncludeGates: true, IncludeInfra: true, IncludeEphemeral: true, + SortBy: "priority", + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("SearchListRequest = %+v, want %+v", got, want) + } +} diff --git a/issueops/template_errors.go b/issueops/template_errors.go new file mode 100644 index 000000000..73dc50501 --- /dev/null +++ b/issueops/template_errors.go @@ -0,0 +1,31 @@ +package issueops + +import ( + "errors" + "fmt" +) + +// ErrTemplateReadOnly is returned when a mutation that guards templates names +// one. Every update does (Lifecycle.Update, a BatchApplier update item), and so +// does every close (Lifecycle.Close, BatchCloser, a BatchApplier close item); +// not every verb does yet (bd-jkp9v3). Templates are read-only: the way to get +// work out of one is to pour it (`bd mol pour`), which creates new issues and +// leaves the template untouched. There is no force bypass — no Force flag +// waives it; only an update that sets UpdateRequest.AllowTemplate (bd label, +// bd set-state) is let through. +var ErrTemplateReadOnly = errors.New("templates are read-only") + +// TemplateReadOnlyError reports the template a mutation was refused for. Its +// message is the sentence `bd` has always printed for the refusal, so a caller +// that renders err.Error() reads the same line whichever backend refused. +type TemplateReadOnlyError struct { + // IssueID names the template that refused the mutation. + IssueID string +} + +func (e *TemplateReadOnlyError) Error() string { + return fmt.Sprintf("cannot modify template %s: templates are read-only; use 'bd mol pour' to create a work item", e.IssueID) +} + +// Unwrap makes TemplateReadOnlyError match ErrTemplateReadOnly. +func (e *TemplateReadOnlyError) Unwrap() error { return ErrTemplateReadOnly } diff --git a/journalops/BUILD.bazel b/journalops/BUILD.bazel index 47588b368..5449e5601 100644 --- a/journalops/BUILD.bazel +++ b/journalops/BUILD.bazel @@ -23,3 +23,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/memoryops/BUILD.bazel b/memoryops/BUILD.bazel index f4d5c924c..fb622d6a2 100644 --- a/memoryops/BUILD.bazel +++ b/memoryops/BUILD.bazel @@ -24,3 +24,64 @@ filegroup( ) # --- end go_srcs --- + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/memoryops/errors.go b/memoryops/errors.go index c63c53e15..126aed3c5 100644 --- a/memoryops/errors.go +++ b/memoryops/errors.go @@ -23,13 +23,8 @@ var ErrValidation = beadserrors.ErrValidation // THERE IS DELIBERATELY NO ErrNotFound ON THIS ROLE. // -// beadserrors declares one; this leaf does not re-export it. The storage seam -// beneath it cannot tell an absent config row from a row stored as the empty -// string (issueops/workspaceconfig.go states the same conflation for settings, -// and it is the same table). A role that answered a Recall of an unknown key -// with ErrNotFound would be minting an error out of a distinction it cannot -// actually see, and the first out-of-band empty write would make it a lie. -// -// Misses are RESULT-CARRIED instead — RecallResult.Found, ForgetResult.Found — -// and the front doors translate: the CLI to its SilentExit contract, an HTTP -// door to its 404. That keeps the invention where a door can justify it. +// beadserrors declares one; this leaf does not re-export it. Misses are +// RESULT-CARRIED instead — RecallResult.Found, ForgetResult.Found — and the +// front doors translate: the CLI to its SilentExit contract, an HTTP door to +// its 404. That lets callers handle absence without classifying an operational +// error and keeps presentation policy at the door. diff --git a/memoryops/memories.go b/memoryops/memories.go index fd36482de..7788f1761 100644 --- a/memoryops/memories.go +++ b/memoryops/memories.go @@ -40,11 +40,7 @@ type RememberResult struct { // observation and the act it describes. // // A previous value that was the EMPTY STRING reports Replaced true. The ROW - // existed, even though a Recall of that key would have answered Found - // false. That divergence is the storage seam's conflation showing through - // (see RecallResult.Found); it is stated here rather than smoothed over, - // because smoothing it would mean this field reporting "nothing was there" - // about a write that overwrote something. + // existed, regardless of what it held. Replaced bool } @@ -60,15 +56,9 @@ type RecallResult struct { Key string // Value is the stored content, or "" — and Found says how to read the "". Value string - // Found is Value != "". A MEMORY STORED AS THE EMPTY STRING AND AN ABSENT - // MEMORY ARE THE SAME ANSWER: Found false, nil error. - // - // No front door can create the first of those — Remember refuses empty - // content — but an out-of-band config write can, and this role does not - // invent a distinction the seam beneath it cannot see. List DOES enumerate - // such a row, because its KEY exists, and that is the one way a caller can - // tell the two apart: the same same-answer-different-row asymmetry the - // settings contract pins for `bd config get`. + // Found reports whether the row exists, independently of Value. A memory + // stored as the empty string therefore reports Found true; an absent memory + // reports Found false with the same empty Value. Found bool } @@ -84,9 +74,8 @@ type ForgetResult struct { // read in the SAME TRANSACTION as the delete, so it is what was actually // removed rather than what a previous read happened to see. Value string - // Found false means nothing was stored under Key (or an empty string was: - // the same conflation RecallResult.Found describes) and NOTHING WAS - // DELETED. + // Found false means no row was stored under Key and NOTHING WAS DELETED. A + // row holding the empty string is found and deleted. // // It is a result, not an error. The front doors own the not-found // presentation — the CLI has an exit-code contract for it — and a role that @@ -160,7 +149,7 @@ type Memories interface { // THE REFUSALS, in the order they are applied: // // - Content empty after trimming is ErrValidation. There is nothing to - // remember, and a row stored empty is a row Recall would then deny; + // remember; // - Content from which no key can be derived, when Key is empty, is // ErrValidation. The caller's recourse is an explicit key, which the // message says. diff --git a/open_backend_selection_test.go b/open_backend_selection_test.go index 1ffbaa449..36ca6bb7e 100644 --- a/open_backend_selection_test.go +++ b/open_backend_selection_test.go @@ -3,8 +3,11 @@ package beads_test import ( "context" "errors" + "maps" + "net/http" "os" "path/filepath" + "slices" "strings" "testing" @@ -15,6 +18,36 @@ import ( var errRegistryBackendOpen = errors.New("registry backend open sentinel") +var errRegistryBackendOpenWith = errors.New("registry backend OpenWith sentinel") + +// fixtureCredential is a minimal beads.Credential implementation for tests: +// a bare marker, since OpenOptions.Credential is deliberately opaque. +type fixtureCredential struct{} + +func (fixtureCredential) BackendCredential() {} + +// registerOpenWithCapturingBackend registers a backend whose OpenWith +// records the beadsDir and opts it received (via the returned pointers), and +// whose Open errors if dispatch ever falls back to it — proving +// OpenBestAvailableWith reaches OpenWith, not Open, when the backend has one. +func registerOpenWithCapturingBackend(t *testing.T, name string, gotBeadsDir *string, gotOpts *beads.OpenOptions, calls *int) { + t.Helper() + open := func(context.Context, string) (storage.DoltStorage, error) { + return nil, errors.New("fixture: Open called despite backend having OpenWith") + } + backends.Register(name, backends.Backend{ + Open: open, + OpenReadOnly: open, + OpenWith: func(_ context.Context, beadsDir string, opts backends.OpenOptions) (storage.DoltStorage, error) { + *calls++ + *gotBeadsDir = beadsDir + *gotOpts = opts + return nil, errRegistryBackendOpenWith + }, + }) + t.Cleanup(func() { backends.Deregister(name) }) +} + // registerWorkspaceBackend registers a fake WorkspaceIsBeadsDir backend whose // Open/OpenReadOnly report a sentinel instead of touching a store, so tests can // assert that discovery and open dispatch to the registry without provisioning @@ -33,6 +66,29 @@ func registerWorkspaceBackend(t *testing.T, name string) { t.Cleanup(func() { backends.Deregister(name) }) } +// plainDoltServerModeBeadsDir writes metadata.json naming the default "dolt" +// backend in explicit server mode, and forces the dial target to a port +// nobody listens on via env vars that GetDoltServerPort/GetDoltServerHost +// check BEFORE metadata.json — TestMain's shared test Dolt container already +// sets BEADS_DOLT_PORT ambiently for the whole process, which would +// otherwise silently out-rank a port pinned only in metadata.json and make +// this open attempt succeed against the wrong server. t.Setenv scopes the +// override to the calling (sub)test and its cleanup. +func plainDoltServerModeBeadsDir(t *testing.T) string { + t.Helper() + t.Setenv("BEADS_DOLT_SERVER_HOST", "127.0.0.1") + t.Setenv("BEADS_DOLT_SERVER_PORT", "1") + beadsDir := filepath.Join(t.TempDir(), ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatalf("create .beads: %v", err) + } + metadata := `{"backend":"dolt","dolt_mode":"server"}` + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(metadata), 0o600); err != nil { + t.Fatalf("write metadata: %v", err) + } + return beadsDir +} + func writeBackendMetadata(t *testing.T, backend string) string { t.Helper() beadsDir := filepath.Join(t.TempDir(), ".beads") @@ -246,3 +302,367 @@ func TestFindDatabasePathDiscoversRegisteredWorkspace(t *testing.T) { } } } + +// TestOpenBestAvailableWithDispatchesRegisteredBackendAndPassesOptions proves +// the two S1 guarantees together: OpenBestAvailableWith dispatches to a +// registered backend's OpenWith (not Open), and the OpenOptions the caller +// supplied reach that OpenWith unchanged. +func TestOpenBestAvailableWithDispatchesRegisteredBackendAndPassesOptions(t *testing.T) { + const name = "registry-openwith" + var gotBeadsDir string + var gotOpts beads.OpenOptions + var calls int + registerOpenWithCapturingBackend(t, name, &gotBeadsDir, &gotOpts, &calls) + + beadsDir := writeBackendMetadata(t, name) + cred := fixtureCredential{} + client := &http.Client{} + wantOpts := beads.OpenOptions{Credential: cred, HTTPClient: client, UserAgent: "test-agent/1.0"} + + store, err := beads.OpenBestAvailableWith(context.Background(), beadsDir, wantOpts) + if store != nil { + _ = store.Close() + t.Fatal("OpenBestAvailableWith returned a store instead of the backend's OpenWith result") + } + if !errors.Is(err, errRegistryBackendOpenWith) { + t.Fatalf("OpenBestAvailableWith error = %v, want registered backend OpenWith result", err) + } + if calls != 1 { + t.Fatalf("OpenWith called %d times, want 1", calls) + } + if gotOpts.Credential != cred { + t.Fatalf("OpenWith opts.Credential = %v, want %v", gotOpts.Credential, cred) + } + if gotOpts.HTTPClient != client { + t.Fatalf("OpenWith opts.HTTPClient = %v, want %v", gotOpts.HTTPClient, client) + } + if gotOpts.UserAgent != "test-agent/1.0" { + t.Fatalf("OpenWith opts.UserAgent = %q, want test-agent/1.0", gotOpts.UserAgent) + } +} + +// TestOpenBestAvailableWithZeroOptionsMatchesOpenBestAvailable is the S1 +// back-compat requirement: OpenBestAvailableWith with a zero OpenOptions must +// behave identically to OpenBestAvailable for every existing path — +// registered backend without OpenWith, registered backend with OpenWith, and +// plain Dolt (no registered backend at all). +// +// OpenBestAvailable now simply delegates to OpenBestAvailableWith with a zero +// OpenOptions (see beads_cgo.go and beads_nocgo.go), so a subtest that calls +// both and compares their results would be vacuous: it can never fail +// regardless of what either returns, because they are the same code path. +// Each subtest instead pins a fixed, independently-meaningful expected result +// — a sentinel identity, a concrete error message, or a concrete +// store-presence/nilness — so that a future change which breaks the +// delegation (e.g. a stray early return, or dropped opts threading) still has +// something to fail against. +func TestOpenBestAvailableWithZeroOptionsMatchesOpenBestAvailable(t *testing.T) { + t.Run("registered backend without OpenWith", func(t *testing.T) { + const name = "registry-backcompat-open-only" + registerWorkspaceBackend(t, name) + beadsDir := writeBackendMetadata(t, name) + + store, err := beads.OpenBestAvailableWith(context.Background(), beadsDir, beads.OpenOptions{}) + if store != nil { + _ = store.Close() + t.Fatal("OpenBestAvailableWith(zero opts) returned a non-nil store, want nil: the fixture's Open always fails") + } + if !errors.Is(err, errRegistryBackendOpen) { + t.Fatalf("OpenBestAvailableWith(zero opts) error = %v, want errRegistryBackendOpen", err) + } + }) + + t.Run("registered backend with OpenWith", func(t *testing.T) { + const name = "registry-backcompat-openwith" + var gotBeadsDir string + var gotOpts beads.OpenOptions + var calls int + registerOpenWithCapturingBackend(t, name, &gotBeadsDir, &gotOpts, &calls) + beadsDir := writeBackendMetadata(t, name) + + _, errNew := beads.OpenBestAvailableWith(context.Background(), beadsDir, beads.OpenOptions{}) + if !errors.Is(errNew, errRegistryBackendOpenWith) { + t.Fatalf("OpenBestAvailableWith(zero opts) error = %v, want OpenWith sentinel", errNew) + } + if calls != 1 { + t.Fatalf("OpenWith called %d times, want 1", calls) + } + if gotOpts != (beads.OpenOptions{}) { + t.Fatalf("OpenWith opts = %+v, want the zero value (OpenBestAvailable never set any)", gotOpts) + } + if gotBeadsDir != beadsDir { + t.Fatalf("OpenWith beadsDir = %q, want %q", gotBeadsDir, beadsDir) + } + }) + + t.Run("no registered backend (plain Dolt, server mode)", func(t *testing.T) { + // dolt_mode:"server" plus an unreachable port (127.0.0.1:1) makes + // the dial fail fast with a fixed, well-known error rather than + // spinning up embedded Dolt (slow, and exercises a path this slice + // does not touch). + beadsDir := plainDoltServerModeBeadsDir(t) + store, err := beads.OpenBestAvailableWith(context.Background(), beadsDir, beads.OpenOptions{}) + if store != nil { + _ = store.Close() + t.Fatal("OpenBestAvailableWith(zero opts) returned a non-nil store, want nil: 127.0.0.1:1 is unreachable") + } + if err == nil { + t.Fatal("plain Dolt server mode against an unreachable port unexpectedly opened") + } + const wantSubstring = "Dolt server unreachable at 127.0.0.1:1" + if !strings.Contains(err.Error(), wantSubstring) { + t.Fatalf("OpenBestAvailableWith(zero opts) error = %q, want it to contain %q", err.Error(), wantSubstring) + } + }) +} + +// TestOpenBestAvailableWithRefusesCredentialWithoutOpenWithOnRegisteredBackend +// covers the registered-backend half of the design's refusal requirement: +// a backend with no OpenWith must never silently drop a caller's Credential. +func TestOpenBestAvailableWithRefusesCredentialWithoutOpenWithOnRegisteredBackend(t *testing.T) { + const name = "registry-credential-refusal" + registerWorkspaceBackend(t, name) // Open/OpenReadOnly only, no OpenWith + beadsDir := writeBackendMetadata(t, name) + + store, err := beads.OpenBestAvailableWith(context.Background(), beadsDir, beads.OpenOptions{ + Credential: fixtureCredential{}, + }) + if store != nil { + _ = store.Close() + t.Fatal("OpenBestAvailableWith returned a store alongside the Credential refusal") + } + if !errors.Is(err, beads.ErrCredentialWithoutOpenWith) { + t.Fatalf("OpenBestAvailableWith error = %v, want %v", err, beads.ErrCredentialWithoutOpenWith) + } +} + +// TestOpenBestAvailableWithRefusesPerOpenOptionsOnPlainDolt covers the other +// half: no registered backend at all (plain Dolt, embedded or server) has no +// per-open seam either, so the same refusal applies to each of Credential, +// HTTPClient, and UserAgent. Those refusal arms are duplicated in +// beads_cgo.go and beads_nocgo.go, so this runs against whichever copy the +// build's CGO setting compiles. +func TestOpenBestAvailableWithRefusesPerOpenOptionsOnPlainDolt(t *testing.T) { + tests := []struct { + name string + opts beads.OpenOptions + want error + }{ + {name: "Credential", opts: beads.OpenOptions{Credential: fixtureCredential{}}, want: beads.ErrCredentialWithoutOpenWith}, + {name: "HTTPClient", opts: beads.OpenOptions{HTTPClient: &http.Client{}}, want: beads.ErrHTTPClientWithoutOpenWith}, + {name: "UserAgent", opts: beads.OpenOptions{UserAgent: "test-agent/1.0"}, want: beads.ErrUserAgentWithoutOpenWith}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + beadsDir := filepath.Join(t.TempDir(), ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatalf("create .beads: %v", err) + } + + store, err := beads.OpenBestAvailableWith(context.Background(), beadsDir, tt.opts) + if store != nil { + _ = store.Close() + t.Fatalf("OpenBestAvailableWith returned a store alongside the %s refusal", tt.name) + } + if !errors.Is(err, tt.want) { + t.Fatalf("OpenBestAvailableWith error = %v, want %v", err, tt.want) + } + // The fail-closed guarantee includes never provisioning a database + // while refusing to honor the option. + for _, artifact := range []string{"embeddeddolt", "dolt"} { + if _, statErr := os.Stat(filepath.Join(beadsDir, artifact)); !os.IsNotExist(statErr) { + t.Fatalf("%s refusal on plain Dolt created %s (stat error: %v)", tt.name, artifact, statErr) + } + } + }) + } +} + +// graphWorkspaceMetadata is the metadata.json a graph-preview build of bd +// writes for a graph_mode "link" workspace: the marker and its binding beside +// an ordinary embedded Dolt backend. +const graphWorkspaceMetadata = `{ + "database": "", + "backend": "dolt", + "graph_mode": "link", + "graph_scope_url": "https://example.test/scope", + "graph_authority_id": "0123456789abcdef0123456789abcdef", + "graph_workspace": "/work/repo/.beads", + "graph_schema_version": 7, + "graph_ready": true, + "dolt_mode": "embedded", + "dolt_database": "beads_graph_0123456789abcdef0123456789abcdef", + "project_id": "0123456789abcdef0123456789abcdef" +}` + +// graphWorkspaceMetadataStripped is graphWorkspaceMetadata as a bd that +// predates graph_mode rewrites it: the graph fields are gone, but the database +// name still points at the graph database. +const graphWorkspaceMetadataStripped = `{ + "database": "", + "backend": "dolt", + "dolt_mode": "embedded", + "dolt_database": "beads_graph_0123456789abcdef0123456789abcdef", + "project_id": "0123456789abcdef0123456789abcdef" +}` + +// publicOpens are the public entry points that open a workspace from its +// metadata. +var publicOpens = map[string]func(context.Context, string) (beads.Storage, error){ + "OpenBestAvailable": beads.OpenBestAvailable, + "OpenBestAvailableWith": func(ctx context.Context, beadsDir string) (beads.Storage, error) { + return beads.OpenBestAvailableWith(ctx, beadsDir, beads.OpenOptions{}) + }, + "OpenFromConfig": beads.OpenFromConfig, + "OpenGated": func(ctx context.Context, beadsDir string) (beads.Storage, error) { + return beads.OpenGated(ctx, beadsDir, 0) + }, +} + +// workspaceTreeDigest records every path under root with its kind and, for +// files, its content, so a test can prove an open left a workspace untouched. +func workspaceTreeDigest(t *testing.T, root string) map[string]string { + t.Helper() + digest := map[string]string{} + err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + rel, err := filepath.Rel(root, path) + if err != nil { + return err + } + if d.IsDir() { + digest[rel] = "dir" + return nil + } + content, err := os.ReadFile(path) + if err != nil { + return err + } + digest[rel] = "file:" + string(content) + return nil + }) + if err != nil { + t.Fatalf("digest %s: %v", root, err) + } + return digest +} + +// TestPublicOpensRefuseGraphWorkspace is the library half of the graph_mode +// fence the CLI applies at admission: every public open of a workspace whose +// metadata or graph-preview-format marker declares another data model refuses +// it with the typed error before it opens, creates or modifies anything, in +// the workspace or beside it (the workspace gate file OpenGated takes lives +// beside .beads). +func TestPublicOpensRefuseGraphWorkspace(t *testing.T) { + // If the fence were missing, a server-mode open must fail fast rather + // than reach TestMain's shared test server. + t.Setenv("BEADS_DOLT_SERVER_HOST", "127.0.0.1") + t.Setenv("BEADS_DOLT_SERVER_PORT", "1") + layouts := []struct { + name string + filename string // "" writes no metadata file + metadata string + mode string + embedded bool + // marker writes the graph-preview-format marker graph-preview builds + // leave in .beads; the refusal then names the marker, not a mode. + marker bool + }{ + {name: "link embedded", filename: "metadata.json", metadata: graphWorkspaceMetadata, mode: "link", embedded: true}, + {name: "link server", filename: "metadata.json", metadata: `{"backend":"dolt","dolt_mode":"server","dolt_database":"beads_graph_0123","graph_mode":"link"}`, mode: "link"}, + {name: "unknown marker", filename: "metadata.json", metadata: `{"backend":"dolt","graph_mode":"future-format"}`, mode: "future-format"}, + // A refused open must not migrate a legacy config.json either. + {name: "link legacy config.json", filename: "config.json", metadata: graphWorkspaceMetadata, mode: "link", embedded: true}, + // A graph workspace whose metadata was never written, was lost, or + // was rewritten without graph_mode is still declared by the marker. + {name: "marker only", marker: true}, + {name: "marker beside stripped metadata", filename: "metadata.json", metadata: graphWorkspaceMetadataStripped, embedded: true, marker: true}, + {name: "marker beside stripped legacy config.json", filename: "config.json", metadata: graphWorkspaceMetadataStripped, embedded: true, marker: true}, + {name: "marker beside server metadata", filename: "metadata.json", metadata: `{"backend":"dolt","dolt_mode":"server","dolt_database":"beads_graph_0123"}`, marker: true}, + {name: "marker beside dependency metadata", filename: "metadata.json", metadata: `{"backend":"dolt","dolt_mode":"server","graph_mode":"dependency"}`, marker: true}, + {name: "marker beside unparseable metadata", filename: "metadata.json", metadata: `{"backend":"dolt",`, marker: true}, + } + for _, layout := range layouts { + for name, open := range publicOpens { + t.Run(layout.name+"/"+name, func(t *testing.T) { + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatal(err) + } + if layout.filename != "" { + if err := os.WriteFile(filepath.Join(beadsDir, layout.filename), []byte(layout.metadata), 0o600); err != nil { + t.Fatal(err) + } + } + if layout.marker { + if err := os.WriteFile(filepath.Join(beadsDir, "graph-preview-format"), []byte("link-preview-v9\n"), 0o600); err != nil { + t.Fatal(err) + } + } + if layout.embedded { + graphDB := filepath.Join(beadsDir, "embeddeddolt", "beads_graph_0123456789abcdef0123456789abcdef", ".dolt") + if err := os.MkdirAll(graphDB, 0o750); err != nil { + t.Fatal(err) + } + } + before := workspaceTreeDigest(t, root) + + // Check err, not store: a failed OpenFromConfig can return a + // typed-nil store. + store, err := open(t.Context(), beadsDir) + if err == nil { + _ = store.Close() + t.Fatalf("%s opened a graph_mode %q workspace", name, layout.mode) + } + var formatErr *beads.UnsupportedWorkspaceFormatError + if !errors.As(err, &formatErr) { + t.Fatalf("%s error = %v, want *beads.UnsupportedWorkspaceFormatError", name, err) + } + if formatErr.BeadsDir != beadsDir || formatErr.GraphMode != layout.mode || formatErr.FormatMarker != layout.marker { + t.Fatalf("refusal = %+v, want BeadsDir %q, GraphMode %q and FormatMarker %v", formatErr, beadsDir, layout.mode, layout.marker) + } + if layout.marker && !strings.Contains(err.Error(), "graph-preview-format marker") { + t.Fatalf("refusal does not name the format marker: %v", err) + } + if !strings.Contains(err.Error(), "no storage database was opened or modified") { + t.Fatalf("refusal lacks the data-safety guarantee: %v", err) + } + if after := workspaceTreeDigest(t, root); !maps.Equal(after, before) { + t.Fatalf("%s changed the workspace: before %v, after %v", name, slices.Sorted(maps.Keys(before)), slices.Sorted(maps.Keys(after))) + } + }) + } + } +} + +// TestPublicOpensAdmitDependencyWorkspace pins the other side of the fence: a +// "dependency" marker is the ordinary Issue workspace, so the open proceeds to +// its backend (here, a server nothing listens on) instead of being refused. +func TestPublicOpensAdmitDependencyWorkspace(t *testing.T) { + t.Setenv("BEADS_DOLT_SERVER_HOST", "127.0.0.1") + t.Setenv("BEADS_DOLT_SERVER_PORT", "1") + for name, open := range publicOpens { + t.Run(name, func(t *testing.T) { + beadsDir := filepath.Join(t.TempDir(), ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatal(err) + } + metadata := `{"backend":"dolt","dolt_mode":"server","graph_mode":"dependency"}` + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(metadata), 0o600); err != nil { + t.Fatal(err) + } + store, err := open(t.Context(), beadsDir) + if err == nil { + _ = store.Close() + t.Fatalf("%s opened a store on an unreachable server", name) + } + var formatErr *beads.UnsupportedWorkspaceFormatError + if errors.As(err, &formatErr) || !strings.Contains(err.Error(), "unreachable") { + t.Fatalf("%s error = %v, want the backend's unreachable-server error", name, err) + } + }) + } +} diff --git a/platforms/BUILD.bazel b/platforms/BUILD.bazel new file mode 100644 index 000000000..66e541ea9 --- /dev/null +++ b/platforms/BUILD.bazel @@ -0,0 +1,91 @@ +# rbe_worker: the execution platform of every build (.bazelrc selects it +# unconditionally with --extra_execution_platforms, so every action and test +# executes on it and local, fork-cache and remote runs hash alike). +# +# Test actions exec host tools (bash, git, python3, coreutils, ...) and load +# the shared libraries of every cgo binary they link (glibc, libstdc++), so +# the worker host is an input to every cached result. Its exec_properties +# enter each action's key: worker-env is the sha256 of +# tools/rbe/worker-env.txt, the toolchain manifest of the pinned worker host +# (arch, OS release, Go, dolt, and the upstream releases of the libraries and +# tools actions reach; not the image's security patch revisions). +# +# rbe-west's OSS pool is shared with gastownhall/gascity, which owns the +# worker image: its tools/rbe/blacksmith-worker.sh advertises the sha256 of +# the manifest it measures on its own host (gascity tools/rbe/worker-env), +# and the schedulers match worker-env exactly, so these actions run only on +# the pinned toolchain. tools/rbe/worker-env.txt is a byte-for-byte copy of +# gascity's: when gascity moves its pin (a toolchain change: a distribution, +# library or tool release, Go or dolt), copy its manifest here and update +# this sha256 in the same commit, which is a new key for every action. +# scripts/rbe_worker_env_test.go keeps the pin and the manifest in step, and +# tools/rbe/worker-env-sync (nightly) compares both with gascity's main. +platform( + name = "rbe_worker", + exec_properties = { + "worker-env": "sha256:0c6c05c2196c246dba37e106a3d028e2f47f2e3d7eae0e41c2fe2bd9b2e4f6f0", + }, + parents = ["@bazel_tools//tools:host_platform"], + visibility = ["//visibility:public"], +) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/plugins/beads/BUILD.bazel b/plugins/beads/BUILD.bazel index 152264079..feed1f222 100644 --- a/plugins/beads/BUILD.bazel +++ b/plugins/beads/BUILD.bazel @@ -31,3 +31,64 @@ exports_files( ], visibility = ["//:__pkg__"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/plugins/beads/skills/beads/resources/ASYNC_GATES.md b/plugins/beads/skills/beads/resources/ASYNC_GATES.md index b504ca223..2f99506a6 100644 --- a/plugins/beads/skills/beads/resources/ASYNC_GATES.md +++ b/plugins/beads/skills/beads/resources/ASYNC_GATES.md @@ -52,6 +52,7 @@ bd gate create --type bead --blocks bd-abc \ **Optional**: - `--type ` — Gate type: `human`, `timer`, `gh:run`, `gh:pr`, `bead` (default `human`) - `--await-id ` — Condition identifier (run ID, PR number, `rig:bead-id`, etc.) +- `--repo ` — For `gh:run`/`gh:pr` only: the GitHub repository the condition is checked in (also `HOST/OWNER/REPO`). Default: the blocked issue's `metadata.repo`, else the current repository — a gate on another repository's PR needs this, or it escalates as "not found" on every check. - `--reason ` — Stored on the gate as its description (what is being gated) - `--timeout ` — **Only timer gates enforce this** via `bd gate check`. You can set it on other types for documentation, but `check` does not auto-resolve/escalate human or GitHub gates based on timeout. diff --git a/schema/BUILD.bazel b/schema/BUILD.bazel index c2de6036f..ccf861bdb 100644 --- a/schema/BUILD.bazel +++ b/schema/BUILD.bazel @@ -13,3 +13,64 @@ go_test( srcs = ["schema_test.go"], deps = [":schema"], ) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/scripts/BUILD.bazel b/scripts/BUILD.bazel index f7aa0b8cb..58c3b6da5 100644 --- a/scripts/BUILD.bazel +++ b/scripts/BUILD.bazel @@ -1,74 +1,89 @@ load("@rules_go//go:def.bzl", "go_test") -# CI and repo-policy tests: they parse the workflows and run the CI shell -# scripts against fixtures. +# CI and repo-policy tests: they parse the workflows, run the CI shell scripts +# against fixtures, and check repository-wide rules (BUILD tag taxonomy, skip +# allowlist, managed BUILD blocks, shard manifests, tracked-file scans). # -# Tags: -# host-tools: the scripts and fixtures run the host's git, python3, awk, -# sed, find, grep and timeout (beyond the bash the test wrapper needs). -# Under Bazel a missing git or bash fails the test (under go test it -# skips). -# no-remote-exec: so they always run where that inventory is known (the -# developer machine or the CI runner). The farm workers do have these -# tools today (the target passes there), so this can be dropped once that -# is guaranteed. -# no-remote-cache: the action key does not cover the host's tools, so a -# result from one host is neither uploaded for nor served to another. +# They are one Go package but several go_test targets, each compiling only +# the files whose tests it runs and declaring only what those tests read, so +# that a change re-runs only the targets that read it: a Go-only change runs +# no workflow policy test, a docs-only or workflow-only change no Go-source +# scan. The data are the partitions of the checkout that tools/bazel/go_srcs.py +# generates (//:repo_go_srcs, //:repo_go_test_srcs, //:repo_doc_files, +# //:repo_other_files, and per package) or single files; only +# :tracked_files_test declares //:repo_files, every tracked file. +# +# Every *_test.go here is in exactly one of these targets, except the +# helpers-only files (no Test functions) that several compile; srcs are kept +# by hand (`# keep` stops gazelle from putting every file back into +# scripts_test), and TestScriptsTestTargetsPartitionTheTests +# (scripts_targets_test.go) fails on a file in no target or a test in two. +# +# No tags: they run remotely like any other target. The scripts and fixtures +# run bash, git, python3, jq, yq, curl, openssl, unzip and coreutils from the +# executor (the rbe-west worker image, or the runner in fork-cache mode); a +# missing tool fails the test under Bazel instead of skipping it +# (host_tools_test.go), so a cached pass never stands for an executor that +# could not run it. Go and the release formula come in hermetically. + +# The CI and Bazel policy tests: workflows, the setup-bazel action, .bazelrc, +# MODULE.bazel, every BUILD and .bzl file, tools/bazel and the CI scripts, +# all in //:repo_other_files (every tracked file but Go and Markdown source), +# plus the one Go file whose dolt image pin they compare. go_test( name = "scripts_test", srcs = [ "bazel_autofix_push_test.go", "bazel_cache_mode_test.go", + "bazel_dolt_int_test.go", + "bazel_dolt_race_test.go", "bazel_farm_workflow_test.go", "bazel_fork_mode_test.go", + "bazel_go_repository_tools_test.go", + "bazel_hermetic_cc_test.go", + "bazel_invocations_test.go", "bazel_policy_test.go", "bazel_rbe_prewarm_test.go", - "bazel_skip_allowlist_test.go", - "check_build_tags_test.go", - "check_doc_freshness_test.go", - "check_release_cross_compile_test.go", - "check_testing_short_test.go", - "check_winget_portable_alias_test.go", + "bazel_rrc_test.go", "ci_actions_policy_test.go", + "ci_analytics_workflow_test.go", "ci_blacksmith_runner_test.go", - "ci_capability_selector_test.go", "ci_f7b_review_test.go", "ci_f7c_advisory_test.go", + "ci_merge_queue_test.go", "ci_workflow_apt_get_timeout_test.go", + "ci_workflow_core_test.go", "ci_workflow_test.go", - "complexity_script_test.go", - "conformance_script_test.go", "embedded_shard_count_test.go", "host_tools_test.go", - "install_dolt_test.go", + "makefile_bazel_primary_test.go", + "migration_corpus_bazel_test.go", + "nogo_integration_step_script_test.go", + "nogo_lint_policy_test.go", + "pinned_shards_helpers_test.go", + "pinned_shards_test.go", "pr_lanes_bazel_coverage_test.go", - "pr_preflight_test.go", "pr_risk_bazel_coverage_test.go", - "pull_dolt_image_test.go", - "release_script_test.go", - "required_suite_test.go", - "test_script_test.go", - "upgrade_smoke_loop_test.go", - "windows_test_binaries_manifest_test.go", - ], + "rbe_worker_env_test.go", + "repo_helpers_test.go", + "worker_env_autosync_test.go", + ], # keep data = [ - ":scripts_files", - "//:.githooks/pre-commit", - "//:.goreleaser.yml", - "//:bazel_policy_files", - "//:engdocs/LINTING.md", - "//:mcp_package_policy_files", - "//:test_sh_files", - "//:workflow_files", + "//:repo_other_files", "//internal/testutil:testdoltcommon.go", - "//tools/bazel:dolt.bzl", - ], - tags = [ - "host-tools", - "no-remote-cache", - "no-remote-exec", + "@go_sdk//:bin/go", + "@go_sdk//:files", ], + # The Go SDK is go.mod's toolchain, whatever go the executor has on PATH. + # No //:repo_go_srcs here (F5 S2, cost fix, independent review of #7486): + # T4 (TestNogoIntegrationStepCoversItsConfiguration) and the + # unvalidated_integration_tests.txt exactness check moved to their own + # :nogo_integration_scan_test target below, which alone depends on + # //:repo_go_srcs and //:repo_go_test_srcs, so a Go-only change no longer + # re-runs the rest of this suite too. + env = {"BEADS_TEST_GO": "$(rlocationpath @go_sdk//:bin/go)"}, deps = [ + "//internal/doltversion", "//internal/formula", "//internal/testutil/bazeltest", "//scripts/internal/testbash", @@ -76,18 +91,245 @@ go_test( ], ) -# The scripts scripts_test reads and runs (CI helpers, check-*.sh, release.sh, -# test.sh, conformance.sh, ...). Globs stop at subpackages, so this is only -# this package's own tree. -filegroup( - name = "scripts_files", - srcs = glob( - ["**"], - exclude = [ - "BUILD.bazel", - "**/*_test.go", - ], - ), +# T4 (TestNogoIntegrationStepCoversItsConfiguration) and T6 +# (TestUnvalidatedIntegrationTestsFileIsExact, independent review of #7486 +# must-fix 6): both source-scan every tracked .go file (test and non-test) +# for the "integration" build tag, so they alone depend on //:repo_go_srcs +# and //:repo_go_test_srcs. Carved out of scripts_test (cost fix, same +# review): with this data in scripts_test, any Go-only change re-ran the +# whole nogo-policy suite, raising scripts_test's rerun rate from 73% to 91% +# of main commits. bazel_invocations_test.go and ci_workflow_core_test.go are +# helper-only files (no Test functions) shared with scripts_test, so neither +# copy duplicates the other's parsing logic. +go_test( + name = "nogo_integration_scan_test", + srcs = [ + "bazel_invocations_test.go", + "ci_workflow_core_test.go", + "nogo_integration_scan_test.go", + "repo_helpers_test.go", + ], # keep + data = [ + "//:repo_go_srcs", + "//:repo_go_test_srcs", + "//:repo_other_files", + ], + deps = [ + "//internal/testutil/bazeltest", + "@in_gopkg_yaml_v3//:yaml_v3", + ], +) + +# The shell scripts' own behavior, run against fixtures: this package's +# scripts and their testdata, the few root files they read, and the release +# formula. +go_test( + name = "shell_scripts_test", + srcs = [ + "check_build_tags_test.go", + "check_doc_freshness_test.go", + "check_release_cross_compile_test.go", + "check_testing_short_test.go", + "check_winget_portable_alias_test.go", + "ci_analytics_extract_test.go", + "complexity_script_test.go", + "conformance_script_test.go", + "host_tools_test.go", + "install_dolt_test.go", + "oracle_a_script_test.go", + "pr_preflight_test.go", + "pre_push_suite_test.go", + "pull_dolt_image_test.go", + "release_script_test.go", + "repo_helpers_test.go", + "required_suite_test.go", + "test_script_test.go", + "update_nix_vendorhash_test.go", + "update_nix_vendorhash_unix_test.go", + "upgrade_smoke_loop_test.go", + ], + data = [ + ":repo_other_files", + "//:.buildflags", + "//:.githooks/pre-push", + "//:.test-skip", + "//:tests/oracle-a/run-oracle-a.sh", + "//internal/httpclient:repo_other_files", + "//test/conformance:repo_go_test_srcs", + "//test/conformance:repo_other_files", + "//tools/bazel:repo_other_files", + "@beads_formulas//:beads-release.formula.toml", + ], + # The release formula lives in .beads/ (in .bazelignore: it also holds + # live bd data), so it comes in through its own local repository. + env = {"BEADS_TEST_RELEASE_FORMULA": "$(rlocationpath @beads_formulas//:beads-release.formula.toml)"}, + deps = [ + "//internal/formula", + "//internal/testutil/bazeltest", + "//scripts/internal/testbash", + ], +) + +# Scans of the Go test files: the Bazel-skip allowlist, the managed local +# lane, and the shard manifests and scripts against the tests they shard. +# Every _test.go file (//:repo_go_test_srcs) but no non-test Go source, so a +# non-test Go change leaves it cached. +go_test( + name = "go_test_sources_test", + srcs = [ + "bazel_skip_allowlist_test.go", + "embedded_lane_coverage_test.go", + "embedded_shard_count_test.go", + "host_tools_test.go", + "managed_local_lane_test.go", + "pinned_shards_helpers_test.go", + "pinned_shards_sources_test.go", + "proxied_lane_coverage_test.go", + "repo_helpers_test.go", + "scripts_targets_test.go", + "shard_manifest_test.go", + ], + data = [ + "BUILD.bazel", + "ci/_embedded_shard_manifest_lib.py", + "ci/embedded_cmd_test_durations.json", + "ci/embedded_storage_test_durations.json", + "ci/gen_embedded_cmd_shard_manifest.py", + "ci/gen_embedded_storage_shard_manifest.py", + "ci/gen_proxied_shard_manifest.py", + "ci/proxied_test_durations.json", + "//:.github/scripts/embedded-cmd-test-shards.txt", + "//:.github/scripts/embedded-storage-test-shard.sh", + "//:.github/scripts/embedded-storage-test-shards.txt", + "//:.github/scripts/embedded-test-shard.sh", + "//:.github/scripts/proxied-cmd-test-shards.txt", + "//:.github/scripts/proxied-test-shard.sh", + "//:.github/scripts/server-storage-test-shard.sh", + "//:.github/scripts/server-storage-test-shards.txt", + "//:nested_go_modules", + "//:repo_go_test_srcs", + "//backend/http:repo_other_files", + "//backend/http/corpus:repo_other_files", + "//cmd/bd:repo_other_files", + "//internal/httpclient:repo_other_files", + "//internal/storage/dolt:repo_other_files", + "//internal/storage/embeddeddolt:repo_other_files", + "//tests/regression:repo_other_files", + "//tools/bazel:check_shard_coverage.py", + "//tools/bazel:equivalence_allowlist.txt", + ], + deps = ["//internal/testutil/bazeltest"], +) + +# check-testing-short.sh over every Go file, test and non-test, plus the +# Go-exec half of the host-go-under-Bazel policy (host_tool_exec_policy_test.go +# scans //:repo_go_srcs and //:repo_go_test_srcs for a literal go/gofmt exec). +# The shell-script half (host_tool_shell_policy_test.go) is its own +# :shell_host_tool_policy_test below: it reads a fixed, narrow list of shell +# scripts, not every Go source file, so it would otherwise pay this target's +# full re-run cost for files it never looks at. +go_test( + name = "go_sources_test", + srcs = [ + "host_tool_exec_policy_test.go", + "repo_helpers_test.go", + "testing_short_tree_test.go", + ], + data = [ + "check-testing-short.sh", + "//:repo_go_srcs", + "//:repo_go_test_srcs", + ], + deps = ["//internal/testutil/bazeltest"], +) + +# The shell-script half of the host-go-under-Bazel policy +# (host_tool_shell_policy_test.go: see its package comment for shellPolicyScope +# and the detection tradeoffs). Split out of go_sources_test (which otherwise +# re-ran on every Go-source change to serve only this file) with data limited +# to exactly the shell scripts shellPolicyScope names -- no BUILD.bazel/.bzl +# walk, and so no //:repo_other_files: TestShellPolicyScopeCoversBazelShellData +# (dropped; see that test's old doc comment in version control) could not +# parse a `//pkg:file.sh` label or a glob() either, so paying 758 extra input +# files and ~4 points of cache-rerun rate across the whole repo for a walk +# that demonstrably still missed real in-scope scripts was not worth it. +go_test( + name = "shell_host_tool_policy_test", + srcs = [ + "host_tool_shell_policy_test.go", + "repo_helpers_test.go", + ], + data = [ + "check-build-tags.sh", + "check-doc-freshness.sh", + "check-go-install-guidance.sh", + "check-migration-hygiene.sh", + "check-testing-short.sh", + "check-versions.sh", + "check-winget-portable-alias.sh", + "check-workapi-frontend-boundary.sh", + "ci/fmt-check.sh", + "ci/gofmt-bin.sh", + "ci/pr-lint.sh", + "conformance.sh", + "migrate-legacy-to-current.sh", + "migration-test/historical-dolt-upgrade-test.sh", + "migration-test/legacy-bridge-test.sh", + "migration-test/lib/binary.sh", + "release.sh", + "test.sh", + "upgrade-smoke-test.sh", + "//:.github/scripts/embedded-storage-test-shard.sh", + "//:.github/scripts/embedded-test-shard.sh", + "//:.github/scripts/proxied-test-shard.sh", + "//:.github/scripts/server-storage-test-shard.sh", + "//scripts/repochecks:run_check.sh", + "//scripts/repochecks:types_gen_drift_test.sh", + ], + deps = ["//internal/testutil/bazeltest"], +) + +# Scans of every tracked file (//:repo_files): any change re-runs them, so +# keep them few and fast. +go_test( + name = "tracked_files_test", + srcs = [ + "repo_helpers_test.go", + "tracked_files_test.go", + ], + data = ["//:repo_files"], + deps = ["//internal/testutil/bazeltest"], +) + +# pr.yml's check-doc-freshness-platforms Linux leg: `go test +# -tags integration ./scripts -count=1 -run '^(TestDocFreshness.*| +# TestRequiredSuiteContract)$' -args -required-suite=doc-freshness`, whose +# TestMain fails unless exactly the doc-freshness inventory is compiled and +# selected. shell_scripts_test runs those tests too (in the integration lane); +# this target adds the inventory and selection contract, over only the files +# the suite reads (its fixtures copy check-doc-freshness.sh). The macOS and +# Windows legs stay in pr.yml. +# Tags: +# integration-only: every TestDocFreshness test is //go:build integration, +# so --config=integration's lane runs it. +go_test( + name = "doc_freshness_required_test", + srcs = [ + "check_doc_freshness_test.go", + "repo_helpers_test.go", + "required_suite_test.go", + ], + args = [ + "-test.count=1", + "-test.run=^(TestDocFreshness.*|TestRequiredSuiteContract)$$", + "-required-suite=doc-freshness", + ], + data = ["check-doc-freshness.sh"], + tags = ["integration-only"], + deps = [ + "//internal/testutil/bazeltest", + "//scripts/internal/testbash", + ], ) exports_files( @@ -95,6 +337,25 @@ exports_files( visibility = ["//scripts/migration-test/catalog:__pkg__"], ) +# The historical-upgrade harness (scripts/migration-test) and the public +# SQLite bridge it drives, for //tests/migration's per-release targets. +filegroup( + name = "migration_harness", + srcs = [ + "migrate-legacy-to-current.sh", + "migration-test/historical-dolt-upgrade-test.sh", + "migration-test/legacy-bridge-test.sh", + "migration-test/lib/binary.sh", + "migration-test/lib/versions.sh", + ], + visibility = ["//tests/migration:__pkg__"], +) + +exports_files( + ["upgrade-smoke-test.sh"], + visibility = ["//tests/upgrade_smoke:__pkg__"], +) + exports_files( [ "ci/fmt-check.sh", @@ -104,11 +365,6 @@ exports_files( visibility = ["//scripts/prlintmake:__pkg__"], ) -exports_files( - ["README.md"], - visibility = ["//:__pkg__"], -) - exports_files( ["ci/gofmt-bin.sh"], visibility = ["//scripts/prlintmake:__pkg__"], @@ -120,3 +376,76 @@ exports_files( ["check-versions.sh"], visibility = ["//scripts/check-versions:__pkg__"], ) + +# Scripts the docs and agent instructions link to by path, which +# //test/docsync checks resolve. +exports_files( + [ + "bump-version.sh", + "check-cli-docs-drift.sh", + "generate-cli-docs.sh", + "test.sh", + ], + visibility = ["//test/docsync:__pkg__"], +) + +# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- + +filegroup( + name = "repo_doc_files", + srcs = glob( + [ + "**/*.md", + "**/*.mdx", + ], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_srcs", + srcs = glob( + ["**/*.go"], + allow_empty = True, + exclude = [ + "**/*_test.go", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_go_test_srcs", + srcs = glob( + ["**/*_test.go"], + allow_empty = True, + exclude = ["**/node_modules/**"], + ), + visibility = ["//:__subpackages__"], +) + +filegroup( + name = "repo_other_files", + srcs = glob( + ["**"], + exclude = [ + "**/*.db", + "**/*.exe", + "**/*.go", + "**/*.md", + "**/*.mdx", + "**/*.out", + "**/*.prof", + "**/*.pyc", + "**/*.test", + "**/__pycache__/**", + "**/node_modules/**", + ], + ), + visibility = ["//:__subpackages__"], +) + +# --- end repo_files --- diff --git a/scripts/README.md b/scripts/README.md index d1969de1b..d6c073ba6 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -9,7 +9,6 @@ the target CI tiers; Make targets are aliases for local discoverability. ```bash make ci-pr-core -make ci-pr-policy make ci-pr-lint make ci-package-mcp make ci-package-npm @@ -19,15 +18,16 @@ Each wrapper auto-detects the repository root, sources `.buildflags` when it invokes Go in the default build mode, and records per-command timing through `scripts/ci/lib/timing.sh`. -`ci-pr-lint` keeps its supported Bash/Make entrypoint but delegates native and -Windows/non-CGO target selection to the checkout-owned `scripts/pr-lint` Go -driver. This is the same shell-free lint authority used by `bd preflight` in a -Beads source checkout. +`ci-pr-lint` keeps its supported Bash/Make entrypoint but delegates to the +checkout-owned `scripts/pr-lint` Go driver, which runs nogo (`//tools/nogo`) +under Bazel natively and cross-configured for windows/amd64 and darwin/arm64 +(see [engdocs/LINTING.md](../engdocs/LINTING.md)). This is the same shell-free +lint authority used by `bd preflight` in a Beads source checkout. Broad Go test wrappers also source `scripts/ci/lib/test-env.sh`, which creates a temporary HOME/XDG/Dolt root, isolates Git global/system config, clears runtime Beads/Dolt environment variables, and sets `BEADS_TEST_SKIP=dolt` before tests -run. This keeps local `make test` and `make ci-pr-core` results comparable to +run. This keeps local `make test-go` and `make ci-pr-core` results comparable to the fast PR-core contract even on shared agent hosts. Set `BEADS_TEST_ENV_RUN_DOLT=1` only when intentionally running the Dolt-dependent tests through these broad wrappers, or `BEADS_TEST_ENV_DISABLE=1` when debugging @@ -37,7 +37,8 @@ The broad Go wrappers also cap package and test parallelism to `4` by default (`GO_TEST_PKG_PARALLEL` and `GO_TEST_PARALLEL`). This avoids turning high-core shared hosts into a different test topology than GitHub Actions. -`make ci-pr-policy` includes `scripts/check-testing-short.sh`, which enforces +`scripts/check-testing-short.sh` (`make check-testing-short`; CI runs it in +`//scripts:go_sources_test`) enforces that `testing.Short()` is only used for runtime, stress, or large-fixture skips. Use build tags, environment checks, or named wrappers for integration/e2e/API boundaries. @@ -136,7 +137,6 @@ This master script automates the **entire release process**: - Clean git working directory - All changes committed -- golangci-lint installed - Homebrew installed (for local upgrade) - Push access to gastownhall/beads diff --git a/scripts/bazel-autofix-push.sh b/scripts/bazel-autofix-push.sh index 2af204d89..90db02264 100755 --- a/scripts/bazel-autofix-push.sh +++ b/scripts/bazel-autofix-push.sh @@ -36,12 +36,13 @@ # RUN_ID workflow run id that produced the patch (for comment text) # RUN_URL html url of that run (for commit/comment provenance) # GH_TOKEN token for gh api calls (PR lookup, comments) - needs the -# workflow's pull-requests:write; never the PAT +# workflow's pull-requests:write; never the App token # PUSH_TOKEN token for git fetch/push only (optional; defaults to -# GH_TOKEN), so the shared DOCS_AUTOFIX_TOKEN needs -# contents:write only -# AUTOFIX_TOKEN_KIND "pat" when a dedicated push token is in use, "default" -# for the workflow's GITHUB_TOKEN (retrigger caveat) +# GH_TOKEN), so the minted gastownhall-autofix App token +# needs contents:write only +# AUTOFIX_TOKEN_KIND "app" when the minted App push token is in use, +# "default" for the workflow's GITHUB_TOKEN (retrigger +# caveat) # # Exit 0 on every non-actionable outcome (PR closed, head moved, no patch); # exit 1 on a refused patch or a genuine error so the workflow surfaces them. @@ -486,7 +487,7 @@ fi if [ "$AUTOFIX_TOKEN_KIND" = "default" ]; then cat >> "$BODY" <<'EOF' -Note: this commit was pushed with the default workflow token, which does **not** retrigger PR checks - re-run them (or push any commit) to refresh the gate. Configuring the `DOCS_AUTOFIX_TOKEN` repo secret (shared with the docs autofix) removes this step. +Note: this commit was pushed with the default workflow token, which does **not** retrigger PR checks - re-run them (or push any commit) to refresh the gate. This only happens if the gastownhall-autofix App token could not be minted for this push. EOF fi post_or_update_comment "$BODY" diff --git a/scripts/bazel_autofix_push_test.go b/scripts/bazel_autofix_push_test.go index 646c34ee6..9ced90c7d 100644 --- a/scripts/bazel_autofix_push_test.go +++ b/scripts/bazel_autofix_push_test.go @@ -161,17 +161,6 @@ func writeRawPatch(t *testing.T, body string) string { return file } -// requireAutofixBash skips when bash cannot run the autofix scripts: they run -// on Linux runners and use bash 4 associative arrays, and macOS runners ship -// /bin/bash 3.2. -func requireAutofixBash(t *testing.T) { - t.Helper() - requireHostTool(t, "bash") - if err := exec.Command("bash", "-c", "declare -A probe=()").Run(); err != nil { - t.Skip("bash lacks associative arrays (bash >= 4 required)") - } -} - func runAutofixCheck(t *testing.T, script, dir, patch string) (string, error) { t.Helper() requireAutofixBash(t) @@ -528,7 +517,7 @@ func TestBazelAutofixPushFlow(t *testing.T) { t.Errorf("subject = %q", subject) } if !strings.Contains(res.log, "") || !strings.Contains(res.log, "Pushed `") || - !strings.Contains(res.log, "DOCS_AUTOFIX_TOKEN") { + !strings.Contains(res.log, "gastownhall-autofix App token") { t.Errorf("want a pushed-commit comment with the token note:\n%s", res.log) } if strings.Contains(res.log, "push-token") { diff --git a/scripts/bazel_cache_mode_test.go b/scripts/bazel_cache_mode_test.go index e942f7378..3c5994fe4 100644 --- a/scripts/bazel_cache_mode_test.go +++ b/scripts/bazel_cache_mode_test.go @@ -1,14 +1,23 @@ package scripts_test import ( + "bytes" "encoding/base64" + "encoding/binary" + "encoding/pem" + "errors" + "io" + "net/http" + "net/http/httptest" "os" "os/exec" "path/filepath" "regexp" "sort" "strings" + "sync/atomic" "testing" + "time" ) // Mode cache, end to end, for every way a bazel.yml run can start: the rbe @@ -47,7 +56,8 @@ func TestBazelCacheModeReachesTheRC(t *testing.T) { // setup-bazel's env values: `needs.rbe.outputs.X == 'v' && RHS || ''`, // RHS a secret or a literal. Anything else fails the test, so the - // simulation cannot drift from the workflow. + // simulation cannot drift from the workflow; in particular no repository + // variable (fork pull_request runs see none). setupExpr := regexp.MustCompile(`^\$\{\{ needs\.rbe\.outputs\.(enabled|mode) == '([a-z]+)' && (?:secrets\.([A-Z_]+)|'([^']*)') \|\| '' \}\}$`) evalSetup := func(t *testing.T, expr, mode, enabled, tier string, haveSecrets bool) string { t.Helper() @@ -61,6 +71,8 @@ func TestBazelCacheModeReachesTheRC(t *testing.T) { return tier case "${{ github.event.pull_request.number }}": return "7123" // every start that reaches a fork mode is a pull_request + case "true": // BAZEL_RRC_READ, a literal (the remote repo contents cache readers) + return "true" } m := setupExpr.FindStringSubmatch(expr) if m == nil { @@ -100,6 +112,8 @@ func TestBazelCacheModeReachesTheRC(t *testing.T) { "GITHUB_OUTPUT=" + filepath.Join(dir, "out"), "BAZEL_CI_CACHE_DIR=" + filepath.Join(dir, "bazel-ci-cache"), "BAZEL_CI_SECRET_DIR=" + secretDir, + // Mode cache's zstd probe: a refused port, never rbe-cache. + "RBE_CACHE_PROBE_URL=" + refusedProbeURL, } for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) @@ -200,8 +214,8 @@ func TestBazelCacheModeReachesTheRC(t *testing.T) { var lanes []string for name, job := range workflow.Jobs { - if name == bazelRBEJobName { - continue + if name == bazelRBEJobName || isBazelRRCJob(name) { + continue // not lanes: never in a PR call (bazel_rrc_test.go) } runs := bazelLaneRunModes(t, name, job.If, s.with)[mode] switch { @@ -213,7 +227,9 @@ func TestBazelCacheModeReachesTheRC(t *testing.T) { // no longer forwards the app secrets either, so there is no // audience left for pre-warming in fork-ro or fork-rw (see // bazel.yml's comment on the job). - case strings.HasPrefix(mode, "fork-") && !runs && !bazelPackageJobs[name] && !(name == bazelRBEPrewarmJobName && strings.HasPrefix(mode, "fork-")): + // Nor does a union lane (bazelUnionLanes): mode remote only, + // its members run in the fork modes. + case strings.HasPrefix(mode, "fork-") && !runs && !bazelPackageJobs[name] && !(name == bazelRBEPrewarmJobName && strings.HasPrefix(mode, "fork-")) && bazelUnionLanes[name] == nil: t.Errorf("%s does not run in mode %s (every lane runs remotely)", name, mode) case mode == "cache" && (name == bazelIntegJobName || name == bazelCmdDoltJobName) && !runs: t.Errorf("%s does not run in mode cache", name) @@ -273,13 +289,17 @@ func TestBazelCacheModeReachesTheRC(t *testing.T) { if bazelPackageJobs[lane] { continue } - if !ran[lane] { + // A union lane's run reports for its members + // (bazel_dolt_race_test.go). + if !ran[lane] && !ran[bazelUnionOf(lane)] { wantSkips = append(wantSkips, id) } } - // Flag-gated lanes' skips are accepted whatever the flag says. + // Flag-gated lanes' skips are accepted whatever the flag says, + // unless their union lane ran instead (bazel-dolt-int, for + // bazel-cmd-dolt, in mode remote: item 5 A2). for lane, g := range bazelFlagGatedLanes { - if !ran[lane] { + if !ran[lane] && !ran[bazelUnionOf(lane)] { wantSkips = append(wantSkips, g.id) } } @@ -323,6 +343,22 @@ func checkModeRC(t *testing.T, lane, mode, outputs, rc string, files []string, l t.Errorf("%s (mode %s): rc lacks %q:\n%s", lane, mode, strings.TrimSpace(want), rc) } } + // zstd: no mode here asks for compression. Mode cache's probe is + // refused here (TestSetupBazelRCWriter runs it passing); the trusted + // schedulers and rbe-fork advertise none, and Bazel refuses such a + // remote. + if has("remote_cache_compression") { + t.Errorf("%s (mode %s): rc asks for compression:\n%s", lane, mode, rc) + } + // The remote repo contents cache: mode cache's probe is refused here too + // (TestSetupBazelRCWriter runs it answered), and no other mode probes, + // so no rc here reads it (the trusted lanes read through bazel.yml's own + // reader steps, in .bazelrc.local). + for _, line := range bazelRRCReadLines { + if has(line) { + t.Errorf("%s (mode %s): rc carries %q:\n%s", lane, mode, line, rc) + } + } credentialFree := func() { for _, bad := range []string{"remote_executor", "remote-exec", "tls_", "remote_instance_name", "--remote_upload_local_results", "--remote_cache", "--remote_header", "--bes_", "farm.invalid"} { if has(bad) { @@ -382,3 +418,404 @@ func checkModeRC(t *testing.T, lane, mode, outputs, rc string, files []string, l t.Errorf("%s runs in mode %q", lane, mode) } } + +// cacheZstdProbe: setup-bazel's zstd probe for the fork cache (a byte copy +// of gascity's tools/rbe/cache-zstd-probe.sh). +const cacheZstdProbe = setupBazelActionDir + "/cache-zstd-probe.sh" + +// cacheRRCProbe: setup-bazel's remote repo contents cache probe for the fork +// cache (a copy of gascity's tools/rbe/cache-rrc-probe.sh; the kill switch +// line, cacheRRCKillLine, is beads' own). +const ( + cacheRRCProbe = setupBazelActionDir + "/cache-rrc-probe.sh" + cacheRRCKillLine = "fork_rrc_read=on" +) + +// refusedProbeURL: a loopback port nothing listens on, the probe's URL in +// tests that do not serve one (a refused connection: no flag). +const refusedProbeURL = "https://127.0.0.1:1" + +// GetCapabilities bodies for a stand-in rbe-cache. capsLive is what rbe-cache +// answered on 2026-10-04, before it advertised zstd (cache_capabilities: +// SHA256 and BLAKE3, action cache read-only, 64 MiB batches, symlinks +// allowed; API 2.0 to 2.3); capsZstd is the same with supported_compressors +// [ZSTD]. +var ( + capsLiveCache = []byte{0x0a, 0x02, 0x01, 0x09, 0x12, 0x02, 0x08, 0x01, 0x20, 0x80, 0x80, 0x04, 0x28, 0x01} + capsLiveAPIVersions = []byte{0x22, 0x02, 0x08, 0x02, 0x2a, 0x04, 0x08, 0x02, 0x10, 0x03} + capsLive = capsWithCache(capsLiveCache) + capsZstd = capsWithCache(pbBytes(6, []byte{1}), capsLiveCache) + // GetCapabilitiesRequest{instance_name: "oss"}, fork-cache's instance. + capsRequest = grpcMessage(pbBytes(1, []byte("oss"))) +) + +// capsWithCache: a ServerCapabilities with the live API versions and a +// cache_capabilities of the given fields. +func capsWithCache(cache ...[]byte) []byte { + return append(pbBytes(1, bytes.Join(cache, nil)), capsLiveAPIVersions...) +} + +func pbBytes(field int, b []byte) []byte { + out := binary.AppendUvarint(nil, uint64(field)<<3|2) + return append(binary.AppendUvarint(out, uint64(len(b))), b...) +} + +func pbVarint(field int, v uint64) []byte { + return binary.AppendUvarint(binary.AppendUvarint(nil, uint64(field)<<3), v) +} + +// grpcMessage frames m as one uncompressed gRPC message. +func grpcMessage(m []byte) []byte { + return append(binary.BigEndian.AppendUint32([]byte{0}, uint32(len(m))), m...) +} + +// capsAnswer is how the stand-in rbe-cache answers GetCapabilities: HTTP +// status (0: 200), body, and grpc-status ("": none; with no body, in the +// headers, as gRPC's trailers-only errors are), after delay. ac and bs answer +// cache-rrc-probe.sh's GetActionResult and ByteStream Read the same way; nil +// is rbe-cache's answer for a key no action has, or a blob it does not hold: +// a trailers-only NOT_FOUND. +type capsAnswer struct { + status int + grpc string + body []byte + delay time.Duration + ac, bs *capsAnswer +} + +// acNotFound: rbe-cache's answer to a GetActionResult for a key no action +// has, or a ByteStream Read for a blob it does not hold (capsAnswer.ac's and +// capsAnswer.bs's default). +var acNotFound = capsAnswer{grpc: "5"} + +// acRequest: cache-rrc-probe.sh's GetActionResultRequest{instance_name: +// "oss", action_digest: {sha256("cache-rrc-probe: no action has this key"), +// 1}}, a key no action has. +var acRequest = grpcMessage(append(pbBytes(1, []byte("oss")), + pbBytes(2, append(pbBytes(1, []byte("ad12d7a2f1dec188fc1f2c4f5535a4a65eb630fa2f309eca423695e6ec7abee7")), pbVarint(2, 1)...))...)) + +// bsRequest: cache-rrc-probe.sh's ReadRequest{resource_name: +// "oss/blobs//1"}, a blob the CAS does not hold. +var bsRequest = grpcMessage(pbBytes(1, []byte("oss/blobs/ad12d7a2f1dec188fc1f2c4f5535a4a65eb630fa2f309eca423695e6ec7abee7/1"))) + +// serveCapabilities answers a like rbe-cache's Caddy, over TLS and HTTP/2, +// after checking the request is a probe's GetCapabilities, or +// cache-rrc-probe.sh's GetActionResult or ByteStream Read, for instance oss. +// It returns the probe's RBE_CACHE_PROBE_URL, a CA file for curl's +// CURL_CA_BUNDLE, and the request count. +func serveCapabilities(t *testing.T, a capsAnswer) (url, caFile string, hits *atomic.Int32) { + t.Helper() + hits = new(atomic.Int32) + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + body, _ := io.ReadAll(r.Body) + path, want, answer := "/build.bazel.remote.execution.v2.Capabilities/GetCapabilities", capsRequest, a + switch r.URL.Path { + case "/build.bazel.remote.execution.v2.ActionCache/GetActionResult": + path, want, answer = r.URL.Path, acRequest, acNotFound + if a.ac != nil { + answer = *a.ac + } + case "/google.bytestream.ByteStream/Read": + path, want, answer = r.URL.Path, bsRequest, acNotFound + if a.bs != nil { + answer = *a.bs + } + } + if r.ProtoMajor != 2 || r.Method != http.MethodPost || r.URL.Path != path || + r.Header.Get("Content-Type") != "application/grpc" || !bytes.Equal(body, want) { + t.Errorf("probe sent %s %s %s, content-type %q, body %x; want HTTP/2 POST %s, application/grpc, %x", + r.Proto, r.Method, r.URL.Path, r.Header.Get("Content-Type"), body, path, want) + w.WriteHeader(http.StatusBadRequest) + return + } + select { + case <-time.After(answer.delay): + case <-r.Context().Done(): + return + } + w.Header().Set("Content-Type", "application/grpc") + trailer := answer.grpc != "" && answer.body != nil + if trailer { + w.Header().Set("Trailer", "Grpc-Status") + } else if answer.grpc != "" { + w.Header().Set("Grpc-Status", answer.grpc) + } + status := answer.status + if status == 0 { + status = http.StatusOK + } + w.WriteHeader(status) + _, _ = w.Write(answer.body) + // Streamed, as gRPC servers answer: Go drops the trailer of a + // response it can give a content-length. + w.(http.Flusher).Flush() + if trailer { + w.Header().Set("Grpc-Status", answer.grpc) + } + })) + srv.EnableHTTP2 = true + srv.StartTLS() + t.Cleanup(srv.Close) + caFile = filepath.Join(t.TempDir(), "ca.pem") + if err := os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0o644); err != nil { + t.Fatal(err) + } + return srv.URL, caFile, hits +} + +// requireCacheZstdProbeTools: the probe needs curl and python3 (without +// them it leaves the flag off, which the refused-probe tests cover). +func requireCacheZstdProbeTools(t *testing.T) { + t.Helper() + requireHostTool(t, "curl") + requireHostTool(t, "python3") +} + +// TestCacheZstdProbe runs cache-zstd-probe.sh against a stand-in rbe-cache. +// Only an answer listing ZSTD in cache_capabilities.supported_compressors +// (the field Bazel checks) passes; every other answer, error, refusal or +// timeout fails, and write-bazelrc.sh then writes no flag. The probe never +// writes stdout (write-bazelrc.sh appends its stdout to the rc) and always +// says why on stderr. +func TestCacheZstdProbe(t *testing.T) { + bash := requireHostTool(t, "bash") + requireCacheZstdProbeTools(t) + root := sourceRepoRoot(t) + script := filepath.Join(root, cacheZstdProbe) + + // The probe asks what fork-cache uses: rbe-cache, instance oss. + probeText := readPolicyFile(t, root, cacheZstdProbe) + for _, want := range []string{ + "url=${RBE_CACHE_PROBE_URL:-https://rbe-cache.ops.gascity.com:8443}\n", + `printf '\000\000\000\000\005\012\003oss'`, + "--connect-timeout 3 --max-time \"$max_time\"", + "max_time=${RBE_CACHE_PROBE_MAX_TIME:-5}\n", + } { + if !strings.Contains(probeText, want) { + t.Errorf("%s lacks %q", cacheZstdProbe, want) + } + } + if !bytes.Equal(capsRequest, []byte("\x00\x00\x00\x00\x05\x0a\x03oss")) { + t.Fatalf("capsRequest = %x", capsRequest) + } + bazelrc := readPolicyFile(t, root, ".bazelrc") + for _, want := range []string{"\nbuild:fork-cache --remote_cache=" + forkCacheEndpoint + "\n", "\nbuild:fork-cache --remote_instance_name=" + forkCacheInstance + "\n"} { + if !strings.Contains(bazelrc, want) { + t.Errorf(".bazelrc lacks %q, which the probe asks", strings.TrimSpace(want)) + } + } + if forkCacheEndpoint != "grpcs://rbe-cache.ops.gascity.com:8443" || forkCacheInstance != "oss" { + t.Errorf("fork-cache is %s instance %s; the probe asks rbe-cache.ops.gascity.com:8443 instance oss", forkCacheEndpoint, forkCacheInstance) + } + + zstd := grpcMessage(capsZstd) + cases := []struct { + name string + answer capsAnswer + want bool + }{ + {"rbe-cache before zstd", capsAnswer{grpc: "0", body: grpcMessage(capsLive)}, false}, + {"zstd advertised", capsAnswer{grpc: "0", body: zstd}, true}, + {"zstd among others, unpacked", capsAnswer{grpc: "0", body: grpcMessage(capsWithCache(capsLiveCache, pbVarint(6, 2), pbVarint(6, 1)))}, true}, + {"deflate only", capsAnswer{grpc: "0", body: grpcMessage(capsWithCache(capsLiveCache, pbBytes(6, []byte{2})))}, false}, + {"zstd for batch updates only", capsAnswer{grpc: "0", body: grpcMessage(capsWithCache(capsLiveCache, pbBytes(7, []byte{1})))}, false}, + {"zstd outside cache_capabilities", capsAnswer{grpc: "0", body: grpcMessage(append(capsLive, pbBytes(2, pbBytes(6, []byte{1}))...))}, false}, + {"gRPC error after the answer", capsAnswer{grpc: "13", body: zstd}, false}, + {"no grpc-status", capsAnswer{body: zstd}, false}, + {"trailers-only UNIMPLEMENTED", capsAnswer{grpc: "12"}, false}, + {"HTTP 502", capsAnswer{status: http.StatusBadGateway, grpc: "0", body: zstd}, false}, + {"compressed message", capsAnswer{grpc: "0", body: append([]byte{1}, zstd[1:]...)}, false}, + {"truncated message", capsAnswer{grpc: "0", body: zstd[:len(zstd)-1]}, false}, + {"truncated field", capsAnswer{grpc: "0", body: grpcMessage(capsZstd[:4])}, false}, + {"not gRPC", capsAnswer{grpc: "0", body: []byte("bad gateway")}, false}, + {"timeout", capsAnswer{grpc: "0", body: zstd, delay: 10 * time.Second}, false}, + } + run := func(t *testing.T, env ...string) (bool, string, string) { + t.Helper() + cmd := exec.Command(bash, script) + cmd.Dir = t.TempDir() + cmd.Env = append([]string{"PATH=" + os.Getenv("PATH"), "RBE_CACHE_PROBE_MAX_TIME=1"}, env...) + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err := cmd.Run() + var exit *exec.ExitError + if err != nil && !errors.As(err, &exit) { + t.Fatalf("run %s: %v", cacheZstdProbe, err) + } + return err == nil, stdout.String(), stderr.String() + } + check := func(t *testing.T, ok bool, stdout, stderr string, want bool) { + t.Helper() + if ok != want { + t.Errorf("probe passed: %v, want %v; stderr:\n%s", ok, want, stderr) + } + if stdout != "" { + t.Errorf("probe wrote stdout %q; write-bazelrc.sh would append it to the rc", stdout) + } + verdict := "; the fork cache stays identity\n" + if want { + verdict = "; the fork cache uses zstd\n" + } + if !strings.HasPrefix(stderr, "rbe-cache zstd probe: ") || !strings.HasSuffix(stderr, verdict) { + t.Errorf("probe stderr %q; want one verdict line ending %q", stderr, verdict) + } + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + url, ca, hits := serveCapabilities(t, c.answer) + start := time.Now() + ok, stdout, stderr := run(t, "RBE_CACHE_PROBE_URL="+url, "CURL_CA_BUNDLE="+ca) + check(t, ok, stdout, stderr, c.want) + if hits.Load() != 1 { + t.Errorf("probe asked %d times, want 1", hits.Load()) + } + if d := time.Since(start); d > 5*time.Second { + t.Errorf("probe took %v; RBE_CACHE_PROBE_MAX_TIME=1 bounds it", d) + } + }) + } + t.Run("refused", func(t *testing.T) { + ok, stdout, stderr := run(t, "RBE_CACHE_PROBE_URL="+refusedProbeURL) + check(t, ok, stdout, stderr, false) + }) + t.Run("untrusted certificate", func(t *testing.T) { + url, _, hits := serveCapabilities(t, capsAnswer{grpc: "0", body: zstd}) + ok, stdout, stderr := run(t, "RBE_CACHE_PROBE_URL="+url) + check(t, ok, stdout, stderr, false) + if hits.Load() != 0 { + t.Errorf("probe completed a request through an untrusted certificate") + } + }) +} + +// TestCacheRRCProbe runs cache-rrc-probe.sh against a stand-in rbe-cache: +// only a gRPC status 0 GetCapabilities answer with cache_capabilities, then +// NOT_FOUND for the probe's GetActionResult key and ByteStream Read blob, +// passes; every error, refusal, timeout or unreadable answer fails, and so +// does a copy with the kill switch off, without asking rbe-cache at all. The probe never writes +// stdout and always says why on stderr, with the TCP connect time (without +// the DNS lookup) once it has one. +func TestCacheRRCProbe(t *testing.T) { + bash := requireHostTool(t, "bash") + requireCacheZstdProbeTools(t) + root := sourceRepoRoot(t) + probeText := readPolicyFile(t, root, cacheRRCProbe) + for _, want := range []string{ + "\n" + cacheRRCKillLine + "\n", + "url=${RBE_CACHE_PROBE_URL:-https://rbe-cache.ops.gascity.com:8443}\n", + `printf '\000\000\000\000\005\012\003oss'`, + "--connect-timeout 3 --max-time \"$max_time\"", + "max_time=${RBE_CACHE_PROBE_MAX_TIME:-5}\n", + } { + if strings.Count(probeText, want) != 1 { + t.Errorf("%s lacks %q (once)", cacheRRCProbe, want) + } + } + switchedOff := filepath.Join(t.TempDir(), "cache-rrc-probe.sh") + if err := os.WriteFile(switchedOff, []byte(strings.Replace(probeText, "\n"+cacheRRCKillLine+"\n", "\nfork_rrc_read=off\n", 1)), 0o644); err != nil { + t.Fatal(err) + } + run := func(t *testing.T, script string, env ...string) (bool, string, string) { + t.Helper() + cmd := exec.Command(bash, script) + cmd.Dir = t.TempDir() + cmd.Env = append([]string{"PATH=" + os.Getenv("PATH"), "RBE_CACHE_PROBE_MAX_TIME=1"}, env...) + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err := cmd.Run() + var exit *exec.ExitError + if err != nil && !errors.As(err, &exit) { + t.Fatalf("run %s: %v", script, err) + } + return err == nil, stdout.String(), stderr.String() + } + check := func(t *testing.T, ok bool, stdout, stderr string, want bool) { + t.Helper() + if ok != want { + t.Errorf("probe passed: %v, want %v; stderr:\n%s", ok, want, stderr) + } + if stdout != "" { + t.Errorf("probe wrote stdout %q; write-bazelrc.sh would mistake it for its reason", stdout) + } + verdict := "; this lane fetches external repositories itself\n" + if want { + verdict = "; this lane reads the remote repo contents cache\n" + } + if !strings.HasPrefix(stderr, "rbe-cache rrc probe: ") || !strings.HasSuffix(stderr, verdict) || strings.Count(stderr, "\n") != 1 { + t.Errorf("probe stderr %q; want one verdict line ending %q", stderr, verdict) + } + } + script := filepath.Join(root, cacheRRCProbe) + live := grpcMessage(capsZstd) + acWith := func(a capsAnswer) capsAnswer { return capsAnswer{grpc: "0", body: live, ac: &a} } + bsWith := func(a capsAnswer) capsAnswer { return capsAnswer{grpc: "0", body: live, bs: &a} } + for _, c := range []struct { + name string + answer capsAnswer + want bool + asks int32 // GetCapabilities, GetActionResult, ByteStream Read: each only after a good answer + }{ + {"rbe-cache today", capsAnswer{grpc: "0", body: live}, true, 3}, + {"rbe-cache before zstd", capsAnswer{grpc: "0", body: grpcMessage(capsLive)}, true, 3}, + {"no cache_capabilities", capsAnswer{grpc: "0", body: grpcMessage(capsLiveAPIVersions)}, false, 1}, + {"gRPC error after the answer", capsAnswer{grpc: "13", body: live}, false, 1}, + {"no grpc-status", capsAnswer{body: live}, false, 1}, + {"trailers-only PERMISSION_DENIED", capsAnswer{grpc: "7"}, false, 1}, + {"HTTP 502", capsAnswer{status: http.StatusBadGateway, grpc: "0", body: live}, false, 1}, + {"compressed message", capsAnswer{grpc: "0", body: append([]byte{1}, live[1:]...)}, false, 1}, + {"truncated message", capsAnswer{grpc: "0", body: live[:len(live)-1]}, false, 1}, + {"not gRPC", capsAnswer{grpc: "0", body: []byte("bad gateway")}, false, 1}, + {"timeout", capsAnswer{grpc: "0", body: live, delay: 10 * time.Second}, false, 1}, + {"action cache answers the key", acWith(capsAnswer{grpc: "0", body: grpcMessage(nil)}), false, 2}, + {"action cache PERMISSION_DENIED", acWith(capsAnswer{grpc: "7"}), false, 2}, + {"action cache UNAVAILABLE", acWith(capsAnswer{grpc: "14"}), false, 2}, + {"action cache no grpc-status", acWith(capsAnswer{body: []byte{}}), false, 2}, + {"action cache HTTP 502", acWith(capsAnswer{status: http.StatusBadGateway, grpc: "5"}), false, 2}, + {"action cache timeout", acWith(capsAnswer{grpc: "5", delay: 10 * time.Second}), false, 2}, + {"CAS serves the blob", bsWith(capsAnswer{grpc: "0", body: grpcMessage(pbBytes(10, []byte{0}))}), false, 3}, + {"CAS UNAVAILABLE", bsWith(capsAnswer{grpc: "14"}), false, 3}, + {"CAS PERMISSION_DENIED", bsWith(capsAnswer{grpc: "7"}), false, 3}, + {"CAS HTTP 502", bsWith(capsAnswer{status: http.StatusBadGateway, grpc: "5"}), false, 3}, + {"CAS timeout", bsWith(capsAnswer{grpc: "5", delay: 10 * time.Second}), false, 3}, + } { + t.Run(c.name, func(t *testing.T) { + url, ca, hits := serveCapabilities(t, c.answer) + start := time.Now() + ok, stdout, stderr := run(t, script, "RBE_CACHE_PROBE_URL="+url, "CURL_CA_BUNDLE="+ca) + check(t, ok, stdout, stderr, c.want) + if hits.Load() != c.asks { + t.Errorf("probe asked %d times, want %d", hits.Load(), c.asks) + } + if c.asks > 1 && !regexp.MustCompile(` \(tcp connect [0-9]+\.[0-9] ms\); `).MatchString(stderr) { + t.Errorf("probe stderr %q lacks the GetCapabilities TCP connect time", stderr) + } + if d := time.Since(start); d > 5*time.Second { + t.Errorf("probe took %v; RBE_CACHE_PROBE_MAX_TIME=1 bounds each call", d) + } + }) + } + t.Run("refused", func(t *testing.T) { + ok, stdout, stderr := run(t, script, "RBE_CACHE_PROBE_URL="+refusedProbeURL) + check(t, ok, stdout, stderr, false) + }) + t.Run("untrusted certificate", func(t *testing.T) { + url, _, hits := serveCapabilities(t, capsAnswer{grpc: "0", body: live}) + ok, stdout, stderr := run(t, script, "RBE_CACHE_PROBE_URL="+url) + check(t, ok, stdout, stderr, false) + if hits.Load() != 0 { + t.Errorf("probe completed a request through an untrusted certificate") + } + }) + t.Run("kill switch off", func(t *testing.T) { + url, ca, hits := serveCapabilities(t, capsAnswer{grpc: "0", body: live}) + ok, stdout, stderr := run(t, switchedOff, "RBE_CACHE_PROBE_URL="+url, "CURL_CA_BUNDLE="+ca) + check(t, ok, stdout, stderr, false) + if !strings.Contains(stderr, "switched off") { + t.Errorf("switched-off probe stderr %q does not say it is switched off", stderr) + } + if hits.Load() != 0 { + t.Errorf("switched-off probe asked rbe-cache %d times, want 0", hits.Load()) + } + }) +} diff --git a/scripts/bazel_dolt_int_test.go b/scripts/bazel_dolt_int_test.go new file mode 100644 index 000000000..c961fab73 --- /dev/null +++ b/scripts/bazel_dolt_int_test.go @@ -0,0 +1,752 @@ +package scripts_test + +import ( + "cmp" + "maps" + "os/exec" + "path" + "path/filepath" + "reflect" + "regexp" + "slices" + "strconv" + "strings" + "testing" +) + +// The dolt-int union lane (item 5 A2): in mode remote, bazel.yml's +// bazel-dolt-int job runs --config=dolt-int, the union of +// --config=doltserver-integration and --config=doltserver-cmd, in one +// `bazel test`, in place of the bazel-server-storage and bazel-cmd-dolt jobs; +// in every other mode those two run as before. Unlike dolt-race, the members +// have different gating categories: bazel-server-storage is plain-gated +// (BAZEL_SERVER_STORAGE), bazel-cmd-dolt is flag-gated and advisory +// (BAZEL_CMD_DOLT, continue-on-error) until pr.yml's BAZEL_CMD_DOLT_REQUIRED +// is "true". The union itself carries no job-level continue-on-error (see +// TestBazelDoltIntIsGated): only the `bazel test` step does, and an always() +// classify step (tools/bazel/classify_tier_results.py) computes each tier's +// own result from the BEP and fails the job iff server-storage's tier +// failed, so a cmd-dolt-only failure still leaves the job green, exactly as +// bazel-cmd-dolt's own continue-on-error already does outside mode remote. +const ( + bazelDoltIntJobName = "bazel-dolt-int" + bazelDoltIntConfig = "dolt-int" + // Mode remote and integration not "off": exactly where the members do + // not run (see #7491's members, which skip on integration == "off" too). + bazelDoltIntJobIf = "${{ needs.rbe.outputs.mode == 'remote' && inputs.integration != 'off' }}" +) + +func init() { + // bazelUnionLanes (declared in bazel_dolt_race_test.go): a union job -> the + // gated member jobs it runs in place of in mode remote. Each member keeps + // its gate id/flag and its workflow_call output, which reads the union's + // result first and the member's own otherwise (bazelLaneCallOutput). + bazelUnionLanes[bazelDoltIntJobName] = []string{bazelServerJobName, bazelCmdDoltJobName} +} + +// bazelDoltIntJobTimeoutMargin: as bazelDoltRaceJobTimeoutMargin. +const bazelDoltIntJobTimeoutMargin = 5 + +// bazelDoltIntTestStepTimeout: the union's `bazel test` step timeout. Both +// members share the same 1200 s Bazel test_timeout cap; the step allows about +// 3 minutes past that cap so Bazel writes TIMEOUT logs before GitHub kills the +// step, plus the margin server-storage's own step budgeted for a cold +// compile (its own step was 25). +const bazelDoltIntTestStepTimeout = 25 + +// bazelDoltIntClassifyRun: the classify step's run body, exactly (must-fix 3, +// PR #7535 review): pinned by equality, not substring, so an appended +// --gate-tier or a second --tier/--check cannot sneak past a Contains check +// (argparse and dict() would otherwise just let the last value silently +// win, un-gating or re-gating a tier). +const bazelDoltIntClassifyRun = `python3 tools/bazel/classify_tier_results.py --bep "$RUNNER_TEMP/bazel-bep.json" --rc "$TEST_RC" --tier server-storage=//internal/storage/dolt:dolt_server_full_test,//internal/storage/dolt:dolt_server_conformance_test --tier cmd-dolt=//cmd/bd:bd_dolt_server_test,//tests/regression:regression_test --gate-tier server-storage --check "server-storage=$CHECK_SS_OUTCOME" --check "cmd-dolt=$CHECK_CD_OUTCOME" --github-output "$GITHUB_OUTPUT"` + +// bazelDoltIntTestRun: the union's `bazel test` step body, exactly. Unlike +// the retired tiers' (bazelTierTestRun), it captures rc as a step output (no +// job-level continue-on-error to rely on job.status instead) for the +// classify step to read, alongside its own exit. +const bazelDoltIntTestRun = `set -o pipefail +start=$(date +%s) +rc=0 +bazel test //... --config=dolt-int ${BAZEL_FRESH:+"$BAZEL_FRESH"} \ + --build_event_json_file="$RUNNER_TEMP/bazel-bep.json" \ + --execution_log_compact_file="$RUNNER_TEMP/bazel-exec.log.zst" \ + --profile="$RUNNER_TEMP/bazel-profile.json" \ + --experimental_build_event_upload_strategy=local \ + 2>&1 | tee "$RUNNER_TEMP/bazel-test.log" || rc=$? +echo "bazel test --config=dolt-int: exit $rc, $(( $(date +%s) - start ))s wall" | tee -a "$GITHUB_STEP_SUMMARY" +echo "rc=$rc" >> "$GITHUB_OUTPUT" +exit "$rc"` + +// The union's members, and the tag filter each owns. +var bazelDoltIntMembers = []struct{ config, tag string }{ + {"doltserver-integration", "dolt-server-integration"}, + {"doltserver-cmd", "dolt-server-cmd"}, +} + +// TestBazelDoltIntConfigIsMemberUnion: --config=dolt-int is exactly the set +// union of its members' lines, except that each member's --test_tag_filters +// is replaced by one filter naming both members' tags. Every flag stays a +// member's own, so each member target's test action is unchanged in the +// sense that matters for caching (item 5 A2, aquery-verified: byte-identical +// remote action digests, the key RBE's cache lookups use; each action's +// local actionKey differs, since dolt-int reaches these flags through the +// target's own env/args rather than the member's build configuration). Both +// arms run, the mode deciding which, so drift between them would split +// results by mode: a flag added to a member must be added to the union too. +func TestBazelDoltIntConfigIsMemberUnion(t *testing.T) { + rc := readPolicyFile(t, bazelPolicyRoot(t), ".bazelrc") + const tagPrefix = "test --test_tag_filters=" + + var want []string + var tags []string + for _, m := range bazelDoltIntMembers { + lines := bazelRCConfigLines(rc, m.config) + if len(lines) == 0 { + t.Fatalf(".bazelrc has no --config=%s lines", m.config) + } + var memberTags []string + for _, l := range lines { + if v, ok := strings.CutPrefix(l, tagPrefix); ok { + memberTags = append(memberTags, v) + continue + } + if !slices.Contains(want, l) { + want = append(want, l) + } + } + if len(memberTags) != 1 || memberTags[0] != m.tag { + t.Errorf("--config=%s tag filters %v, want exactly [%s]", m.config, memberTags, m.tag) + } + tags = append(tags, m.tag) + } + + got := bazelRCConfigLines(rc, bazelDoltIntConfig) + var gotTags []string + var gotRest []string + for _, l := range got { + if v, ok := strings.CutPrefix(l, tagPrefix); ok { + gotTags = append(gotTags, v) + continue + } + gotRest = append(gotRest, l) + } + if wantTag := strings.Join(tags, ","); len(gotTags) != 1 || gotTags[0] != wantTag { + t.Errorf("--config=%s tag filters %v, want exactly [%s]", bazelDoltIntConfig, gotTags, wantTag) + } + if !sameStringSet(gotRest, want) { + t.Errorf("--config=%s is not the union of its members' lines (tag filter aside):\ngot:\n%s\nwant (any order):\n%s", + bazelDoltIntConfig, strings.Join(gotRest, "\n"), strings.Join(want, "\n")) + } + if len(gotRest) != len(want) { + t.Errorf("--config=%s repeats a line: %d lines for %d distinct member lines", bazelDoltIntConfig, len(gotRest), len(want)) + } + // No nested --config: the union is spelled out, so the policy above sees + // every flag. + for _, l := range got { + if strings.Contains(l, "--config=") { + t.Errorf("--config=%s line %q: spell the members' flags out, no nested --config", bazelDoltIntConfig, l) + } + } +} + +// TestBazelDoltIntSoleRunIsInTheUnion: the members never add --config=sole-run +// or read $BAZEL_SOLE_RUN (unlike bazel-test/bazel-pure/bazel-doltserver); +// each bakes --config=sole-run's one line (no retry on a remote cache +// eviction) directly and unconditionally into its own .bazelrc config +// instead. The union must carry that same line itself (not nested +// --config=sole-run: TestBazelDoltIntConfigIsMemberUnion forbids nesting), +// so both tiers' actions are the same whether the member or the union runs +// them. +func TestBazelDoltIntSoleRunIsInTheUnion(t *testing.T) { + rc := readPolicyFile(t, bazelPolicyRoot(t), ".bazelrc") + sole := bazelRCConfigLines(rc, "sole-run") + if len(sole) == 0 { + t.Fatal(".bazelrc has no --config=sole-run lines") + } + union := bazelRCConfigLines(rc, bazelDoltIntConfig) + for _, l := range sole { + if !slices.Contains(union, l) { + t.Errorf("--config=sole-run line %q is not in --config=%s: the members' remote runs and the union would differ", l, bazelDoltIntConfig) + } + } + // And the union job takes no sole-run of its own: nothing to add. + test := readCIWorkflow(t, bazelWorkflowName).job(t, bazelDoltIntJobName).step(t, "bazel test //... --config="+bazelDoltIntConfig) + if strings.Contains(test.Run, "BAZEL_SOLE_RUN") || strings.Contains(test.Run, "sole-run") { + t.Errorf("%s test step adds sole-run; --config=%s already has its lines", bazelDoltIntJobName, bazelDoltIntConfig) + } +} + +// TestBazelDoltIntIsGated pins the cutover: the union job carries no +// job-level continue-on-error (per-tier results come from an always() +// classify step instead: see the package comment above), it runs the union +// config with the members' checks once over its BEP (the new Shard balance +// step is bespoke, --label-scoped to server-storage's own target), and both +// members' workflow_call outputs read its per-tier result first. +func TestBazelDoltIntIsGated(t *testing.T) { + workflow := readCIWorkflow(t, bazelWorkflowName) + job := workflow.job(t, bazelDoltIntJobName) + + if job.If != bazelDoltIntJobIf { + t.Errorf("%s if: %q, want %q", bazelDoltIntJobName, job.If, bazelDoltIntJobIf) + } + // Unlike dolt-race (both members plain-gated): bazel-cmd-dolt is + // flag-gated/advisory with its own continue-on-error everywhere else, + // but a job-level continue-on-error here would make job.status read + // success regardless of the `bazel test` step's own result, so a + // server-storage failure would end green on push/nightly/dispatch + // (nothing there reads BAZEL_SERVER_STORAGE off a workflow_call output + // to catch it), where it must stay red exactly as on main today. The + // job must therefore carry no continue-on-error of its own; the classify + // step's own exit code decides job.status per-tier instead. + if job.ContinueOnError { + t.Errorf("%s: want no job-level continue-on-error (per-tier results come from the classify step's exit code instead)", bazelDoltIntJobName) + } + if job.Name != "dolt-int" { + // ci-analytics' collector maps the check name "Bazel / dolt-int" to + // lane dolt-int. + t.Errorf("%s name = %q, want dolt-int", bazelDoltIntJobName, job.Name) + } + if !slices.Equal(job.Needs, []string{bazelRBEJobName}) { + t.Errorf("%s needs %v, want [%s]", bazelDoltIntJobName, job.Needs, bazelRBEJobName) + } + wantOutputs := map[string]string{ + "server_storage_result": "${{ steps.classify.outputs.server_storage_result }}", + "cmd_dolt_result": "${{ steps.classify.outputs.cmd_dolt_result }}", + } + if !reflect.DeepEqual(job.Outputs, wantOutputs) { + t.Errorf("%s outputs = %v, want %v (per-tier, from the classify step)", bazelDoltIntJobName, job.Outputs, wantOutputs) + } + + // The test step: the union config, as the member lanes run theirs, plus + // its own continue-on-error and rc capture (must-fix 2: per-tier results, + // not job-level continue-on-error; see the job's own comment). + test := job.step(t, "bazel test //... --config="+bazelDoltIntConfig) + if want := bazelDoltIntTestRun; strings.TrimSpace(test.Run) != want { + t.Errorf("%s test step run changed; want exactly:\n%s\ngot:\n%s", bazelDoltIntJobName, want, test.Run) + } + if v, ok := test.ContinueOnError.(bool); !ok || !v { + t.Errorf("%s test step: want continue-on-error: true (the classify step below decides the job's own result per-tier), got %v", bazelDoltIntJobName, test.ContinueOnError) + } + if test.ID != "test" { + t.Errorf("%s test step id = %q, want %q (the classify step reads steps.test.outcome/outputs.rc)", bazelDoltIntJobName, test.ID, "test") + } + classify := job.step(t, "Classify tier results") + if classify.ContinueOnError != nil && classify.ContinueOnError != false { + t.Errorf("%s classify step: want no continue-on-error (its own exit code must decide job.status), got %v", bazelDoltIntJobName, classify.ContinueOnError) + } + if classify.ID != "classify" { + t.Errorf("%s classify step id = %q, want %q (the job's outputs read steps.classify.outputs.*)", bazelDoltIntJobName, classify.ID, "classify") + } + if classify.If != "${{ always() && steps.test.outcome != 'skipped' }}" { + t.Errorf("%s classify step if = %q, want always() guarded by steps.test.outcome (a dead job before this step must leave both outputs empty)", bazelDoltIntJobName, classify.If) + } + // steps.test.outputs.rc and each per-tier check step's own outcome reach + // the script through env, not interpolated directly into the run script + // (TestBazelWorkflowForkFarmInputs forbids "${{" in any run: body; see + // "Record job result"'s JOB_STATUS for the existing pattern this + // follows). + for env, want := range map[string]string{ + "TEST_RC": "${{ steps.test.outputs.rc }}", + "CHECK_SS_OUTCOME": "${{ steps.check-ss.outcome }}", + "CHECK_CD_OUTCOME": "${{ steps.check-cd.outcome }}", + } { + if got := classify.Env[env]; got != want { + t.Errorf("%s classify step env.%s = %q, want %q", bazelDoltIntJobName, env, got, want) + } + } + // Pinned by exact equality, not substring (must-fix 3): see + // bazelDoltIntClassifyRun's own comment. + if got, want := strings.TrimSpace(classify.Run), bazelDoltIntClassifyRun; got != want { + t.Errorf("%s classify step run changed; want exactly:\n%s\ngot:\n%s", bazelDoltIntJobName, want, got) + } + if strings.Contains(classify.Run, "${{") { + t.Errorf("%s classify step run interpolates an expression directly: %q", bazelDoltIntJobName, classify.Run) + } + // server-storage's own "No test target is marked flaky" and "Every + // listed test ran in its shard" steps (cmd-dolt has neither): textually + // identical, once over the union's BEP. "Every target and shard ran + // tests" is bespoke per tier below (should-fix 2: split, continue-on- + // error, --label-scoped, and the result folded into that tier alone). + for member, steps := range map[string][]string{ + bazelServerJobName: {"No test target is marked flaky", "Every listed test ran in its shard"}, + } { + m := workflow.job(t, member) + for _, name := range steps { + want, got := m.step(t, name), job.step(t, name) + if strings.TrimSpace(got.Run) != strings.TrimSpace(want.Run) || got.If != want.If { + t.Errorf("%s step %q = (if %q) %q, want %s's (if %q) %q", bazelDoltIntJobName, name, got.If, got.Run, member, want.If, want.Run) + } + } + } + // The split check_testcases steps (should-fix 2, PR #7535 review): each + // --label-scoped to its own tier, continue-on-error so a zero-testcase + // shard in either tier cannot fail the job by itself -- the classify + // step's --check folds each step's own outcome into that tier's result + // instead (bazelDoltIntClassifyRun pins the --check args). + for id, want := range map[string]struct { + name string + labels []string + }{ + "check-ss": {"Every target and shard ran tests (server-storage)", []string{ + "//internal/storage/dolt:dolt_server_full_test", + "//internal/storage/dolt:dolt_server_conformance_test", + }}, + "check-cd": {"Every target and shard ran tests (cmd-dolt)", []string{ + "//cmd/bd:bd_dolt_server_test", + "//tests/regression:regression_test", + }}, + } { + step := job.step(t, want.name) + if step.ID != id { + t.Errorf("%s step %q id = %q, want %q (the classify step reads steps.%s.outcome)", bazelDoltIntJobName, want.name, step.ID, id, id) + } + if step.If != "${{ always() && steps.test.outcome != 'skipped' }}" { + t.Errorf("%s step %q if = %q, want always() guarded by steps.test.outcome", bazelDoltIntJobName, want.name, step.If) + } + if v, ok := step.ContinueOnError.(bool); !ok || !v { + t.Errorf("%s step %q: want continue-on-error: true (its outcome feeds the classify step's --check, not job.status directly), got %v", bazelDoltIntJobName, want.name, step.ContinueOnError) + } + if !strings.Contains(step.Run, "check_testcases.py") { + t.Errorf("%s step %q run = %q, want it to run check_testcases.py", bazelDoltIntJobName, want.name, step.Run) + } + for _, label := range want.labels { + if !strings.Contains(step.Run, "--label "+label) { + t.Errorf("%s step %q run missing --label %s:\n%s", bazelDoltIntJobName, want.name, label, step.Run) + } + } + } + // Shard balance is bespoke: server-storage's own step has no --label (it + // has only ever budgeted its own target), the union's scopes to that same + // target with --label so cmd-dolt's untested shards do not skew it (see + // the job's own comment and shard_budget.py's docstring). + storageShardBalance := workflow.job(t, bazelServerJobName).step(t, "Shard balance") + unionShardBalance := job.step(t, "Shard balance") + if strings.TrimSpace(unionShardBalance.Run) == strings.TrimSpace(storageShardBalance.Run) { + t.Errorf("%s Shard balance step is textually identical to %s's; want it scoped with --label", bazelDoltIntJobName, bazelServerJobName) + } + if !strings.Contains(unionShardBalance.Run, "--label //internal/storage/dolt:dolt_server_full_test") { + t.Errorf("%s Shard balance step = %q, want --label //internal/storage/dolt:dolt_server_full_test", bazelDoltIntJobName, unionShardBalance.Run) + } + + // Upload test logs (must-fix 4, PR #7535 review): the `bazel test` step + // carries its own continue-on-error, so failure() alone stays false on an + // ordinary test failure until the classify step (which runs after this + // one) exits non-zero -- by which point this step has already been + // evaluated. steps.test.outcome == 'failure' catches that case directly; + // no other test in this suite pins this job's own "Upload test logs" if + // (TestBazelWorkflowSecretsAndFailureSurface only inventories + // continue-on-error paths, and bazel_dolt_race_test.go/ci_workflow_test.go + // pin only the other lanes' upload-logs steps), so a future accidental + // revert of this condition to plain failure() would otherwise go + // unnoticed (mutation G, PR #7535 review round 3). + logs := job.step(t, "Upload test logs") + const wantLogsIf = "${{ (failure() || steps.test.outcome == 'failure') && steps.test.outcome != 'skipped' }}" + if logs.If != wantLogsIf { + t.Errorf("%s Upload test logs if = %q, want %q", bazelDoltIntJobName, logs.If, wantLogsIf) + } + if logs.With["name"] != "bazel-dolt-int-testlogs" { + t.Errorf("%s Upload test logs name = %q, want bazel-dolt-int-testlogs", bazelDoltIntJobName, logs.With["name"]) + } + + for _, member := range bazelUnionLanes[bazelDoltIntJobName] { + for _, step := range workflow.job(t, member).Steps { + if strings.Contains(step.Run, "shard_budget.py") && member != bazelServerJobName { + t.Errorf("%s step %q: a per-lane check the union does not run", member, step.Name) + } + if strings.Contains(step.Run, "check_shard_coverage.py") && member != bazelServerJobName { + t.Errorf("%s step %q: a per-lane check the union does not run", member, step.Name) + } + } + } + + // No job depends on it, and every member's output reads it first. + for name, other := range workflow.Jobs { + if slices.Contains(other.Needs, bazelDoltIntJobName) { + t.Errorf("job %s needs %s", name, bazelDoltIntJobName) + } + } + call := readBazelWorkflowCall(t) + for _, member := range bazelUnionLanes[bazelDoltIntJobName] { + if got, want := call.Outputs[member].Value, bazelLaneCallOutput(member); got != want { + t.Errorf("workflow_call output %s = %q, want %q", member, got, want) + } + } + for name := range call.Outputs { + if strings.Contains(name, bazelDoltIntConfig) { + t.Errorf("workflow_call output %s: the union reports through its members' outputs, not one of its own (the gate ids stay)", name) + } + } +} + +// TestBazelDoltIntJobTimeouts: the union's test step has a 25-minute timeout, +// every step has one, and the job's exceeds their sum by +// bazelDoltIntJobTimeoutMargin minutes (a hang fails a named step) while +// staying under the merge queue's check timeout. +func TestBazelDoltIntJobTimeouts(t *testing.T) { + job := readCIWorkflow(t, bazelWorkflowName).job(t, bazelDoltIntJobName) + test := job.step(t, "bazel test //... --config="+bazelDoltIntConfig) + if test.TimeoutMinutes != bazelDoltIntTestStepTimeout { + t.Errorf("%s test step timeout-minutes = %d, want %d", bazelDoltIntJobName, test.TimeoutMinutes, bazelDoltIntTestStepTimeout) + } + sum := 0 + for i, step := range job.Steps { + if step.TimeoutMinutes <= 0 { + t.Errorf("%s step %d (%q) has no timeout-minutes; a hang would run into the job timeout", + bazelDoltIntJobName, i, cmp.Or(step.Name, step.Uses)) + } + sum += step.TimeoutMinutes + } + if job.TimeoutMinutes < sum+bazelDoltIntJobTimeoutMargin { + t.Errorf("%s timeout-minutes %d, want at least the sum of its step timeouts (%d) + %d", + bazelDoltIntJobName, job.TimeoutMinutes, sum, bazelDoltIntJobTimeoutMargin) + } + if job.TimeoutMinutes >= bazelDoltRaceMergeQueueTimeout { + t.Errorf("%s timeout-minutes %d, want below the merge queue's %d-minute check timeout", + bazelDoltIntJobName, job.TimeoutMinutes, bazelDoltRaceMergeQueueTimeout) + } +} + +// TestBazelDoltIntArmsExactlyOnePerMode evaluates the union's and the +// members' if: for every execution mode and every event bazel.yml runs on: +// the union runs exactly in mode remote, never beside a member, and each +// member's gate id/flag is reported by exactly one job wherever that member +// ran before the union (bazel-server-storage: the remote-executing modes +// plus cache, when enabled and integration is not off; bazel-cmd-dolt: where +// bazel-integration runs) and by none elsewhere, so bazel-gate.sh's per-mode +// skips are unchanged. The workflow_call outputs, evaluated as GitHub does, +// carry the running arm's result: a failed or cancelled union reds both +// ids/flags, and a union that never reported reads as skipped, which no mode +// it runs in allows. +func TestBazelDoltIntArmsExactlyOnePerMode(t *testing.T) { + workflow := readCIWorkflow(t, bazelWorkflowName) + union := workflow.job(t, bazelDoltIntJobName) + members := map[string]struct { + ifExpr string + before func(mode string) bool // where the member ran before the union + }{ + bazelServerJobName: {bazelServerStorageIf, func(m string) bool { return bazelRemoteModes[m] }}, + bazelCmdDoltJobName: {bazelCmdDoltMemberIf, func(m string) bool { return bazelRemoteModes[m] || m == "cache" }}, + } + if got := slices.Sorted(maps.Keys(members)); !slices.Equal(got, slices.Sorted(slices.Values(bazelUnionLanes[bazelDoltIntJobName]))) { + t.Fatalf("members %v, want bazelUnionLanes' %v", got, bazelUnionLanes[bazelDoltIntJobName]) + } + for name, m := range members { + if got := workflow.job(t, name).If; got != m.ifExpr { + t.Errorf("%s if = %q, want %q", name, got, m.ifExpr) + } + } + for _, mode := range bazelRBEModes { + for _, event := range []string{"pull_request", "merge_group", "pull_request_target", "push", "schedule", "workflow_dispatch"} { + for _, integration := range []string{"", "off"} { + ctx := map[string]string{ + "needs.rbe.outputs.mode": mode, + "needs.rbe.outputs.enabled": bazelModeEnabled(mode), + "github.event_name": event, + "inputs.integration": integration, + } + wantUnionRuns := mode == "remote" && integration != "off" + unionRuns := evalRRCIf(t, union.If, ctx) + if unionRuns != wantUnionRuns { + t.Errorf("mode %s, %s, integration %q: %s runs = %v, want %v", mode, event, integration, bazelDoltIntJobName, unionRuns, wantUnionRuns) + } + for name, m := range members { + runs := evalRRCIf(t, workflow.job(t, name).If, ctx) + if unionRuns && runs { + t.Errorf("mode %s, %s, integration %q: %s and %s both run", mode, event, integration, bazelDoltIntJobName, name) + } + wantBefore := integration != "off" && m.before(mode) + if got, want := unionRuns || runs, wantBefore; got != want { + t.Errorf("mode %s, %s, integration %q: %s's tier reported by a job = %v, want %v (where it ran before the union)", mode, event, integration, name, got, want) + } + for _, res := range []string{"success", "failure", "cancelled", ""} { + jobs := map[string]string{} + switch { + case unionRuns: + jobs[bazelDoltIntJobName] = res + case runs: + jobs[name] = res + } + want := res + if !unionRuns && !runs { + want = "" + } + if got := bazelCallOutputValue(t, name, jobs); got != want { + t.Errorf("mode %s, %s, integration %q, reporting job %q: output %s = %q, want %q", mode, event, integration, res, name, got, want) + } + } + } + } + } + } + // The union's runner is the lanes' ternary: Blacksmith in mode remote, + // the only mode it runs in. + if union.RunsOn != bazelLaneRunsOn { + t.Errorf("%s runs-on = %q, want %q", bazelDoltIntJobName, union.RunsOn, bazelLaneRunsOn) + } +} + +// classifyTierResultsTest: tools/bazel/classify_tier_results_test.py's own +// path, run directly (its docstring), not through a Bazel target: locally +// authored, so no SHA256 content pin is needed (unlike the vendored-from- +// gascity Python test files this repo also wraps, e.g. bazel_rrc_test.go's +// rrc_verify_test.py). +const classifyTierResultsTest = "tools/bazel/classify_tier_results_test.py" +const checkTestcasesTest = "tools/bazel/check_testcases_test.py" + +// TestClassifyTierResultsUnitTests runs classify_tier_results.py's own +// behavioural test (must-fix 2(f)): the script the "Classify tier results" +// step above calls, covering ss-fail-only, cmd-fail-only, both, build +// failure and rc=0 over a synthetic BEP/test summary. +func TestClassifyTierResultsUnitTests(t *testing.T) { + root := sourceRepoRoot(t) + python := requireHostTool(t, "python3") + cmd := exec.Command(python, filepath.Join(root, classifyTierResultsTest), "-v") + cmd.Dir = filepath.Join(root, "tools", "bazel") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("%s failed: %v\n%s", classifyTierResultsTest, err, out) + } +} + +// TestCheckTestcasesUnitTests runs check_testcases.py's own behavioural test +// (should-fix 2 of PR #7535's review): the script the union's two per-tier +// "Every target and shard ran tests" steps (check-ss, check-cd) each call +// with their own --label set, covering that --label both restricts the +// check to its own tier's targets and still fails closed on a label the BEP +// has no result for, or a zero-testcase shard within its own tier. +func TestCheckTestcasesUnitTests(t *testing.T) { + root := sourceRepoRoot(t) + python := requireHostTool(t, "python3") + cmd := exec.Command(python, filepath.Join(root, checkTestcasesTest), "-v") + cmd.Dir = filepath.Join(root, "tools", "bazel") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("%s failed: %v\n%s", checkTestcasesTest, err, out) + } +} + +// bazelDoltIntTestActions: the union's test actions, 17 server-storage + 46 +// cmd-dolt (aquery, item 5 A2). +const bazelDoltIntTestActions = 63 + +// TestBazelDoltIntFitsTheJobsBudget pins the one-wave rule (closed PR #7542, +// carried from dolt-race: see TestBazelDoltRaceFitsTheJobsBudget's own +// comment for the mechanism and the measured +575s regression): a union's +// total test actions must fit in the effective --jobs +// (bazelUnionEffectiveJobs) so every action starts in Bazel's first wave, +// since Bazel does not schedule the longest action first and a second-wave +// tail test adds its own full duration to the critical path instead of +// overlapping it. The union runs both tiers' shards in one invocation under +// that budget, so all of them must fit at once or the slower tier's shards +// queue behind the other's. Every rule tagged with one of the union's tags, +// read from the BUILD files: its shard_count (1 when unsharded), summed. +func TestBazelDoltIntFitsTheJobsBudget(t *testing.T) { + root := bazelPolicyRoot(t) + rc := readPolicyFile(t, root, ".bazelrc") + budget := bazelUnionEffectiveJobs(t, rc, bazelDoltIntConfig) + + var tags []string + for _, mem := range bazelDoltIntMembers { + tags = append(tags, `"`+mem.tag+`"`) + } + ruleStart := regexp.MustCompile(`(?m)^[A-Za-z_][A-Za-z0-9_]*\($`) + total, targets := 0, 0 + for _, f := range repoFiles(t, root, 300) { + if path.Base(f) != "BUILD.bazel" { + continue + } + build := readPolicyFile(t, root, f) + for _, line := range strings.Split(build, "\n") { + for _, tag := range tags { + if strings.Contains(line, tag) && !strings.HasPrefix(line, " tags = [") { + t.Errorf("%s: %q outside a one-line tags list: %q", f, tag, line) + } + } + } + for _, loc := range ruleStart.FindAllStringIndex(build, -1) { + end := strings.Index(build[loc[0]:], "\n)\n") + if end < 0 { + continue + } + rule := build[loc[0] : loc[0]+end] + tagged := false + for _, line := range strings.Split(rule, "\n") { + if strings.HasPrefix(line, " tags = [") && slices.ContainsFunc(tags, func(tag string) bool { return strings.Contains(line, tag) }) { + tagged = true + } + } + if !tagged { + continue + } + shards := 1 + if sm := shardCountPattern.FindStringSubmatch(rule); sm != nil { + shards, _ = strconv.Atoi(sm[1]) + } + total += shards + targets++ + } + } + if total != bazelDoltIntTestActions { + t.Errorf("--config=%s: %d test actions over %d targets, want %d (aquery-verified at the cutover): re-check against --jobs=%d and update", bazelDoltIntConfig, total, targets, bazelDoltIntTestActions, budget) + } + if total > budget { + t.Errorf("--config=%s: %d test actions, more than the effective --jobs=%d: a second wave would add its tail test's full duration to the critical path instead of overlapping it (closed PR #7542 measured up to +575s from exactly this)", bazelDoltIntConfig, total, budget) + } +} + +// bazelDoltIntTierNames maps each member's tag to the --tier/--check name +// bazel.yml's classify step uses for it. +var bazelDoltIntTierNames = map[string]string{ + "dolt-server-integration": "server-storage", + "dolt-server-cmd": "cmd-dolt", +} + +// bazelDoltIntTaggedLabels returns, for each of the union's tags, the exact +// sorted set of labels the BUILD files tag with it: the same rule-block walk +// TestBazelDoltIntFitsTheJobsBudget uses to sum shard counts, but keeping +// each rule's own label (//pkg:name) instead. +func bazelDoltIntTaggedLabels(t *testing.T) map[string][]string { + t.Helper() + root := bazelPolicyRoot(t) + ruleStart := regexp.MustCompile(`(?m)^[A-Za-z_][A-Za-z0-9_]*\($`) + nameLine := regexp.MustCompile(`(?m)^ name = "([^"]+)",$`) + out := map[string][]string{} + for _, f := range repoFiles(t, root, 300) { + if path.Base(f) != "BUILD.bazel" { + continue + } + build := readPolicyFile(t, root, f) + pkg := path.Dir(f) + if pkg == "." { + pkg = "" + } + for _, loc := range ruleStart.FindAllStringIndex(build, -1) { + end := strings.Index(build[loc[0]:], "\n)\n") + if end < 0 { + continue + } + rule := build[loc[0] : loc[0]+end] + nm := nameLine.FindStringSubmatch(rule) + if nm == nil { + continue + } + for _, mem := range bazelDoltIntMembers { + tagLine := `"` + mem.tag + `"` + for _, line := range strings.Split(rule, "\n") { + if strings.HasPrefix(line, " tags = [") && strings.Contains(line, tagLine) { + out[mem.tag] = append(out[mem.tag], "//"+pkg+":"+nm[1]) + break + } + } + } + } + } + for tag := range out { + slices.Sort(out[tag]) + } + return out +} + +// TestBazelDoltIntTierLabelsMatchTheTags ties the classify step's --tier +// label lists, and the per-tier check_testcases.py steps' --label lists, to +// the BUILD files' own tag sets -- the same sets TestBazelDoltIntFitsTheJobsBudget +// walks (must-fix 1, PR #7535 review): classify_tier_results.py fails every +// tier closed on a non-PASSED result for a label outside every --tier, but +// only if these lists actually name every tagged target. A target tagged +// dolt-server-integration or dolt-server-cmd without a matching update here +// (and to bazelDoltIntTestActions/bazelDoltIntClassifyRun, which this test +// also indirectly guards) would otherwise run untracked. +func TestBazelDoltIntTierLabelsMatchTheTags(t *testing.T) { + tagged := bazelDoltIntTaggedLabels(t) + workflow := readCIWorkflow(t, bazelWorkflowName) + job := workflow.job(t, bazelDoltIntJobName) + + classify := job.step(t, "Classify tier results") + tierArg := regexp.MustCompile(`--tier ([a-z-]+)=(\S+)`) + gotTiers := map[string][]string{} + for _, m := range tierArg.FindAllStringSubmatch(classify.Run, -1) { + gotTiers[m[1]] = strings.Split(m[2], ",") + } + + checkSteps := map[string]string{ + "dolt-server-integration": "Every target and shard ran tests (server-storage)", + "dolt-server-cmd": "Every target and shard ran tests (cmd-dolt)", + } + + for _, mem := range bazelDoltIntMembers { + want := tagged[mem.tag] + if len(want) == 0 { + t.Fatalf("no BUILD rule is tagged %q", mem.tag) + } + tierName := bazelDoltIntTierNames[mem.tag] + + got := slices.Clone(gotTiers[tierName]) + slices.Sort(got) + if !slices.Equal(got, want) { + t.Errorf("classify step --tier %s=... labels %v, want the %q-tagged labels from the BUILD files %v", tierName, got, mem.tag, want) + } + + step := job.step(t, checkSteps[mem.tag]) + for _, label := range want { + if !strings.Contains(step.Run, "--label "+label) { + t.Errorf("%s step %q missing --label %s (one of %q's tagged labels)", bazelDoltIntJobName, checkSteps[mem.tag], label, mem.tag) + } + } + gotLabelCount := strings.Count(step.Run, "--label ") + if gotLabelCount != len(want) { + t.Errorf("%s step %q has %d --label args, want exactly %d (%v)", bazelDoltIntJobName, checkSteps[mem.tag], gotLabelCount, len(want), want) + } + } +} + +// bazelDoltIntCmdDoltPinnedArgsAndEnv: the two dolt-server-cmd-tagged +// targets that carry the moved -test.timeout=19m arg and +// BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION env var (item 5 A2: moved off +// --config=doltserver-cmd's --test_arg/--test_env onto the targets +// themselves, so --config=dolt-int does not also apply them to +// server-storage's targets). Nothing else pins these two lines once they +// live on the target instead of in .bazelrc, so a drive-by edit that drops +// or alters either one would silently fall back to Bazel's own default test +// timeout, or leave BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION unset, with every +// other policy test (TestBazelDoltIntConfigIsMemberUnion, +// TestBazelDoltIntFitsTheJobsBudget, TestBazelDoltIntTierLabelsMatchTheTags) +// none the wiser, since none of them inspect a tagged rule's own args/env +// bodies. +var bazelDoltIntCmdDoltPinnedArgsAndEnv = []struct { + file, rule string +}{ + {"tests/regression/BUILD.bazel", "regression_test"}, + {"cmd/bd/BUILD.bazel", "bd_dolt_server_test"}, +} + +func TestBazelDoltIntCmdDoltTimeoutAndEnvPinned(t *testing.T) { + root := bazelPolicyRoot(t) + ruleStart := regexp.MustCompile(`(?m)^[A-Za-z_][A-Za-z0-9_]*\($`) + nameLine := regexp.MustCompile(`(?m)^ name = "([^"]+)",$`) + const wantArg = ` "-test.timeout=19m",` + const wantEnv = ` "BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION": "1",` + + for _, tc := range bazelDoltIntCmdDoltPinnedArgsAndEnv { + build := readPolicyFile(t, root, tc.file) + var rule string + for _, loc := range ruleStart.FindAllStringIndex(build, -1) { + end := strings.Index(build[loc[0]:], "\n)\n") + if end < 0 { + continue + } + candidate := build[loc[0] : loc[0]+end] + if nm := nameLine.FindStringSubmatch(candidate); nm != nil && nm[1] == tc.rule { + rule = candidate + break + } + } + if rule == "" { + t.Fatalf("%s: no rule named %q found", tc.file, tc.rule) + } + if !strings.Contains(rule, wantArg) { + t.Errorf("%s %q: missing exact args line %q (the moved --config=doltserver-cmd -test.timeout=19m, PR #7535 item 5 A2)", tc.file, tc.rule, wantArg) + } + if !strings.Contains(rule, wantEnv) { + t.Errorf("%s %q: missing exact env line %q (the moved --config=doltserver-cmd BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION, PR #7535 item 5 A2)", tc.file, tc.rule, wantEnv) + } + } +} diff --git a/scripts/bazel_dolt_race_test.go b/scripts/bazel_dolt_race_test.go new file mode 100644 index 000000000..ef0ae2d86 --- /dev/null +++ b/scripts/bazel_dolt_race_test.go @@ -0,0 +1,575 @@ +package scripts_test + +import ( + "cmp" + "maps" + "path" + "reflect" + "regexp" + "slices" + "strconv" + "strings" + "sync" + "testing" +) + +// The dolt-race union lane (item 5): in mode remote, bazel.yml's +// bazel-dolt-race job runs --config=dolt-race, the union of +// --config=doltserver and --config=doltserver-proxied, in one `bazel test`, +// in place of the bazel-doltserver and bazel-proxied jobs; in every other +// mode those two run as before. Its job.status is both members' workflow_call +// output, so pr.yml's gate ids (BAZEL_DOLTSERVER, BAZEL_PROXIED), ci-gate.sh +// and bazel-gate.sh are unchanged. Outside mode remote one client would do +// both tiers' work with no in-flight deduplication, so the union would cost +// the sum of the two tiers rather than the max: the members stay there. + +const ( + bazelDoltRaceJobName = "bazel-dolt-race" + bazelDoltRaceConfig = "dolt-race" + // Mode remote, on every event that reaches it (same-repo pull requests, + // merge groups, push, nightly, dispatch, bazel-farm.yml's authorized + // call): exactly where the members do not run. + bazelDoltRaceJobIf = "${{ needs.rbe.outputs.mode == 'remote' }}" + // The members: their pre-union rules (bazel-test's skip rule; remote + // execution only), minus mode remote. + bazelDoltMemberIf = "${{ needs.rbe.outputs.mode != 'skip' && needs.rbe.outputs.mode != 'remote' }}" + bazelProxiedMemberIf = "${{ needs.rbe.outputs.enabled == 'true' && needs.rbe.outputs.mode != 'remote' }}" +) + +// bazelUnionLanes: a union job -> the gated member jobs it runs in place of +// in mode remote (bazelDoltRaceJobIf). Each member keeps its gate id +// (bazelLaneGateIDs) and its workflow_call output, which reads the union's +// result first and the member's own otherwise (bazelLaneCallOutput). +var bazelUnionLanes = map[string][]string{ + bazelDoltRaceJobName: {bazelDoltJobName, bazelProxiedJobName}, +} + +// bazelUnionHasFlagGatedMember reports whether a union job runs in place of +// at least one flag-gated, advisory member (bazel-dolt-int's bazel-cmd-dolt, +// item 5 A2): such a union must carry that member's own continue-on-error, so +// a failure confined to that member's tier stays out of the call's aggregate +// result (BAZEL) in the union's mode exactly as it already is through the +// member outside it. The gated member's id still reads the union's result +// directly (bazelLaneReporter), unaffected either way. +func bazelUnionHasFlagGatedMember(job string) bool { + for _, m := range bazelUnionLanes[job] { + if _, ok := bazelFlagGatedLanes[m]; ok { + return true + } + } + return false +} + +// bazelUnionOf: the union job a gated member belongs to, or "". +func bazelUnionOf(member string) string { + for union, members := range bazelUnionLanes { + if slices.Contains(members, member) { + return union + } + } + return "" +} + +// bazelUnionMemberOutputKey: the union job's own output key that carries a +// member's tier result, for unions that do not report "result" uniformly +// (item 5 A2's bazel-dolt-int: must-fix 2's per-tier outputs, since a +// job-level continue-on-error would hide a server-storage failure from +// anything that is not itself gated on that one tier). Members not listed +// here read their union's plain "result" output, as dolt-race's do. +var bazelUnionMemberOutputKey = map[string]string{ + bazelServerJobName: "server_storage_result", + bazelCmdDoltJobName: "cmd_dolt_result", +} + +// bazelLaneCallOutput: the workflow_call output value bazel.yml must declare +// for a lane that reports its job.status. +func bazelLaneCallOutput(lane string) string { + if union := bazelUnionOf(lane); union != "" { + key := cmp.Or(bazelUnionMemberOutputKey[lane], "result") + return "${{ jobs." + union + ".outputs." + key + " || jobs." + lane + ".outputs.result }}" + } + return "${{ jobs." + lane + ".outputs.result }}" +} + +// bazelLaneReporter: the job whose result a gated lane's output carries in +// this mode (lanes: job -> modes it runs in), or "" when neither the lane +// nor its union runs (an expected skip). +func bazelLaneReporter(lanes map[string]map[string]bool, lane, mode string) string { + if lanes[lane][mode] { + return lane + } + if union := bazelUnionOf(lane); union != "" && lanes[union][mode] { + return union + } + return "" +} + +var ( + bazelCallOutputsMu sync.Mutex + bazelCallOutputsCache map[string]string +) + +// bazelCallOutputValue evaluates bazel.yml's workflow_call output name with +// jobs (job -> its result output; missing or "" = not reported), the way +// GitHub does: what pr.yml's needs.bazel.outputs. reads. +func bazelCallOutputValue(t *testing.T, name string, jobs map[string]string) string { + t.Helper() + bazelCallOutputsMu.Lock() + if bazelCallOutputsCache == nil { + bazelCallOutputsCache = map[string]string{} + for n, out := range readBazelWorkflowCall(t).Outputs { + bazelCallOutputsCache[n] = out.Value + } + } + expr, ok := bazelCallOutputsCache[name] + bazelCallOutputsMu.Unlock() + if !ok { + t.Fatalf("%s has no workflow_call output %s", bazelWorkflowName, name) + } + ctx := map[string]string{} + for _, m := range regexp.MustCompile(`jobs\.([A-Za-z0-9_-]+)\.outputs\.([A-Za-z0-9_-]+)`).FindAllStringSubmatch(expr, -1) { + // Every job.outputs reference in a lane's own workflow_call output + // expression carries that job's conclusion for gating purposes, + // whatever its output key is named (plain "result", or one of a + // union's per-tier keys: must-fix 2). jobs is keyed by job name only, + // so every reference to a given job resolves to the same simulated + // value regardless of which output key reads it. + ctx[m[0]] = jobs[m[1]] + } + v, err := evalGHExpr(expr, ctx) + if err != nil { + t.Fatalf("workflow_call output %s = %q: %v", name, expr, err) + } + str, _ := v.(string) + return str +} + +// bazelDoltRaceJobTimeoutMargin: the minutes the union job's timeout-minutes +// must exceed the sum of all its step timeouts (runner setup, post-job +// cleanup), so a hang fails a named step, not the job. +const bazelDoltRaceJobTimeoutMargin = 5 + +// bazelDoltRaceMergeQueueTimeout: the merge queue's check timeout (ruleset +// merge_queue.check_response_timeout_minutes). The union job is required in +// every merge group, so its own timeout stays below it. +const bazelDoltRaceMergeQueueTimeout = 60 + +// bazelDoltRaceTestStepTimeout: the union's `bazel test` step timeout. Its +// shards run about 55-95 s on rbe-west, each capped at 1200 s; the step allows +// about 3 minutes past that cap so Bazel writes TIMEOUT logs before GitHub +// kills the step. +const bazelDoltRaceTestStepTimeout = 23 + +// The union's members, and the tag filter each owns. +var bazelDoltRaceMembers = []struct{ config, tag string }{ + {"doltserver", "dolt-server"}, + {"doltserver-proxied", "dolt-server-proxied"}, +} + +// bazelRCConfigLines returns .bazelrc's option lines for --config=name +// (any command: test:name, build:name, ...), as "