Skip to content

hide-ai owns the codex app-server and the label watcher exits with its host (issue #82 Part A) - #92

Merged
yansfil merged 7 commits into
mainfrom
prd/ai-process-ownership
Sep 20, 2026
Merged

yansfil merged 7 commits into
mainfrom
prd/ai-process-ownership

Conversation

@yansfil

@yansfil yansfil commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

라벨 플러그인 하나가 codex app-server 자손 1,699개와 11.6 GB를 이틀간 붙들고 Mac을 멈춘 사고(issue #82)의 Part A를 고칩니다.
hide-ai가 자신이 띄운 codex app-server를 온전히 소유하도록 바꿉니다.

  • 세션마다 소유자 전용(0700) 임시 CODEX_HOME을 만들어 그 안에 사용자 auth.json symlink 하나만 두고 넘깁니다(app-server가 자기 상태 파일을 그 옆에 쓰지만 sessions/ rollout은 남기지 않습니다). config.toml이 없으니 app-server가 MCP 서버를 하나도 띄우지 않습니다(실측: -c mcp_servers={}와 thread config 오버라이드 모두 무효였음). 세션이 끝나면 디렉터리를 지우고, 만들지 못하면 ProviderUnavailable(codex_home_unavailable:...)로 실패하며 ~/.codex로 되돌아가지 않습니다.
  • 종료를 graceful 한 경로로 모읍니다: stdin close → 3초 → SIGTERM → 3초 → SIGKILL. Session::drop, 세션 교체, 상한 초과 재시작이 모두 이 경로를 지납니다. 소유자가 kill -9로 죽어도 자식은 stdin EOF로 따라 죽습니다.
  • 유휴 10분이면 app-server를 내리고(ai.app_server.idle_exit), 다음 요청이 새로 띄웁니다.
  • RouterConfig에 budget 상수를 더합니다: 동시 요청 1, 분당 30, 자손 4, RSS 1 GiB. 요청 상한 초과는 제출 전 AiError::OverBudget(재시도 안전, fallback 안 함), 프로세스 상한 초과는 app-server를 종료·재시작하며 연속 3회에서 ProviderUnavailable(app_server_restart_cap). 측정은 macOS libproc로 커널에서 읽고 서브프로세스를 띄우지 않으며, 다른 플랫폼은 Unavailable.
  • 라벨 watcher는 부모(Herdr)가 사라지면 watcher_host_gone을 남기고 exit 0 하여 app-server를 데리고 내려갑니다. 플러그인은 OverBudget을 환경 실패로 다뤄 마지막 라벨을 유지하고 10분 뒤 다시 묻습니다.

Related

Breaking change

운영자가 할 일은 없습니다. 설치·상태 디렉터리·저장된 설정·공개 계약은 그대로입니다.
저장소 내부 계약만 바뀝니다: hide_ai::CodexAppServerBackend::new가 이제 Arc<dyn AiLogSink>를 받습니다(호출부 herdr-core/src/ai.rs, plugins/agent-context-labels/src/provider.rs 모두 이 PR에서 갱신). AiError에 OverBudget 변형이 추가됩니다.

Review focus

  • 사람이 판단할 것: 자격 증명 symlink 접근 방식(0700 임시 디렉터리 + symlink만 + 세션 종료 시 삭제, 파일 자체는 읽지 않음)이 허용 가능한지. budget 상수 값(자손 4 / RSS 1 GiB / 분당 30 / 동시 1)이 운영 기준으로 적절한지.
  • 위험한 파일: hide-ai/src/codex.rs(사설 CODEX_HOME 생성·삭제, graceful 종료, 유휴 reaper 스레드, 측정), hide-ai/src/router.rs(budget 카운팅·프로세스 상한·재시작 상한), hide-ai/src/process.rs(libproc FFI), plugins/agent-context-labels/src/lib.rs(host-death exit, getppid 폴링).
  • 리뷰어에게 묻는 것: codex의 토큰 갱신이 symlink 위로 atomic rename을 쓰면 갱신본이 임시 디렉터리에서 유실될 수 있습니다(아래 Risk surface). 실제 turn 관찰(codex 주간 한도 리셋, 2026-09-19 17:10 KST) 뒤 확인 예정이니, 그 전 merge 여부를 판단해 주세요.

Risk surface

  • Ownership: 이 변경은 hide-ai가 소유한 codex app-server 프로세스의 생명주기입니다(Herdr pane/PTY 소유와 무관). spawn 하나, 종료 하나, 자식은 소유자와 함께 죽고, 자원마다 상한이 있습니다(resident-process practice 1·3·4).
  • Failure path: 사설 CODEX_HOME 생성 실패 → ProviderUnavailable(codex_home_unavailable:<stage>:<kind>). 요청 상한 초과 → OverBudget(로그 ai.budget.exceeded). 프로세스 상한 초과 → ai.app_server.over_budget + 재시작, 연속 3회 → ProviderUnavailable(app_server_restart_cap). 모두 호출자에게 보이는 타입이며 로그 줄에 측정값과 상한이 남습니다. 프롬프트·토큰·경로는 로그에 없습니다.
  • 자격 증명: auth.json을 가리키는 symlink가 0700 임시 디렉터리에 생기고, hide-ai는 그 파일을 열지 않습니다. 디렉터리 삭제는 symlink만 지우고 원본은 건드리지 않습니다(Security 리뷰 확인). codex 0.155.1의 기본 file 자격 증명 저장소는 CODEX_HOME/auth.json을 truncate 모드로 열어 제자리에 쓰며 temp+rename이 없으므로 symlink를 따라 실파일이 갱신됩니다(codex-rs/login/src/auth/storage.rs @ rust-v0.155.1에서 확인, 2026-09-20). keyring/auto 저장소는 사설 홈에 항목이 없어 needs_login이 되며 지원 범위 밖입니다.

Evidence

  • 결정적 검증(deterministic verification report): PASS. agents/runs/ai-process-ownership/verification-report.json / verification-report.md, base 92969b5, head 99eee2c.
  • 확인한 것: sealed suite 3레인 모두 PASS — bash scripts/verify-cargo.sh test, bash scripts/verify-swift.sh test, bash scripts/verify-cargo.sh lint. 신규 계약 테스트: 가짜 app-server로 thread마다 자식을 띄우는 500건을 실제 라우터 경로로 돌려 자손 수가 상한(4) 아래에서 안정이며 over-budget 재시작이 발생함을 단언(hide-ai/tests/process_ownership.rs); 소유자 kill -9 뒤 5초 안에 자손 0; codex 스키마에 thread/close가 생기면 실패하는 guard; watcher 부모 사망 시 watcher_host_gone 로그와 exit(plugins/agent-context-labels/tests/cli.rs); router budget 단위 테스트(in-flight/per-minute/프로세스 상한·재시작 상한). 네이티브 리뷰 3종(Fidelity/Code/Security)을 동일 diff(head 99eee2c)에 실행: Code가 지적한 High 1건(dead 세션을 락 안에서 drop) 수정 후 재리뷰 통과, Fidelity/Security는 Fix now 없음. 최신 origin/main에 rebase한 트리(내용 무변·충돌 없음)에서도 sealed suite 3레인 PASS를 확인해 upstream과의 통합을 검증했고(head 0eaa046), 이 브랜치는 저장소의 merge-commit 관례에 따라 fork 지점(92969b5) 위에 내 커밋만 담아 배포합니다.
  • 확인하지 못한 것과 그 이유: 실제 codex turn 관찰(D-09 e)은 2026-09-20 한도 리셋 뒤 실행했습니다: verify-provider --provider codex가 5.7초에 accepted, 트리는 node 래퍼 -> codex app-server로 MCP 자식 0, 사설 홈 0700, 종료 후 삭제, ~/.codex/auth.json inode/mtime 불변. 이 실행이 첫 릴리스 후보의 descendants=0을 드러냈고(proc_listchildpids 반환값을 바이트로 나눠 1~3개 자손이 0으로 측정되던 버그), 747cb6e에서 고쳐 이제 descendants=1;rss_bytes=137117696(래퍼 47 MB + app-server 86 MB)로 측정됩니다. 중첩 sh 트리를 정확히 3으로 세는 단위 테스트를 추가했습니다. 사설 CODEX_HOME에서 MCP 자식 0을 단언하는 real_codex_starts_no_mcp_children은 #[ignore]이며 문서화된 명령으로 로컬 실행합니다(cargo test -p hide-ai --test process_ownership -- --ignored real_codex); 수정 후 real codex descendants: 1로 통과(2026-09-20). 단언은 <= 1로 조였습니다. Linux 프로세스 측정은 Unavailable(운영 환경 macOS 전용).
  • 화면 증거: N/A - UI 변경 없음(디자인 계약 무관).

AI tooling

  • 사람이 직접 작성 - [ ] 일부를 AI 도구로 작성 - [x] 대부분을 AI 도구로 작성

손으로 확인한 것: budget 상수와 실측 근거의 일치, graceful 종료 순서와 락 범위, watcher host-death 경로를 실제 프로세스로 재현(부모 종료 시 exit 0 + watcher_host_gone), 그리고 세 네이티브 리뷰의 Fix now 처리를 직접 대조했습니다.

hide-ai now owns the codex app-server it starts: a private 0700 CODEX_HOME
holding only an auth.json symlink (no config.toml, so no MCP children), one
graceful shutdown path (stdin close -> SIGTERM -> SIGKILL), a ten-minute idle
exit, per-request descendant/RSS measurement via libproc on macOS, and budget
caps in RouterConfig with OverBudget and a capped over-budget restart. The
context-label watcher exits when its parent process is gone, and treats
OverBudget as an environmental failure.

Tests: fake app-server 500-request descendant stability, kill -9 owner leaves
zero survivors, ignored real-codex zero-MCP check, a guard that fails when the
codex schema gains thread/close, verify-provider prints descendants, and the
watcher exits when its host dies.
execute() tore down a lost session in place while holding the session mutex;
a connection lost with the child still alive would then run the full graceful
shutdown under the lock, blocking the idle reaper, restart, and the backend's
own Drop. Take it out, release the lock, then drop it, matching restart().
Resolves four conflicts: the claude runner keeps main's ChildEnvironment
apply ahead of the crate's spawn helper, the label watcher keeps the
initial-parent read and drops the needs_bootstrap flag main removed, and
the two docs carry both sides' entries.
proc_listchildpids returns a pid count for both the size query and the
filled buffer, unlike proc_listpids. Dividing it by the int size again
made one to three descendants measure as zero, so the descendant cap and
the tree resident size never saw the real app-server under the node
wrapper. A unit test now asserts a nested sh tree measures exactly three,
and the real-codex test allows at most the wrapper's one child.

The provider doc names what codex writes into the private CODEX_HOME,
that a kill -9 owner leaves the directory behind, how the file credential
store refreshes through the symlink, that a healthy tree measures one
descendant, and the working order of the verify-provider environment.
@yansfil
yansfil merged commit a3d9bd2 into main Sep 20, 2026
5 checks passed
@yansfil
yansfil deleted the prd/ai-process-ownership branch September 20, 2026 02:25
yansfil added a commit that referenced this pull request Sep 28, 2026
Related: #116, #92

## Summary

Closes #116.
A codex app-server's private `CODEX_HOME` is removed in `Drop`, which a
`kill -9` never runs, so homes piled up in `$TMPDIR`.
Each `CodexAppServerBackend` now sweeps, on a detached thread when it is
built, the `hide-ai-codex-home-<pid>-<nanos>` directories whose owner
pid is gone.
A live pid keeps its homes even if the pid was reused; unparsed names,
non-directories, symlinks and other users' entries are never touched.
One sweep removes at most 32 and logs `ai.codex_home.swept` (removed,
bytes, failed, unreadable, capped, first error kind), which hided now
writes to `Logs/core.jsonl`; no screen changes, so no screenshot.

```
before: dead=344 live=3 total_kb=300088   (this machine's $TMPDIR, pid checked with kill -0)
after:  dead=0   live=2 total_kb=5512     (after the workspace test lane built backends)
```

## Review

- **Please decide**: a reused pid that is alive keeps the dead owner's
home (the task said to err toward keeping); the issue proposed also
sweeping when the live pid "is not a hide-ai process". I did not add
process-identity checks.
- **Please decide**: one summary event per sweep (count, bytes) instead
of the issue's one line per removed directory with its pid, as the batch
task asked.
- **Please decide**: the core sink forwards every AI event, not only the
sweep's, so Project Memory's `ai.attempt`/`ai.request.finished` now also
land in `core.jsonl` (1 MB rotating); forward only failures if that is
too much.
- **Files to watch**: `hide-ai/src/codex_home.rs` `sweep`/`pid_alive` -
failure path that deletes files; check the keep-on-doubt rules.
- **Files to watch**: `herdr-core/src/ai.rs` `DiagnosticLogSink` -
replaces three `NoopLogSink`s; `diagnostic!` only `try_send`s, and no
router or backend here runs under `Mutex<Runtime>` (Settings reader
worker, Project Memory write thread).
- **Files to watch**: `hide-ai/src/codex.rs`
`CodexAppServerBackend::new` - spawns the sweep thread and never blocks
the caller.

## Evidence

- **Confirmed**: `codex_home` unit tests with fixture roots: a dead
owner (a reaped child's pid) is removed and the `auth.json` symlink
target survives; a live owner (own pid), five malformed names, a plain
file and a top-level symlink are kept; pid 1 (EPERM) is kept; a limit of
2 over 3 homes removes 2 then 1; an unremovable dead home logs
`failed=1` with `first_error=permission denied`.
- **Confirmed**: `ai::tests` in herdr-core: an event becomes `{"kind",
"component": "ai", ...}` with absent fields omitted.
- **Confirmed**: `cargo test -p hide-ai` all pass (45 unit, 13
claude_cli, 8 codex_app_server, 3 process_ownership);
`scripts/verify-cargo.sh lint` clean;
`check-no-workstation-identity.sh`,
`check-capability-readers-off-lock.sh` pass.
- **Confirmed**: real-path sweep on this machine: the workspace test
lane builds real backends, and the dead-owner home count went 344 to 0
while both live-owner homes stayed.
- **Not confirmed**: locally `scripts/verify-cargo.sh test
--no-fail-fast` passes every binary except `hide-agent-hooks`
`hook_deadline`, a regression on `main` from 23aca6d (not this change;
`hide-agent-hooks` reaches `hide-ai` through `hide-memory`); CI's rust
workspace lane passed on the first push.
- **Not confirmed**: an `ai.codex_home.swept` line in a running hided's
`core.jsonl`; the sink is covered by the unit test and the shared
`diagnostic!` path, not a live daemon run.
- **Not confirmed**: no live codex on this machine, so no real `kill -9`
of a codex owner followed by a restart; Linux behavior (pid namespaces
with a shared `/tmp` would make a live owner look dead) is untested.

<details><summary>More evidence</summary>

First code review found no path that deletes a live owner's home or
follows a symlink out of `$TMPDIR` (`remove_dir_all` on rustc 1.97.1
walks with `O_NOFOLLOW`).
Fixed from it: the doc omitted the thread-spawn case of `sweep_failed`,
and wrongly claimed the CI kill test leaves a home (its owner is a
stand-in that never creates one).
Second review (of the log routing) found the records lacked the
`component` key other core diagnostics carry; fixed.
Follow-ups: 32 or more permanently unremovable homes that sort first
would block the sweep on every start; integration tests sweep the
developer's real `$TMPDIR` (harmless, dead owners only); an orphaned
app-server can outlive a killed owner for a few seconds, during which
its home may be swept; the context-label plugin's `EventLog` could reuse
the new `Serialize` instead of its own key=value format.

</details>

**AI tooling**: mostly AI tools; the keep-on-doubt rules and the
before/after counts were checked against this machine's `$TMPDIR`.
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