Skip to content

various restart/devbox fixes - #288

Merged
scott-cotton merged 6 commits into
mainfrom
restart-init-also-on-nil
Dec 12, 2025
Merged

scott-cotton merged 6 commits into
mainfrom
restart-init-also-on-nil

Conversation

@scott-cotton

@scott-cotton scott-cotton commented Dec 11, 2025 •

Copy link
Copy Markdown
Member

Fix: Devbox Session Management and Service Recovery Improvements

Overview

This branch includes several critical fixes and improvements to devbox session management and service recovery:

  1. Fixed stale HTTP connection errors in devbox session renewals
  2. Removed shutdown-on-release mechanism - renewals now automatically claim new sessions
  3. Removed sessionReleased field - no longer tracked since renewals auto-claim
  4. Dynamic session ID tracking - sandbox watcher adapts to session ID changes
  5. Fixed restart loop - tunnel proxy monitor respects grace period for all checks

It also adds hidden gops-root-addr and gops-non-root-addr flags to signadot local connect to facilitate getting gops stacks and info on locald root manager and locald sandboxmanager.

Problem 1: Stale HTTP Connections After Sleep

Issue

After a sleep period during signadot local connect, the devbox session manager would encounter "connection reset by peer" errors when trying to renew the session. This was caused by reusing a cached HTTP client with stale TCP connections.

Root Cause

The SessionManager was storing a single apiClient instance and reusing it across all renewal requests. After sleep periods, the underlying TCP connections would be closed by the server, but the client would attempt to reuse them.

Solution

Changed to create a fresh API client for each renewal request. This ensures each request gets a new HTTP client/transport, avoiding stale connection errors.

Key Changes:

  • Removed apiClient field from SessionManager struct
  • Modified renewSession() to create a new API client for each call
  • Modified releaseSession() to create a new API client for each call

Problem 2: Shutdown on Session Release

Issue

When a devbox session was released server-side, the session manager would trigger a shutdown of the entire sandbox manager, requiring manual reconnection.

Root Cause

The code was designed to shut down when a session was released, but the server-side API semantics changed: renewals now automatically claim a new session if the current one is released.

Solution

Removed the shutdown-on-release mechanism entirely. Renewals now automatically claim a new session if released, so there's no need to shut down.

Key Changes:

  • Removed shutdownCh parameter from NewSessionManager()
  • Removed triggerShutdown() method
  • Removed all shutdown triggers on session release
  • Updated handleSessionChange() to gracefully handle session ID changes without shutdown

Problem 3: Session Released State Tracking

Issue

The code tracked a sessionReleased boolean state, but since renewals automatically claim new sessions when released, this state was meaningless and always false.

Root Cause

The sessionReleased field was based on the assumption that renewals would fail when a session was released. However, renewals now succeed and claim a new session, so the released state is never observable.

Solution

Removed sessionReleased field and all references to it throughout the codebase.

Key Changes:

  • Removed sessionReleased field from SessionManager struct
  • Removed WasSessionReleased() method
  • Updated GetStatus() to return 5 values instead of 6 (removed sessionReleased)
  • Removed sessionReleased from DevboxSessionStatus proto message
  • Updated all callers to remove sessionReleased checks
  • Removed deadend state logic from sandbox_manager.go
  • Updated status reporting and printing code

Problem 4: Static Session ID in Sandbox Watcher

Issue

The sandbox watcher used a static devboxSessionID that was set at initialization. If the session ID changed during runtime (e.g., after a renewal claims a new session), the watcher would continue watching with the old session ID, missing sandboxes associated with the new session.

Root Cause

The watcher stored the session ID as a string field set once during initialization. Watch streams are long-lived, so even if the session ID changed, the watcher wouldn't pick up the change until the stream errored out (which could take a long time).

Solution

Changed the watcher to use a function that dynamically retrieves the current session ID. Added periodic checks during the watch stream to detect session ID changes and proactively restart the stream.

Key Changes:

  • Changed devboxSessionID string field to getDevboxSessionID func() string
  • Updated watchSandboxes() to call getDevboxSessionID() for each new watch stream
  • Added periodic session ID check in readStream() (every 5 seconds)
  • If session ID changes, proactively closes the current stream and restarts with new ID

Problem 5: Restart Loop After WiFi Reconnection

Issue

After turning WiFi off and back on, the tunnel proxy monitor would restart services repeatedly, causing excessive pfctl operations and log spam.

Root Cause

The agent-metrics health check didn't respect the 30-second startup grace period. When WiFi reconnected, the check would fail and immediately trigger a restart, which would fail again on the next check (1 second later), creating a restart loop.

Solution

Made the agent-metrics check respect the same grace period logic as other health checks. During the startup phase (first 30 seconds), failed checks wait instead of immediately restarting.

Key Changes:

  • Updated agent-metrics check to use shouldRestartDueToUnhealthy() helper
  • Now respects the 30-second maxStartingTime grace period
  • Prevents restart loops during network reconnection scenarios

Technical Details

Session Manager Changes

Before:

type SessionManager struct {
    apiClient *client.SignadotAPI  // ❌ Cached, causes stale connections
    shutdownCh chan struct{}       // ❌ Triggers shutdown on release
    sessionReleased bool           // ❌ Meaningless state
}

After:

type SessionManager struct {
    currentSessionID string  // ✅ Tracks current session (may change)
    // No apiClient - created fresh per request
    // No shutdownCh - removed shutdown mechanism
    // No sessionReleased - removed entirely
}

Sandbox Watcher Changes

Before:

type sbmWatcher struct {
    devboxSessionID string  // ❌ Static, never updates
}

func watchSandboxes() {
    sbwClient.WatchLocalSandboxes(MachineId: sbw.devboxSessionID)  // ❌ Old ID
}

After:

type sbmWatcher struct {
    getDevboxSessionID func() string  // ✅ Dynamic function
    currentWatchedSessionID string    // ✅ Tracks watched ID
}

func watchSandboxes() {
    currentID := sbw.getDevboxSessionID()  // ✅ Gets current ID
    // Periodic check in readStream() detects changes
}

Tunnel Proxy Monitor Changes

Before:

resp, err := cli.Get("http://agent-metrics.signadot.svc:9090/metrics")
if err != nil {
    restartSvcs = true  // ❌ Immediate restart, no grace period
}

After:

resp, err := cli.Get("http://agent-metrics.signadot.svc:9090/metrics")
if err != nil {
    if shouldRestart := mon.shouldRestartDueToUnhealthy(); shouldRestart {
        restartSvcs = true  // ✅ Respects 30s grace period
    }
}

Benefits

  • ✅ No more stale connection errors - fresh HTTP client per request
  • ✅ Automatic session recovery - renewals claim new sessions without shutdown
  • ✅ Simplified state management - removed meaningless sessionReleased field
  • ✅ Proper renewal scheduling - ticker runs correctly for periodic renewals
  • ✅ Dynamic session tracking - watcher adapts to session ID changes
  • ✅ No restart loops - grace period prevents rapid restarts during network issues
  • ✅ Better reliability - system recovers automatically from various failure scenarios

Testing Considerations

  • ✅ Verify renewals work correctly after sleep periods
  • ✅ Test that session ID changes are detected and handled gracefully
  • ✅ Confirm that released sessions are automatically claimed via renewals
  • ✅ Ensure no restart loops occur during WiFi reconnection
  • ✅ Verify sandbox watcher picks up new session IDs within 5 seconds (it took longer to re-connect sandboxes b/c of control plane side delays)
  • ✅ Test that services recover properly after network interruptions

@scott-cotton
scott-cotton requested a review from foxish December 11, 2025 21:56
@scott-cotton scott-cotton changed the title restart init also on nil various restart/devbox fixes Dec 12, 2025
@scott-cotton

Copy link
Copy Markdown
Member Author

@daniel-de-vera comments addressed

@scott-cotton

Copy link
Copy Markdown
Member Author

@daniel-de-vera comments addressed

sorry there was some cross-fire, one thing pending...

Comment thread internal/devbox/session_manager.go Resolved
Comment thread internal/devbox/session_manager.go Resolved
@daniel-de-vera

Copy link
Copy Markdown
Contributor

@scott-cotton, I'm done with the code review, will do some testing now.

Also distinguish restart from not-ok more correctly
in tp_monitor
@scott-cotton
scott-cotton force-pushed the restart-init-also-on-nil branch from a2fdad9 to 6a2e592 Compare December 12, 2025 15:50
@scott-cotton

Copy link
Copy Markdown
Member Author

@scott-cotton, I'm done with the code review, will do some testing now.

now all comments addressed and re-tested.

please note regarding

don't think we need to set the mon.starting and mon.beginStarting here (since it's being handled within checkTunnelProxyAccess()).

I didn't do that because I want the state to be top-down readable, and the timeouts are a function of restarting so separating them seems less readable to me.

However, following your advice would have fixed another hole.

So, I refactored for additional clarity -- new sub functions and distinguish need to restart from checks passed explicitly.

}

func (mon *tpMonitor) checkTunnelProxyAccess(ctx context.Context) bool {
func (mon *tpMonitor) checkTunnelProxyAccess(ctx context.Context) (success bool, restarted bool) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: I would remove the named return values (as we are not using them).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I like the documentation effect upon reading the signature :)

@daniel-de-vera daniel-de-vera left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM, just left one minor comment about named return values.

@scott-cotton
scott-cotton merged commit f0e9de5 into main Dec 12, 2025
@scott-cotton
scott-cotton deleted the restart-init-also-on-nil branch December 12, 2025 17:20
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.

2 participants