beads/cmd/bd/compact_gc_size_test.go
ecuthiell 8269a88cbf
fix(compact): target external GC at the active database (#6327)
* fix(compact): report active database size (#5619)

Measure legacy admin compact --dolt reporting through ActiveDatabaseSizer so sibling databases cannot distort reclaimed-space numbers. Omit unavailable advisory measurements without blocking GC.

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* docs(compact): explain the legacy size field names

Keep the existing compact JSON schema distinct from the newer GC helper.
The active external-GC target is addressed by the separate issue6313 leaf.

* fix(compact): select the authoritative local active GC directory

Ask the active storage instance for its optional external-GC directory
capability. Reuse the authority captured at store open, and refuse stale,
unsupported or invalid local targets rather than guessing from a root,
general CLI path or advisory size. Preserve archive-level fallback behavior.

Add native owned-process target and no-launch regressions plus instance
authority tests; retain the parent active-size and legacy JSON contracts.

Fixes #6313

* fix(compact): resolve GC capability through storage decorators

Use the existing storage unwrapping boundary so external GC sees the captured
active database behind the root command's dependency, telemetry and hook
decorators. Cover owned, shared and unsupported stores through the real chain,
and describe the active database in compact help.

Refs gastownhall/beads#6313
Agent: unknown-model/unknown-reasoning

* fix(compact): preserve external GC refusal diagnostics (#6313)

Route all four new target refusals through the standard error/hint formatter
and assert their stderr schema, message, hint and exit status. Preserve the
relative-path refusal and unavailable dry-run target omission. Update the
requested compact and flatten help mirrors without regenerating other docs.

Addresses the diagnostics and documentation review on PR #6327. Existing
PR #5668 ancestry and mandatory parent-first sequencing remain unchanged.

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* docs(compact): align flag help with active GC target (saa-cgh.94)

Authored by /root/cgh86_review; closes the independent root review help finding.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs: retain release-pinned CLI references (saa-cgh.94)

Preserve corrected live compact/flatten help while generated references continue to match docs/cli-docs.pin v1.2.2. Fix the exact six-line hosted docs-policy failure without changing pin authority.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(compact): classify cancellation before the GC authority refusal

Maintainer review fixes for #6327, review iteration 1. Non-gating findings
only: the synthesis and the quality scorecard both returned approve with no
blocker and no major finding.

Taken:

- Error Handling & Resilience (minor, both lanes). runCompactDolt formatted a
  cancelled or expired context as the permanent "cannot select a local
  database" refusal plus its four-cause hint, and in --dry-run turned it into a
  hard exit-1. Classify context.Canceled/DeadlineExceeded ahead of the
  ErrUnsupported arm and report the interruption instead. The ctx probe stays
  in ExternalGCPath: it is the only cancellation checkpoint before the
  uninterruptible external `dolt gc`, so the finding's other arm (drop the
  probe) would trade a misleading message for launching a multi-minute GC on an
  interrupted command.

- Change Impact / Blast Radius (minor). Document why
  resolveLocalActiveDatabaseDir keeps the cfg.AutoStart conjunct, and make the
  CLI hint name the remedy (`bd config set dolt.auto-start true`) instead of
  only the condition. The offered code arm is declined: AutoStart rides
  resolveAutoStart's own exclusions (forced false for ServerModeExternal and
  under BEADS_TEST_MODE=1), so dropping it widens GC authority - a behavior
  change, not a cleanup.

- Release Safety (minor). Add the three new test files to the gazelle explicit
  go_test srcs lists so this PR's assertions are visible under `bazel test`.
  Verified with `bazel run //:gazelle -- --mode=diff`: gazelle requests none of
  the three, so the rows match its own output. The two rows it still wants are
  pre-existing base drift in unrelated files and are left alone.

- Test Evidence Quality (nit). The two "unsupported ... through decorators"
  rows were measured vacuous for the decorator claim. Pin the refusal's origin
  through ErrUnsupported.Backend ("external" = the active store refused,
  "active store" = the interface assertion missed) and pin the opposite
  polarity on the size-only/locator-only rows. Residual recorded on the test:
  the dry-run decorator row still cannot discriminate, because its benign
  preview is identical for both origins.

Declined, and carried to the human-approval summary:

- Debuggability & Operability (minor, gate impact none). Reusing the `bd gc`
  companions adds production output in an iteration no further review pass
  grades, and the alternative arm would assert the refs are left in place
  "deliberately", which nothing in the change establishes.

- Resource Lifecycle & Cleanup (nit, Required fix: none). exec.CommandContext
  would kill a mid-flight `dolt gc`; that is a data-safety question for the GC
  path rather than a cleanup.

Validation: `go build ./...` and `go vet` on cmd/bd + internal/storage{,/dolt}
clean; scripts/ci/pr-lint.sh against the pinned base green (gofmt,
golangci-lint 0 issues, windows cross-lint 0 issues), proved non-vacuous by a
misspell planted on an added line; 66 PASS / 0 FAIL / 0 SKIP over the covering
cmd/bd selectors. Both new pins are mutation-proved: removing the
classification arm reds exactly the three new cancellation rows and nothing
else, and dropping storage.UnwrapStore now reds three decorator rows where it
previously reddened two. internal/storage/dolt/store.go is comment-only.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Gas City Merge Queue <merge-queue@gascity.local>
2026-09-29 08:27:43 -07:00

88 lines
2.7 KiB
Go

package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
)
func TestRunCompactDoltDryRunUsesActiveDatabaseSizer(t *testing.T) {
output := runCompactDoltDryRunForTest(t, &gcSizeStoreStub{size: 42}, true)
var result map[string]interface{}
if err := json.Unmarshal([]byte(output), &result); err != nil {
t.Fatalf("decode dry-run JSON: %v\noutput: %s", err, output)
}
if got := result["size_before"]; got != float64(42) {
t.Fatalf("size_before = %#v, want 42 from ActiveDatabaseSizer", got)
}
if got := result["size_display"]; got != "42 B" {
t.Fatalf("size_display = %#v, want %q", got, "42 B")
}
}
func TestRunCompactDoltDryRunOmitsUnsupportedSize(t *testing.T) {
unsupported := &gcSizeStoreStub{err: &storage.ErrUnsupported{
Op: "ActiveDatabaseSize",
Backend: "external",
}}
t.Run("JSON", func(t *testing.T) {
output := runCompactDoltDryRunForTest(t, unsupported, true)
var result map[string]interface{}
if err := json.Unmarshal([]byte(output), &result); err != nil {
t.Fatalf("decode dry-run JSON: %v\noutput: %s", err, output)
}
for _, key := range []string{"size_before", "size_display"} {
if got, ok := result[key]; ok {
t.Fatalf("unsupported measurement emitted %s=%#v", key, got)
}
}
})
t.Run("text", func(t *testing.T) {
output := runCompactDoltDryRunForTest(t, unsupported, false)
if strings.Contains(output, "Current size:") {
t.Fatalf("unsupported measurement emitted a text size line:\n%s", output)
}
if !strings.Contains(output, "Run without --dry-run") {
t.Fatalf("dry-run completion guidance missing:\n%s", output)
}
})
}
func runCompactDoltDryRunForTest(t *testing.T, candidate storage.DoltStorage, asJSON bool) string {
t.Helper()
oldStore, oldDryRun, oldJSON := store, compactDryRun, jsonOutput
t.Cleanup(func() {
store, compactDryRun, jsonOutput = oldStore, oldDryRun, oldJSON
})
beadsDir := filepath.Join(t.TempDir(), ".beads")
doltDir := filepath.Join(beadsDir, "dolt")
if err := os.MkdirAll(doltDir, 0o755); err != nil {
t.Fatalf("create shared Dolt root: %v", err)
}
// This sibling-root content makes the old recursive-walk behavior return a
// value distinct from the fake active database measurement.
if err := os.WriteFile(filepath.Join(doltDir, "sibling-data"), make([]byte, 128), 0o644); err != nil {
t.Fatalf("seed sibling data: %v", err)
}
t.Setenv("BEADS_DIR", beadsDir)
active := filepath.Join(doltDir, "active")
if err := os.Mkdir(active, 0o755); err != nil {
t.Fatal(err)
}
store = &compactGCStoreStub{DoltStorage: candidate, directory: active}
compactDryRun = true
jsonOutput = asJSON
return captureStdout(t, func() error {
return runCompactDolt(t.Context())
})
}