Skip to content

fix: release native PTY spawn environment after setup - #21140

Merged
OrcaWin merged 1 commit into
mainfrom
np-oom-scan-native-pty-spawn-env
Sep 18, 2026
Merged

OrcaWin merged 1 commit into
mainfrom
np-oom-scan-native-pty-spawn-env

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​128 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​128
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1587 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1586

The native PTY exit callback keeps the complete spawn arguments reachable to read one boolean. Those arguments include the merged environment, which therefore remains owned for the live terminal's lifetime.

Copy reportsChildExitStatus before registering the callback. The sole production caller passes a fresh argument object containing this completed spawn fact. Required PATH and foreground metadata stay available; spawning, disposal, signal authority and exit ordering follow the same paths.

Validation

  • Actual wrapper, foreground tracker and installed node-pty JavaScript emitter: live arguments/environment retained before, collectible after on Node 26 and Electron 43.7 / Node 24. Exit status, signal causes, early output/exit replay and disposal controls pass.
  • 114 tests pass with four existing platform skips; the reversed-source lifetime regression fails as expected, with 29 controls passing.
  • Node typecheck, focused normal/type-aware lint, changed-code quality and independent review pass.

docs/audits/native-pty-spawn-env-retention/ contains the portable, source-hash-checked proof. It uses an inert native process port and small environment objects. Environment values may share other owners; this does not measure native allocations, resident bytes or the cause of #19831.

@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The PTY subprocess handle now copies args.reportsChildExitStatus before registering the exit callback. This prevents the callback from retaining the full spawn arguments and merged environment. New unit tests and an audit harness verify object collection, PTY lifecycle behavior, exit-status mapping, source hashes, and Node/Electron reproduction results. Documentation records the audit scope and validation outputs.

Priority: ⬇️ Low

Severity of issue fixed: Low

Merge Risk: 🔵 Low · up to b1119

The audit's documented reproduction can fail on a clean install because a required package is undeclared. Add the dependency before merging to preserve reproducibility.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the technical change and validation, but it omits most required template sections, including ELI5, Why, the required Linked Issue format, Visual Proof or N/A, Testing checkbox… Rewrite the description using all required template headings. Add an ELI5 summary, user-facing before and after behavior, the reason for this approach, a linked issue using the required Fixes # format, Visual Proof or N/A with a reason, tes…
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 6 files. (6 skipped: 6… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main production change: releasing the native PTY spawn environment after setup.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description explains the technical change and validation, but it omits most required template sections, including ELI5, Why, the required Linked Issue format, Visual Proof or N/A, Testing checkboxes, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist.

Resolution

Rewrite the description using all required template headings. Add an ELI5 summary, user-facing before and after behavior, the reason for this approach, a linked issue using the required Fixes # format, Visual Proof or N/A with a reason, testing steps and platforms, AI disclosure if applicable, review notes, the Agent skill upstream boundary checkbox, security and compatibility notes, and the checklist confirmations.

Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 6 files. (6 skipped: 6 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: bf469a56-3eb3-4c18-b0fb-0e38262e92f9

📥 Commits

Reviewing files that changed from the base of the PR and between 631b51f and b11197c.

📒 Files selected for processing (12)
  • docs/audits/native-pty-spawn-env-retention/README.md
  • docs/audits/native-pty-spawn-env-retention/before.config.mjs
  • docs/audits/native-pty-spawn-env-retention/electron-results.json
  • docs/audits/native-pty-spawn-env-retention/fix.patch
  • docs/audits/native-pty-spawn-env-retention/node-results.json
  • docs/audits/native-pty-spawn-env-retention/reproduce.cjs
  • docs/audits/native-pty-spawn-env-retention/scenario.cjs
  • docs/audits/native-pty-spawn-env-retention/source-versions.json
  • docs/audits/native-pty-spawn-env-retention/sources.cjs
  • docs/audits/native-pty-spawn-env-retention/validation.json
  • src/main/daemon/pty-subprocess-env-retention.test.ts
  • src/main/daemon/pty-subprocess/subprocess-handle.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.

const Module = require('node:module')
const esbuild = require('esbuild')
const sha = (value) => createHash('sha256').update(value).digest('hex')
const { applyPatch, parsePatch, reversePatch } = require('diff')

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

pwd
find .. -name package.json -not -path '*/node_modules/*' -print
rg -n '"diff"|native-pty-spawn-env-retention|before\.config|reproduce\.cjs' package.json pnpm-lock.yaml .github config docs src --glob '!**/node_modules/**'
sed -n '1,120p' docs/audits/native-pty-spawn-env-retention/sources.cjs

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

python3 - <<'PY'
from pathlib import Path
import json, re

root = Path('.')
manifests = sorted(p for p in root.rglob('package.json') if 'node_modules' not in p.parts)
print('MANIFESTS')
for p in manifests:
    try:
        d = json.loads(p.read_text())
    except Exception as e:
        print(f'{p}: JSON_ERROR {e}')
        continue
    print(f'\n[{p}]')
    print('name=', d.get('name'))
    print('packageManager=', d.get('packageManager'))
    print('workspaces=', d.get('workspaces'))
    for section in ('dependencies','devDependencies','optionalDependencies','peerDependencies'):
        vals = d.get(section, {})
        if 'diff' in vals or section in ('dependencies','devDependencies','optionalDependencies'):
            print(section + '=', {k:v for k,v in vals.items() if k == 'diff' or (p == root/'package.json' and k in ('pnpm','vitest','diff'))})
    scripts = d.get('scripts', {})
    if scripts:
        hits = {k:v for k,v in scripts.items() if any(x in v for x in ('audit','native-pty-spawn-env-retention','vitest'))}
        if hits:
            print('scripts=', hits)

print('\nWORKSPACE_CONFIG')
for name in ('pnpm-workspace.yaml', 'pnpm-workspace.yml', '.npmrc', '.pnpmfile.cjs', 'pnpm-lock.yaml'):
    p = root/name
    if p.exists():
        print(f'{p}: exists')
        if p.name != 'pnpm-lock.yaml':
            print(p.read_text()[:8000])

lock = root/'pnpm-lock.yaml'
if lock.exists():
    text = lock.read_text()
    print('\nLOCKFILE_HEADER')
    print('\n'.join(text.splitlines()[:45]))
    lines = text.splitlines()
    print('\nLOCKFILE_DIFF_CONTEXT')
    for i,line in enumerate(lines):
        if re.search(r'(^|\s)diff(?:@|:|$)', line) or re.search(r'/diff@', line):
            lo=max(0,i-8); hi=min(len(lines),i+15)
            print(f'--- lines {lo+1}-{hi} ---')
            print('\n'.join(f'{j+1}: {lines[j]}' for j in range(lo,hi)))

print('\nAUDIT_FILES')
for p in sorted(root.rglob('*')):
    if p.is_file() and 'node_modules' not in p.parts and any(x in p.name.lower() for x in ('config','audit','reproduce')):
        try:
            txt=p.read_text(errors='replace')
        except Exception:
            continue
        if any(x in txt for x in ('native-pty-spawn-env-retention','sources.cjs','vitest','require(\'diff\')')):
            print(f'--- {p} ---')
            print(txt[:12000])
PY

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

python3 - <<'PY'
from pathlib import Path
import json, re

root = Path('.')
manifests = sorted(p for p in root.rglob('package.json') if 'node_modules' not in p.parts)
print('MANIFESTS')
for p in manifests:
    try:
        d = json.loads(p.read_text())
    except Exception as e:
        print(f'{p}: JSON_ERROR {e}')
        continue
    print(f'\n[{p}]')
    print('name=', d.get('name'))
    print('packageManager=', d.get('packageManager'))
    print('workspaces=', d.get('workspaces'))
    for section in ('dependencies','devDependencies','optionalDependencies','peerDependencies'):
        vals = d.get(section, {})
        if 'diff' in vals or section in ('dependencies','devDependencies','optionalDependencies'):
            print(section + '=', {k:v for k,v in vals.items() if k == 'diff' or (p == root/'package.json' and k in ('pnpm','vitest','diff'))})
    scripts = d.get('scripts', {})
    hits = {k:v for k,v in scripts.items() if any(x in v for x in ('audit','native-pty-spawn-env-retention','vitest'))}
    if hits:
        print('scripts=', hits)

print('\nWORKSPACE_CONFIG')
for name in ('pnpm-workspace.yaml', 'pnpm-workspace.yml', '.npmrc', '.pnpmfile.cjs', 'pnpm-lock.yaml'):
    p = root/name
    if p.exists():
        print(f'{p}: exists')
        if p.name != 'pnpm-lock.yaml':
            print(p.read_text()[:8000])

lock = root/'pnpm-lock.yaml'
if lock.exists():
    text = lock.read_text()
    print('\nLOCKFILE_HEADER')
    print('\n'.join(text.splitlines()[:45]))
    lines = text.splitlines()
    print('\nLOCKFILE_DIFF_CONTEXT')
    for i,line in enumerate(lines):
        if re.search(r'(^|\s)diff(?:@|:|$)', line) or re.search(r'/diff@', line):
            lo=max(0,i-8); hi=min(len(lines),i+15)
            print(f'--- lines {lo+1}-{hi} ---')
            print('\n'.join(f'{j+1}: {lines[j]}' for j in range(lo,hi)))

print('\nAUDIT_FILES')
for p in sorted(root.rglob('*')):
    if p.is_file() and 'node_modules' not in p.parts and any(x in p.name.lower() for x in ('config','audit','reproduce')):
        try:
            txt=p.read_text(errors='replace')
        except Exception:
            continue
        if any(x in txt for x in ('native-pty-spawn-env-retention','sources.cjs','vitest','require(\'diff\')')):
            print(f'--- {p} ---')
            print(txt[:12000])
PY

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

sed -n '1,220p' /tmp/coderabbit-shell-logs/shell-output-NinL6Q | grep -E '(^|/)(package\.json|pnpm-lock\.yaml|before\.config\.mjs|sources\.cjs)|"diff"|native-pty-spawn-env-retention' | head -200

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

log=/tmp/coderabbit-shell-logs/shell-output-zsf0a7
printf '%s\n' '--- manifest and workspace summary ---'
rg -n -C 3 '^(MANIFESTS|WORKSPACE_CONFIG|LOCKFILE_HEADER|LOCKFILE_DIFF_CONTEXT|AUDIT_FILES)|^\[[^]]*package\.json\]|^name=|^packageManager=|^workspaces=|^scripts=|^dependencies=|^devDependencies=|^optionalDependencies=' "$log" | head -300
printf '%s\n' '--- diff lockfile contexts ---'
rg -n -C 12 'diff@8\.0\.4|/diff@|(^|[[:space:]])diff:' "$log" | head -240
printf '%s\n' '--- audit invocation/config contexts ---'
rg -n -C 8 'native-pty-spawn-env-retention|sources\.cjs|before\.config\.mjs|vitest|audit' "$log" | tail -240

Repository: stablyai/orca

Length of output: 19178


🏁 Script executed:

printf '%s\n' '--- root manifest ---'
nl -ba package.json | sed -n '1,180p'
printf '%s\n' '--- root lockfile importer ---'
nl -ba pnpm-lock.yaml | sed -n '1,180p'
printf '%s\n' '--- diff dependency snapshot owner ---'
nl -ba pnpm-lock.yaml | sed -n '13960,14020p'
printf '%s\n' '--- target audit files ---'
nl -ba docs/audits/native-pty-spawn-env-retention/sources.cjs
nl -ba docs/audits/native-pty-spawn-env-retention/before.config.mjs
printf '%s\n' '--- target audit references and invocation ---'
rg -n -C 4 'native-pty-spawn-env-retention|sources\.cjs|before\.config\.mjs' package.json config docs .github --glob '!**/node_modules/**'

Repository: stablyai/orca

Length of output: 47779


Declare the diff package. The documented audit command loads before.config.mjs, which calls loadSources() and reaches this require('diff'). The root importer does not declare diff; the lockfile provides it only through shadcn. A clean pnpm install can therefore throw MODULE_NOT_FOUND.

Add diff to the root devDependencies and update the lockfile.

@pullfrog pullfrog Bot 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.

✅ No new issues found.

Reviewed changes

A one-line lifetime fix, a regression test, and a self-contained audit proof.

  • Spawn-env release — subprocess-handle.ts now copies args.reportsChildExitStatus into a local const before registering the onExit callback, so the long-lived closure no longer captures the whole argument object that carries the merged spawn env.
  • Regression test — pty-subprocess-env-retention.test.ts asserts, via WeakRef + forced GC, that args/env collect while the handle is live, then confirms PATH, raw foreground lookup, pre-listener data/exit replay, both exit-status interpretations, dead-handle signal guards, and idempotent disposal still hold.
  • Audit proof — docs/audits/native-pty-spawn-env-retention/ reverses fix.patch in memory against the real wrapper and measures before/after retention on Node 26 and Electron 43.

I verified the fix independently rather than trusting the write-up: the new test passes on the branch (3 passed), and the before.config.mjs overlay, which reverses the patch, makes the retention assertion genuinely fail pre-fix (expected {...} to be undefined) — so it is not theatre. Every other args.* read in the function is synchronous or feeds the foreground tracker's own argument object, so no returned closure keeps args reachable after the change. The recorded fixedHashes for subprocess-handle.ts (e28a2043…) also match the shipped file exactly.

The README scopes the claim honestly (per-handle JS retention only, inert process port, not native allocation or the cause of #19831), and reportsChildExitStatus is an immutable spawn fact passed by the sole caller as a fresh literal, so the copy is behavior-preserving. Nothing actionable.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@OrcaWin
OrcaWin merged commit b899b22 into main Sep 18, 2026
34 checks passed
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
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.

1 participant