Skip to content

fix(backend): a list scans off the event loop, so progress and cancel stay live - #247

Merged
thisisgm merged 1 commit into
thisisgm:mainfrom
itsmunzir:fix/mtp-transfer-responsiveness
Oct 13, 2026
Merged

thisisgm merged 1 commit into
thisisgm:mainfrom
itsmunzir:fix/mtp-transfer-responsiveness

Conversation

@itsmunzir

@itsmunzir itsmunzir commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #144.

Problem

Issue #144: moving a large file off an MTP phone showed no progress and Cancel did nothing. The
backend has one event loop, and it was the only reader of Event::Op and Event::Request. A list
ran scan() inline on that loop, and a read_dir held by gvfs/MTP for as long as the device takes
holds everything behind it: transferprogress lines pile up unwritten and a transfercancel sits
unread, so the copy runs to its natural end and the window looks hung.

Solution

Half of this is already on main: spawn_reader sets the running operation's flag as it reads the
cancel line (60a07b9, src/backend/events.rs), so a transfercancel reaches the operation without
the loop, and the transfer card's bytes/rate/time-left work is upstream too. This PR is the other half
the report asks for — the loop that keeps writing progress.

  • src/backend/listwork.rs (new) owns the off-loop scan. listwork::start does the walk-end and
    watch.begin on the loop exactly as the inline arm did, then spawns the scan on its own thread and
    returns the Job. The scan posts Event::List(Done) on the loop's one channel, the way a thumbnail
    or a size posts its own. listwork::finish does what the arm did inline: picker filter, ordering,
    watch.commit/abandon, adopt, fsinfo.list_arrived, prefetch::first_rows_sent.
  • Gate preserves request ordering. The protocol is a sequential command stream — tests/protocol.sh
    sends list A, list B, paths [0] and requires the refusal that only exists if B replaced A
    before paths ran — so every request that arrives while a scan is out waits in Gate and replays in
    arrival order once the scan lands. quit or a closed stdin waits too, so a listing a script asked for
    is still answered before the process leaves, exactly as the inline scan did.
  • A watch burst read during a scan is decided after it, against whichever descriptor
    watch.commit/abandon made current, so a change in the directory just left answers nothing — as it
    did when the loop was inside the scan.
  • A failed scan's st_mode is read on the scan's own thread and rides the answer, so the loop never
    stats the stalled mount after the answer lands.

New regression and seams:

  • tests/mtp-scan.sh (new, registered in tests/run-all.sh): FLEA_GIO_BIN is a fake gio that blocks
    until the script releases it, so the scan is provably out and blocked before any line is judged. A
    4 GiB sparse copy is started and cancelled while the scan is out, and progress and the cancelled
    transferdone must be written before the scan's listed line. Deterministic — no clock races.
  • src/backend/listwork_tests.rs pins the two seams without a mount: a blocked scan does not hold the
    channel, and requests queued behind a scan replay in order.
  • tools/flea-file-budget records src/backend/run.rs 448 → 460 for the gate and the two extra
    handle_line call sites.

Verification

On this revision (base 58fc89f):

  • cargo test — 1144 passed, 0 failed.
  • cargo build — ok.
  • Clippy — PASS (denied = 0, rose = 0, fell = 0).
  • tools/flea-file-budget — passed.
  • tests/js.sh transfer — 39 passed, 0 failed.
  • tests/mtp-scan.sh — passed: fake gio blocked, progress and the cancelled transferdone land before
    the scan's listed line.
  • tests/protocol.sh — 222+ assertions pass.
  • cargo fmt --check is not claimed as passing: this tree already fails it on pre-existing
    formatting drift unrelated to this change.

Deterministic smoke:

cargo build
tests/mtp-scan.sh
cargo test --lib backend::listwork

Limitations

  • No MTP hardware was tested. The proof is a fake gio that blocks on demand plus a sparse copy, not
    a phone; the reporter's Pixel 7a transfer is not re-run in this PR.
  • A second same-backend list cannot overtake the first while it is out. The gate answers in request
    order, which is the only order protocol.sh accepts, and a client waiting on the older listed line
    would otherwise never clear its own listInFlight. Nothing shipped asks for one: ui/js/Nav.js's
    openWithoutHistory and the TUI's Model::open refuse a navigation while a list is in flight, and
    dual panes run one backend each (ui/WindowBody.qml). A slow MTP folder therefore delays only the
    pane that asked for it; another pane's local folder is a separate backend and answers at once.
  • Still synchronous on the loop, and named rather than quietly fixed: peek (preview, columns,
    network-repair), listpaths (per-path lstat), window's stat_range, and a size/mtime sort's
    stat_all. None is on the path the report measured — opening or re-reading a phone folder — and a
    gvfs listing answers stat from its gio store, so a phone folder's default name order pays none of
    them.
  • This is a list-path fix, not a universal "no hangs" claim: a genuine blocking syscall elsewhere on
    the loop still blocks it.

Summary by CodeRabbit

  • New Features
    • Directory listings on slow MTP and network mounts now run without blocking transfer progress.
    • You can continue to see copy progress and cancel an active transfer while a listing is still in progress.
    • Listings are displayed when scanning completes, with queued requests handled in their original order.

… stay live

Issue 144: a `list` ran `scan()` inline on the loop that is also the only
reader of `Event::Op` and `Event::Request`, so a `read_dir` held by an MTP or
network mount froze the transfer card and left `transfercancel` unread.

Upstream already landed the cancel half: `spawn_reader` sets the running
operation's flag as the line is read (60a07b9, src/backend/events.rs), which is
what lets a cancel land whatever the loop is doing. This is the other half, the
loop that keeps writing progress: `src/backend/listwork.rs` spawns the scan on
its own thread and answers with `Event::List(Done)`, the way a thumbnail or a
size posts its own. `Gate` holds every request that arrives while a scan is out
and replays it in arrival order once the scan lands, so the sequential command
stream (`list A`, `list B`, `paths [0]`) sees the same ordering it did when the
scan was inline; a closed stdin waits too, so a listing a script asked for is
answered before the process leaves.

Limitations, stated honestly:
- A second same-backend list cannot overtake the first while it is out. Nothing
  shipped asks for one: Nav.js's `openWithoutHistory` and the TUI's `Model::open`
  refuse a navigation while a list is in flight, and dual panes run one backend
  each. A slow folder delays only the pane that asked for it.
- `peek`, `listpaths`, `window`'s `stat_range` and a size/mtime `sort`'s
  `stat_all` stay synchronous on the loop. None is on the reported path (an MTP
  folder answers stat from its gio store), and they are named rather than folded
  in.
- No MTP hardware is available here; the proof is a blocked fake gio plus a
  sparse copy, not a phone.

Regression: tests/mtp-scan.sh blocks a fake gio so the scan is provably out,
then starts and cancels a 4 GiB sparse copy and requires progress and the
cancelled transferdone to be written before the scan's listed line.
listwork_tests.rs pins the seams without a mount.
@coderabbitai

coderabbitai Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4d82a157-da41-44e5-8779-829dbf8c5d0d
📥 Commits

Reviewing files that changed from the base of the PR and between 58fc89f and f3ace52.

📒 Files selected for processing (10)
  • AGENTS.md
  • CHANGELOG.md
  • src/backend/events.rs
  • src/backend/listwork.rs
  • src/backend/listwork_tests.rs
  • src/backend/mod.rs
  • src/backend/run.rs
  • tests/mtp-scan.sh
  • tests/run-all.sh
  • tools/flea-file-budget

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

Directory listing scans now run on a worker thread. The backend event loop continues handling other events while a scan runs, then installs the result and replays deferred requests in arrival order.

Changes

Asynchronous listing

Layer / File(s) Summary
Listing worker and completion
src/backend/events.rs, src/backend/listwork.rs, src/backend/mod.rs, src/backend/listwork_tests.rs, AGENTS.md
The worker scans the requested path and returns a completion event. Completion handles listing ordering, watch commit or abandonment, and scan errors. Tests cover worker responsiveness and failure-mode reporting. Documentation describes the scan flow and synchronous operations that remain.
Event-loop coordination
src/backend/run.rs, src/backend/listwork.rs, tests/mtp-scan.sh, tests/run-all.sh, CHANGELOG.md, AGENTS.md, tools/flea-file-budget
The event loop defers requests during a scan, records watch changes, handles the completed listing, then replays requests in order. The integration test checks that transfer progress and cancellation occur while an MTP scan is blocked. The headless runner includes the test; the changelog and file-budget entry are updated.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant Backend as Backend event loop
  participant Start as listwork start
  participant Worker as Scan worker
  participant Events as Event channel
  participant Finish as listwork finish
  participant Gate as Gate
  Backend->>Start: Start listing job
  Start->>Worker: Scan requested path
  par Scan is pending
    Backend->>Events: Process other events
    Events-->>Backend: Deliver progress or cancel request
  and Scan completes
    Worker->>Events: Send Event::List(Done)
  end
  Events-->>Backend: Deliver Event::List(Done)
  Backend->>Finish: Finish and install listing
  Backend->>Gate: Retrieve deferred requests in order
Loading

Suggested reviewers: thisisgm

Merge Risk: ⚪ Minimal · up to f3ace

No actionable merge-blocking issue remains in the reviewed listing change; normal checks can proceed.

Security Architecture Review

Security architecture risk: 🔵 Low · up to f3ace

The change improves responsiveness without a demonstrated expansion of privileges or access. Its asynchronous coordination preserves the checked ownership controls, but verification of failure and interruption behavior remains incomplete.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The inspected change affects listing and operation coordination within one backend process and its existing filesystem authority. No new tenant, service, secret, or infrastructure authority was identified in these paths; broader deployment exposure was not established.

Trust Boundaries and Controls

  • observed — Client input becomes Request events, whereas the scan worker creates List completions. FIFO deferral and replay-time row-generation checks prevent queued row-based actions from bypassing the checked listing-identity control.

Resilience and Maintainability Implications

  • inferred — Completion-to-job identity is enforced by serialization, not by a token in Done. The current caller starts only one scan, defers subsequent starts, and the worker sends one completion. No reachable duplicate or stale producer was found, so missing explicit identity is not retained as an active concern.

Hardening Proposals

  • proposed — Before permitting overlapping scans, scan replacement, or retries, carry an explicit job identity in completions and reject mismatches so those extensions cannot install results into a different active job.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 30 functions across 7 files. (3 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: directory scans run off the backend event loop so transfer progress and cancellation remain responsive.
Linked Issues check ✅ Passed [#144] listwork runs scans on a worker thread and returns results as Event::List; the PR summary reports that run defers and replays requests while the scan is active. events::read_line sets t…
Out of Scope Changes check ✅ Passed The added gate and scan tests, MTP regression test, changelog and design notes, test registration, and file-budget update support the [#144] off-loop listing change. No unrelated change is identified.
Full details: Docstring Coverage

Explanation

Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 30 functions across 7 files. (3 skipped: 3 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@thisisgm
thisisgm merged commit 9d18c12 into thisisgm:main Oct 13, 2026
1 check passed
@thisisgm

Copy link
Copy Markdown
Owner

merged as authored; a list scans off the event loop so progress and cancel stay live, with a follow-up on top (f3ace52, 816820b, v0.3.10). Thanks @itsmunzir! https://github.com/thisisgm/flea/releases/tag/v0.3.10

@thisisgm

Copy link
Copy Markdown
Owner

A blocked FUSE source read could still delay cancellation after the listing fix; the separate follow-up at 693a43b518 stops waiting and removes the partial copy in v0.3.11, while physical-phone verification remains tracked under #144. Thanks @itsmunzir! Release.

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.

Transfer from an MTP mount: progress never updates and Cancel is ignored, because scan() blocks the backend's main loop

2 participants