Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

Retry the final --follow upload and keep following when only the record fails

Claudec53599d95033
diff --git a/cli/beacon/cmd/share_follow.go b/cli/beacon/cmd/share_follow.go
index cf9a38e7..94f5d64b 100644
--- a/cli/beacon/cmd/share_follow.go
+++ b/cli/beacon/cmd/share_follow.go
@@ -27,6 +27,9 @@ import (
const (
shareFollowDefaultInterval = 10 * time.Second
shareFollowMinInterval = time.Second
+ // shareFollowFinalRetries bounds how many more times --follow tries to upload a session's last
+ // messages after the session ended, one interval apart, before it gives up with an error.
+ shareFollowFinalRetries = 3
)
var (
@@ -67,10 +70,13 @@ func runShareFollow(cmd *cobra.Command, client *account.ShareClient, subject sha
fmt.Fprintf(errOut, "Following %s session %s, uploading new messages every %s. Ctrl+C stops.\n", subject.session.Harness, subject.session.ID, interval)
}
var (
- lastPrint string
- last shareResult
- uploads int
- ended bool
+ lastPrint string
+ last shareResult
+ uploads int
+ ended bool
+ lastErr error
+ finalFailures int
+ finalErr error
)
for {
if subject.fromLog {
@@ -89,6 +95,13 @@ func runShareFollow(cmd *cobra.Command, client *account.ShareClient, subject sha
opts.Visibility = visibility
}
result, aligned, upErr := shareUpload(ctx, client, subject, opts)
+ var recordErr *shareRecordError
+ if errors.As(upErr, &recordErr) {
+ // The trace is up; only the local session.shared event is missing. Say so and keep
+ // following, as a later upload's record failure does.
+ fmt.Fprintf(errOut, "warning: the session was shared, but the runtime log was not updated: %v\n", recordErr.err)
+ upErr = nil
+ }
switch {
case upErr == nil:
subject, last, lastPrint = aligned, result, fingerprint
@@ -103,14 +116,28 @@ func runShareFollow(cmd *cobra.Command, client *account.ShareClient, subject sha
default:
// beacon.sh or the network failed after the first upload: say so and retry on the
// next poll, since the next upload resends whatever this one lacked.
+ lastErr = upErr
fmt.Fprintf(errOut, "warning: upload failed, retrying in %s: %v\n", interval, upErr)
}
} else if err != nil && uploads == 0 && !errors.Is(err, errShareNothingYet) {
return err
}
- if ended || ctx.Err() != nil {
+ if ctx.Err() != nil {
break
}
+ if ended {
+ if err != nil || fingerprint == lastPrint {
+ break
+ }
+ // The session ended with messages beacon.sh does not have yet. There is no next poll
+ // to catch up on, so retry a few times and then fail rather than report a trace that
+ // is missing its end.
+ finalFailures++
+ if finalFailures > shareFollowFinalRetries {
+ finalErr = fmt.Errorf("the session ended, but its last messages were not uploaded after %d attempts (%s holds %d messages): %w", finalFailures, last.SharedURL, last.MessageCount, lastErr)
+ break
+ }
+ }
if shareFollowWait(ctx, interval) != nil {
break
}
@@ -126,6 +153,9 @@ func runShareFollow(cmd *cobra.Command, client *account.ShareClient, subject sha
fmt.Fprintf(errOut, "warning: the runtime log was not updated: %v\n", err)
}
}
+ if finalErr != nil {
+ return finalErr
+ }
return printShareFollow(out, errOut, last, false, true, ended)
}
diff --git a/cli/beacon/cmd/share_follow_test.go b/cli/beacon/cmd/share_follow_test.go
index 2c1c97c5..186a37e1 100644
--- a/cli/beacon/cmd/share_follow_test.go
+++ b/cli/beacon/cmd/share_follow_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"os"
+ "path/filepath"
"strings"
"sync"
"testing"
@@ -159,3 +160,130 @@ func shareEventsIn(t *testing.T, logPath string) []schema.Event {
}
return out
}
+
+// When the poll that sees the session end cannot upload its last messages, --follow retries a
+// bounded number of times and then fails, rather than reporting a trace that lacks its end.
+func TestShareFollowRetriesTheFinalUploadThenFails(t *testing.T) {
+ env := newShareEnv(t)
+ src := &growingSource{
+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},
+ events: shareFixtureEvents(env.projectDir),
+ }
+ stubHandoffSources(t, src)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+ polls := 0
+ prevWait := shareFollowWait
+ shareFollowWait = func(ctx context.Context, d time.Duration) error {
+ polls++
+ if polls == 1 {
+ // The session ends while beacon.sh is down.
+ src.add(followEvent(env.projectDir, "2026-10-01T10:03:00.000000000Z", "session.ended"))
+ srv.mu.Lock()
+ srv.failBatches = true
+ srv.mu.Unlock()
+ }
+ if polls > 10 {
+ return errors.New("the loop did not give up")
+ }
+ return nil
+ }
+ t.Cleanup(func() { shareFollowWait = prevWait })
+
+ _, stderr, err := runShareCommand(t, "--follow", "--cwd", env.projectDir, "--log-path", env.logPath)
+ if err == nil || !strings.Contains(err.Error(), "last messages were not uploaded") {
+ t.Fatalf("follow err = %v\n%s", err, stderr)
+ }
+ // One wait before the end, then one per retry.
+ if polls != 1+shareFollowFinalRetries {
+ t.Fatalf("waits = %d, want %d", polls, 1+shareFollowFinalRetries)
+ }
+ if n := strings.Count(stderr, "warning: upload failed"); n != 1+shareFollowFinalRetries {
+ t.Fatalf("failed uploads reported = %d\n%s", n, stderr)
+ }
+ if strings.Contains(stderr, "The session ended;") {
+ t.Fatalf("reported success:\n%s", stderr)
+ }
+
+ // The outage ends during the retries: the end is uploaded and follow succeeds.
+ env = newShareEnv(t)
+ src = &growingSource{
+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},
+ events: shareFixtureEvents(env.projectDir),
+ }
+ stubHandoffSources(t, src)
+ srv = newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+ polls = 0
+ shareFollowWait = func(ctx context.Context, d time.Duration) error {
+ polls++
+ srv.mu.Lock()
+ defer srv.mu.Unlock()
+ switch polls {
+ case 1:
+ src.add(followEvent(env.projectDir, "2026-10-01T10:03:00.000000000Z", "session.ended"))
+ srv.failBatches = true
+ case 2:
+ srv.failBatches = false
+ case 10:
+ return errors.New("the loop did not stop")
+ }
+ return nil
+ }
+ _, stderr, err = runShareCommand(t, "--follow", "--cwd", env.projectDir, "--log-path", env.logPath)
+ if err != nil || !strings.Contains(stderr, "The session ended;") {
+ t.Fatalf("recovered follow: err=%v\n%s", err, stderr)
+ }
+ srv.mu.Lock()
+ defer srv.mu.Unlock()
+ if len(srv.messages) != 5 {
+ t.Fatalf("server has %d messages, want the fixture's four and the end", len(srv.messages))
+ }
+}
+
+// A first upload that succeeds but cannot write its session.shared event warns, prints the link
+// and keeps following.
+func TestShareFollowKeepsGoingWhenTheFirstRecordFails(t *testing.T) {
+ env := newShareEnv(t)
+ src := &growingSource{
+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},
+ events: shareFixtureEvents(env.projectDir),
+ }
+ stubHandoffSources(t, src)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+ // A log path under a regular file cannot be written.
+ blocker := filepath.Join(env.home, "not-a-dir")
+ if err := os.WriteFile(blocker, []byte("x"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ logPath := filepath.Join(blocker, "runtime.jsonl")
+ polls := 0
+ prevWait := shareFollowWait
+ shareFollowWait = func(ctx context.Context, d time.Duration) error {
+ polls++
+ switch polls {
+ case 1:
+ src.add(followEvent(env.projectDir, "2026-10-01T10:03:00.000000000Z", "session.ended"))
+ case 10:
+ return errors.New("the loop did not stop")
+ }
+ return nil
+ }
+ t.Cleanup(func() { shareFollowWait = prevWait })
+ stdout, stderr, err := runShareCommand(t, "--follow", "--cwd", env.projectDir, "--log-path", logPath)
+ if err != nil {
+ t.Fatalf("follow: %v\n%s", err, stderr)
+ }
+ if !strings.HasPrefix(stdout, "https://beacon.sh/s/k3xabc") || !strings.Contains(stderr, "runtime log was not updated") || !strings.Contains(stderr, "The session ended;") {
+ t.Fatalf("stdout=%q stderr=%q", stdout, stderr)
+ }
+ if polls != 1 {
+ t.Fatalf("waits = %d, want 1", polls)
+ }
+ srv.mu.Lock()
+ defer srv.mu.Unlock()
+ if len(srv.messages) != 5 {
+ t.Fatalf("server has %d messages, want 5", len(srv.messages))
+ }
+}
diff --git a/cli/beacon/cmd/share_test.go b/cli/beacon/cmd/share_test.go
index 64190618..c336770f 100644
--- a/cli/beacon/cmd/share_test.go
+++ b/cli/beacon/cmd/share_test.go
@@ -237,6 +237,8 @@ type fakeShareServer struct {
messages []asymptoteobserve.ShareMessageV1
requests []string
auth map[string]bool
+ // failBatches makes every message upload fail, as an outage would.
+ failBatches bool
}
func newFakeShareServer(t *testing.T) *fakeShareServer {
@@ -264,6 +266,10 @@ func newFakeShareServer(t *testing.T) *fakeShareServer {
f.trace = &trace
fmt.Fprintf(w, `{"id":"k3xabc","external_id":%q,"url":"https://beacon.sh/s/k3xabc","visibility":%q,"message_count":%d,"created":%v}`, id, trace.Visibility, len(f.messages), created)
case r.Method == http.MethodPost && strings.HasSuffix(id, "/messages/batch"):
+ if f.failBatches {
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
zr, err := gzip.NewReader(r.Body)
if err != nil {
http.Error(w, "want gzip", 400)
diff --git a/cli/beacon/cmd/share_upload.go b/cli/beacon/cmd/share_upload.go
index 142c0267..d5870e6a 100644
--- a/cli/beacon/cmd/share_upload.go
+++ b/cli/beacon/cmd/share_upload.go
@@ -15,6 +15,16 @@ type shareUploadOptions struct {
Record bool
}
+// shareRecordError is shareUpload's error when the upload succeeded and only writing the
+// session.shared event failed; the result it returns with it is the upload's.
+type shareRecordError struct{ err error }
+
+func (e *shareRecordError) Error() string {
+ return "shared, but the runtime log was not updated: " + e.err.Error()
+}
+
+func (e *shareRecordError) Unwrap() error { return e.err }
+
// shareUpload creates or updates subject's shared trace, sending only what beacon.sh lacks. It is
// the path every non-interactive upload takes (the pre-push hook, --follow), so it applies the same
// rules as `beacon share refresh`: an existing trace is checked against this copy of the session
@@ -65,7 +75,7 @@ func shareUpload(ctx context.Context, client *account.ShareClient, subject share
}
if opts.Record {
if err := recordShareEvent(subject.session, result, found); err != nil {
- return result, subject, fmt.Errorf("shared, but the runtime log was not updated: %w", err)
+ return result, subject, &shareRecordError{err: err}
}
}
return result, subject, nil
diff --git a/docs/cli/share.mdx b/docs/cli/share.mdx
index 1ee938f2..93d3df51 100644
--- a/docs/cli/share.mdx
+++ b/docs/cli/share.mdx
@@ -120,7 +120,7 @@ beacon share refresh # this session, found like --current
## Follow a running session
-`--follow` keeps the trace current while the session runs. It shares the session, then checks it again every `--interval` (default `10s`, at least `1s`) and uploads what changed, until the session records its end (`session.ended`) or you press Ctrl+C. A check is a local read; a request is made only when the session's messages changed, and it sends only what beacon.sh lacks, the same way `refresh` does. A failed upload after the first is reported and retried on the next check.
+`--follow` keeps the trace current while the session runs. It shares the session, then checks it again every `--interval` (default `10s`, at least `1s`) and uploads what changed, until the session records its end (`session.ended`) or you press Ctrl+C. A check is a local read; a request is made only when the session's messages changed, and it sends only what beacon.sh lacks, the same way `refresh` does. A failed upload after the first is reported and retried on the next check. When the session has ended and its last messages cannot be uploaded, `--follow` retries three more times, one interval apart, and then exits non-zero naming what the trace holds. If the runtime log cannot be written after an upload, `--follow` warns and keeps going.
```bash
beacon share --follow # this session, until it ends