Skip to content

ENG-1113: -f/--follow for sandbox logs (client-side polling) - #353

Merged
foxish merged 4 commits into
mainfrom
davido/eng-1113-cli-follow-sandbox-logs
Jul 30, 2026
Merged

foxish merged 4 commits into
mainfrom
davido/eng-1113-cli-follow-sandbox-logs

Conversation

@davixcky

Copy link
Copy Markdown
Contributor

What

Adds -f/--follow to signadot logs for the sandbox path (ENG-1113).

Stacked on #351 (ENG-1112) — base is feat/sandbox-logs; will retarget to main once #351 merges.

The sandbox-scoped endpoint is a point-in-time snapshot, so follow tails by polling on an interval (2s) and advancing sinceTime. Native pod-log streaming is a fast-follow (ENG-1115). The job path already streams via SSE and is unchanged.

Correctness

  • Per-container de-dup. All containers share a single sinceTime per request, so a global high-water mark would drop lines from a lagging container. Instead each container is de-duped against its own last-printed timestamp, and the next poll uses the oldest per-container high-water mark — no lost or repeated lines across multiple containers.
  • Error handling. The first poll surfaces selector errors (unknown workload/container/resource/step) so a typo fails fast; subsequent transient errors (pod not running yet, restarts) are reported once to stderr and retried.
  • Graceful stop on SIGINT/SIGTERM.
  • Rejected with -o json|yaml (follow streams plain lines only).

Testing (live, local cluster)

Followed a 2-container fork (app + sidecar, each logging every 1s):

$ signadot logs --sandbox follow-test --workload multi -f
[app] APP 0
[sidecar] SIDE 0
[app] APP 1
...
  • ~10s of -f: 70 lines, 70 unique (0 duplicates), 35 [app] + 35 [sidecar], sequential with no gaps.
  • -f -c app → single container, raw (unprefixed), tails live.
  • -f -o json → Error: --follow cannot be combined with -o json.
  • -f --workload nope → first poll surfaces 400 … workload "nope" not found ….
  • SIGTERM/Ctrl-C → stops promptly.

🤖 Generated with Claude Code

cursor[bot]
cursor Bot approved these changes Jul 17, 2026 •
Base automatically changed from feat/sandbox-logs to main July 21, 2026 19:21
The sandbox endpoint is a snapshot, so --follow tails by polling on an interval
and advancing sinceTime. Correctness details:

- per-container de-dup: multiple containers share one sinceTime per request, so
  each container is de-duped against its own last-printed timestamp and the next
  poll uses the oldest per-container high-water mark (no lost/repeated lines).
- first poll surfaces selector errors (unknown workload/container/etc.); later
  transient errors (pod not running yet, restarts) are reported once and retried.
- graceful stop on SIGINT/SIGTERM.
- rejected with -o json|yaml (streamed plain lines only).

Job path unchanged (already streams via SSE).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@davixcky
davixcky force-pushed the davido/eng-1113-cli-follow-sandbox-logs branch from e908efb to 814d85c Compare July 21, 2026 19:28
cursor[bot]
cursor Bot approved these changes Jul 21, 2026 •
go-sdk #90 merged (squash) and its branch was deleted, so pin the released
main revision instead of the now-non-canonical generate branch commit.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
cursor[bot]
cursor Bot approved these changes Jul 21, 2026 •
@scott-cotton

Copy link
Copy Markdown
Member

Code Review

Thoughtful, well-scoped change. Follow is implemented client-side by polling the snapshot endpoint every 2s, advancing sinceTime, and de-duping per container. The per-container high-water-mark design (use the oldest container mark as the shared sinceTime, dedup each container against its own last-printed timestamp) is the correct approach and avoids the naive-global-watermark bug. The fetchSandboxLogs/printLogLine refactor is clean and preserves JSON/YAML behavior.

A few things worth resolving before merge:

Correctness / risks

1. Dedup can drop lines when timestamps aren't unique (main risk). The boundary filter is !t.After(last) — it skips any line <= the last-printed timestamp. If two distinct lines share the exact timestamp of the last-printed one and the snapshot boundary falls between them, the second is silently dropped:

Poll 1: prints line@T2, last["app"]=T2, since=T2
Poll 2 (sinceTime=T2) returns [T2(dup), T2b(new, same ts), T3]
        -> T2b is skipped because !T2b.After(T2), though it was never printed

At 1 line/sec (as tested) timestamps are distinct so this never fires — but with bursty logs or coarse server-side timestamp precision (second/ms rather than ns) many lines share a timestamp and lines will be lost at every poll boundary. Worth confirming the endpoint's timestamp precision. Robust fix: remember the set/count of messages seen at exactly the max timestamp and only suppress those, rather than everything <= last. At minimum, add a comment noting the limitation.

2. Catastrophic duplication if Time is empty. LogsLogItem.Time is omitempty. If the server ever returns lines without timestamps, time.Parse fails, the dedup branch is skipped so every line prints, and the high-water mark never advances — so oldestSince returns current unchanged and the entire window reprints every 2s indefinitely. Live testing implies Time is always populated, but there's no guard. Consider a message-based fallback, or at least don't reprint when timestamps are missing.

3. First-poll fail-fast also rejects not-yet-running pods. On first, any error returns immediately. Ideal for a typo'd --workload, but a user running -f right after creating a sandbox (pod not scheduled yet) gets a hard error instead of the "waiting for logs…" retry that follow implies. If the API distinguishes 4xx selector errors from transient "not running", consider hard-failing only on the former on the first poll.

Minor / style

  • --follow with --job is silently ignored. logs.go explicitly documents "Reject cross-source flags rather than silently ignoring them," yet -f is accepted with --job and does nothing (the job path never reads Follow). Either wire it in, add it to the mutual-exclusion set with --job, or document the no-op.
  • multi prefix can flap mid-stream. multi := len(resp) > 1 is recomputed each poll, so if a second container starts logging later, early lines print unprefixed and later ones gain [container] prefixes. Consider latching multi once true, or keying off cfg.Container == "".
  • Missing SIGHUP. Almost every other command in the repo (sandbox/apply.go, plan/run.go, traffic/record.go, …) also traps syscall.SIGHUP; this long-running follow doesn't.

Tests

No tests added, and the package has no *_test.go. oldestSince is a pure function and the dedup loop is deterministic given a fixed []*models.LogsContainerLogs sequence — table-driven tests for "duplicate timestamp across poll boundary" (#1) and "lagging second container" would directly de-risk the trickiest part here and guard against regressions.

None of these block the happy path that was tested live, but #1 and #2 are the difference between "works in my test" and "correct under load." Also a reminder to retarget/rebase onto main now that #351 has landed.

🤖 Generated with Claude Code

- Boundary dedup: per-container high-water mark + set of messages seen at
  exactly that timestamp, so distinct lines sharing the boundary timestamp are
  no longer dropped (was: skip all <= last).
- Untimestamped lines: emit only on the first poll, never reprint (guards
  against infinite re-emit if the watermark can't advance).
- --follow first poll fails fast on selector errors but retries transient ones
  (pod not running yet / restart / gateway) via isTransientFollowErr.
- Reject --follow with --job (was silently ignored), matching the other
  cross-source flag guards.
- Latch the multi-container [name] prefix so it can't flap mid-stream.
- Trap SIGHUP alongside SIGINT/SIGTERM.
- Add table-driven tests for followState.observe (boundary dup, older-than-hwm,
  empty timestamp, independent containers) and sinceTime (oldest hwm, fallback).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@davixcky

Copy link
Copy Markdown
Contributor Author

Thanks Scott — all addressed in 22efbca, with the risky bits now unit-tested and re-verified live against staging.

#1 — dedup dropping distinct same-timestamp lines. Fixed. Each container now keeps its high-water mark plus the set of messages already printed at exactly that timestamp; a line is emitted if it's strictly newer, or shares the boundary timestamp but its exact message hasn't been printed. So a distinct line sharing the boundary ts is no longer dropped. Table-test boundary-same-timestamp covers it. On precision: the endpoint emits nanosecond k8s timestamps (e.g. 2026-07-27T11:47:42.176673009Z), so real collisions are practically impossible — but it's now correct regardless.

#2 — catastrophic reprint on empty Time. Fixed. Untimestamped lines are emitted only on the first (snapshot) poll and skipped afterward, so a missing timestamp can never cause the window to reprint. Test empty-timestamp covers it.

#3 — first-poll fail-fast vs not-yet-running. Fixed. First poll now fails fast only on non-transient errors; isTransientFollowErr (pod "not ready"/"no running pods"/gateway/connection) retries instead. Verified live: -f --workload <typo> still errors immediately, while a not-ready pod would wait. (Heuristic on message text, noted pending typed errors in ENG-1115.)

--follow + --job silently ignored. Fixed — now in the mutual-exclusion set:
Error: if any flags in the group [job follow] are set none of the others can be.

multi prefix flap. Latched once >1 container is seen, so early lines can't later flip prefix form.

SIGHUP. Added to signal.NotifyContext alongside SIGINT/SIGTERM.

Tests. Added sandbox_test.go — table-driven followState.observe (boundary dup, older-than-hwm, empty ts, independent containers) and sinceTime (oldest hwm / fallback). go test ./internal/command/logs/ green.

Also rebased onto main and re-pinned go-sdk to the released revision (post go-sdk#90). Re-ran the staging suite (workload/resource/container/since/since-time/follow + all guards) — green.

cursor[bot]
cursor Bot approved these changes Jul 27, 2026 •
@scott-cotton

scott-cotton commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

Below comment is now tracked in https://github.com/signadot/signadot/issues/7271
it is api side issue not blocking this PR which can go in independently.

Follow loop — two gaps

The previous round is well handled: the boundary-set dedup and the "untimestamped lines only on the first poll" rule are the right shapes, and the table tests hit the cases that actually matter. Build and go test ./internal/command/logs/ are green at 22efbca.

Two things this round didn't reach. Both come from the server side of the contract (sandboxes/internal/control/logs/pods/fetch.go in the control plane), so they aren't visible from the CLI alone.

sinceTime pins to a container that has stopped logging. sinceTime() takes the min hwm across containers, and TestFollowStateSinceTime locks that in. But "lagging" and "stopped" are indistinguishable to it: a sidecar that logs at startup and goes quiet — istio-proxy on any mesh-injected fork, or a completed create-step pod under -f --resource — keeps its hwm forever, so every later poll re-requests the whole window from that stale mark. The server caps a fetch at logReqTailLines = 1000 / logReqLimitBytes = 1MB (fetch.go:33-34), so this stays bounded and correct — but steady state goes from "fetch the ~10 new lines" to "fetch, parse and re-dedup 1000 lines through the cluster tunnel every 2s, indefinitely," per follower. Clamp the rewind: since = max(oldestHWM, newestHWM - grace), grace a few poll intervals. Containers in a pod share a clock, so a genuinely lagging one won't be further behind than that.

That same 1000-line cap truncates silently. A container emitting more than ~500 lines/s loses everything but the newest 1000 in an interval, the hwm jumps the gap, and nothing tells the user. Since --tail is rejected on the sandbox path there's no knob either. If a poll returns exactly 1000 lines for a container, say so on stderr rather than letting -f quietly drop lines under load.

Smaller: the followState doc says distinct lines sharing the boundary timestamp are "NOT dropped". That's true client-side, but end-to-end the server's filterLogs filters on strict .After(sinceTime), so for the container that defines the mark such a line never arrives at all. Worth narrowing the claim to what the client can actually guarantee.

@scott-cotton

scott-cotton commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

isTransientFollowErr matches the wrong string

sandbox.go:218 — the guard at :101 decides fail-fast vs. retry by running strings.Contains over err.Error(). For an API error that string isn't the server's message, it's the whole formatted response — operation, status, marshalled payload, requestId:

[GET /orgs/{orgName}/sandboxes/{sandboxName}/logs][400] getSandboxLogsBadRequest {"error":"container \"x\" not found; containers: app, istio-proxy","requestId":"..."}

Two consequences:

  • The message embeds the selector the user typed and the list of valid names the API returns alongside it. A container or fork named connection-pool or timeout-worker makes a genuine typo match the "connection" / "timeout" entries, so the first-poll guard silently retries forever instead of failing fast — the exact behavior it was added to prevent.
  • "502"/"503"/"504" are matched as substrings of that same blob rather than as status codes.

Both go away by matching the typed error instead of the text. The generated client exposes the payload and the code:

if r, ok := err.(interface{ GetPayload() *models.ErrorResponse }); ok {
    // r.GetPayload().Error — just the server's message
}
if c, ok := err.(interface{ IsClientError() bool }); ok {
    // 4xx vs 5xx, no substring matching
}

That narrows the text match to the two readiness phrases and takes the user-supplied names out of the match surface entirely.

…ansient guard

- isTransientFollowErr now matches the go-sdk *transport.APIError (via
  errors.As) and its Code/message fields, never err.Error(). The formatted
  string prefixes the status text and splices in the user's selector + valid
  names, so a fork/container named connection-pool or timeout-worker made a
  typo retry forever; 5xx retries, 4xx only for the server's readiness message.
- followState.sinceTime clamps the rewind to newestHWM-grace so a container
  that logs once and goes quiet (startup-only sidecar, completed step pod)
  doesn't pin the shared sinceTime and re-request its whole capped window every
  poll indefinitely.
- Warn on stderr when a container's fetch hits the server tail cap
  (serverTailCap=1000) instead of silently dropping older lines under load.
- Narrow the followState doc: the boundary-dedup guarantee only covers lines
  the server re-sends; the container defining sinceTime never receives a
  same-timestamp line (server filters strict After).
- Tests: rewind clamp case + TestIsTransientFollowErr (5xx retry, 4xx readiness
  retry, connection-pool/timeout-worker selector fail-fast, transport retry).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@davixcky

Copy link
Copy Markdown
Contributor Author

Thanks — all four addressed in 52a3b82, with the transient guard proven live.

isTransientFollowErr matched the whole formatted response. Fixed, and this was worse than the substring smell suggested: the guard never reached a typed branch at all. FixAPIErrors wraps every 4xx/5xx as fmt.Errorf("%v: %w", statusText, *transport.APIError), so err.Error() is 400 Bad Request: <server msg incl. the user's selector + valid names> — a fork named timeout-worker made err.Error() contain "timeout" and my readiness/transport list matched it, retrying forever. Now:

var apiErr *transport.APIError
if errors.As(err, &apiErr) {
    switch {
    case apiErr.Code >= 500: return true                              // gateway/tunnel/k8s hiccup
    case apiErr.Code >= 400: return isReadinessMsg(apiErr.ErrorResponse.Error) // clean msg only
    default: return false
    }
}
return isTransportErr(err.Error()) // only non-API (pre-response) transport failures

apiErr.ErrorResponse.Error is the bare server message — no status prefix, no requestId, no echoed selector list — and readiness matches only "may not be ready" / "no running pods". Note the readiness cases are 4xx (fetch.go returns them as 400), so a blanket "4xx = fail fast" would've been wrong; this keeps them retryable while selector 400s fail fast.

Proven live against staging — a fork name containing "timeout" now fails fast instead of looping:

$ time signadot logs --sandbox <sb> --workload timeout-worker -f
Error: 400 Bad Request: workload "timeout-worker" not found ...; loggable workloads: apiserver
0.78s total          # was: looped "waiting for logs" for the full timeout

sinceTime pinned to a stopped container. Fixed — sinceTime() now clamps the rewind to newestHWM - grace (followRewindGrace = 3× poll interval). A startup-only sidecar (istio-proxy) or completed create-step pod no longer holds sinceTime at its stale mark and forces a full-window re-fetch every 2s. As you noted, containers share a pod clock, so a genuinely lagging active container stays within the grace and keeps its lines. Test added.

Silent 1000-line truncation. Fixed — when a container's fetch returns >= serverTailCap (1000, mirroring the server's logReqTailLines with a comment pointing at it), -f warns on stderr that older lines were dropped. Throttled to once per burst (re-warns if it recovers then recurs) so it signals sustained overload without drowning the stream.

Doc claim. Narrowed: the boundary-dedup guarantee is now scoped to "lines the server re-sends," and the comment states the container that defines sinceTime never receives a same-timestamp line because the server filters on strict After.

go test ./internal/command/logs/ green (TestFollowState*, TestIsTransientFollowErr). The two server-side items you flagged (the cap itself; typed errors so the CLI needn't message-match at all) are tracked for the streaming follow-up in ENG-1156.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Risk: medium. Cursor Bugbot was not present on this PR; evaluated using remaining signals. Approved — sandbox follow-logs changes are bounded with prior review feedback addressed and unit tests present. Reviewers already assigned; no new reviewers added.

Open in Web View Automation 

Sent by Cursor Approval Agent: Pull Request Approver

@foxish foxish left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Verified at 52a3b82: both rounds of Scott's feedback are addressed in code (boundary-set dedup, first-poll-only untimestamped lines, transient-error fail-fast via errors.As on *transport.APIError, --job/--follow exclusion, latched multi prefix, SIGHUP, rewind clamp, truncation warning, narrowed doc claim). Build, go vet, and go test ./internal/command/logs/ are green locally; go-sdk pin is a merged main revision; confirmed FixAPIErrors wraps *APIError with %w so the typed guard holds in production. Known limitations (server cap mirror, readiness message matching) are commented and tracked in #7271 / ENG-1156 / ENG-1115.

🤖 Reviewed with Claude Code

@foxish
foxish merged commit e9d48f0 into main Jul 30, 2026
1 check passed
@foxish
foxish deleted the davido/eng-1113-cli-follow-sandbox-logs branch July 30, 2026 16:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants