Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(server): cut idle preview port scans by 85% #4187

ClosedQuicksaver(GitHub profile, opens in a new tab)wants to merge 88 commits intomain fromrefs/pull/4187/headopened View on GitHub

Summary

Preview discovery launched a system-wide listener scan every three seconds for as long as any client retained it. Long-running sessions kept paying for lsof and listener probes when nothing had changed, while new subscriptions and unchanged managed-terminal reports could add redundant scans.

Discovery now scans immediately when managed-terminal process IDs change or a retainer adds an unscanned configured URL. It replays cached results to subscribers and leaves system-wide discovery to a 10-second active or 20-second idle safety net. That cuts idle scan frequency by 85% while still finding T3-managed servers promptly and covering servers started elsewhere.

What changed

  • Pass configured URLs into retention. The first retainer, or one that adds an unscanned URL, runs one immediate scan before subscription replays that subscriber's cached projection
  • Publish only browser-ready HTTP(S) listeners and cache readiness results for 15 seconds
  • Run the broad safety-net scan every 10 seconds when a browser-ready server is known and every 20 seconds otherwise, with immediate rescheduling when that state changes
  • Scan after managed-terminal process changes and run one bounded settle scan for child processes that bind shortly afterward
  • Serialize scans, snapshot publication, and final-retainer invalidation so stale results cannot replace the current snapshot
  • Deliver subscriber updates through per-listener queues outside the global locks, preserving order without deadlocking callback-triggered scans or terminal updates
  • Remove failed or interrupted subscriptions without blocking healthy listeners or stranding publisher acknowledgments
  • Preserve caller interruption during immediate background scans so scoped terminal polling can shut down promptly

Validation

  • The focused port scanner suite passed all 36 tests, covering replay and broadcast ordering, callback-triggered terminal changes and public scans, interruption and cleanup paths, snapshot invalidation, scope shutdown, publisher acknowledgments, adaptive scheduling, the bounded terminal settle scan, and concurrent scan serialization
  • Formatting passed for BRANCH_DETAILS.md, PortScanner.ts, and PortScanner.test.ts; file-scoped lint passed for PortScanner.ts and PortScanner.test.ts
  • The affected server typecheck and git diff --check passed

🤖 Generated by gpt-5.6-sol in Codex via T3 Code


Note

Medium Risk Touches core preview discovery concurrency, subscription lifecycle, and polling semantics; interval changes can slightly delay discovery for non-terminal servers, though behavior is heavily regression-tested.

Overview Cuts background preview port discovery cost by replacing the always-on 3 second lsof/listener sweep with 10s active and 20s idle safety-net polling, while keeping immediate scans for retention, new configured URLs, and managed-terminal PID changes.

PortDiscovery now retain(configuredUrls?) refcount-scopes discovery and runs one immediate scan when discovery was idle or the retainer introduces URLs not in the last scan; subscribe drops initialSnapshot and replays the cached per-subscriber projection after registration. ws.ts wires preview subscriptions through retain(configuredUrls) then subscribe, removing the extra scan() + manual initial queue push.

Scan publication and final-retainer invalidation go through a scanLock; updates are delivered via per-listener notification queues (with replay ordering, failed-replay rollback, and reentrant scan/terminal paths that avoid deadlocks). Terminal registrations get a bounded settle rescan after PID-set changes; when the last retainer leaves, snapshots are cleared so stale servers cannot replay. HTTP readiness stays on a 15s cache, including reuse on the first active poll tick.

Adds BRANCH_DETAILS.md and a large PortScanner.test.ts expansion for the new scheduling, retention, concurrency, and cleanup behavior.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c26fcb2843a85e2b5189125b37941998e1619103. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Cut idle PortDiscovery preview port scans with adaptive polling and replay

  • Replaces single POLL_INTERVAL (3s) with ACTIVE_POLL_INTERVAL (10s) and IDLE_POLL_INTERVAL (20s), so the safety-net poll runs slower when no browser-ready servers are known
  • Refactors PortDiscovery.make to serialize scans via scanLock, deliver per-listener snapshots through dedicated queues with acknowledgments, and replay the last snapshot on subscribe without an extra scan
  • Changes retain to a function accepting configuredUrls; first retention or new URLs trigger an immediate scan, and final release invalidates cached snapshots and projections
  • Terminal process registrations now trigger at most one settle scan when PIDs stabilize instead of scanning on every update
  • Risk: PortDiscovery.subscribe no longer accepts initialSnapshot and retain is now a function call — callers in ws.ts and server.test.ts are updated; out-of-tree consumers must adapt to the new signature
Macroscope summarized 7a9baca.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 32c5c6e8-81b0-4987-b0a9-6477ec11b8d3

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR introduces major architectural changes to the port discovery system, including a new queue-based notification mechanism, dual locking for concurrency control, and adaptive polling intervals. While extensive tests are added, the complexity of these concurrency and infrastructure changes warrants human review.

      Notes:

      • No code objects were reviewed. Approvability was decided on eligibility alone.
      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High

      https://github.com/pingdotgg/t3code/blob/8a2719fc4c26f435782ac88b4039456edf7f4682/apps/server/src/preview/PortScanner.ts#L296

      subscribe calls the listener inside notificationLock.withPermit, so a listener that synchronously calls registerTerminalProcesses or unregisterTerminal triggers pollTick → publishSnapshot, which waits on the same notificationLock — this deadlocks and the subscription never completes. The same reentrancy deadlock affects broadcast, since publishSnapshot also holds notificationLock while invoking all listeners. Consider invoking listeners outside the lock so subscriber callbacks cannot reenter it.

      ✅ Resolved in 326c399b5c2d35d010c9346d6b3ae30783f3a331

    5. Fixed in 326c399. Port notifications now flow through ordered per-listener queues, so callbacks run outside the global notification lock. External publications still await delivery, while callback-reentrant publications enqueue without waiting on themselves; ordered stop markers also prevent unsubscribe from stranding publisher acknowledgments. A focused regression verifies that a replay callback can trigger terminal registration and deliver the newer snapshot without deadlocking. Validation: 11 PortScanner tests, targeted lint, affected server package typecheck, and git diff --check pass.

    6. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    7. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit eedca9b0cca7eb78393ef635740e4983f5cf56ae. Configure [here](https://www.cursor.com/dashboard/bugbot).
    8. Branch will be rebased and PR reopened at a later time.

      🤖 Generated by gpt-5.6-sol in Codex via T3 Code

Sign in to join this conversation.