beads/cmd/bd/dolt_autopush_test.go
Rongjun GENG 8da2ae4328
fix(embeddeddolt): commit pending changes before push (#5433) (#5795)
* fix(embeddeddolt): commit pending changes before push (#5433)

Every Pull variant (Pull, PullWithStrategy, PullRemoteWithStrategy,
PullRemote, PullFrom) auto-commits pending working-set changes first
(GH#2474, so a crashed command's leftovers don't make the merge
refuse to start), but no Push variant (Push, ForcePush, PushRemote,
PushTo) did. A write that landed in the working set but was never
explicitly committed -- auto-commit configured off, or a session that
ended right after a write with no intervening commit -- silently
pushed nothing new while `bd dolt push` still printed "Push
complete." and exited 0.

This is the half of #5433's silent-stall report the maintainer traced
and confirmed in code (issue comment, quoting exact line numbers this
matches on current main): "every Pull variant calls CommitPending
before pulling... no Push variant does... push never flushes the
working set, then prints 'Push complete.' on nil error with no
remote-ref or working-set check. Strongest hook for a narrow
push-honesty PR." Reporter confirmed: "Yes, please open the
push-honesty PR. That is the surface that actually cost us."

Scoped to exactly this half -- the confirmed, traced, mechanical gap
matching an already-established pattern (copy Pull's own guard to
Push). Did NOT attempt the harder half discussed in the same thread:
verifying the remote ref actually advanced and reporting honestly
when it didn't. That needs a deliberate design call the maintainer
themselves treated as separate (distinguishing a legitimate no-op
push, already in sync, from one that had something to send but
transferred nothing) and risks false positives if done carelessly --
a bigger change than this issue's narrowed scope asked for. Flagging
in the relay rather than guessing at that design.

Also confirmed the server-mode backend (internal/storage/dolt) has
the identical asymmetry -- Push/ForcePush/PushRemote all route through
pushToRemote, which likewise never calls CommitPending -- but the
issue's repro and the maintainer's trace are both embedded-mode
specific, so left server-mode untouched pending its own verification.

Does not claim to fix the mysterious full stall itself (bd dolt
commit also returning "Nothing to commit" while HEAD stays frozen,
even when called directly) -- the reporter and maintainer both
independently concluded that has no known deterministic trigger.
This closes one real, confirmed contributing gap: push not flushing
pending changes the way pull always has.

RED: added TestPushCommitsPendingChangesFirst, table-driven over all
four Push variants. Creates an issue (a genuinely pending, uncommitted
change -- verified via GetCurrentCommit before/after CreateIssue, so
the test would fail loudly if CreateIssue ever started auto-committing
on its own), then calls each Push variant and asserts HEAD moved.
Push/ForcePush/PushRemote route through the swappable vcPush/
vcForcePush vars (remote_peer_auth_test.go's existing
captureRemoteEntryPoints seam) so the test stops with errStopRemote
before any network IO; PushTo calls versioncontrolops.Push directly
with no equivalent seam, so it actually attempts the push and fails on
"remote not found" in this remote-less test store -- still proves
CommitPending ran first, since that failure only happens after this
fix's guard clause. All four failed pre-fix (HEAD did not move).
GREEN: all four pass after the fix.

Verified: full remote-verb/peer-auth suite (TestWithPeerAuth and its
variants, TestRemoteVerbsPresentStoredPeerCredentials,
TestRemoteVerbPlainRemote*) still green -- confirms this fix doesn't
disturb credential resolution or the swappable-seam test
infrastructure it shares. go vet clean, go build ./... clean across
the repo.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018c3vLFNVgPebSpCJrd8xTD

* chore(bazel): enumerate push_commit_pending_test.go in embeddeddolt go_test srcs

Generated by `bazel run //:gazelle`. The PR predates base's addition of
internal/storage/embeddeddolt/BUILD.bazel, so its new test file was not in
the explicit go_test srcs list; bazel would have silently run zero of its
cases. Base parity at the rebase base was 118/118 enumerated.

* fix(autopush): record post-push HEAD, and cover the clean-store push path

Maintainer review fixup for #5795 (adopt-pr review iteration 1).

Push now commits pending changes before pushing (GH#5433), so HEAD can move
across the call. maybeAutoPush read HEAD only before the push and recorded that
hash as LastCommit, which is now the parent of what was actually pushed, so the
next tick saw a mismatch and pushed once redundantly before re-latching. Route
the recorded hash through pushedCommitForState, which re-reads HEAD after a
successful push and falls back to the pre-push value if the re-read fails (the
push itself already succeeded, so dropping LastCommit would lose change
detection entirely).

Also:

- Add a clean-store arm to TestPushCommitsPendingChangesFirst. The guard relies
  on commitAll(tolerateEmpty=true) mapping Dolt's "nothing to commit" to
  (false, nil) for every push against an already-committed store, and nothing
  in this package asserted it. Flipping that flag reds the new arm alone, with
  the four pending-change arms still green.

- Correct the `bd dolt remote reset-data` confirmation, which promised the
  remote is "rebuilt from local HEAD" while the push now adds a commit created
  after the operator types y.

Not taken here, tracked separately: extending auto-push change detection to also
fire on a dirty working set (that gate predates this PR, so skipping it is an
incompleteness rather than a regression this PR introduces), and the PR-body
disclosure that push now commits on the auto-push and `bd sync` cadences.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-30 15:58:51 -07:00

293 lines
8.2 KiB
Go

package main
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"time"
"github.com/steveyegge/beads/internal/config"
)
type fakeAutoPushTarget struct {
commit string
commitErr error
push func(context.Context) error
}
func (f *fakeAutoPushTarget) GetCurrentCommit(context.Context) (string, error) {
return f.commit, f.commitErr
}
func (f *fakeAutoPushTarget) Push(ctx context.Context) error {
return f.push(ctx)
}
func TestIsDoltAutoPushEnabled_ExplicitConfig(t *testing.T) {
// Cannot be parallel: modifies global env vars and config.
tests := []struct {
name string
envVal string // "true"/"false" = explicit config via env
wantResult bool
}{
{
name: "explicit true → enabled",
envVal: "true",
wantResult: true,
},
{
name: "explicit false → disabled",
envVal: "false",
wantResult: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("BD_DOLT_AUTO_PUSH", tt.envVal)
config.ResetForTesting()
t.Cleanup(func() { config.ResetForTesting() })
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
// With explicit config, store check is bypassed
// (store is nil in this test, which would return false for auto-detection)
got := isDoltAutoPushEnabled(context.Background())
if got != tt.wantResult {
t.Errorf("isDoltAutoPushEnabled() = %v, want %v", got, tt.wantResult)
}
})
}
}
func TestIsDoltAutoPushEnabled_DefaultOff(t *testing.T) {
// Default (no explicit config) must return false — auto-push is opt-in only.
os.Unsetenv("BD_DOLT_AUTO_PUSH")
t.Cleanup(func() { os.Unsetenv("BD_DOLT_AUTO_PUSH") })
config.ResetForTesting()
t.Cleanup(func() { config.ResetForTesting() })
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
got := isDoltAutoPushEnabled(context.Background())
if got != false {
t.Errorf("isDoltAutoPushEnabled() default = %v, want false", got)
}
}
func TestMaybeAutoPush_NilStore(t *testing.T) {
// maybeAutoPush should be a no-op when store is nil (no panic).
os.Unsetenv("BD_DOLT_AUTO_PUSH")
t.Cleanup(func() { os.Unsetenv("BD_DOLT_AUTO_PUSH") })
config.ResetForTesting()
t.Cleanup(func() { config.ResetForTesting() })
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
// Should not panic with nil store
maybeAutoPush(context.Background())
}
func TestAutoPush_SkippedForReadOnlyCommands(t *testing.T) {
// Read-only commands should not trigger auto-push (GH#2191).
readOnly := []string{"list", "ready", "show", "stats", "blocked", "search", "query", "graph"}
for _, cmd := range readOnly {
if !isReadOnlyCommand(cmd) {
t.Errorf("isReadOnlyCommand(%q) = false, want true", cmd)
}
}
writeCmds := []string{"create", "update", "close", "import"}
for _, cmd := range writeCmds {
if isReadOnlyCommand(cmd) {
t.Errorf("isReadOnlyCommand(%q) = true, want false", cmd)
}
}
}
func TestAutoPushTimeoutConstants(t *testing.T) {
// Verify timeout defaults are reasonable (GH#3370).
if autoPushTimeout < 10*time.Second || autoPushTimeout > 120*time.Second {
t.Errorf("autoPushTimeout = %s, want 10s-120s range", autoPushTimeout)
}
}
func TestPushWithContextReturnsPushResult(t *testing.T) {
target := &fakeAutoPushTarget{
push: func(context.Context) error {
return nil
},
}
if err := pushWithContext(context.Background(), target); err != nil {
t.Fatalf("pushWithContext() = %v, want nil", err)
}
}
func TestPushWithContextReturnsPushError(t *testing.T) {
wantErr := errors.New("push failed")
target := &fakeAutoPushTarget{
push: func(context.Context) error {
return wantErr
},
}
err := pushWithContext(context.Background(), target)
if !errors.Is(err, wantErr) {
t.Fatalf("pushWithContext() = %v, want %v", err, wantErr)
}
}
func TestPushWithContextBoundsIgnoredContext(t *testing.T) {
started := make(chan struct{})
release := make(chan struct{})
target := &fakeAutoPushTarget{
push: func(context.Context) error {
close(started)
<-release
return nil
},
}
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
start := time.Now()
err := pushWithContext(ctx, target)
elapsed := time.Since(start)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("pushWithContext() = %v, want deadline exceeded", err)
}
select {
case <-started:
default:
t.Fatal("pushWithContext returned before Push started")
}
if elapsed > 500*time.Millisecond {
t.Fatalf("pushWithContext took %s, want under 500ms", elapsed)
}
}
func TestMaybeAutoPush_CancelledContext(t *testing.T) {
// maybeAutoPush should handle cancelled context gracefully (GH#3370).
t.Setenv("BD_DOLT_AUTO_PUSH", "true")
config.ResetForTesting()
t.Cleanup(func() { config.ResetForTesting() })
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
maybeAutoPush(ctx)
}
func TestMaybeAutoPush_DisabledByConfig(t *testing.T) {
// When explicitly disabled, maybeAutoPush should be a no-op.
t.Setenv("BD_DOLT_AUTO_PUSH", "false")
config.ResetForTesting()
t.Cleanup(func() { config.ResetForTesting() })
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
// Should not panic or attempt push
maybeAutoPush(context.Background())
}
func TestLoadSavePushState(t *testing.T) {
// Create a temp .beads dir with metadata.json so FindBeadsDir works
tmp := t.TempDir()
beadsDir := filepath.Join(tmp, ".beads")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{}`), 0o644); err != nil {
t.Fatal(err)
}
t.Setenv("BEADS_DIR", beadsDir)
// No file yet → nil, nil
ps, err := loadPushState()
if err != nil {
t.Fatalf("loadPushState (no file): %v", err)
}
if ps != nil {
t.Fatalf("loadPushState (no file): got %+v, want nil", ps)
}
// Save and reload
want := &pushState{LastPush: "2026-03-09T12:00:00Z", LastCommit: "abc123"}
if err := savePushState(want); err != nil {
t.Fatalf("savePushState: %v", err)
}
got, err := loadPushState()
if err != nil {
t.Fatalf("loadPushState: %v", err)
}
if got == nil || got.LastPush != want.LastPush || got.LastCommit != want.LastCommit {
t.Errorf("loadPushState = %+v, want %+v", got, want)
}
}
func TestLoadPushState_CorruptJSON(t *testing.T) {
tmp := t.TempDir()
beadsDir := filepath.Join(tmp, ".beads")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{}`), 0o644); err != nil {
t.Fatal(err)
}
t.Setenv("BEADS_DIR", beadsDir)
// Write garbage
if err := os.WriteFile(filepath.Join(beadsDir, "push-state.json"), []byte(`not json`), 0o644); err != nil {
t.Fatal(err)
}
_, err := loadPushState()
if err == nil {
t.Error("loadPushState with corrupt JSON: expected error, got nil")
}
}
// TestPushedCommitForState pins the push-state hash recorded after a successful
// auto-push. Push commits pending changes before pushing (GH#5433), so HEAD can
// move during the push call and the pre-push hash is no longer what was pushed.
func TestPushedCommitForState(t *testing.T) {
ctx := context.Background()
t.Run("records the post-push commit", func(t *testing.T) {
target := &fakeAutoPushTarget{commit: "after"}
if got := pushedCommitForState(ctx, target, "before"); got != "after" {
t.Fatalf("pushedCommitForState() = %q, want %q (the commit the guard created, not its parent)", got, "after")
}
})
// The push already succeeded here, so a failed re-read must not drop
// LastCommit -- that would lose change detection entirely. The fake still
// returns a commit alongside the error, so this can only pass if the error
// branch is actually taken.
t.Run("falls back to the pre-push commit when the re-read fails", func(t *testing.T) {
target := &fakeAutoPushTarget{commit: "after", commitErr: errors.New("engine closed")}
if got := pushedCommitForState(ctx, target, "before"); got != "before" {
t.Fatalf("pushedCommitForState() = %q, want %q (pre-push fallback)", got, "before")
}
})
}