Skip to content

Dynamic attrs sugar 2 - #167

Closed
shlevy wants to merge 2 commits into
NixOS:masterfrom
shlevy:dynamic-attrs-sugar-2
Closed

shlevy wants to merge 2 commits into
NixOS:masterfrom
shlevy:dynamic-attrs-sugar-2

Conversation

@shlevy

@shlevy shlevy commented Sep 21, 2013

Copy link
Copy Markdown
Member

This adds new syntax for attribute names:

  • attrs."${name}" => getAttr name attrs
  • attrs ? "${name}" => isAttrs attrs && hasAttr attrs name
  • attrs."${name}" or def => if attrs ? "${name}" then attrs."${name}" else def
  • { "${name}" = value; } => listToAttrs [{ inherit name value; }]

Of course, it's a bit more complicated than that. The attribute chains
can be arbitrarily long and contain combinations of static and dynamic
parts (e.g. attrs."${foo}".bar."${baz}" or qux), which is relatively
straightforward for the getAttrs/hasAttrs cases but is more complex for
the listToAttrs case due to rules about duplicate attribute definitions.

For attribute sets with dynamic attribute names, duplicate static
attributes are detected at parse time while duplicate dynamic attributes
are detected when the attribute set is forced. So, for example, { a = null; a.b = null; "${"c"}" = true; } will be a parse-time error, while
{ a = {}; "${"a"}".b = null; c = true; } will be an eval-time error
(technically that case could theoretically be detected at parse time,
but the general case would require full evaluation). The rules for
duplicate attributes are the same in both cases, though: if some
sub-chain of an attribute path already has a value, that's an error (for
example, { a.b = true; a.b.c = false; } would cause an error when
parsing the a.b.c since a.b, a sub-chain, has a value. { a.b.d = true; a.b.c = false; }, on the other hand, is fine as neither is a
subchain of the other.

Finally, recursive attribute sets with dynamic attributes have the
static attributes in scope but not the dynamic ones. So rec { a = true; "${"b"}" = a; } is equivalent to { a = true; b = true; } but rec { "${"a"}" = true; b = a; } would be an error or use a from the
surrounding scope if it exists.

Note that the error checking for attribute sets is pretty hairy, in part
because I wanted to leave the non-dynamic code path as untouched as I
could. Essentially, this creates a list of lists of attribute paths (
e.g. { a.b.c = 1; a.d = 2; } would go to [ [ "a" "b" "c" ] [ "a" "d"] ]
) for all of the attributes, static and dynamic, and then as each
dynamic attribute is added to the set its attribute path is checked
against that list. Possibly this could be cleaned up a bit.

This is an alternative solution to #134

Certain desugaring schemes may require the parser to use some builtin
function to do some of the work (e.g. currently `throw` is used to
lazily cause an error if a `<>`-style path is not in the search path)
Unfortunately, these names are not reserved keywords, so an expression
that uses such a syntactic sugar will not see the expected behavior
(see tests/lang/eval-okay-redefine-builtin.nix for an example).

This adds the ExprBuiltin AST type, which when evaluated uses the value
from the rootmost variable scope (which of course is initialized
internally and can't shadow any of the builtins).

Signed-off-by: Shea Levy <[email protected]>
This adds new syntax for attribute names:

* attrs."${name}" => getAttr name attrs
* attrs ? "${name}" => isAttrs attrs && hasAttr attrs name
* attrs."${name}" or def => if attrs ? "${name}" then attrs."${name}" else def
* { "${name}" = value; } => listToAttrs [{ inherit name value; }]

Of course, it's a bit more complicated than that. The attribute chains
can be arbitrarily long and contain combinations of static and dynamic
parts (e.g. attrs."${foo}".bar."${baz}" or qux), which is relatively
straightforward for the getAttrs/hasAttrs cases but is more complex for
the listToAttrs case due to rules about duplicate attribute definitions.

For attribute sets with dynamic attribute names, duplicate static
attributes are detected at parse time while duplicate dynamic attributes
are detected when the attribute set is forced. So, for example, { a =
null; a.b = null; "${"c"}" = true; } will be a parse-time error, while
{ a = {}; "${"a"}".b = null; c = true; } will be an eval-time error
(technically that case could theoretically be detected at parse time,
but the general case would require full evaluation). The rules for
duplicate attributes are the same in both cases, though: if some
sub-chain of an attribute path already has a value, that's an error (for
example, { a.b = true; a.b.c = false; } would cause an error when
parsing the a.b.c since a.b, a sub-chain, has a value. { a.b.d =
true; a.b.c = false; }, on the other hand, is fine as neither is a
subchain of the other.

Finally, recursive attribute sets with dynamic attributes have the
static attributes in scope but not the dynamic ones. So rec { a = true;
"${"b"}" = a; } is equivalent to { a = true; b = true; } but rec {
"${"a"}" = true; b = a; } would be an error or use a from the
surrounding scope if it exists.

Note that the error checking for attribute sets is pretty hairy, in part
because I wanted to leave the non-dynamic code path as untouched as I
could. Essentially, this creates a list of lists of attribute paths (
e.g. { a.b.c = 1; a.d = 2; } would go to [ [ "a" "b" "c" ] [ "a" "d"] ]
) for all of the attributes, static and dynamic, and then as each
dynamic attribute is added to the set its attribute path is checked
against that list. Possibly this could be cleaned up a bit.

This is an alternative solution to NixOS#134

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

shlevy commented Sep 21, 2013

Copy link
Copy Markdown
Member Author

cc @edolstra

@edolstra edolstra mentioned this pull request Oct 16, 2013
@edolstra

edolstra commented Dec 2, 2013

Copy link
Copy Markdown
Member

This PR gives a merge error currently.

I'm wondering if it wouldn't be easier to implement dynamic attrs like this:

  • Add a field std::vector<std::pair<Expr *, Expr *>> dynamicAttrs to ExprAttrs, denoting the pairs ${e1} = e2; in the attribute set.
  • During parsing, add every ${e1} = e2; to the dynamicAttrs vector of the current ExprAttrs.
  • In ExprAttrs::eval(), build the resulting attribute set normally, then for each element of dynamicAttrs, evaluate the name expression, check that if doesn't already exist in the resulting set, and add it to the resuling set.

The only problem I can see with this is that it doesn't handle repeated occurrences of the same dynamic attribute, e.g.

systemd.services."${name}".description = "Foo";
systemd.services."${name}".wantedBy = [...];

I guess ExprAttrs::eval() could just do a union if there are multiple occurrences. Alternatively, we could require people to write

@edolstra

edolstra commented Dec 2, 2013

Copy link
Copy Markdown
Member

This PR gives a merge error currently.

I'm wondering if it wouldn't be easier to implement dynamic attrs like this:

  • Add a field std::vector<std::pair<Expr *, Expr *>> dynamicAttrs to ExprAttrs, denoting the pairs ${e1} = e2; in the attribute set.
  • During parsing, add every ${e1} = e2; to the dynamicAttrs vector of the current ExprAttrs.
  • In ExprAttrs::eval(), build the resulting attribute set normally, then for each element of dynamicAttrs, evaluate the name expression, check that if doesn't already exist in the resulting set, and add it to the resuling set.

The only problem I can see with this is that it doesn't handle repeated occurrences of the same dynamic attribute, e.g.

systemd.services."${name}".description = "Foo";
systemd.services."${name}".wantedBy = [...];

I guess ExprAttrs::eval() could just do a union if there are multiple occurrences. Alternatively, we could require people to write

systemd.services."${name}" =
  { description = "Foo";
    wantedBy = [...];
  };

@shlevy

shlevy commented Dec 2, 2013

Copy link
Copy Markdown
Member Author

@edolstra Sure, we can do that. I thought you wanted this to be pure syntactic sugar, if we're willing to change how evaluation stage works this could probably be improved a bit.

For the problem with repeated occurrences, we can just check if the previous occurrence of the thing in the attribute set has an ExprAttrs as its value much like we do now during parsing.

@shlevy

shlevy commented Dec 4, 2013

Copy link
Copy Markdown
Member Author

@edolstra So should I just reimplement this with your suggestion for dynamic attrsets?

@edolstra

Copy link
Copy Markdown
Member

Yes, please do.

For simplicity, I think we can skip merging multiple definitions of the same attribute for now, as in

systemd.services."${name}".description = "Foo";
systemd.services."${name}".wantedBy = [...];

since it's not really clear that this is desirable. E.g. if you write

systemd.services."${name1}".description = "Foo";
systemd.services."${name2}".wantedBy = [...];

and name1 == name2, it's not clear if they should be merged or you should get an error.

@shlevy shlevy mentioned this pull request Jan 1, 2014
@shlevy

shlevy commented Jan 1, 2014

Copy link
Copy Markdown
Member Author

Obsoleted by #188

@shlevy shlevy closed this Jan 1, 2014
edolstra pushed a commit that referenced this pull request Jan 6, 2014
This adds new syntax for attribute names:

* attrs."${name}" => getAttr name attrs
* attrs ? "${name}" => isAttrs attrs && hasAttr attrs name
* attrs."${name}" or def => if attrs ? "${name}" then attrs."${name}" else def
* { "${name}" = value; } => listToAttrs [{ inherit name value; }]

Of course, it's a bit more complicated than that. The attribute chains
can be arbitrarily long and contain combinations of static and dynamic
parts (e.g. attrs."${foo}".bar."${baz}" or qux), which is relatively
straightforward for the getAttrs/hasAttrs cases but is more complex for
the listToAttrs case due to rules about duplicate attribute definitions.

For attribute sets with dynamic attribute names, duplicate static
attributes are detected at parse time while duplicate dynamic attributes
are detected when the attribute set is forced. So, for example, { a =
null; a.b = null; "${"c"}" = true; } will be a parse-time error, while
{ a = {}; "${"a"}".b = null; c = true; } will be an eval-time error
(technically that case could theoretically be detected at parse time,
but the general case would require full evaluation). Moreover, duplicate
dynamic attributes are not allowed even in cases where they would be
with static attributes ({ a.b.d = true; a.b.c = false; } is legal, but {
a."${"b"}".d = true; a."${"b"}".c = false; } is not). This restriction
might be relaxed in the future in cases where the static variant would
not be an error, but it is not obvious that that is desirable.

Finally, recursive attribute sets with dynamic attributes have the
static attributes in scope but not the dynamic ones. So rec { a = true;
"${"b"}" = a; } is equivalent to { a = true; b = true; } but rec {
"${"a"}" = true; b = a; } would be an error or use a from the
surrounding scope if it exists.

Note that the getAttr, getAttr or default, and hasAttr are all
implemented purely in the parser as syntactic sugar, while attribute
sets with dynamic attribute names required changes to the AST to be
implemented cleanly.

This is an alternative solution to and closes #167

Signed-off-by: Shea Levy <[email protected]>
@shlevy
shlevy deleted the dynamic-attrs-sugar-2 branch March 10, 2014 10:54
zolodev pushed a commit to zolodev/nix that referenced this pull request Jan 1, 2024
P-E-Meunier pushed a commit to P-E-Meunier/nix that referenced this pull request Feb 26, 2025
P-E-Meunier pushed a commit to P-E-Meunier/nix that referenced this pull request Feb 26, 2025
CertainLach pushed a commit to deltarocks/nix that referenced this pull request Sep 4, 2025
…cache

Use WAL mode for SQLite cache databases (2nd attempt)
ConnorBaker added a commit to ConnorBaker/nix that referenced this pull request May 22, 2026
Two adversarial-review and two pattern-discovery passes (Opus 4.7, 1M ctx,
~5,300 lines under doc/inventory/review/) walked the existing 217-entry
catalog and found cross-shard patterns the per-shard catalogers couldn't
see. This commit folds the four reports into the catalog.

Catalog scope rewrite. The README's "Performance work without duplication
or complexity to fix" exclusion was wrong: hot-path container choices,
allocations in inner loops, cache-line alignment costs, and missed
concurrency are all in scope on their own merits. Same for modernisation:
shrinking the Boost dependency surface or migrating hand-rolled idioms
to stdlib equivalents is a real simplification, even when no underlying
duplication backs the change. The README "What this catalog targets"
section adds an explicit "Performance" bullet and rewrites the
modernisation bullet to be in scope; the anti-list now excludes only
cosmetic changes and feature additions.

Verdict-table corrections. NixOS#50 (resolved-by-design) and NixOS#148 (INVALID,
windowSize destruction-order hazard) had verdict-table rows that
contradicted their validation paragraphs; tables now match. NixOS#171
upgraded VALID per the scope rewrite. Section-17 header updated from
"Five VALID; nine PARTIALLY VALID" to "Six VALID; eight PARTIALLY
VALID" to track.

Reclassifications and corrections from the deeper passes:

- NixOS#140 reframed as dead code (zero callers anywhere; not a SIOF
  hazard as the original framing suggested).
- NixOS#149 mechanism corrected: the `created = 123;` debug field is a
  guard against gcc bug 80431 miscompilation, not a use-after-free
  sentinel as pass-1 had stated.
- NixOS#170 corrected to three Goal subclasses + Waker (not four Goal
  subclasses as the catalog body had said).
- NixOS#147 demoted to PARTIALLY VALID; the singleton-leak path is
  load-bearing for legacy callers and must be retained alongside
  any per-Store ownership migration.
- NixOS#122 expanded with two ABI hazards the prior reviewer missed:
  layout drift in `PrimOp::impl` (allocated by `nix_alloc_primop`
  C-API) and symbol-mangle break in `extern fun<...>
  stackOverflowHandler`.
- NixOS#138 expanded: two C-API readers of `settings.readOnlyMode`, not
  one as pass-1 had stated.
- NixOS#160 expanded with HALO-incompatibility hazard for any
  `boost::asio::awaitable<T>` migration that touches `final_awaiter`.
- NixOS#129 expanded with destructor-throw caveat for the
  `MaintainCount` -> `Finally` replacement.
- NixOS#143 expanded with TLS-fallback shutdown-ordering hazard.
- NixOS#56 reframed as a real ODR fix: different TUs previously saw
  different definitions of the explicit specialisation; the values
  coincidentally matched so behaviour was preserved but the program
  was technically ill-formed.

Count corrections (each verified independently via grep): NixOS#137 register
sites = 16 (15 production + 1 test), NixOS#166 forward-decl headers =
9/21/12 (Store +2 over the catalog body), NixOS#167 buffer-size literals =
10 in libutil / 19 tree-wide, NixOS#169 friend declarations = 16 (one
duplicate `ExprVar`), NixOS#172 `unreachable()` sites = 64-65, NixOS#173 pragma
sites = 10, NixOS#176 daemon cases = 37 (35 distinct bodies), NixOS#178
trust-check sites = 11+1, NixOS#146 env vars = 14 in src/.

Forty-four cross-shard candidates (N1-N44) folded into four new section
files (22-25). The N-numbered range is intentionally separate from
1-217 to keep cross-references stable. Pattern clusters A-G,
architectural debt themes A1-A7, C++23/Boost uplift series U1-U10
(with U7 split per pass-2's refinement), and ten redundant-abstraction
pairs R1-R10 are documented in new README subsections.

Eight follow-up agents (E1-E8) deferred for source-level investigation:
verify `impureOutputHash` deletion path, audit C-API `*Settings`
surface lockstep, write a Goal::Co property test pinning O(1) frame
depth, build a daemon-client error-message preservation matrix, set up
periodic branch verification, validate test-support consolidation,
audit forward-decl source-compat, and choose the
`vTrue`/`vFalse`/`vNull`/`vEmptyList` invariant.

The four review reports plus the consolidation log live under
doc/inventory/review/ and stay in-tree for traceability.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ConnorBaker added a commit to ConnorBaker/nix that referenced this pull request May 24, 2026
Landed 18 commits across 6 shards covering 20 candidates:
- libstore +8 (NixOS#1+NixOS#3, NixOS#7, NixOS#11, NixOS#55, NixOS#59, NixOS#101, NixOS#153, NixOS#185)
- libexpr +3 covering 4 (NixOS#192, NixOS#202+NixOS#203 folded, NixOS#204)
- libutil +4 (NixOS#97, NixOS#124, NixOS#167, NixOS#224)
- libfetchers +1 (NixOS#53)
- libflake +1 (NixOS#133, rename only — deviation documented)
- libmain +1 (NixOS#223; NixOS#222 already on branch)

Skipped: NixOS#76 (libc++ in dev shell lacks <generator>) and several
RED-bucket items.

4-pass review chain: Pass A (parallel adversarial) caught 2
BLOCKERS — libstore NixOS#153 over-broad rename corrupted the
external-builders JSON wire-key, and libutil NixOS#97 dropped the
inline allowed-name list breaking eval-fail-hashString-2.err.exp.
Both fixed via amend; parseEnumOrThrow extended to render
'a', 'b', or 'c' with Oxford comma + suggestions. Pass B
(/code-review) found no blockers; substantive amends include
libexpr's callFunction hot-path now reading a ctor-frozen
profilerHooks snapshot, libstore's tryUpperFallLower returning
std::pair<R, bool>, libutil completing three migration gaps.
Pass C found one real clang-tidy error (parse-enum.hh missing
configuration.hh include); other shards only show the 5 known
pre-existing master errors. Pass D nix build -L . green on all
six shards.

New catalog candidates surfaced by review: NixOS#225 (libfetchers
getUserRegistry/getSystemRegistry/getGlobalRegistry share NixOS#53's
first-call-wins shape on the hot path), NixOS#226 (showCompressionAlgo
vs printHashAlgo enum-rendering inconsistency).

Catalog total: 226 + 44.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ConnorBaker added a commit to ConnorBaker/nix that referenced this pull request May 24, 2026
The May 2026 whole-branch review pass surfaced ~45 follow-up items
across the seven cleanup branches: correctness amends, doc-branch
corrections, in-source doc staleness, missing rl-next entries, new
catalog candidates, and compound-win cleanups. Track them in a
single in-tree ledger so the work can't slip across context
compactions or agent handoffs. Wire entries into STATUS.md
"Currently in flight" and HANDOFF.md "Step 1 — read in order".

Five batches, sequenced A → B → C → D → E:
- A: orphan-ref + stale-commit-body amends on cleanup branches
- B: doc-branch Branch line + catalog-scope corrections
- C: in-source doc staleness + missing rl-next entries
- D: file new catalog candidates NixOS#227-NixOS#233
- E: implementation of NixOS#227-NixOS#229 plus NixOS#167/NixOS#124 cross-shard
  extensions (deferred until A-D land)

Push policy unchanged: explicit-only, per-commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ConnorBaker added a commit to ConnorBaker/nix that referenced this pull request May 24, 2026
All seven Batch A items landed across the cleanup branches via
`git rebase -i` rewords. New tip SHAs recorded in the Cleanup
branches (live) table.

- libexpr orphan NixOS#217 ref: bfc3c23 (tip 380b332)
- libstore orphan NixOS#54+NixOS#56+NixOS#57+NixOS#60 ref: in tip e2d92cb
- libstore NixOS#101 body reflowed (drop dead swallowMissingCaDerivations)
- nix-cli NixOS#89 body corrected re prefetch.cc disposition (tip 2a34c31)
- libutil NixOS#167 body uses kBufferedStreamSize, lists six sites
- libutil NixOS#224 body lists four sites
- libutil io-buffer-sizes.hh docblock lists all six users

All cleanup branches build green via ninja after the rebases.
No push.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ConnorBaker added a commit to ConnorBaker/nix that referenced this pull request May 24, 2026
…ification

Batch E shipped three implementation commits on libexpr:

- f452e2d NixOS#227: drop dead EvalProfiler NVI cache + default no-op
  virtuals; mark hooks pure; rl-next entry added.
- d6f0904 NixOS#228: extend NumOp to BitAnd/BitOr/BitXor (`isIntOnly<Op>`
  arm in primNumeric); banner comment + static_assert in arithmetic-
  result lambda for the implicit `Op ∈ {Add,Sub,Mul}` invariant.
- 76b6808 NixOS#229: parameterise SeenSet (`TypedSeenSet<T>`); migrate
  the two single-pointer-kind walkers (`forceValueDeep`,
  `getDerivations::Done`) to `TypedSeenSet<Value>` /
  `TypedSeenSet<Bindings>`; switch underlying container to
  `boost::unordered_flat_set` per the project's strong preference
  for boost flat containers over STL ordered/unordered.

All three reviewed via the full Pass A/B/C/D chain:
- Pass A (adversarial): 4 fixes amended (rl-next, banner, public/
  private symmetry, Bindings forward-decl)
- Pass B (/code-review): 1 fix amended (static_assert in primNumeric);
  1 efficiency follow-up folded into NixOS#229 (boost-flat container)
- Pass C (clang-tidy, sequential per shard): no regressions; all
  seven shards exhibit only the 5 known pre-existing master errors
  (4× rapidcheck/Gen.hpp, 1× libcmd/network-proxy.cc)
- Pass D (`nix build -L .`): green

Two cross-shard items remain blocked on libutil landing upstream
before they can land on libstore (NixOS#167 extension to local-store.cc
and derivations.cc; NixOS#124 extension to daemon.cc). Documented in
FOLLOWUPS.md.

libexpr cleanup-branch tip: `76b6808f0`.

No push.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ConnorBaker added a commit to ConnorBaker/nix that referenced this pull request May 24, 2026
Six sites previously open-coded the same two magic numbers with no
shared rationale: 65536 in serialise.cc::Source::drainInto,
tarfile.cc::defaultBufferSize (used in two ctors), file-system.cc::
writeFile, file-descriptor.cc::drainFD and copyFdRange; and 32 * 1024
in compression.cc::ChunkedCompressionSink::outbuf and the
BufferedSink/BufferedSource defaults in serialise.hh.

Add nix/util/io-buffer-sizes.hh with two constants:
  - kDefaultIOBlockSize = 65536 — page-multiple block size for
    streaming I/O between Source/Sink and the kernel; used by
    drainInto's pump array, by the libarchive wrapper's default
    read/write buffer, and by writeFile/drainFD/copyFdRange.
  - kBufferedStreamSize = 32 * 1024 — buffer size for the
    chunked-codec inner loop and the BufferedSink/BufferedSource
    defaults; half of kDefaultIOBlockSize so the codec state-machine
    amortises across multiple iterations per upstream block.

Each constant carries a docblock explaining the rationale rather
than leaving a bare integer literal at every site.

Scope is intentionally narrow. Out of scope:
  - tarfile.cc's 128 * 1024 raw-block buffer is left alone — its
    rationale is libarchive block alignment, not page size.
  - PosTable's linesCacheCapacity = 65536 is left alone — line
    count, not bytes.
  - libstore's local-store.cc and derivations.cc 65536 literals are
    cross-shard; they belong on the libstore branch and are queued
    as a NixOS#167 follow-up.

Public API: io-buffer-sizes.hh ships via install_headers; the
BufferedSink / BufferedSource default-argument values are unchanged
(numerically identical), so the ABI of those constructors is
preserved.

Catalog candidate NixOS#167.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ConnorBaker added a commit to ConnorBaker/nix that referenced this pull request May 25, 2026
… audit

The post-Batch-G adversarial audit asked whether claimed-unfiled
opportunities were genuinely untracked or sub-scope of existing
candidates. The auditor found three of my eight "unfiled" claims
were wrong — already covered by NixOS#190 (prim_fetchTree), NixOS#108
(mkLazyValueThunk), or NixOS#4/NixOS#57 (proto-helper macro hygiene). The
remaining five lacked tracking numbers and lived only in commit
bodies, FIXMEs, or buried Branch-line prose. File them as
proper candidate entries:

NixOS#234 — Store::signPathInfo / signRealisation re-read every
  secret-key file from disk on every signing call. NixOS#100's
  helper-only landing intentionally excluded the cache; the
  FIXME comment in store-api.cc is the canonical pointer but
  no candidate tracked the lift. Filed in
  12-libutil-libstore-core-extras.md.

NixOS#235 — addPermRoot GC-root-naming has three behavioural
  divergences across the two legacy CLI sites that NixOS#91's helper
  extraction deliberately left unresolved (counter-increment
  timing, absPath timing, printGCWarning gating). NixOS#91's Branch
  line names the deferral but no separate candidate tracked
  the audit work needed before substitution. Filed in
  11-legacy-cli.md.

NixOS#236 — CmdHash is the only getCommandsFor-eligible
  NixMultiCommand that can't migrate without a registry-with-
  args mechanism. NixOS#93's Branch line names this as deferred but
  no separate candidate tracked it. Two paths sketched: per-
  format subclass split or registry-with-args extension. Filed
  in 11-legacy-cli.md.

NixOS#237 — Two libstore call sites still use bare 65536 literals
  for I/O buffer sizing (local-store.cc::addToStoreFromDump
  and derivations.cc::Derivation::unparse) where NixOS#167's
  kDefaultIOBlockSize is the canonical name. Cross-shard,
  blocked on libutil upstream merge per Batch-E ledger. Now
  has a tracking number beyond the FOLLOWUPS-ledger entry.
  Filed in 17-cross-cutting.md.

NixOS#238 — GitArchiveInputScheme::isLocked carries an in-source
  FIXME proposing Git tree hashes as the locking primitive
  instead of NAR hashes. Predates NixOS#51 and is independent of it
  (different function, different scope). Now has a tracking
  number rather than living only in source. Filed in
  19-eval-core-fetcher-lookup-json.md.

STATUS.md: catalog count bumped to 238 + 44; added a sentence
to the "Catalog split into 25 sections" recently-completed
entry explaining the NixOS#234-NixOS#238 origin.

FOLLOWUPS.md: new "Batch G follow-ups (adversarial-audit
second pass)" subsection with all five strikethroughs naming
the filed candidates and their homes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ConnorBaker added a commit to ConnorBaker/nix that referenced this pull request May 25, 2026
…ixOS#240

User-mandated removal of two cross-shard violations on the
libstore cleanup branch. Both commits combined a libutil header
addition with a libstore consumer migration in a single commit,
which would have prevented the two branches from landing
independently upstream. The audit also turned up a third commit
(the rl-next entry for NixOS#119) that lived on libstore but should
follow the API change to libutil.

Three commits dropped from cleanup-libstore via non-interactive
rebase:
- aa00e07 — NixOS#119 BaseSetting<T>::overrideIfSet header +
  HttpBinaryCacheStore consumer
- ae7167e — NixOS#221 parseSettingTokens / renderSettingTokens
  header lift + globals.cc consumer
- b9a750f — NixOS#119 rl-next entry

The libutil header halves were replayed as two single-shard
commits on cleanup-libutil (f2ead5163 and 1ac18fe9a) plus the
rl-next entry (fdb46ab33). The libstore consumer halves were
dropped outright and re-filed here as queued candidates:

NixOS#239 — HttpBinaryCacheStore::makeRequest should adopt
  BaseSetting<T>::overrideIfSet once NixOS#119's libutil API lands
  upstream. Trivial; blocked-on-merge.

NixOS#240 — libstore/globals.cc's parseStoreReferenceCollection /
  renderStoreReferenceCollection should adopt the lifted libutil
  helpers once NixOS#221's libutil API lands upstream. Trivial;
  blocked-on-merge.

Same shape as the existing Batch-E cross-shard extensions
(NixOS#167, NixOS#124).

STATUS.md cleanup-branches table:
- libstore row: removed NixOS#119/NixOS#221 cross-shard claims; added a
  Cross-shard cleanup paragraph documenting what was dropped
  and where the consumer halves are tracked. Tip now ec50b5b
  (was b9a750f).
- libutil row: added NixOS#119/NixOS#221 (header-only halves) to the
  candidates list; added a Cross-shard cleanup note. Tip now
  fdb46ab33 (was da1e0d7).

Catalog count bumped from 238+44 to 240+44.

`nix build -L .` post-rebase green on both branches.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ConnorBaker added a commit to ConnorBaker/nix that referenced this pull request May 25, 2026
…+ add FOLLOWUPS preamble disclaimer

Manual sweep of every SHA-shaped token across doc/inventory/.
Built reachable index from master..HEAD per worktree (7 cleanup
branches) plus master and the doc branch. Cross-checked 85
distinct cited SHAs against the index; 53 were dangling (cited
but not reachable from any branch HEAD). Classified each:

(a) Historical-narrative entries in STATUS chronological log:
    legitimate; disclaimed by the Current tip SHAs block at the
    document tail.
(b) FOLLOWUPS [x] strike-through items recording past-completion
    state ("Done; new tip X"): legitimate at write-time but
    became stale when later rebases bumped the SHAs. Added a
    one-time "SHA citation note" to the FOLLOWUPS preamble
    pointing readers at STATUS's Current tip SHAs block before
    acting on any historical SHA.
(c) Candidate Branch lines explicitly framed as "former commit"
    / "landed and reverted" / "was dropped" / "post-NixOS#224-reword
    cascade": legitimate historical-supersession.
(d) Stale-as-current citations: TWO found, both fixed in this
    commit.

Stale-as-current fixes:

1. candidates/15-globals-settings.md NixOS#141 Branch line claimed
   `static GcRootNamer gcRootNamer;` was "introduced earlier on
   this branch in `43a4225b6` (NixOS#142's vicinity)". `43a4225b6`
   is dangling (pre-rebase SHA). The actual commit on
   cleanup-nix-cli is `6a237f8e9` ("nix: extract GcRootNamer
   helper for --add-root counter logic"). Refreshed.

2. FOLLOWUPS.md Batch-E "Cross-shard NixOS#167 extension" item
   line 373 cited the libutil cleanup branch as having "tip
   `2c9005abe`" — dangling (pre-NixOS#163-revert SHA). The current
   tip is `834a52639`, but rebases may bump this further;
   refreshed to point at the Current tip SHAs block in STATUS
   so the reference is self-updating.

Added a "SHA citation note" to FOLLOWUPS.md's preamble (just
above the `---` rule before Batch A). The note: strike-through
items record SHAs that were current at completion time and
many have since been rewritten; verify against the Current tip
SHAs block before acting on any historical SHA. Forward-looking
("active") items should always cite current SHAs; a stale SHA
on an active item is a bug.

No code changes. The lesson learned ("re-grep doc/inventory
for stale SHAs after every history rewrite of a catalog-tracked
branch") is now baked into the FOLLOWUPS preamble — future
agents that rebase a cleanup branch will see the discipline
note.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
angerman added a commit to angerman/nix that referenced this pull request Aug 5, 2026
…les(codegen)

Rule 0 — S0.3 (NixOS#165) commits the architecture from the S0.1+S0.2 data (git-noted
d12d11e/746fbc219). Phase S0 (de-risk) COMPLETE → GO.

DECISION — two collectors share one safepoint, split by axis:
- RSS exploit (S2) = BARTLETT mostly-copying. At peak only 3.6% (M5) / 12.5% (firefox)
  of live cells are conservative-C-stack-only, so pin-those + compact-the-rest captures
  ~87-96% of the reclaim with NO handle migration. The mid-eval mark-sweep ALREADY runs
  at exitDepth>0 (value-stack consistent + conservative C-stack scan + remembered set) —
  it's non-moving only because moving was gated off. S2.1's real work is the MOVER, not
  new safepoint plumbing.
- CPU exploit (S3) = precise handles + JIT stack maps (codegen can't use conservative
  pinning of hot frames). ~7 hot primops to wrap (~25 LoC) + JIT map emission.

RE-SEQUENCED: RSS path (S1.3 verify-safepoint -> S1.4 roots-complete -> S2.1 mover ->
S2.2 -> S2.3) DECOUPLES from codegen path (S1.1 handles -> S1.2 migrate -> S3.1 maps ->
S3.2 -> S3.3); after S0.3 they run in PARALLEL. (NixOS#152 now also blockedBy NixOS#167.)

Open refinements for S2.1 (don't block S0.3): pin at 128B LINE granularity; both-
reachable cells must pin (true pinned >= measured conservativeOnly); the mover must
RELOCATE via the remembered set (S0.2: dirty-list marks 61-181K cells precise misses).

Realized estimate: Bartlett ~90% capture -> firefox ~1.15-1.25x / M5 ~1.4-1.5x RSS
(better than the original envelope). Decision doc:
lode/SAFEPOINT_FOUNDATION_S0.3_DECISION_2026-06-24.md

Copyright (c) 2026 Moritz Angermann <[email protected]>, Input Output
Group. SPDX-License-Identifier: Apache-2.0
angerman added a commit to angerman/nix that referenced this pull request Aug 5, 2026
…t migration target

Rule 0 — S1.2 (NixOS#167) increment + a measure-first redirect. Adds the missing handle
primitive and records WHERE the precise migration must actually go. Additive (new
primitive + tests; no production code uses it yet → default unaffected; gc-root-handles
is in --brute).

PRIMITIVE: GcRootRange(Value* data, size_t n) — RAII range-root for a contiguous Value
array, walked+rewritten in place like GcRoot. The canonical target is the primop
`Value args[8]` (a C++-LOCAL copy popped off the value-stack — vm.cc OP_CALL_PRIMOP — so
NOT otherwise a precise root). +/- tests in gc-root-handles.cc (testRangeRelocation):
relocating visitor rewrites every element, scalar untouched, pops n on dtor. ALL OK.

MEASURE-FIRST FINDING (redirects the migration): wiring GcRootRange onto the primop
args[] (gated NIX_V3_PRECISE_ARGS) was byte-id on hello BUT (a) did NOT reduce the
mid-eval conservativeOnly fraction (firefox 12.5% unchanged with vs without) → the
primop args[] are NOT the conservative-only pin source; and (b) regressed iterative-force
under moving stress (21/22). So the pins the S2.3 RSS pivot needs to remove come from
PER-PRIMOP INTERNAL live-across-callback locals (foldl' acc, filter `kept`, etc. — the
S0.2 census targets), NOT the args array. The args-rooting wiring is reverted (kept the
primitive); it's necessary-for-completeness later (args dangle once the conservative scan
is removed) but its iterative-force interaction is deferred to that completeness phase.

NEXT (S1.2 redirected): root the ~7 re-entrant primops' INTERNAL accumulators/containers
(GcRoot for single Values, GcRootRange for vectors) + re-read raw pointers after
callbacks; re-measure conservativeOnly per migration → iterate toward ~0 → then remove
the conservative C-stack scan (→ no scattered pins → blocks free → the RSS win).

Copyright (c) 2026 Moritz Angermann <[email protected]>, Input Output
Group. SPDX-License-Identifier: Apache-2.0
angerman added a commit to angerman/nix that referenced this pull request Aug 5, 2026
Rule 0 — S1.2 (NixOS#167): first real per-primop precise-root migration, establishing the
template the other re-entrant primops follow.  Behavior-preserving; validated byte-id
(foldl' sum + hello.drvPath) + full --brute 22/22 (default).

foldl' holds op / acc / the list Value live ACROSS callClosure2 (re-enters the VM).
Migration: GcRoot(op), GcRoot(acc), GcRoot(args[2]) make them precise + rewritable; the
list is RE-READ each iteration (args[2].asList()) instead of caching a raw `src` that
would dangle after a relocation (size cached once — stable across a relocation).  This
moves foldl's loop-carried roots from conservative-only to PRECISE, the prerequisite for
eventually removing the conservative C-stack scan (S2.3 pivot: scattered conservative
pins block whole-block-frees → no RSS reclaim).

THE TEMPLATE (for filter/partition/concatMap/groupBy/genericClosure/__foldlMap + the
primops firefox/M5 actually use): root every v3 Value held across a callback (GcRoot for
scalars, GcRootRange for vectors) + RE-READ raw cell pointers after each callback.
firefox conservativeOnly (12.5%) drops INCREMENTALLY as each used primop migrates; a
clean per-primop delta needs a workload dominated by that primop.  Broad (every
re-entrant site + the FFI bridge) → multi-week; this lands the pattern + the first site.

Copyright (c) 2026 Moritz Angermann <[email protected]>, Input Output
Group. SPDX-License-Identifier: Apache-2.0
angerman added a commit to angerman/nix that referenced this pull request Aug 5, 2026
…ccumulation)

Rule 0 — S1.2 (NixOS#167): two more re-entrant primops migrated to precise roots via the
template. Byte-id (filter→499, foldl'+map fusion→9900, hello/git/firefox.drvPath) +
full --brute 22/22. Behavior-preserving (conservative scan still on); moves these
primops' loop-carried roots from conservative-only to PRECISE.

__foldlMap (Rules 1-3, like foldl'): GcRoot(op/acc/f/list); re-read the list each
iteration; fx is forced+consumed within the iteration (Rule 3) so no extra root.

filter (Rule 4 made CLEAN via index-accumulation): a std::vector<Value> of kept elements
would hold raw copies a relocation leaves stale (not GC-walked) AND re-rooting a growing
vector is the Rule-4 hard case.  Since filter SELECTS source elements, accumulate INDICES
(plain ints — no relocation hazard) into the GcRoot'd source list, then rebuild by re-read
(Rule 2).  Same elements, same order → byte-identical.  This is the clean sub-pattern for
SELECT-style primops (filter/partition); concatMap/groupBy compute NEW values and will
need the harder growing-Value-vector handling (re-root after growth, or accumulate into a
rooted v3 list cell).

Migrated so far: foldl', __foldlMap, filter.  Remaining: partition (index pattern),
concatMap/groupBy (Rule-4 hard), + the primops firefox/M5 use heavily (map/mapAttrs/
listToAttrs/...) + the FFI bridge → then remove the conservative scan.

Copyright (c) 2026 Moritz Angermann <[email protected]>, Input Output
Group. SPDX-License-Identifier: Apache-2.0
angerman added a commit to angerman/nix that referenced this pull request Aug 5, 2026
…tMap (compute)

Rule 0 — S1.2 (NixOS#167): both Rule-4 sub-patterns now established + two more primops
migrated. Byte-id (partition.right→3, concatMap→6, hello/git/firefox.drvPath) + full
--brute 22/22 + GcRootVec unit test. Behavior-preserving; gate-free.

GcRootVec (new primitive, gc_root.hh/cc + test): roots a GROWING std::vector<Value>
accumulator by registering the VECTOR and walking its CURRENT data()/size() each GC —
REALLOC-SAFE + covers post-construct growth (GcRootRange's fixed data+n can't). The
compute-style Rule-4 tool. +/- test: 64-element vector (forces reallocs), relocating
visitor rewrites ALL current elements.

partition (Rule 4 SELECT-style, like filter): accumulate two INDEX vectors (no
relocation hazard) into the GcRoot'd source; rebuild by re-read. Byte-identical.

concatMap (Rule 4 COMPUTE-style — produces NEW sub-lists, indices don't apply): GcRoot
fn + list; GcRootVec the result accumulator `all`; re-read source each iter. The inner
sub-list copy has no callback so `r` is stable + dead after (elements live on in rooted
`all`).

Migrated: foldl', __foldlMap, filter, partition, concatMap. Both Rule-4 sub-patterns
proven (index for select; GcRootVec for compute). Remaining: groupBy (compute, map of
vectors), genericClosure, + firefox/M5 hot primops (map/mapAttrs/listToAttrs) + FFI
bridge → then remove the conservative scan.

Copyright (c) 2026 Moritz Angermann <[email protected]>, Input Output
Group. SPDX-License-Identifier: Apache-2.0
angerman added a commit to angerman/nix that referenced this pull request Aug 5, 2026
…ure (hard case)

Rule 0 — S1.2 (NixOS#167): groupBy migrated; genericClosure deferred with a documented plan.
Byte-id (groupBy .big→3, names→2, hello/git/firefox.drvPath) + full --brute 22/22.

groupBy (Rule 4 SELECT-style, like filter/partition): buckets hold SOURCE elements, so
key the buckets by INDEX (std::unordered_map<string, vector<uint32_t>>) not Value copies;
GcRoot keyFn + the source list; the key is converted to std::string in-iteration (Rule 3,
no held root); rebuild each bucket from the rooted source by re-read.  Byte-identical.

genericClosure DEFERRED (the hardest primop): its dedup set is std::set<Value> whose keys
REFERENCE ARENA CELLS — the existing code comment notes it's only GC-safe because no
collection fires mid-BFS today (gen-major at exitDepth==0).  Under mid-eval moving GC
those keys would relocate, dangling AND breaking the set's ordering.  Plus a std::deque
work-list + a std::vector result (both compute-style).  Migrating it needs a stable-key
rewrite (key the set by value-CONTENT — int64/double/string copy per valueLessHelper —
not the cell pointer) + GcRootVec(result) + rooting the deque.  The conservative scan
still covers it, so it's safe until the scan is removed (the final step) — deferred to
just before that, with the plan recorded here.

Migrated (6): foldl', __foldlMap, filter, partition, concatMap, groupBy.  Toolkit
complete (GcRoot/GcRootRange/GcRootVec) + both Rule-4 sub-patterns proven.  Remaining:
the firefox/M5-hot map/mapAttrs/listToAttrs (next), genericClosure (stable-key rewrite),
+ FFI bridge → then remove the conservative scan.

Copyright (c) 2026 Moritz Angermann <[email protected]>, Input Output
Group. SPDX-License-Identifier: Apache-2.0
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