diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,10 @@
 # Changelog
 
+## 0.14.0.0 - 2026-11-27
+
+- **`narPrefix` in `NovaCache.NAR.Stream` parses a NAR that more input follows: it finishes at the root node's close, without awaiting more input, with the bytes after that close. `NarStep` takes the type of the result `NarDone` carries, which is `()` from `narStream`.** The parser accepted an archive only at the end of its input and failed on any byte after the root node, so a NAR inside a stream that goes on past it, as the worker protocol sends one followed by the rest of the request, could not be parsed without knowing its length first. Upstream's `parseDump` at 2.36.0 reads a NAR from such a stream by stopping at the root node's close and leaving what follows to the stream's next reader, and `narPrefix` does the same, through the node parsing `narStream` uses. The bytes it finishes with are a suffix of the last chunk fed, so the archive is every byte fed before them, which is what a caller hashes and counts. An input that ends before the root node's close fails as truncated, as `narStream` fails it. `narStream` still requires the end of input after the root node, and a consumer matching its `NarDone` now matches `NarDone ()`.
+- **The NAR parser refuses what upstream's parser refuses past the grammar: a keyword over 32 bytes, an entry name over 255, a symlink target over 4095, a symlink target that is empty or holds NUL, and a node 64 directories deep. `serialiseFromPath` and `withNarSource` refuse an entry 64 levels below the root with `path '<path>' exceeds maximum NAR directory depth of 64`. `maxWireStringBytes` and `narStreamBounded` go.** Upstream's `parseDump` at 2.36.0 reads each keyword with a 32-byte limit, a name with 255 and a target with 4095, the magic with its own 13 and the executable marker with 0, refusing a longer declared length from its prefix before the bytes it declares are read; it refuses an empty target or one holding NUL once read, and a node at depth 64, the root at 0, once its entry's `node` keyword is read. The parser held every structural string to 64 KiB instead and checked neither targets nor depth, so it accepted archives upstream refuses, and `narStream`, `narPrefix` and `deserialise` now refuse them at the same points, naming the string and its limit or the entry. Upstream's dump refuses a tree that deep as well, so the walk does too, before reading the entry's status; it still archives a name or a target past its limit, as upstream's dump does, and such an archive does not parse. Every structural string now has a limit of at most 4095 bytes, so the 64 KiB bound never applied: `narStream` holds no bound of its own, and `deserialise` drives it as it is. The depth limit is exported as `narMaxDepth`.
+
 ## 0.13.0.0 - 2026-11-16
 
 - **The server removes entries and NARs itself: `DELETE /<hash>.narinfo` removes an entry, `POST /reclaim` removes the NARs no narinfo names and the abandoned multipart uploads, and `GET /reclaim` lists what it would remove.** No request removed anything, and the one removal path, `reclaim-nars --delete`, ran on the host against the store directory and shared no lock with the server, so it raced the server twice: a narinfo that arrived after its listing, for a NAR past the minimum age, lost that NAR, as upstream's `nix copy` can send one after skipping a NAR the cache holds, and a NAR uploaded again after its listing was removed despite its new modification time. The README asked for no push in progress during a run. The server now orders its removals against its uploads through a gate each `FileStore` carries: a narinfo upload holds it, alongside other uploads, from the check of its NAR through its write, each rename into `nar/` holds it for the rename, and a reclaim or a narinfo removal holds it alone, the reclaim from its scan through its last removal. So a narinfo is never stored naming a NAR a reclaim removes, and a NAR that arrives during a reclaim lands after it. A removal waiting for the gate lets nothing new take it, so a stream of uploads cannot hold it off; uploads wait while a reclaim reads the store, and no request body is read under the gate. A run's rules are unchanged: a minimum age of two weeks by modification time (`?min-age-hours=N` sets another, and any other query is refused with 400), a narinfo that cannot be resolved or a store with NARs and no narinfo blocks the run with 409, and a removal that fails makes the answer a 500. All three requests need the write key, which can already replace any entry. `DELETE` leaves the NAR to the reclaim, which removes it once nothing names it, as attic's garbage collection reaps a NAR once no object refers to it. A narinfo uploaded for a path the cache holds replaces the entry, which lets a push store a smaller encoding of the same NAR, and the NAR it displaces is reclaimed the same way. Upstream ships no garbage collection for binary caches, so there is no server behavior to match, only its client's: `BinaryCacheStore::narFromPath` turns a missing NAR into `SubstituteGone`, which a substitution logs as a warning before it tries the next substituter (2.35.6), so a client holding a narinfo whose NAR was removed sees a miss, not a failure. One server serves a store directory.
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -21,13 +21,13 @@
 ## Installation
 
 ```cabal
-build-depends: nova-cache >= 0.13 && < 0.14
+build-depends: nova-cache >= 0.14 && < 0.15
 ```
 
 The codecs are separate sublibraries, named alongside the main library:
 
 ```cabal
-build-depends: nova-cache:{nova-cache, xz, zstandard} >= 0.13 && < 0.14
+build-depends: nova-cache:{nova-cache, xz, zstandard} >= 0.14 && < 0.15
 ```
 
 libbz2 and libzstd are bundled. liblzma comes from the `xz` package, which
diff --git a/nova-cache.cabal b/nova-cache.cabal
--- a/nova-cache.cabal
+++ b/nova-cache.cabal
@@ -4,7 +4,7 @@
 -- 3.0 an in-package component name shadowed its external namesake
 -- (the hazard the zstandard library's name dodges, documented there).
 name:               nova-cache
-version:            0.13.0.0
+version:            0.14.0.0
 synopsis:           Nix binary cache protocol: NAR, narinfo, signing and a WAI server
 description:
   The Nix binary cache protocol in Haskell: nix-base32, NAR serialization
@@ -201,6 +201,7 @@
     , containers          >= 0.6 && < 0.9
     , crypton             >= 1.1 && < 2
     , directory           >= 1.3.1.0 && < 1.4
+    , filepath            >= 1.4.100 && < 1.6
     , http-types          >= 0.12 && < 0.13
     , nova-cache
     -- 2.12 dropped InsufficientCoverage, leaving the four Result
diff --git a/src/NovaCache/NAR.hs b/src/NovaCache/NAR.hs
--- a/src/NovaCache/NAR.hs
+++ b/src/NovaCache/NAR.hs
@@ -58,9 +58,10 @@
   ( NarEvent (..),
     NarStep (..),
     isWindowsHazardName,
+    narMaxDepth,
     narPad,
     narPadOf,
-    narStreamBounded,
+    narStream,
     tokContents,
     tokDirectory,
     tokEntry,
@@ -114,7 +115,11 @@
 -- Serialization (pure Builder pipeline)
 -- ---------------------------------------------------------------------------
 
--- | Serialise a 'NarEntry' to NAR binary format.
+-- | Serialise a 'NarEntry' to NAR binary format.  Any tree serialises,
+-- including one 'deserialise' refuses: a name the grammar refuses, a
+-- name, a symlink target or a nesting past the limits
+-- "NovaCache.NAR.Stream" holds archives to, or a symlink target that
+-- is empty or holds NUL.
 serialise :: NarEntry -> ByteString
 serialise = BL.toStrict . B.toLazyByteString . buildArchive
 
@@ -178,18 +183,16 @@
 
 -- | Deserialise NAR binary format to a 'NarEntry'.
 --
--- Drives "NovaCache.NAR.Stream" over the whole input, folding its
--- events back into a tree.  The structural-string bound is the input's
--- own length - a wire string cannot outgrow its container - so this
--- accepts exactly what the dedicated whole-input parser accepted,
--- with no extra ceiling.  Contents events are slices of the input, so
+-- Drives 'narStream' over the whole input, folding its events back
+-- into a tree, so it accepts exactly the archives that parser accepts,
+-- limits included.  Contents events are slices of the input, so
 -- single-chunk files rebuild by sharing, not copying.
 deserialise :: ByteString -> Either String NarEntry
-deserialise input = drive True (narStreamBounded (fromIntegral (BS.length input))) [] Nothing
+deserialise input = drive True narStream [] Nothing
   where
     drive !firstFeed step !stack !root = case step of
       NarFail err -> Left err
-      NarDone -> case (stack, root) of
+      NarDone () -> case (stack, root) of
         ([], Just entry) -> Right entry
         _ -> Left malformedEventStream
       NarYield event continue -> do
@@ -211,7 +214,7 @@
 
 -- | Apply one event to the frame stack.  The machine already validated
 -- the grammar, so the mismatch arms are unreachable through
--- 'narStreamBounded'; they fail closed rather than building partially.
+-- 'narStream'; they fail closed rather than building partially.
 applyEvent :: NarEvent -> [BuildFrame] -> Maybe NarEntry -> Either String ([BuildFrame], Maybe NarEntry)
 applyEvent event stack root = case (event, stack) of
   (EventRegularBegin isExec _declaredSize, _) ->
@@ -412,8 +415,12 @@
 -- classifies each path as regular file, directory, or symlink and
 -- delegates to pure constructors.  Any other type (a FIFO, a socket, a
 -- device) is refused with the 'IOException' @file \'\<path\>\' has an
--- unsupported type@, as upstream's dump refuses it.  A failure of an
--- access 'WalkAccess' names throws t'NarWalkError'.
+-- unsupported type@, as upstream's dump refuses it.  So is an entry
+-- 'narMaxDepth' levels below the root, before its status is read, with
+-- @path \'\<path\>\' exceeds maximum NAR directory depth of 64@, as
+-- upstream's dump refuses it and as no parser here would accept its
+-- archive.  A failure of an access 'WalkAccess' names throws
+-- t'NarWalkError'.
 serialiseFromPath :: FilePath -> IO NarEntry
 serialiseFromPath = serialiseFromPathOpts defaultSerialiseOptions
 
@@ -424,20 +431,22 @@
 
 -- | 'serialiseFromPath' with every knob explicit.
 serialiseFromPathOpts :: SerialiseOptions -> FilePath -> IO NarEntry
-serialiseFromPathOpts opts path = walkPath opts =<< encodeFS path
+serialiseFromPathOpts opts path = walkPath opts 0 =<< encodeFS path
 
--- | Walk one platform-native path.  The walk runs on 'OsPath' so child
--- names reach the archive byte-true ('osPathBytes'); only the root
--- enters as 'FilePath', and the root's own name never appears in a
--- NAR.
-walkPath :: SerialiseOptions -> OsPath -> IO NarEntry
-walkPath opts path = do
-  kind <- entryType path
-  case kind of
-    RegularEntry -> buildRegularFile (soExecBit opts) path
-    DirectoryEntry -> buildDirectory opts path
-    SymlinkEntry -> NarSymlink <$> (symlinkTargetBytes =<< accessing WalkReadLink path (getSymbolicLinkTarget path))
-    UnsupportedEntry -> unsupportedType path
+-- | Walk one platform-native path at the given depth below the root.
+-- The walk runs on 'OsPath' so child names reach the archive byte-true
+-- ('osPathBytes'); only the root enters as 'FilePath', and the root's
+-- own name never appears in a NAR.
+walkPath :: SerialiseOptions -> Int -> OsPath -> IO NarEntry
+walkPath opts depth path
+  | depth >= narMaxDepth = tooDeep path
+  | otherwise = do
+      kind <- entryType path
+      case kind of
+        RegularEntry -> buildRegularFile (soExecBit opts) path
+        DirectoryEntry -> buildDirectory opts depth path
+        SymlinkEntry -> NarSymlink <$> (symlinkTargetBytes =<< accessing WalkReadLink path (getSymbolicLinkTarget path))
+        UnsupportedEntry -> unsupportedType path
 
 -- | An entry's type as the walk reads it: one of the three a NAR holds,
 -- or any other (a FIFO, a socket, a device).
@@ -487,14 +496,22 @@
   shownPath <- decodeFS path
   fail ("file '" ++ shownPath ++ "' has an unsupported type")
 
--- | Build a directory entry by recursively walking children.
-buildDirectory :: SerialiseOptions -> OsPath -> IO NarEntry
-buildDirectory opts path = do
+-- | Refuse an entry 'narMaxDepth' levels below the root, in upstream's
+-- words: its archive would not parse.
+tooDeep :: OsPath -> IO a
+tooDeep path = do
+  shownPath <- decodeFS path
+  fail ("path '" ++ shownPath ++ "' exceeds maximum NAR directory depth of " ++ show narMaxDepth)
+
+-- | Build a directory entry at the given depth by recursively walking
+-- children.
+buildDirectory :: SerialiseOptions -> Int -> OsPath -> IO NarEntry
+buildDirectory opts depth path = do
   resolved <- resolvedDirEntries (soCaseHack opts) path
   NarDirectory <$> traverse walkChild resolved
   where
     walkChild (entryName, diskName) = do
-      entry <- walkPath opts (path </> diskName)
+      entry <- walkPath opts (depth + 1) (path </> diskName)
       pure (entryName, entry)
 
 -- | A directory's children as (NAR name, on-disk name) pairs under the
@@ -768,7 +785,7 @@
 -- never contents.
 planSegments :: SerialiseOptions -> OsPath -> IO [NarSegment]
 planSegments opts path = do
-  pieces <- planNode opts path
+  pieces <- planNode opts 0 path
   pure (coalesce (PieceBytes (narStr tokMagic) : pieces))
 
 -- | Plan pieces before coalescing: structural builders, or a deferred
@@ -791,23 +808,25 @@
       let bytes = BL.toStrict (B.toLazyByteString pending)
        in if BS.null bytes then segments else SegmentBytes bytes : segments
 
--- | Plan one node, mirroring 'walkPath'.
-planNode :: SerialiseOptions -> OsPath -> IO [PlanPiece]
-planNode opts path = do
-  kind <- entryType path
-  case kind of
-    RegularEntry -> planRegular (soExecBit opts) path
-    DirectoryEntry -> planDirectory opts path
-    SymlinkEntry -> do
-      target <- symlinkTargetBytes =<< accessing WalkReadLink path (getSymbolicLinkTarget path)
-      pure [PieceBytes (buildNode (NarSymlink target))]
-    UnsupportedEntry -> unsupportedType path
+-- | Plan one node at the given depth, mirroring 'walkPath'.
+planNode :: SerialiseOptions -> Int -> OsPath -> IO [PlanPiece]
+planNode opts depth path
+  | depth >= narMaxDepth = tooDeep path
+  | otherwise = do
+      kind <- entryType path
+      case kind of
+        RegularEntry -> planRegular (soExecBit opts) path
+        DirectoryEntry -> planDirectory opts depth path
+        SymlinkEntry -> do
+          target <- symlinkTargetBytes =<< accessing WalkReadLink path (getSymbolicLinkTarget path)
+          pure [PieceBytes (buildNode (NarSymlink target))]
+        UnsupportedEntry -> unsupportedType path
 
 -- | Plan a directory.  Children are ordered by their NAR-name bytes -
 -- the same order 'buildNode' emits - not by on-disk order, which can
 -- differ on Windows where 'OsPath' sorts by UTF-16 units.
-planDirectory :: SerialiseOptions -> OsPath -> IO [PlanPiece]
-planDirectory opts path = do
+planDirectory :: SerialiseOptions -> Int -> OsPath -> IO [PlanPiece]
+planDirectory opts depth path = do
   resolved <- resolvedDirEntries (soCaseHack opts) path
   children <- traverse planChild (sortBy (comparing fst) resolved)
   pure
@@ -817,7 +836,7 @@
     )
   where
     planChild (entryName, diskName) = do
-      node <- planNode opts (path </> diskName)
+      node <- planNode opts (depth + 1) (path </> diskName)
       pure
         ( PieceBytes
             ( narStr tokEntry
diff --git a/src/NovaCache/NAR/Stream.hs b/src/NovaCache/NAR/Stream.hs
--- a/src/NovaCache/NAR/Stream.hs
+++ b/src/NovaCache/NAR/Stream.hs
@@ -6,9 +6,21 @@
 -- the same grammar incrementally: feed chunks as they arrive - from a
 -- download, a decompressor - and act on events as they complete.
 -- Regular-file contents pass through as slices of the fed chunks, so
--- memory is bounded by the largest structural wire string
--- ('maxWireStringBytes'), never by archive or file size.
+-- memory is bounded by the largest structural wire string, never by
+-- archive or file size.
 --
+-- 'narStream' parses an archive that is the whole input.  'narPrefix'
+-- parses one that more input follows, as a NAR is followed by the rest
+-- of a stream it is sent in, and finishes with the bytes after it.
+--
+-- Beyond the grammar, both refuse what upstream's parser refuses: a
+-- keyword over 32 bytes, an entry name over 255, a symlink target over
+-- 4095, a nonempty executable marker, an empty symlink target or one
+-- holding NUL, and a node 'narMaxDepth' levels deep.  A string over its
+-- limit is refused from its length prefix, before the bytes it declares
+-- are read, so the largest structural string held is a 4095-byte
+-- target.
+--
 -- The grammar lives here once: 'NovaCache.NAR.deserialise' is the
 -- whole-input instantiation of this machine, and the serialiser draws
 -- its wire vocabulary from the exports below, so the two directions
@@ -20,9 +32,11 @@
     -- * The machine
     NarStep (..),
     narStream,
-    narStreamBounded,
-    maxWireStringBytes,
+    narPrefix,
 
+    -- * Limits
+    narMaxDepth,
+
     -- * Entry-name safety
     checkEntryName,
     isWindowsHazardName,
@@ -137,100 +151,121 @@
   | EventDirectoryEnd
   deriving (Eq, Show)
 
--- | The machine's outward face.  Drive it by pattern matching: hand
--- 'NarAwait' the next chunk (the empty string means end of input, the
--- same convention as 'NovaCache.Store.writeNarStreaming' consumes), and
--- read events off 'NarYield' as they complete.  'NarDone' confirms the
--- archive ended exactly at the root node's close; anything else that
--- can go wrong is a 'NarFail'.
-data NarStep
-  = NarAwait !(ByteString -> NarStep)
+-- | The machine's outward face, finishing with a result of type @r@.
+-- Drive it by pattern matching: hand 'NarAwait' the next chunk (the
+-- empty string means end of input, the same convention as
+-- 'NovaCache.Store.writeNarStreaming' consumes), and read events off
+-- 'NarYield' as they complete.  'NarDone' ends a parse that succeeded:
+-- from 'narStream' it confirms the archive ended exactly at the root
+-- node's close, and from 'narPrefix' it carries the input after that
+-- close.  Anything else that can go wrong is a 'NarFail'.
+data NarStep r
+  = NarAwait !(ByteString -> NarStep r)
   | -- | The continuation is deliberately lazy: yielding is what hands
     -- control back to the consumer, and a strict field would force
     -- each step's successor at construction, materializing the whole
     -- fed chunk's event chain before the consumer acts on the first
     -- event.  Do not add a bang.
-    NarYield !NarEvent NarStep
-  | NarDone
+    NarYield !NarEvent (NarStep r)
+  | NarDone !r
   | NarFail !String
 
--- | The bound 'narStream' places on structural wire strings - tokens,
--- entry names, symlink targets; never file contents, which stream
--- through unaccumulated.  Real names fit a filesystem's 255-byte
--- component limit and targets its path limit, so 64 KiB is generous;
--- without some bound a hostile length prefix could demand an
--- arbitrary-size allocation from one 8-byte read.
-maxWireStringBytes :: Word64
-maxWireStringBytes = 65536
+-- | The parser for an archive that is the whole input, positioned at
+-- its start.  After the root node's close it awaits the end of input,
+-- and any byte before that end fails the parse.
+narStream :: NarStep ()
+narStream = archive archiveEnd
+  where
+    archiveEnd leftover
+      | BS.null leftover = NarAwait confirm
+      | otherwise = NarFail trailingBytes
+    confirm chunk
+      | BS.null chunk = NarDone ()
+      | otherwise = NarFail trailingBytes
+    trailingBytes = "trailing bytes after NAR root node"
 
--- | The parser, positioned at the start of an archive, holding
--- 'maxWireStringBytes' over structural strings.
-narStream :: NarStep
-narStream = narStreamBounded maxWireStringBytes
+-- | The parser for an archive that more input follows, positioned at
+-- its start.  It finishes at the root node's close, without awaiting
+-- more input, with the input after that close: a suffix of the last
+-- chunk fed, so the archive is every byte fed before that suffix.
+-- Upstream reads a NAR from a stream the same way, stopping at the root
+-- node's close and leaving what follows to the stream's next reader.
+-- The end of input before that close fails the parse, as for
+-- 'narStream'.
+narPrefix :: NarStep ByteString
+narPrefix = archive NarDone
 
--- | The largest structural-string bound 'narStreamBounded' honors:
--- the ceiling of 'Int' less alignment headroom, so a payload at the
--- bound still fits 'Int' together with its padding.
-structuralBoundCeiling :: Word64
-structuralBoundCeiling =
-  fromIntegral (maxBound :: Int) - fromIntegral (narAlignment - 1)
+-- ---------------------------------------------------------------------------
+-- Limits
+-- ---------------------------------------------------------------------------
 
+-- | The depth of the first node refused: the root is at depth 0 and an
+-- entry's node one deeper than its directory, so the deepest node
+-- accepted sits below a chain of 63 directories, the root included.
+-- Upstream refuses a node this deep both when it parses an archive and
+-- when it dumps a tree, to bound the stack its recursive walks run on,
+-- and the walk in "NovaCache.NAR" refuses one as its dump does.
+narMaxDepth :: Int
+narMaxDepth = 64
+
+-- | The longest keyword string read: every keyword is at most 10 bytes,
+-- and the slack keeps a short wrong string readable in the error.
+narMaxTag :: Word64
+narMaxTag = 32
+
+-- | The longest entry name, the format's own bound, independent of any
+-- host's name limit.
+narMaxName :: Word64
+narMaxName = 255
+
+-- | The longest symlink target, the format's own bound, independent of
+-- any host's path limit.
+narMaxTarget :: Word64
+narMaxTarget = 4095
+
+-- | The executable marker's length: its value is always the empty
+-- string, so a marker declaring any bytes is refused before they are
+-- read.
+narMaxExecutableMarker :: Word64
+narMaxExecutableMarker = 0
+
 -- ---------------------------------------------------------------------------
 -- Parser
 -- ---------------------------------------------------------------------------
 
 -- | A parse state waiting for its share of the input: apply it to the
 -- unconsumed bytes to proceed.
-type Continue = ByteString -> NarStep
+type Continue r = ByteString -> NarStep r
 
--- | 'narStream' with the structural-string bound explicit.
--- 'NovaCache.NAR.deserialise' passes its whole input's length - a
--- string cannot outgrow its container, so the strict parser accepts
--- exactly what it always accepted - while streaming callers keep the
--- documented default.
-narStreamBounded :: Word64 -> NarStep
-narStreamBounded bound =
-  expectWire limited "archive magic" tokMagic (parseNode limited archiveEnd) BS.empty
-  where
-    -- Declared lengths are compared in Word64 and narrowed only below
-    -- the bound; 'wireString' then demands the narrowed length plus
-    -- its padding in Int, so the bound must sit far enough below Int's
-    -- ceiling that the padded sum cannot wrap.
-    limited = min bound structuralBoundCeiling
-    archiveEnd leftover
-      | BS.null leftover = NarAwait confirm
-      | otherwise = NarFail trailingBytes
-    confirm chunk
-      | BS.null chunk = NarDone
-      | otherwise = NarFail trailingBytes
-    trailingBytes = "trailing bytes after NAR root node"
+-- | Parse the archive magic and the root node, then continue with the
+-- input after the root node's close.  The magic is held to its own
+-- length, so a longer string is refused from its length prefix.
+archive :: Continue r -> NarStep r
+archive k =
+  expectWire (fromIntegral (BS.length tokMagic)) "archive magic" tokMagic (parseNode 0 k) BS.empty
 
--- | Parse one node and continue.
-parseNode :: Word64 -> Continue -> Continue
-parseNode bound k =
-  expectWire bound "node opening" tokLParen
-    $ expectWire bound "type keyword" tokType
-    $ wireString bound "node type" dispatch
+-- | Parse one node at the given depth and continue.
+parseNode :: Int -> Continue r -> Continue r
+parseNode depth k =
+  expectTag "node opening" tokLParen
+    $ expectTag "type keyword" tokType
+    $ wireString narMaxTag "node type" dispatch
   where
     dispatch kind
-      | kind == tokRegular = parseRegular bound k
-      | kind == tokSymlink = parseSymlink bound k
-      | kind == tokDirectory = parseDirectory bound k
+      | kind == tokRegular = parseRegular k
+      | kind == tokSymlink = parseSymlink k
+      | kind == tokDirectory = parseDirectory depth k
       | otherwise = failWith ("unknown NAR entry type: " ++ show kind)
 
 -- | Parse a regular file node: optional executable flag, then contents
 -- streamed through as chunk events.
-parseRegular :: Word64 -> Continue -> Continue
-parseRegular bound k = wireString bound "regular-node keyword" body
+parseRegular :: Continue r -> Continue r
+parseRegular k = wireString narMaxTag "regular-node keyword" body
   where
     body tok
       | tok == tokExecutable =
-          -- The format fixes the executable marker's value as the
-          -- empty string; upstream rejects a nonempty value.
-          wireString bound "executable marker" $ \marker ->
-            if BS.null marker
-              then expectWire bound "contents keyword" tokContents (contentsOf True)
-              else failWith ("executable marker must be empty, got: " ++ show marker)
+          wireString narMaxExecutableMarker "executable marker" $ \_ ->
+            expectTag "contents keyword" tokContents (contentsOf True)
       | tok == tokContents = contentsOf False
       | otherwise =
           failWith ("expected 'executable' or 'contents' in regular, got: " ++ show tok)
@@ -244,12 +279,12 @@
       exactly (narPadOf size) "file contents padding" $ \padding ->
         if BS.any (/= 0) padding
           then failWith nonzeroPadding
-          else expectWire bound "node closing" tokRParen $ \leftover ->
+          else expectTag "node closing" tokRParen $ \leftover ->
             NarYield EventRegularEnd (k leftover)
 
 -- | Yield contents slices until the declared size is consumed.  Slices
 -- are substrings of the fed chunks; nothing accumulates.
-streamContents :: Word64 -> Continue -> Continue
+streamContents :: Word64 -> Continue r -> Continue r
 streamContents remaining k leftover
   | remaining == 0 = k leftover
   | BS.null leftover = NarAwait feed
@@ -265,35 +300,53 @@
       | otherwise = streamContents remaining k chunk
 
 -- | Parse a symlink node.  The target is carried verbatim: upstream
--- imposes no text encoding on it.
-parseSymlink :: Word64 -> Continue -> Continue
-parseSymlink bound k =
-  expectWire bound "target keyword" tokTarget $
-    wireString bound "symlink target" $ \target ->
-      expectWire bound "node closing" tokRParen $ \leftover ->
-        NarYield (EventSymlink target) (k leftover)
+-- imposes no text encoding on it, and refuses only an empty one or one
+-- holding NUL, before the node's closing.
+parseSymlink :: Continue r -> Continue r
+parseSymlink k =
+  expectTag "target keyword" tokTarget $
+    wireString narMaxTarget "symlink target" checked
+  where
+    checked target
+      | BS.null target = failWith "empty NAR symlink target"
+      | BS.elem 0 target = failWith ("NAR symlink target holds NUL: " ++ show target)
+      | otherwise =
+          expectTag "node closing" tokRParen $ \leftover ->
+            NarYield (EventSymlink target) (k leftover)
 
--- | Parse a directory node: entries validated name by name as they
--- open, so a consumer can act on each entry before the next arrives.
-parseDirectory :: Word64 -> Continue -> Continue
-parseDirectory bound k leftover =
+-- | Parse a directory node at the given depth: entries validated name
+-- by name as they open, so a consumer can act on each entry before the
+-- next arrives.  An entry's node too deep is refused once its node
+-- keyword is read, before the node itself, where upstream refuses it.
+parseDirectory :: Int -> Continue r -> Continue r
+parseDirectory depth k leftover =
   NarYield EventDirectoryBegin (entries Nothing leftover)
   where
-    entries prev = wireString bound "directory token" (branch prev)
+    childDepth = depth + 1
+    entries prev = wireString narMaxTag "directory token" (branch prev)
     branch prev tok
       | tok == tokRParen = NarYield EventDirectoryEnd . k
       | tok == tokEntry =
-          expectWire bound "entry opening" tokLParen
-            $ expectWire bound "name keyword" tokName
-            $ wireString bound "entry name" (named prev)
+          expectTag "entry opening" tokLParen
+            $ expectTag "name keyword" tokName
+            $ wireString narMaxName "entry name" (named prev)
       | otherwise = failWith ("expected 'entry' or ')' in directory, got: " ++ show tok)
     named prev entryName = case checkEntryName prev entryName of
       Left err -> failWith err
       Right () ->
         NarYield (EventEntryBegin entryName)
-          . expectWire bound "node keyword" tokNode (parseNode bound (closeEntry entryName))
+          . expectTag "node keyword" tokNode (descend entryName)
+    descend entryName
+      | childDepth >= narMaxDepth =
+          failWith
+            ( "NAR directory nesting exceeds the maximum depth of "
+                ++ show narMaxDepth
+                ++ ": "
+                ++ show entryName
+            )
+      | otherwise = parseNode childDepth (closeEntry entryName)
     closeEntry entryName =
-      expectWire bound "entry closing" tokRParen $ \leftover2 ->
+      expectTag "entry closing" tokRParen $ \leftover2 ->
         NarYield EventEntryEnd (entries (Just entryName) leftover2)
 
 -- ---------------------------------------------------------------------------
@@ -345,28 +398,27 @@
 -- ---------------------------------------------------------------------------
 
 -- | Read one whole wire string - length prefix, payload, zero padding -
--- refusing a declared length over the bound before allocating for it.
--- For structural strings only; file contents go through
--- 'streamContents'.
-wireString :: Word64 -> String -> (ByteString -> Continue) -> Continue
-wireString bound what k = exactly lengthPrefixBytes ("length of " ++ what) withLength
+-- refusing a declared length over the limit from the prefix, before
+-- reading or allocating for the payload, as upstream refuses it.  For
+-- structural strings only; file contents go through 'streamContents'.
+wireString :: Word64 -> String -> (ByteString -> Continue r) -> Continue r
+wireString limit what k = exactly lengthPrefixBytes ("length of " ++ what) withLength
   where
     withLength lenBytes =
       let declared = word64LE lenBytes
-       in if declared > bound
+       in if declared > limit
             then
               failWith
                 ( what
                     ++ ": declared length "
                     ++ show declared
                     ++ " exceeds the "
-                    ++ show bound
-                    ++ "-byte wire-string bound"
+                    ++ show limit
+                    ++ "-byte limit"
                 )
             else
-              -- Safe narrowing and a safe padded demand: declared <=
-              -- bound <= structuralBoundCeiling, which sits enough
-              -- below Int's ceiling that len + narPad len cannot wrap.
+              -- Safe narrowing and a safe padded demand: every limit
+              -- is a few KiB at most.
               let len = fromIntegral declared
                in exactly (len + narPad len) what $ \whole ->
                     case BS.splitAt len whole of
@@ -377,18 +429,22 @@
                         | BS.any (/= 0) padding -> failWith nonzeroPadding
                         | otherwise -> k payload
 
--- | Read a wire string and require an exact token.
-expectWire :: Word64 -> String -> ByteString -> Continue -> Continue
-expectWire bound what expected k = wireString bound what check
+-- | Read a wire string held to the limit and require an exact token.
+expectWire :: Word64 -> String -> ByteString -> Continue r -> Continue r
+expectWire limit what expected k = wireString limit what check
   where
     check got
       | got == expected = k
       | otherwise = failWith ("expected " ++ show expected ++ ", got " ++ show got)
 
+-- | Read a keyword and require an exact one.
+expectTag :: String -> ByteString -> Continue r -> Continue r
+expectTag = expectWire narMaxTag
+
 -- | Demand exactly @n@ bytes, awaiting more chunks as needed, then
 -- continue with them and the leftover.  Held chunks concatenate once,
 -- so pathological chunking costs linear work, not quadratic.
-exactly :: Int -> String -> (ByteString -> Continue) -> Continue
+exactly :: Int -> String -> (ByteString -> Continue r) -> Continue r
 exactly n what k leftover = go [leftover] (BS.length leftover)
   where
     go !heldRev !heldLen
@@ -401,7 +457,7 @@
             else go (chunk : heldRev) (heldLen + BS.length chunk)
 
 -- | Fail from any position that still owes the machine a continuation.
-failWith :: String -> Continue
+failWith :: String -> Continue r
 failWith err _ = NarFail err
 
 nonzeroPadding :: String
diff --git a/test/Main.hs b/test/Main.hs
--- a/test/Main.hs
+++ b/test/Main.hs
@@ -17,7 +17,7 @@
 import Data.Either (isLeft, isRight)
 import Data.Foldable (toList, traverse_)
 import Data.IORef (atomicModifyIORef', newIORef, readIORef, writeIORef)
-import Data.List (isSuffixOf, sort)
+import Data.List (isPrefixOf, isSuffixOf, sort)
 import Data.Maybe (isJust)
 import Data.Set (Set)
 import qualified Data.Set as Set
@@ -43,12 +43,13 @@
 import qualified NovaCache.Store as Store
 import qualified NovaCache.StorePath as StorePath
 import qualified NovaCache.Validate as Validate
-import System.Directory (Permissions, createDirectory, createDirectoryLink, createFileLink, doesDirectoryExist, emptyPermissions, getPermissions, getTemporaryDirectory, listDirectory, readable, removeDirectoryRecursive, removeFile, searchable, setModificationTime, setOwnerExecutable, setOwnerReadable, setOwnerSearchable, setPermissions)
+import System.Directory (Permissions, createDirectory, createDirectoryIfMissing, createDirectoryLink, createFileLink, doesDirectoryExist, emptyPermissions, getPermissions, getTemporaryDirectory, listDirectory, readable, removeDirectoryRecursive, removeFile, searchable, setModificationTime, setOwnerExecutable, setOwnerReadable, setOwnerSearchable, setPermissions)
 import System.Exit (exitFailure, exitSuccess)
+import System.FilePath ((</>))
 import System.IO (hFlush, stdout)
 import System.IO.Error (ioeGetErrorString, isPermissionError, isUserError, mkIOError, permissionErrorType)
 import qualified System.Info
-import Test.QuickCheck (Args (chatty), Gen, Result (Failure, GaveUp, NoExpectedFailure, Success, output), Testable, arbitrary, choose, elements, forAll, frequency, ioProperty, listOf, listOf1, oneof, property, quickCheckWithResult, stdArgs, sublistOf, suchThat, suchThatMap, vectorOf, (.&&.), (===))
+import Test.QuickCheck (Args (chatty), Gen, Result (Failure, GaveUp, NoExpectedFailure, Success, output), Testable, arbitrary, choose, counterexample, elements, forAll, frequency, ioProperty, listOf, listOf1, oneof, property, quickCheckWithResult, stdArgs, sublistOf, suchThat, suchThatMap, vectorOf, (.&&.), (===))
 #if defined(darwin_HOST_OS)
 import Foreign.C.Error (throwErrnoPathIfMinus1_)
 import Foreign.C.String (CString)
@@ -693,12 +694,15 @@
 -- demands zero padding, so a nonzero byte builds archives the parser
 -- must reject - and 'NAR.serialise' (rightly) cannot produce them.
 narWireStr :: Word8 -> ByteString -> ByteString
-narWireStr padByte str = lenLE <> str <> BS.replicate padLen padByte
+narWireStr padByte str = word64LEBytes (fromIntegral n) <> str <> BS.replicate padLen padByte
   where
     n = BS.length str
-    lenLE = BS.pack [fromIntegral ((n `shiftR` (8 * i)) .&. 0xff) | i <- [0 .. 7]]
     padLen = (8 - n `mod` 8) `mod` 8
 
+-- | A wire length prefix: eight bytes, little-endian.
+word64LEBytes :: Word64 -> ByteString
+word64LEBytes n = BS.pack [fromIntegral ((n `shiftR` (8 * i)) .&. 0xff) | i <- [0 .. 7 :: Int]]
+
 -- | A directory NAR whose entries arrive out of sorted order - again not
 -- producible via 'NAR.serialise', which sorts on write.
 outOfOrderDirNar :: ByteString
@@ -715,6 +719,19 @@
   where
     entryFor name = ["entry", "(", "name", name, "node", "(", "type", "regular", "contents", "", ")", ")"]
 
+-- | Archives malformed inside the root node: out of order, nonzero
+-- padding, and entry names the grammar refuses.
+malformedArchives :: [ByteString]
+malformedArchives =
+  [ outOfOrderDirNar,
+    badPaddingNar,
+    evil "..",
+    evil "a/b",
+    evil ""
+  ]
+  where
+    evil name = NAR.serialise (NAR.NarDirectory [(name, NAR.NarRegular False "x")])
+
 -- | A regular-file NAR whose contents padding is nonzero.
 badPaddingNar :: ByteString
 badPaddingNar =
@@ -731,21 +748,172 @@
 -- | Drive the streaming parser over the given chunks (all non-empty),
 -- then signal end of input, collecting events.
 runStream :: [ByteString] -> Either String [Stream.NarEvent]
-runStream = runStreamFrom Stream.narStream
+runStream chunks = drivenEvents <$> driveChunks Stream.narStream chunks
 
--- | 'runStream' from an explicitly constructed machine, for tests that
--- need a bound other than the default.
-runStreamFrom :: Stream.NarStep -> [ByteString] -> Either String [Stream.NarEvent]
-runStreamFrom start chunks = go start chunks []
+-- | What each NAR reader makes of one whole input: 'NAR.deserialise',
+-- 'Stream.narStream', and 'Stream.narPrefix' with nothing after it.
+readersOn :: ByteString -> [Either String ()]
+readersOn bytes =
+  [ void (NAR.deserialise bytes),
+    void (runStream [bytes]),
+    void (driveChunks Stream.narPrefix [bytes])
+  ]
+
+-- | Assert that every NAR reader makes the same of an input.
+assertReaders :: String -> Either String () -> ByteString -> IO Bool
+assertReaders label expected bytes =
+  let outcomes = readersOn bytes
+   in assertEqual label (expected <$ outcomes) outcomes
+
+-- | Each structural string's limit: what the parser calls the string,
+-- the archive's strings before it, and the limit in bytes.
+stringLimits :: [(String, [ByteString], Word64)]
+stringLimits =
+  [ ("archive magic", [], 13),
+    ("type keyword", ["nix-archive-1", "("], 32),
+    ("entry name", ["nix-archive-1", "(", "type", "directory", "entry", "(", "name"], 255),
+    ("symlink target", ["nix-archive-1", "(", "type", "symlink", "target"], 4095),
+    ("executable marker", ["nix-archive-1", "(", "type", "regular", "executable"], 0)
+  ]
+
+-- | Wire strings, each with zero padding, back to back.
+wireTokens :: [ByteString] -> ByteString
+wireTokens = BS.concat . map (narWireStr 0)
+
+-- | A regular file to nest.
+leafFile :: NAR.NarEntry
+leafFile = NAR.NarRegular False "x"
+
+-- | A node below @depth@ directories named @d@, the outermost the
+-- root, so the node sits at that depth.
+nestedIn :: Int -> NAR.NarEntry -> NAR.NarEntry
+nestedIn depth leaf = foldr (\_ inner -> NAR.NarDirectory [("d", inner)]) leaf [1 .. depth]
+
+-- | An archive of directories nested as 'nestedIn' nests them, cut off
+-- just after the node keyword of the entry whose node sits at @depth@.
+chainToNodeKeyword :: Int -> ByteString
+chainToNodeKeyword depth =
+  wireTokens ("nix-archive-1" : concat (replicate depth ["(", "type", "directory", "entry", "(", "name", "d", "node"]))
+
+-- | How every reader refuses a node at depth 64 below entries named @d@.
+depthRefusal :: String
+depthRefusal = "NAR directory nesting exceeds the maximum depth of 64: \"d\""
+
+-- | A parse driven to its end over a list of chunks.
+data Driven r = Driven
+  { -- | The events, in order.
+    drivenEvents :: ![Stream.NarEvent],
+    -- | What the machine finished with.
+    drivenResult :: !r,
+    -- | The chunks the machine finished without asking for.
+    drivenUnfed :: ![ByteString],
+    -- | The last chunk fed, empty if none was.
+    drivenLastFed :: !ByteString,
+    -- | Whether the machine was told the input had ended.
+    drivenEnded :: !Bool
+  }
+
+-- | Feed the given chunks (all non-empty) to a machine as it awaits
+-- them, signalling end of input only when it awaits after the last.
+driveChunks :: Stream.NarStep r -> [ByteString] -> Either String (Driven r)
+driveChunks start chunks = go start chunks BS.empty False []
   where
-    go step pending acc = case step of
+    go step pending lastFed ended acc = case step of
       Stream.NarFail err -> Left err
-      Stream.NarDone -> Right (reverse acc)
-      Stream.NarYield event continue -> go continue pending (event : acc)
+      Stream.NarDone result -> Right (Driven (reverse acc) result pending lastFed ended)
+      Stream.NarYield event continue -> go continue pending lastFed ended (event : acc)
       Stream.NarAwait continue -> case pending of
-        [] -> go (continue BS.empty) [] acc
-        (chunk : rest) -> go (continue chunk) rest acc
+        [] -> go (continue BS.empty) [] lastFed True acc
+        (chunk : rest) -> go (continue chunk) rest chunk ended acc
 
+-- | Directory depth below the root a generated tree reaches.
+generatedTreeDepth :: Int
+generatedTreeDepth = 3
+
+-- | Most entries a generated directory holds.
+generatedDirectoryWidth :: Int
+generatedDirectoryWidth = 4
+
+-- | Longest generated contents, symlink target or trailing run: three
+-- 8-byte wire alignments, so lengths fall on and off a boundary.  The
+-- longest name, target and nesting the parser accepts are cases of
+-- their own, not generated.
+generatedBytesMax :: Int
+generatedBytesMax = 24
+
+-- | Longest generated entry name.
+generatedNameMax :: Int
+generatedNameMax = 12
+
+-- | A NAR tree of every node kind, as 'NAR.deserialise' returns one:
+-- regular files with and without the executable flag, symlinks, and
+-- directories, empty ones included, nested to 'generatedTreeDepth',
+-- with names unique and in byte order.
+genNarEntry :: Gen NAR.NarEntry
+genNarEntry = genNarEntryAt generatedTreeDepth
+
+-- | 'genNarEntry' with @depth@ directory levels left below the node.
+genNarEntryAt :: Int -> Gen NAR.NarEntry
+genNarEntryAt depth =
+  frequency
+    [ (2, NAR.NarRegular <$> arbitrary <*> genBytes),
+      (1, NAR.NarSymlink <$> genSymlinkTarget),
+      (if depth > 0 then 2 else 1, NAR.NarDirectory <$> genChildren)
+    ]
+  where
+    genChildren
+      | depth > 0 = do
+          count <- choose (0, generatedDirectoryWidth)
+          names <- Set.toAscList . Set.fromList <$> vectorOf count genEntryName
+          traverse (\name -> (,) name <$> genNarEntryAt (depth - 1)) names
+      | otherwise = pure []
+
+-- | Bytes of a length up to 'generatedBytesMax'.
+genBytes :: Gen ByteString
+genBytes = do
+  len <- choose (0, generatedBytesMax)
+  BS.pack <$> vectorOf len arbitrary
+
+-- | A symlink target the parser accepts: nonempty and free of NUL.
+genSymlinkTarget :: Gen ByteString
+genSymlinkTarget = do
+  len <- choose (1, generatedBytesMax)
+  BS.pack <$> vectorOf len (arbitrary `suchThat` (/= 0x00))
+
+-- | A name the grammar accepts: nonempty, neither @.@ nor @..@, and
+-- free of @/@ and NUL.
+genEntryName :: Gen ByteString
+genEntryName = genName `suchThat` (`notElem` [".", ".."])
+  where
+    genName = do
+      len <- choose (1, generatedNameMax)
+      BS.pack <$> vectorOf len (arbitrary `suchThat` (`notElem` [0x00, 0x2F]))
+
+-- | What follows an archive: nothing, arbitrary bytes, or another
+-- archive.
+genTrailing :: Gen ByteString
+genTrailing =
+  frequency
+    [ (1, pure BS.empty),
+      (3, genBytes),
+      (1, NAR.serialise <$> genNarEntry)
+    ]
+
+-- | Longest piece of a small-piece chunking: one past the 8-byte wire
+-- alignment, so length prefixes and padding straddle chunk boundaries.
+smallChunkMax :: Int
+smallChunkMax = 9
+
+-- | Split bytes into nonempty chunks of arbitrary lengths, mostly short
+-- ones.
+genChunking :: ByteString -> Gen [ByteString]
+genChunking bytes
+  | BS.null bytes = pure []
+  | otherwise = do
+      len <- frequency [(3, choose (1, smallChunkMax)), (1, choose (1, BS.length bytes))]
+      case BS.splitAt len bytes of
+        (piece, rest) -> (piece :) <$> genChunking rest
+
 -- | Entry shapes the chunking-independence test sweeps: every node
 -- kind, empty and aligned contents, nesting, and a non-UTF-8 name.
 streamCorpus :: [NAR.NarEntry]
@@ -849,45 +1017,150 @@
                   payload
                   (BS.concat [c | Stream.EventRegularChunk c <- events]),
       test "streaming agrees with deserialise on the malformed corpus" $
-        let evil name = NAR.serialise (NAR.NarDirectory [(name, NAR.NarRegular False "x")])
-            malformed =
-              [ outOfOrderDirNar,
-                badPaddingNar,
-                NAR.serialise (NAR.NarRegular False "x") <> "junk1234",
-                evil "..",
-                evil "a/b",
-                evil ""
-              ]
+        let malformed = NAR.serialise (NAR.NarRegular False "x") <> "junk1234" : malformedArchives
             bothReject bytes = isLeft (runStream [bytes]) && isLeft (NAR.deserialise bytes)
          in assertTrue "all rejected by both parsers" (all bothReject malformed),
-      test "the structural bound applies to streaming, not deserialise" $
-        -- deserialise instantiates the machine with its input's length
-        -- as the bound, so a name this size stays accepted there; the
-        -- streaming default caps structural strings at 64 KiB.
-        let longName = BS.replicate 70000 0x61
-            bytes = NAR.serialise (NAR.NarDirectory [(longName, NAR.NarRegular False "x")])
+      test "narPrefix finishes at the root node's close with the bytes after it" $
+        assertRight
+          "events, what follows, and no wait for the end of input"
+          ( [ Stream.EventRegularBegin False 1,
+              Stream.EventRegularChunk "x",
+              Stream.EventRegularEnd
+            ],
+            "junk1234",
+            False
+          )
+          ( (\run -> (drivenEvents run, drivenResult run, drivenEnded run))
+              <$> driveChunks Stream.narPrefix [NAR.serialise (NAR.NarRegular False "x") <> "junk1234"]
+          ),
+      test "narPrefix rejects the malformed corpus" $
+        assertTrue "all rejected" (all (\bytes -> isLeft (driveChunks Stream.narPrefix [bytes])) malformedArchives),
+      -- The NAR alone is what narStream parses, so its events stand for
+      -- the tree deserialise folds them into.  The prefix parse must
+      -- reproduce them, hand back exactly what follows the archive
+      -- (what it finished with, then the chunks it never asked for),
+      -- never wait for the end of input, and finish with a suffix of
+      -- the last chunk it was fed.
+      test "property: narPrefix parses the archive and hands back what follows, over any chunking" $
+        checkProperty $
+          forAll genNarEntry $ \entry ->
+            forAll genTrailing $ \trailing ->
+              let nar = NAR.serialise entry
+               in forAll (genChunking (nar <> trailing)) $ \chunks ->
+                    case (runStream [nar], driveChunks Stream.narPrefix chunks) of
+                      (Right expected, Right run) ->
+                        NAR.deserialise nar === Right entry
+                          .&&. coalesceChunks (drivenEvents run) === coalesceChunks expected
+                          .&&. drivenResult run <> BS.concat (drivenUnfed run) === trailing
+                          .&&. counterexample "awaited the end of input" (not (drivenEnded run))
+                          .&&. counterexample "finished with bytes not at the end of the last chunk" (drivenResult run `BS.isSuffixOf` drivenLastFed run)
+                      (Left err, _) -> counterexample ("narStream: " ++ err) False
+                      (_, Left err) -> counterexample ("narPrefix: " ++ err) False,
+      -- Every byte of a strict prefix of a valid archive matches that
+      -- archive, so the parse can fail only for want of the rest.
+      test "property: narPrefix fails an archive cut short as truncated, over any chunking" $
+        checkProperty $
+          forAll genNarEntry $ \entry ->
+            let nar = NAR.serialise entry
+             in forAll (choose (0, BS.length nar - 1)) $ \cut ->
+                  forAll (genChunking (BS.take cut nar)) $ \chunks ->
+                    case driveChunks Stream.narPrefix chunks of
+                      Left err -> counterexample err ("unexpected end of NAR" `isPrefixOf` err)
+                      Right _ -> counterexample "parsed a truncated archive" False,
+      test "property: narStream parses an archive alone and refuses any bytes after it, over any chunking" $
+        checkProperty $
+          forAll genNarEntry $ \entry ->
+            forAll genTrailing $ \trailing ->
+              let nar = NAR.serialise entry
+                  expected
+                    | BS.null trailing = coalesceChunks <$> runStream [nar]
+                    | otherwise = Left "trailing bytes after NAR root node"
+               in forAll (genChunking (nar <> trailing)) $ \chunks ->
+                    (coalesceChunks <$> runStream chunks) === expected,
+      -- Nothing follows each length prefix, so a reader that went on
+      -- to read the string would fail at the end of input instead.
+      test "a string one past its limit is refused from its length prefix by every reader" $
+        and
+          <$> traverse
+            ( \(what, before, limit) ->
+                assertReaders
+                  what
+                  (Left (what ++ ": declared length " ++ show (limit + 1) ++ " exceeds the " ++ show limit ++ "-byte limit"))
+                  (wireTokens before <> word64LEBytes (limit + 1))
+            )
+            stringLimits,
+      test "a keyword at its limit is read and compared" $
+        let keyword = BS.replicate 32 0x61
+         in assertReaders
+              "32-byte keyword"
+              (Left ("expected \"type\", got " ++ show keyword))
+              (wireTokens ["nix-archive-1", "(", keyword]),
+      test "a name, a target and an executable marker at their limits parse" $
+        and
+          <$> traverse
+            (\entry -> assertReaders (show entry) (Right ()) (NAR.serialise entry))
+            [ NAR.NarDirectory [(BS.replicate 255 0x61, NAR.NarRegular False "x")],
+              NAR.NarSymlink (BS.replicate 4095 0x61),
+              NAR.NarRegular True "x"
+            ],
+      test "a name and a target one past their limits are refused" $
+        do
+          nameOk <-
+            assertReaders
+              "256-byte name"
+              (Left "entry name: declared length 256 exceeds the 255-byte limit")
+              (NAR.serialise (NAR.NarDirectory [(BS.replicate 256 0x61, NAR.NarRegular False "x")]))
+          targetOk <-
+            assertReaders
+              "4096-byte target"
+              (Left "symlink target: declared length 4096 exceeds the 4095-byte limit")
+              (NAR.serialise (NAR.NarSymlink (BS.replicate 4096 0x61)))
+          pure (nameOk && targetOk),
+      -- The target is refused once read, before the node's closing,
+      -- so nothing need follow it.
+      test "an empty symlink target or one holding NUL is refused, a one-byte one read on" $
+        let upToTarget target = wireTokens ["nix-archive-1", "(", "type", "symlink", "target", target]
          in do
-              ok1 <- assertTrue "deserialise accepts" (either (const False) (const True) (NAR.deserialise bytes))
-              ok2 <- assertTrue "streaming rejects" (isLeft (runStream [bytes]))
-              pure (ok1 && ok2),
+              emptyOk <- assertReaders "empty target" (Left "empty NAR symlink target") (upToTarget "")
+              nulOk <-
+                assertReaders
+                  "NUL in the target"
+                  (Left ("NAR symlink target holds NUL: " ++ show ("a\0b" :: ByteString)))
+                  (upToTarget "a\0b")
+              shortOk <- assertReaders "one-byte target" (Left "unexpected end of NAR: length of node closing") (upToTarget "a")
+              wholeOk <- assertReaders "one-byte target archive" (Right ()) (NAR.serialise (NAR.NarSymlink "a"))
+              pure (emptyOk && nulOk && shortOk && wholeOk),
+      test "a node at depth 63 parses and one at depth 64 is refused" $
+        and
+          <$> sequence
+            [ assertRight "deserialise at depth 63" (nestedIn 63 leafFile) (NAR.deserialise (NAR.serialise (nestedIn 63 leafFile))),
+              assertReaders "depth 63" (Right ()) (NAR.serialise (nestedIn 63 leafFile)),
+              assertReaders "an empty directory at depth 63" (Right ()) (NAR.serialise (nestedIn 63 (NAR.NarDirectory []))),
+              assertReaders "depth 64" (Left depthRefusal) (NAR.serialise (nestedIn 64 leafFile)),
+              assertReaders "an empty directory at depth 64" (Left depthRefusal) (NAR.serialise (nestedIn 64 (NAR.NarDirectory [])))
+            ],
+      -- Upstream refuses the node once its node keyword is read, before
+      -- the node's own opening, so nothing need follow that keyword.
+      test "a node too deep is refused from its entry's node keyword" $
+        do
+          refusedOk <- assertReaders "after the 64th node keyword" (Left depthRefusal) (chainToNodeKeyword 64)
+          readOnOk <- assertReaders "after the 63rd node keyword" (Left "unexpected end of NAR: length of node opening") (chainToNodeKeyword 63)
+          pure (refusedOk && readOnOk),
+      -- A length near Int's ceiling would wrap the padded Int demand
+      -- negative if it were narrowed, reading the string as empty at
+      -- an unmoved position; it is refused from its prefix instead.
+      test "a near-maxBound declared length is refused from its prefix" $
+        let declared = fromIntegral (maxBound :: Int) :: Word64
+         in assertReaders
+              "near-maxBound target length"
+              (Left ("symlink target: declared length " ++ show declared ++ " exceeds the 4095-byte limit"))
+              ( wireTokens ["nix-archive-1", "(", "type", "symlink", "target"]
+                  <> word64LEBytes declared
+                  <> narWireStr 0 ")"
+              ),
       test "a truncated archive fails" $
         let bytes = NAR.serialise (NAR.NarRegular False "some contents here")
          in assertLeft "eof" (runStream [BS.take (BS.length bytes - 9) bytes]),
-      -- Regression: under a huge caller bound, a declared length near
-      -- maxBound Int once wrapped the padded Int demand negative, so
-      -- the machine "read" the string instantly as empty at an unmoved
-      -- position and this archive parsed as a complete empty symlink.
-      -- The parse must fail, as upstream would at end of input.
-      test "a near-maxBound declared length fails under a huge bound" $
-        let declared = fromIntegral (maxBound :: Int) :: Word64
-            lenPrefix = BS.pack [fromIntegral ((declared `shiftR` (8 * i)) .&. 0xff) | i <- [0 .. 7]]
-            bytes =
-              BS.concat (map (narWireStr 0) ["nix-archive-1", "(", "type", "symlink", "target"])
-                <> lenPrefix
-                <> narWireStr 0 ")"
-         in assertLeft
-              "overflowing padded demand"
-              (runStreamFrom (Stream.narStreamBounded (maxBound :: Word64)) [bytes]),
       test "the declared contents size arrives before the bytes" $
         case runStream [NAR.serialise (NAR.NarRegular False (BS.replicate 24 0x2A))] of
           Right (Stream.EventRegularBegin False declared : _) ->
@@ -1085,6 +1358,20 @@
             <$> traverse
               (\(entryPoint, outcome) -> assertEqual (entryPoint ++ " raised") (Just UserInterrupt) (either fromException (const Nothing) outcome))
               outcomes,
+      -- The walk counts depth as the parser does: the root at 0, and
+      -- each entry one deeper than its directory.
+      test "a walk archives an entry 63 levels below the root" $
+        withWalkTree $ \root -> do
+          let parent = foldl (</>) root (replicate 62 "d")
+          createDirectoryIfMissing True parent
+          BS.writeFile (parent </> "f") "x"
+          expectArchive (nestedIn 62 (NAR.NarDirectory [("f", leafFile)])) root,
+      test "a walk refuses an entry 64 levels below the root, naming it" $
+        withWalkTree $ \root -> do
+          let parent = foldl (</>) root (replicate 63 "d")
+          createDirectoryIfMissing True parent
+          BS.writeFile (parent </> "f") "x"
+          expectTooDeep (parent </> "f") root,
       test "a walk failure renders as its IOException, the access as location" $
         let cause = mkIOError permissionErrorType "openBinaryFile" Nothing (Just "/d/tree/sub/locked")
          in assertEqual
@@ -1128,6 +1415,15 @@
     "IOException"
     (\refusal -> (isUserError refusal, ioeGetErrorString refusal))
     (True, "file '" ++ path ++ "' has an unsupported type")
+
+-- | Assert that both entry points refuse a tree with upstream's depth
+-- error, naming the entry.
+expectTooDeep :: FilePath -> FilePath -> IO Bool
+expectTooDeep path =
+  expectWalkRefusal
+    "IOException"
+    (\refusal -> (isUserError refusal, ioeGetErrorString refusal))
+    (True, "path '" ++ path ++ "' exceeds maximum NAR directory depth of 64")
 
 -- | Assert that both entry points archive a path as an entry: the walk
 -- builds the entry itself, and the stream pulls its serialised bytes.
