Skip to content

refactor: deduplicate trackPidForPort variants#2494

Merged
lpcox merged 3 commits intomainfrom
fix/dedup-pid-tracker-port-functions
May 4, 2026
Merged

refactor: deduplicate trackPidForPort variants#2494
lpcox merged 3 commits intomainfrom
fix/dedup-pid-tracker-port-functions

Conversation

@lpcox
Copy link
Copy Markdown
Collaborator

@lpcox lpcox commented May 4, 2026

Summary

Extract the shared try/catch + file-read + error-handling pattern from trackPidForPort (async) and trackPidForPortSync into a common trackPidForPortCore helper in src/pid-tracker.ts.

Before

Both functions had ~28 lines of identical error-handling and return-value boilerplate, differing only in fs.readFileSync vs await fsPromises.readFile.

After

trackPidForPortCore accepts a file-reader callback and encapsulates the shared structure. The sync variant delegates directly; the async variant pre-reads the file then falls back to the core for error handling.

Testing

  • All 54 pid-tracker tests pass
  • TypeScript compilation clean

Closes #2480

Extract shared try/catch + file-read pattern from
trackPidForPort (async) and trackPidForPortSync into
a common trackPidForPortCore helper.

Closes #2480

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings May 4, 2026 14:53
@lpcox lpcox requested a review from Mossaka as a code owner May 4, 2026 14:53
@lpcox
Copy link
Copy Markdown
Collaborator Author

lpcox commented May 4, 2026

@copilot address the review feedback

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR refactors src/pid-tracker.ts to reduce duplication between the async and sync PID lookup entry points that read /proc/net/tcp and resolve the owning process.

Changes:

  • Adds a new trackPidForPortCore helper for the shared sync-style read/error-handling flow.
  • Reworks trackPidForPort to perform an async read first and fall back to the new core on error.
  • Updates the function ordering/comments around the async and sync PID-tracking APIs.
Show a summary per file
File Description
src/pid-tracker.ts Extracts shared PID-tracking logic into a helper and rewires the async/sync entry points around it.

Copilot's findings

Tip

Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comments suppressed due to low confidence (2)

src/pid-tracker.ts:400

  • This catch now handles failures from resolvePidFromTcpContent(...) as well as fsPromises.readFile(...). If the parse/lookup path ever throws, the async API silently retries the whole operation with synchronous I/O, which both blocks the event loop and can return a different result because /proc may have changed between the two attempts.
  } catch (err) {
    // Fall back to the synchronous core for consistent error handling
    return trackPidForPortCore(
      (p) => fs.readFileSync(p, 'utf-8'),

src/pid-tracker.ts:400

  • The new fallback branch in the async implementation is not covered by tests. The existing trackPidForPort tests only exercise the happy path and the case where both reads fail, so they would not catch regressions in the new catch behavior that retries synchronously and potentially changes the returned error/result.
  } catch (err) {
    // Fall back to the synchronous core for consistent error handling
    return trackPidForPortCore(
      (p) => fs.readFileSync(p, 'utf-8'),
  • Files reviewed: 1/1 changed files
  • Comments generated: 1

Comment thread src/pid-tracker.ts Outdated
Comment on lines 391 to 396
// Read asynchronously, then delegate to the shared core.
// The core uses a synchronous reader callback, so we pre-read here.
try {
// Read /proc/net/tcp
const tcpPath = path.join(procPath, 'net', 'tcp');
let tcpContent: string;

try {
tcpContent = fs.readFileSync(tcpPath, 'utf-8');
} catch (err) {
return {
pid: -1,
cmdline: 'unknown',
comm: 'unknown',
error: `Failed to read ${tcpPath}: ${err}`,
};
}

const tcpContent = await fsPromises.readFile(tcpPath, 'utf-8');
return resolvePidFromTcpContent(tcpContent, srcPort, procPath);
@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

Copy link
Copy Markdown
Contributor

Copilot AI commented May 4, 2026

@copilot address the review feedback

Fixed in acd380e. The ESLint failure was 'err' is defined but never used (lint rule @typescript-eslint/no-unused-vars) caused by the trackPidForPort catch block discarding the caught error and falling back to trackPidForPortCore (which re-read the file synchronously — a flawed retry pattern).

Removed trackPidForPortCore entirely. Both trackPidForPort and trackPidForPortSync now follow the same structure: do their own I/O (async vs sync), return an error using err on read failure, then delegate to resolvePidFromTcpContent for the parse/lookup logic. All 56 pid-tracker tests pass, lint is now 0 errors.

Copilot finished work on behalf of lpcox May 4, 2026 15:04
@lpcox
Copy link
Copy Markdown
Collaborator Author

lpcox commented May 4, 2026

@copilot address the review feedback

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

Copy link
Copy Markdown
Contributor

Copilot AI commented May 4, 2026

@copilot address the review feedback

Done in e6a965d. Extracted makeTcpReadError(tcpPath, err) — a private helper that builds the { pid: -1, cmdline: 'unknown', comm: 'unknown', error: ... } result. Both trackPidForPort and trackPidForPortSync call it in their catch block, so the error shape lives in exactly one place. The two public functions are now fully symmetric: build tcpPath → I/O → makeTcpReadError on failure → resolvePidFromTcpContent on success.

@github-actions

This comment has been minimized.

Copilot finished work on behalf of lpcox May 4, 2026 15:25
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 4, 2026

Smoke Test Results ✅ PASS

  • ✅ GitHub API: Retrieved last 2 merged PRs
  • ✅ Playwright: github.com title verified
  • ✅ File Writing: Test file created with timestamp
  • ✅ Bash Execution: File contents verified

💥 [THE END] — Illustrated by Smoke Claude

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 4, 2026

Smoke Test: Copilot BYOK — Running in BYOK offline mode (COPILOT_OFFLINE=true) via api-proxy → api.githubcopilot.com

Test Result
1. GitHub MCP (list PRs)
2. GitHub.com HTTP connectivity ⚠️ pre-step data not resolved
3. File write/read ⚠️ pre-step data not resolved
4. BYOK inference (this response)

PR by @lpcox · reviewer: @Mossaka · Overall: PARTIAL (template vars unresolved; inference path confirmed working)

🔑 BYOK report filed by Smoke Copilot BYOK

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 4, 2026

🔬 Smoke Test Results

Test Status
GitHub MCP connectivity
GitHub.com HTTP connectivity ⚠️ (template vars not substituted)
File write/read ⚠️ (template vars not substituted)

PR: "refactor: deduplicate trackPidForPort variants" — author: @lpcox, reviewer: @Mossaka

Overall: PARTIAL — MCP ✅, pre-step data unavailable (workflow template variables were not substituted before agent invocation).

📰 BREAKING: Report filed by Smoke Copilot

@github-actions

This comment has been minimized.

1 similar comment
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 4, 2026

Smoke Test

PRs: refactor: extract runWithSignalHandling helper; refactor: extract createBaseAdapterConfig helper
GitHub MCP review: ❌
Safe-input GH CLI: ❌
Playwright GitHub title: ✅
Tavily search: ❌
File write/read: ✅
AWF build (npm ci && npm run build): ✅
Discussion comment: ✅
Overall status: FAIL

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • registry.npmjs.org

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "registry.npmjs.org"

See Network Configuration for more information.

🔮 The oracle has spoken through Smoke Codex

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 4, 2026

Chroot Version Comparison Results

Runtime Host Version Chroot Version Match?
Python Python 3.12.13 Python 3.12.3 ❌ NO
Node.js v24.14.1 v20.20.2 ❌ NO
Go go1.22.12 go1.22.12 ✅ YES

Result: FAILED — Python and Node.js versions differ between host and chroot environments.

Tested by Smoke Chroot

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 4, 2026

Smoke Test Results

Check Result
Redis PING ❌ Timeout — no response on host.docker.internal:6379
PostgreSQL pg_isready ❌ No response on host.docker.internal:5432
PostgreSQL SELECT 1 ❌ Skipped (pg_isready failed)

Overall: FAILhost.docker.internal is not reachable from this runner environment. Service containers may not be running or the hostname is not resolvable.

🔌 Service connectivity validated by Smoke Services

@lpcox lpcox merged commit 6dab385 into main May 4, 2026
72 of 80 checks passed
@lpcox lpcox deleted the fix/dedup-pid-tracker-port-functions branch May 4, 2026 16:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Duplicate Code] trackPidForPort and trackPidForPortSync duplicate identical try/catch/error-return structure

3 participants