Skip to content

killUser: Handle POSIX kill(2) - #103

Closed
shlevy wants to merge 3 commits into
NixOS:masterfrom
shlevy:handle-POSIX-kill
Closed

shlevy wants to merge 3 commits into
NixOS:masterfrom
shlevy:handle-POSIX-kill

Conversation

@shlevy

@shlevy shlevy commented Mar 18, 2013

Copy link
Copy Markdown
Member

According to POSIX, kill(-1, signo) should kill the calling process as well as all other processes it has permission to kill. On systems that implement this aspect of kill(2), killUser will always fail as the child process will kill itself while killing the other processes of the build user.

This branch fixes this in general by using ps to check for any running processes when the child process dies due to SIGKILL, with a special-case for OSX that uses a variant of kill(2) that doesn't implement this POSIX behavior.

Closes #99, as that approach opened a security hole and this one solves the same problem.

shlevy added 2 commits March 18, 2013 11:13
The kill(2) in Apple's libc follows POSIX semantics, which means that
kill(-1, SIGKILL) will kill the calling process too. Since nix has no
way to distinguish between the process successfully killing everything
and the process being killed by a rogue builder in that case, it can't
safely conclude that killUser was successful.

Luckily, the actual kill syscall takes a parameter that determines
whether POSIX semantics are followed, so we can call that syscall
directly and avoid the issue on Apple.

Signed-off-by: Shea Levy <[email protected]>
According to POSIX, kill(-1, signo) should kill the calling process too,
which will cause the child killUser process to exit with non-zero status
code. To handle this case, killUser needs to distinguish between the
child having successfully killed all the processes (including itself)
and some rogue builder having killed the child first.

Unfortunately, it seems like the only POSIX-compatible way to do so is
to call `ps -u <uid>` and see if any processes are running as that user.
Since this is a corner case that's only hit in the error path (we only
run `ps` when the child exits with non-zero status and was killed by
SIGKILL), though, it's probably fine that it's inefficient.

Signed-off-by: Shea Levy <[email protected]>
Signed-off-by: Shea Levy <[email protected]>
@edolstra

Copy link
Copy Markdown
Member

Brrr, nasty... Is this even guaranteed to work? I.e. if a process forks and exits while ps is running, is ps guaranteed to show at least one of those processes?

@shlevy

shlevy commented Mar 18, 2013

Copy link
Copy Markdown
Member Author

From http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html:

the snapshot it gives is only true for an instant

Which suggests that it is indeed a true snapshot for that instant, but other than that nothing is said with regards to accuracy or races. Though of course implementations may not actually live up to the standard.

@shlevy

shlevy commented Mar 18, 2013

Copy link
Copy Markdown
Member Author

Eh, this is probably more ugly than it's worth. Can you just pull in the first commit (for Apple systems) and if we ever find other systems that behave this way fix them one-by-one?

@shlevy

shlevy commented Jul 2, 2013

Copy link
Copy Markdown
Member Author

@edolstra Thoughts on the first commit to fix for darwin?

@shlevy shlevy closed this Jul 30, 2013
zolodev pushed a commit to zolodev/nix that referenced this pull request Jan 1, 2024
Remove semi-colon from fetchTarball example
ConnorBaker pushed a commit to ConnorBaker/nix that referenced this pull request Jul 25, 2025
ConnorBaker added a commit to ConnorBaker/nix that referenced this pull request May 29, 2026
…OS#259, fixes ledger

Independent whole-branch audit (22 agents -> dedup -> per-finding
adversarial verify): 70 findings, 63 confirmed, 7 refuted.

Catalog corrections (counts/claims re-derived against master):
  - NixOS#65: recorded grep was malformed (anchored `builtins\."` returns 2,
    not 79); restored the unanchored form, noted the 87-name-anchored
    alternative is a different set (F014).
  - NixOS#18: B3's grep returns 24 lines / 23 hand-written, not 17; added the
    six omitted names (F016).
  - NixOS#169/NixOS#217/N33: friend count is 11 Expr* lines / 10 distinct, not
    "10 / 9" (F013).
  - NixOS#103/N6 + verified/05: RewritingSink no longer "tracks match
    positions"; matches is dead and HashModuloSink::finish's loop is
    inert since 3ebe134 (F019).
  - NixOS#138: eval.cc read-site is copyPathToStore, not the nonexistent
    "addToStore" (F006).
  - NixOS#218 + STATUS: placeholder inventory undercounted (6 -> 7-8); the
    wire-marker is the BuildResult compat StringMap, not a DrvOutput
    serialisation; nix-store.cc misfiled as a "legitimate constant"
    (F007-F011).
  - README U7b/U7c + N1: migratable cache count and per-site exclusion
    reasons (F017/F018).
  - verified/19: nix_get_external is a functional bug, not a "quirk";
    nix_store_path_hash missing-preamble outlier (F003/F052).
  - verified/17: tree glyphs live in libutil util.hh, not "libcmd
    headers" (F035).
  - NixOS#11-legacy NixOS#222/NixOS#231 + FOLLOWUPS: --max-freed mechanism and the
    --priority getArg mis-recommendation (F001/F002).

New candidates NixOS#241-NixOS#259 filed into their topical sections (per the
catalog's group-by-symptom principle): 03 (NixOS#244), 07 (NixOS#246), 08 (NixOS#243),
10 (NixOS#253,NixOS#255), 12 (NixOS#241,NixOS#242,NixOS#259), 13 (NixOS#248,NixOS#249,NixOS#251), 16
(NixOS#245,NixOS#247), 17 (NixOS#254,NixOS#256), 20 (NixOS#250,NixOS#252), 23 (NixOS#257,NixOS#258).

NixOS#122: re-verified the stackOverflowHandler symbol-mangle caveat is
correct as written (F062).

The audit is recorded as a STATUS.md "Recently completed" event (it
subsumes the per-finding report; no standalone report file is kept).
The corresponding code fixes are uncommitted on the cleanup worktrees.
Also converted the macOS /Users/cbaker2 paths in HANDOFF.md/STATUS.md to
the Linux /home/cbaker2 paths used on this machine.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
roberth added a commit to roberth/nix that referenced this pull request Aug 9, 2026
Infrastructure for the Ambient redesign (task NixOS#103). Contra-args
identified by their observation set, not by state hash — sibling
callback applies with observably different args get distinct
queryHashes by construction, not by after-the-fact discrimination.

- trace::QueryCallbackApply{fn, argObsSet}: new query variant.
  Payload references an observation set in the CAS pool below.
- ObservationSet CAS pool on TracingDecisionGraph:
  computeObservationSetHash, insertObservationSet, getObservationSet.
  Members are (queryHash, responseHash) tuples; payload is sorted
  CBOR; hash is SHA-256 of the payload. Not the RequestSet trie —
  expected member counts per firing are small, lookups are by
  whole-set hash.

Not yet wired to the writer or walker; wiring is the next slice of
NixOS#103. Baseline tests: 318/7/7 unchanged.

Assisted-by: Claude Code (Claude Opus 4.7)
roberth added a commit to roberth/nix that referenced this pull request Aug 9, 2026
Writer now emits a QueryCallbackApply per finalized cb-apply
firing, with the arg observation set inserted into the CAS pool
and referenced by hash from the CallbackApply payload. Different
observation sets → distinct queryHashes.

Concrete validation on `(cb 10) + (cb 20)`:
- Same fn state hash across both firings.
- Different obsSet hashes (per-firing observation content differs).
- Different QueryCallbackApply queryHashes.

No walker-side handling yet — the emitted CallbackApply queries
are present in the DB but the walker still routes ambient replays
through the existing AmbientAsk / InnerValueResponse path.
Baseline 318/7/7 unchanged.

- Add `fnStateHashHex` field to PendingCbApply, populated in
  openCbApply by parsing the applyQueryPayload's `params.fn`.
- In flushAmbient's per-boundary finalize, when the boundary has a
  non-empty facts group and a captured fnStateHashHex, build an
  Observation list from the group's (query, response) pairs, insert
  the set into the ObservationSet CAS pool, construct the
  QueryCallbackApply payload with (fn, obsSetHash), and insert the
  query into the Requests pool.

Next slice of NixOS#103: walker-side dispatch of QueryCallbackApply
requests. Then progressively cut over ambient dispatch to use the
new path and remove PendingCbApply / AmbientAsk / InnerValueResponse
contextHash.

Assisted-by: Claude Code (Claude Opus 4.7)
roberth added a commit to roberth/nix that referenced this pull request Aug 9, 2026
…all ambient responses

Under the NixOS#103 CallbackApply-slot redesign, every ambient probe's
response is carried on the enclosing CallbackApply query's
`argObsSet` field, content-addressed in the `ObservationSet` CAS
pool. The walker's consumer decodes that pool into an in-memory
map at dispatch time and serves probes from it directly. The
`InnerValueResponse` table's role as a secondary lookup vanishes.

Removed:
- Schema (CREATE TABLE) and prepared statements
  (insert/select) in tracing-decision-graph.cc; added a
  `DROP TABLE IF EXISTS InnerValueResponse` for migration of
  existing DBs.
- `TracingDecisionGraph::insertInnerValueResponse` and
  `getInnerValueResponsePayload` declarations and definitions.
- `TracingWriter::storeAllResponsePayloads` (debug-only flag whose
  only effect was piping env-layer responses into
  InnerValueResponse — nothing consumed them).
- Writer's `insertInnerValueResponse` call in `flushAmbient`'s
  `stampAndEmit` (pre-NixOS#103 emission path).
- Reader's `getInnerValueResponsePayload` fallback in
  `ReplayCallbackArg::readResponse` — the obsSet map is now the
  only source; miss is a real error.
- Unit test that exercised the (requestHash, contextHash)
  first-writer-wins contract.

Suite unchanged at 152/8/5.

Stale comments referencing `InnerValueResponse` remain in a few
places (tracing-replay-evaluator.cc, replay-callback-arg.cc) as
historical narrative; sweeping them is a follow-up.

Assisted-by: Claude Code (Claude Opus 4.7)
roberth added a commit to roberth/nix that referenced this pull request Aug 9, 2026
…p cell[0] shortcut

The prior consumer navigated fn structurally from cell[0].liveObject
via the query's fnPath — a premature optimisation that discriminates
by whichever fn is currently in the outer arg cell, not by the fn
recorded in this specific callbackApply's obsSet. Under sibling
calls with different callback bodies, cell[0].liveObject reflects
the current invocation's fn regardless of which recording's obsSet
we're dispatching, silently returning the wrong fn.

Replace with resolveStateHash(ref.fn) — the slot's fn state hash,
stamped by the writer at emission. resolveStateHash routes through
cell-chain equality on the evolved state hash, finding the fn whose
current state matches the recording's specific call. On miss, return
null cleanly rather than falling back to the structural shortcut.

Correctness-first per task NixOS#103's obsSet MVP framing (repeated live
outer validation calls, no per-cell memoisation). Suite: 10 → 15
fails. Regressions (cb-lazy-result-multi-attr,
cb-forcedness-independence, cb-repeated-cb-apply-diff-args,
cb-xor-evolution-repeated-cb-apply, cb-stats-sidecar-baseline) surface
the upstream gap where fn's state hash doesn't evolve distinctly per
call — the shortcut was masking these by grabbing the currently-live
fn regardless. Correct-or-miss now, wrong-hit before.

Assisted-by: Claude Code (Claude Opus 4.7)
roberth added a commit to roberth/nix that referenced this pull request Aug 9, 2026
…s obsSet CAS

Task NixOS#103's per-observation CallbackApply + content-addressed
ObservationSet CAS supersedes the AmbientAsks chain machinery. The
walker's callbackApply-slot branch fires fn live via dispatchApplyLive
and validates via obsSet lookup; the old AmbientAsks-per-probe
chain-cursor validation added no correctness value on top and was
carrying dead weight.

Removed:
- SQL schema for AmbientAsk table.
- TracingDecisionGraph::insertAmbientAsk / getAmbientAsks methods
  and their prepared statements.
- Writer's stampAndEmit AmbientAsks insertion (behind
  `withAmbientAsks` flag, always emitted at first-finalize).
- Walker's `queryTag == "apply"` branch that called getAmbientAsks
  to decide dispatchApplyLive vs chain-root fallback — this branch
  now misses cleanly (legacy apply Facts without callbackApply slot
  are stale from before NixOS#103's cutover).
- ReplayCallbackArg's advanceChainAndAppendFact (chain-cursor
  navigation via getAmbientAsks) — callers use appendFactToWalk
  directly. validateAgainstAmbientAsks and its setter kept as no-op
  for source compatibility with lingering call sites.

Suite unchanged: 146/16/5 (main). Same failures as before rip-out
— confirms AmbientAsks was dead-weight relative to correctness.

Assisted-by: Claude Code (Claude Opus 4.7)
roberth added a commit to roberth/nix that referenced this pull request Aug 9, 2026
…ixOS#109)

Second half of the AmbientAsks rip-out: the walker's live-fire path
for AmbientAsks-chain-driven cb-apply invocation is gone.
`dispatchApplyLive` and its `inFlightApplyReqs` short-circuit are
removed; the callbackApply-slot path in `dispatchAmbientQuery`
(task NixOS#103) is now the sole live-fire mechanism for cb-apply
dispatches.

The three file-scope helpers (`parsePathFromParams`, `resolveRoots`,
`navigatePath`) are retained — both the callbackApply-slot branch
and the general `from`-based live-validation branch of
`dispatchAmbientQuery` still call them for path parsing / root
resolution / structural navigation.

Suite: 312/335 pass, 16 fail, 7 skipped — same baseline as before
this cleanup, no regression from the removal.

Assisted-by: Claude Code (Claude Opus 4.7)
roberth added a commit to roberth/nix that referenced this pull request Aug 9, 2026
…field

`outerContext` was threaded through every ReplayCallbackArg
constructor and every `readResponse` call, but its only use inside
`readResponse` was `(void) outerContext;` followed by a log-line
substring. No decision, no lookup key, no correctness signal.

Removing the field + its constructor param + its `readResponse`
parameter + the callers' `zeroContext` / `fallbackContextHash`
locals leaves the `<replay-local-lambda>` primop capture list
smaller too. Was the residue of the InnerValueResponse-context
scheme that NixOS#103's obsSet CAS replaced; the doc comment referring
to "boundary/contextHash mechanism" is now truthful (that
mechanism no longer exists in the code).

Suite: 312/16/7, unchanged — confirms the field wasn't
load-bearing.

Assisted-by: Claude Code (Claude Opus 4.7)
roberth added a commit to roberth/nix that referenced this pull request Aug 9, 2026
…s carry it

The localArg sidecar (`{"kind":"localArg","applyResultId":...,"depth":...,"argAncestry":...}`
parked in the Requests pool under a callback arg's state hash) was
the walker's route to reconstructing a cb-arg's `Subject` shape
(`Arg{depth}` at `argAncestry`) when it hit that arg's id during
producer-chain resolution. Under the task NixOS#103 CallbackApply-query
design, `argDepth` and `argAncestry` ride in the CallbackApply query
itself, and the dispatchAmbientQuery slot handles cb-arg construction
end-to-end without touching the Requests pool for cb-args.

Removed:

- Writer: sidecar emission in `expr-from-object.cc` (plus the
  `getTypeLazy` probe that only populated the sidecar's `localType`).
- Writer: `TracingWriter::deferRequest`'s `keyPlaceholder` parameter
  and `PendingRequest::keyPlaceholder` — only the sidecar used the
  non-natural insert key.
- Walker: `resolveStateHash`'s `kind == "localArg"` branch.
- Walker: `isLocalArgId` helper (only caller was the sidecar branch
  of `resolveApplyId`).
- Walker: sidecar-reading branch of `resolveApplyId` (the entire
  `if (isLocalArgId(...))` construction). Arg resolution now
  uniformly goes through `resolveStateHash`.
- ReplayCallbackArg: `validateAgainstAmbientAsks` field,
  `withAmbientAsksValidation`, `hasAmbientAsksValidation`,
  `withChainStart` — all only reachable from the removed sidecar
  branch.

Suite: 312/16/7, same baseline — confirms the sidecar path was
unreachable under the CallbackApply-slot dispatch mechanism.

Assisted-by: Claude Code (Claude Opus 4.7)
roberth added a commit to roberth/nix that referenced this pull request Aug 9, 2026
…xOS#103

Under task NixOS#103, callback observations flow through the
ObservationSet CAS (referenced from CallbackApply queries), not
through per-boundary Ask edges. The CallbackCell struct still
carried a large surface of fields the pre-NixOS#103 flushAmbient
boundary-finalise loop needed — `applyRequestHash`,
`insertionIndex`, `envCurAtOpen`, `outerEnvCurAtOpen`,
`contextCur`, `facts`, `finalized`, `cumulativeFactSet`,
`factHash`, `pos`, `lastProcessedCount`, `runningObsHistory` —
none of which are read anywhere live. Ditto the
`PendingFact` struct, the ~250-line boundary-finalise + late-obs
re-processing loop in `flushAmbient`, and the
`TracingWriter::outerWriter` pointer plumbed to feed
`envCurAtOpen`.

The `logAmbientObservation` name misdescribed its new role
(NixOS#103's obsSet accumulator, not the old "ambient probe"
recording). Renamed to `logCallbackObservation`, matched by
renaming `ambientApplyId` → `applyId` on `TracingCallbackArg`
and `TracingCallbackApplyResult`.

Also removed:

- `logAmbientApplyFact` — pushed to the now-dead `facts` vector;
  its recursive-cb-apply observation isn't wired to the obsSet in
  the current build (nested cb-apply behaviour unchanged, hence
  the deletion, not a rewrite).
- `beginOuterProbe` — cleared the removed `runningObsHistory`.
- `InnerValueRequestPayload` / `InnerValueResponsePayload` — trace
  types for a table (`InnerValueResponse`) already dropped by the
  `DROP TABLE IF EXISTS` in the schema init.

Suite: 312/16/7, unchanged.

Assisted-by: Claude Code (Claude Opus 4.7)
roberth added a commit to roberth/nix that referenced this pull request Aug 9, 2026
…xOS#110 phase 1)

Preparation for NixOS#110 which makes QueryCallbackApply a first-class
Query variant, so both NixOS#103's slot embedding and NixOS#108's applyContext
fold-in workaround are being removed. Under the new design (not yet
implemented), a QueryCallbackApply(f, obs) → WHNF observation is
emitted at each callback-return moment; subsequent probes on the
returned value trace back through it as their from-source.

Removed in this pass:

- `OuterApply::run`'s NixOS#108 emission of an outer-scope observation +
  bridge push into contraArg's applyContext.
- Writer's `logOuterObservation` scanning subject tree for
  ApplyResultSubject, cell lookup by fnStateHashHex, snapshotting
  runningObsSet into CAS, and stamping `params.callbackApply` on
  outer probes.
- Walker's `dispatchAmbientQuery` `params.callbackApply` slot dispatch
  branch (materialise-ReplayCallbackArg + fn->queryApply + trailing
  path traversal).
- `CallbackApplyRef` struct + serializers + parser wiring; optional
  `callbackApply` field on `QueryGetAttr` / `QueryGetWHNF`.
- Related comments referring to the slot.

Suite unchanged at 312/16/7 — confirms neither mechanism was
load-bearing for the current passing set. This is a data point:
the workarounds each nominally addressed sibling-Q collision, but
the tests that pass do so via inner-fallback re-eval rather than
via cache hits routed through those mechanisms.

Phase 2 (upcoming): emit QueryCallbackApply at each callback-return
moment and wire walker dispatch for it.

Assisted-by: Claude Code (Claude Opus 4.7)
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