Skip to content

refactor(transfer): make the directory walk resumable, and scan one level with it - #7612

Merged
oferchen merged 5 commits into
masterfrom
refactor/resumable-dir-walk
Sep 2, 2026
Merged

oferchen merged 5 commits into
masterfrom
refactor/resumable-dir-walk

Conversation

@oferchen

@oferchen oferchen commented Sep 1, 2026 •

Copy link
Copy Markdown
Owner

Why

build_file_list walks the whole source tree by recursing into
scan_directory_batched, so there is no point at which the scan can stop and
resume. INC_RECURSE needs that seam: upstream's send_directory scans one
directory, emits one sub-list and returns, and send_extra_file_list(f, at_least)
resumes it later. Today oc materialises the entire tree and only then partitions
it - the ordering that PR #7611's RED baseline pins.

This change builds the seam without using it yet.

What

walk_path_with_metadata seeds a Vec<WalkStep> and hands it to drive_walk,
which pops steps until the stack empties. The two former recursion sites push
instead of calling.

Behaviour is preserved deliberately, not incidentally, and each of these is a
place where the obvious rewrite would have changed observable output:

  • Sibling order - children are pushed with .rev() so they pop in readdir
    order.
  • Filter-scope nesting - LeaveDir is pushed before ScanChildren, so
    the scan runs inside its own scope (exclude.c push_local_filters /
    pop_local_filters).
  • Diagnostic interleaving - VisitChild(StatResult) defers the
    --copy-dirlinks / --copy-unsafe-links re-stat until the child is
    reached, so a copying unsafe symlink notice still prints after the
    previous sibling's subtree rather than during the parent's batch stat.
  • Who opens the directory - ScanChildren { opened: Option<ReadDir> }
    because the two arms differ: the recursive arm opens the directory before
    pushing that directory's own entry, so an opendir failure is reported ahead
    of the entry; the transfer-root arm opens it after entering the filter scope.

No wire bytes, no ordering, no diagnostics change.

Verification

Measured on this exact change, on this PR's base (81c158629):

  • cargo nextest run -p transfer: 2774 passed, 3 skipped, 0 failed.
  • Full-workspace cargo nextest run: exit 0.
  • cargo fmt --all -- --check: clean.
  • Zero new clippy warnings. A/B'd rather than asserted: the walk.rs warning
    count is 8 before and 8 after, all on untouched code. (The workspace-wide
    collapsible_if hits are a local-toolchain artefact firing on files this PR
    does not touch.)

Two mutations proving the new traversal logic is exercised and load-bearing,
not merely compiled:

mutation result
drop .rev() on the child push (children pop in reverse readdir order) 51 failures
swap the LeaveDir / ScanChildren push order (filter scope released before the scan) 53 failures

Second commit: feat(transfer): scan one directory level without descending

The seam above is only useful once something can ask for less than the whole
tree. This adds the policy that does it.

WalkScope carries the base and a Descent together, so the new decision costs
no extra parameter on the driver. scan_one_directory() enters the
per-directory filter scope, drives the stack under Descent::DivertDirs, and
leaves it - the children are matched against that directory's merge files exactly
as the whole-tree walk matches them.

upstream: send_directory() takes a flags word and send_extra_file_list()
passes FLAG_DIVERT_DIRS, so a subdirectory found while scanning a sub-list is
recorded and diverted rather than descended into. That one flag is why upstream
never materialises the tree: one call costs one level, not one subtree.

Every existing caller constructs WalkScope::recursive, so the tree walk is
unchanged. scan_one_directory has no production caller yet - the budgeted
producer loop that consumes it is the next step, and it is expect(dead_code)
outside tests until then rather than silently unreferenced.

Verification (second commit)

  • cargo nextest run -p transfer: 2776 passed, 3 skipped, 0 failed.
  • cargo fmt --all -- --check clean.
  • Two tests, and the second exists to stop the first being vacuous:
    scan_one_directory_emits_the_subdirectory_but_not_its_contents pins the
    one-level result; the_recursive_walk_still_expands_the_same_fixture proves
    the same fixture does have deeper content to find, so the first assertion is
    about the policy and not about an empty tree.
  • Mutation: forcing descends_into_subdirs() to true (policy inert) reddens
    exactly the one-level test — left: ["sub", "sub/deep.txt", "sub/deeper", "sub/deeper/x.txt", "top.txt"], right: ["sub", "top.txt"] — while the
    companion stays green.

⚠ Note on the first suite run of this branch: 51 integration tests failed at
~0.02s each. That is the binary-freshness guard from #7385 firing because
walk.rs was edited after the last cargo build, not a regression. Rebuilding
the binary returns 2776/2776. The uniform sub-30ms duration is the tell.

@oferchen oferchen changed the title refactor(transfer): make the directory walk resumable refactor(transfer): make the directory walk resumable, and scan one level with it Sep 1, 2026
@oferchen
oferchen force-pushed the refactor/resumable-dir-walk branch from f4c5055 to 4144dbf Compare September 2, 2026 05:30
The generator's file-list walk descends by recursing into
scan_directory_batched, so the scan cannot be suspended between
directories. INC_RECURSE needs exactly that seam: upstream's
send_directory / send_extra_file_list emit one sub-list per directory
and return, rather than materialising the whole tree first.

Convert the implicit call-stack DFS into an explicit WalkStep LIFO
driven by drive_walk. Behaviour is preserved deliberately, not
incidentally:

- children are pushed in reverse so they pop in readdir order;
- LeaveDir is pushed before ScanChildren so a directory's scan runs
  inside its own filter scope, matching push_local_filters /
  pop_local_filters nesting;
- VisitChild(StatResult) defers the --copy-dirlinks / --copy-unsafe-links
  re-stat until the child is reached, so a `copying unsafe symlink`
  notice still prints after the previous sibling's subtree;
- ScanChildren carries opened: Option<ReadDir> because the two call
  sites differ on which side opens the directory - the recursive arm
  opens before pushing the directory's own entry, so an opendir failure
  is reported ahead of the entry.

No wire bytes, no ordering, and no diagnostics change.
The resumable walk can now be told how deep to go. upstream's
send_directory() takes a flags word, and send_extra_file_list() passes
FLAG_DIVERT_DIRS so a subdirectory found while scanning a sub-list is
recorded and diverted rather than descended into. That single flag is
why upstream never materialises the whole tree: one call scans one
level, and the diverted directories become the work list for later
calls.

WalkScope carries the base and the descent policy as one value, so the
policy costs no extra parameter on the driver. scan_one_directory()
enters the per-directory filter scope, drives the stack under
Descent::DivertDirs, and leaves it - the children are matched against
this directory's merge files exactly as the whole-tree walk matches
them.

Every existing caller constructs WalkScope::recursive, so the tree walk
is unchanged. scan_one_directory has no production caller yet; the
budgeted producer loop that consumes it is the next step.
The generator kept the wire-NDX -> flat-index mapping as three parallel
pieces of `IncrementalState`:

    ndx_segments: Vec<(usize, i32)>   // (flat_start, ndx_start)
    segment_parent_flat: Vec<i32>     // aligned 1:1 with the above
    first_segment_idx: usize          // reclaim cursor into both

held in lockstep by an unwritten invariant, searched three different ways
spelled out at their own call sites, and with upstream's `+ 1` parent-gap
rule (flist.c:2966) open-coded at the push site, away from every lookup
that depends on it.

`NdxMap` owns all three. `push_sublist(flat_start, parent_flat)` derives
`ndx_start` and returns it, so the gap rule is stated once; `wire_to_flat`,
`resolve_itemize`, `reclaimable_range` and `advance_reclaimed` replace the
open-coded searches. Eight consumers rewired; no behaviour change.

The container stays a `Vec` plus a cursor, deliberately. Reclaim frees the
*entries* but the NDX->flat mapping must stay total: wire NDXs are absolute
and the peer can still reference an old one, so `first_segment_idx` is a
reclaim cursor, not a deque front. Popping would resolve a stale NDX into
freed storage. The module doc records that.

Mutation-proven:

- delegating `resolve_itemize` straight to `wire_to_flat` (dropping the gap
  redirect) kills 4 tests, including the pre-existing
  `inc_recurse_gap_ndx_itemizes_parent_directory` - so the rewired path is
  the live one, not just the new unit tests.
- dropping the `+ 1` from `push_sublist` kills 8.

transfer 2784/2784, fmt clean, and `clippy --all-targets --all-features`
reports the same 94 warnings as the base commit (zero net new).
The citation ratchet failed with `transfer suspected-drift rose 6 -> 8`.
All three cited lines were resolved against the pinned source in
target/interop/upstream-src/rsync-3.5.0 rather than renumbered by guess:

- ndx_map.rs cited `rsync.c:424` for `i = ndx - cur_flist->ndx_start`;
  that statement is at rsync.c:437.
- ndx_map.rs cited `generator.c:2338` for `ndx = i + cur_flist->ndx_start`;
  that statement is at generator.c:2812, and 2338 is unrelated backup code.
- walk.rs cited `flist.c:1846` for `"link_stat %s failed"` at two sites;
  1846 is `send_file_entry`. The message appears twice in 3.5.0, at 2011
  and 2705. Both walk.rs sites are the recursive directory scan, whose
  arm is flist.c:2011 - the one that splits ENOENT into IOERR_VANISHED
  and everything else into IOERR_GENERAL. flist.c:2705 is the operand
  loop in send_file_list, gated on missing_args, and is a different
  decision.

transfer suspected-drift now reads 4, below the 6 baseline; the ratchet
exits 0. The four remaining entries are pre-existing multi-candidate
anchors in files this branch does not touch, and are deliberately left
alone rather than folded into an unrelated change.
All four Windows cells fail on `the_recursive_walk_still_expands_the_same_fixture`:

    left:  [".", "sub", "sub\\deep.txt", "sub\\deeper", "sub\\deeper\\x.txt", "top.txt"]
    right: [".", "sub", "sub/deep.txt",  "sub/deeper",  "sub/deeper/x.txt",  "top.txt"]

The production walk is CORRECT and unchanged by this PR. A name is derived by
`path.strip_prefix(base)`, which is a `Path`, so it carries the host separator
in memory - `sub\deep.txt` on Windows. The conversion to the wire's `/` is a
separate, existing step at the encode boundary: `path_bytes_to_wire`
(`protocol/src/flist/write/encoding.rs`). Nothing reaches a peer with a
backslash.

So this is the test's defect, and specifically the helper's: `entry_names` is
documented as returning "wire-side relative names" and did not deliver them on
a non-`/` platform. Normalising inside the helper makes it honour its own
contract, and both scan tests inherit it. `tests.rs:4652` already uses the same
`.replace('\\', "/")` idiom on a sibling assertion.

The one-level test could not see this: its expectation is `["sub", "top.txt"]`,
single components with no separator to get wrong. This PR's new two-level test
is the first assertion in the file able to observe it - the defect is newly
VISIBLE, not newly introduced.

Verified: `rustfmt --edition 2024 --check` reports no diff on the changed lines.
@oferchen
oferchen force-pushed the refactor/resumable-dir-walk branch from 4144dbf to 246d910 Compare September 2, 2026 09:27
@oferchen
oferchen merged commit 86a549b into master Sep 2, 2026
70 checks passed
@oferchen
oferchen deleted the refactor/resumable-dir-walk branch September 2, 2026 13:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant