Stop a PDF import

Merged
JO
2d ago
+609-48

Replaces #5825, which came from a fork branch and so couldn't join the stack. Its earlier bot review threads are there.

What and why

An AI PDF import could not be stopped: once ProcessPdfJob started, the only "cancel" action marked work lost as failed, and a late model answer could still write rows and send the next-steps email. This PR adds a cooperative Stop action. It marks the import cancelled, checks that status at every step of the job, and fences late answers out with the existing reread-claim guard. A request already sent keeps its usage row; its result is simply not applied.

Based on: #5784 (feat/ai-4c-typing-hold), the last part of the sequencer stack. This PR is a plain PR — it is not stacked on #5748 or on any other feature PR, and it will retarget to refactor/ai-plumbing when 4c lands.

Plan: delivery plan §1–§2/P1–P2, with the design in PR 3 and the redesign.

What changes

  • Import gains a cancelled status (the status column is already a string). The existing lost-work cancel action and force_fail! are unchanged.
  • Migration: imports.claim (nullable string) records what an importing claim is for: read (an AI reading) or publish (Import#publish_later). It is cleared when the import leaves importing. Stop acts only on a read claim, so a publish is never shown Stop and refuses it.
  • DELETE /pdf_imports/:pdf_import_id/ai_processing stops only a viewable PDF import that is being read, in the family, with statement-write permission. A legacy import without a statement needs write access to its account, or statement-manager permission when it has no account either. The import page hides the button unless PdfImport#stoppable_by? agrees with those checks.
  • ProcessPdfJob checks cancellation before read, upload, extract, row generation and final write, and rescues Ai::Error::Cancelled without recording a failure. Its existing token/status claim rejects late writes. The next-steps email is sent only after the final status write succeeds.
  • Ai::Transport::Base#attempt checks for a Stop before every try, cloud or local, so a Stop during retry backoff sends no further request.
  • A local model's streamed answer checks for a Stop at most once a second (00fe55c07). A Stop closes the connection, so llama.cpp stops generating instead of finishing an answer that would be discarded; the usage row is recorded as cancelled. Cloud calls don't stream, so a request already sent still finishes, and its answer is fenced out.
  • A stopped import can be read again ("Read again as…"), and re-uploading the same PDF after a Stop starts a new import.
  • The import page shows Stop while processing and a stopped state afterwards; the index gets a cancelled badge. English and German strings only.
  • cancelled is exposed in the imports API schemas and status filter, and _status_detail.json.jbuilder treats it as terminal. The rswag documentation is regenerated.
  • Minitest covers the endpoint, permission and status fences, job checkpoints, late answers and usage rows, API filtering, and the UI states. It also covers Stop around publish in both orders (status and posted entries), and the email fence.
  • Also carried here: 030d4098f, an unrelated bugfix. A scanned page whose text layer holds only Unicode spaces now counts as blank, so a mixed PDF isn't marked complete with that page unread.

Known limit: a Stop that lands inside upload_to_vector_store, after the job's last cancelled check, still uploads the statement's search copy.

Validation

Review fixes: Statement-less imports now require statement-manager permission to stop. Round 2 (b88a05105, 706c2be4e): Stop only stops a reading, never a publish (imports.claim); the email waits for the final write; a stopped import can be read again; legacy imports check account write access; and the transport checks for a Stop before every try.

Checks after round 2 (local, on this branch, merged up to 4c): full Rails suite 20,377 runs / 221,901 assertions / 0 failures / 0 errors / 32 skips. RuboCop, erb_lint, Brakeman, Biome lint and the node tests (323) are clean.

Checks (local, on this branch, after the editor pass): full Rails suite 19,327 runs / 212,904 assertions / 0 failures / 0 errors / 32 skips; focused Minitest for the stop endpoint, job checkpoints and API coverage 246 runs / 1,049 assertions / 0 failures / 0 errors; system tests 514 runs / 2,832 assertions / 0 failures / 0 errors. RuboCop, erb_lint, Biome lint and Brakeman are clean. npm run format:check reports the same 77 pre-existing errors as the base commit, none in this diff; the rswag OpenAPI document was regenerated.

Editor pass: removed four redundant cancelled fences and the pass-through Ai::Error::Cancelled rescue from ProcessPdfJob, merged the controller UI states into one test, reduced the job stop tests from 4 to 3, and dropped one implementation-only status test. The permission split between controller and view stays: the controller must distinguish "not processing" from "not authorised".

sure-dev verification: uploaded sample_bank_statement.pdf, saw Stop while the import was importing, submitted the ai_processing Delete form, and got cancelled plus the "Processing stopped" page. A later check confirmed the in-flight AI call added no summary or transactions.

Live provider calls: none. Automated validation used the stubbed transport only; RubyLLM version on this base: 2.2.3 (from Gemfile.lock). The manual dev-pod check used the pod's local llama.cpp service, not a hosted provider.

🤖 Generated with Claude Code

https://claude.ai/code/session_016zAWUWiGdNK4xoU3JEzKbB


Summary by cubic

Adds a Stop action for in-progress PDF AI readings, so users can cancel processing without the import being marked failed. Late model answers can no longer update the import or send the follow-up email; a cloud request already sent may still finish and keeps its usage row.

  • Stop applies only to AI readings, never a publish committing rows; a new imports.claim migration keeps the two apart.
  • Cancellation is checked before each transport try, at each job checkpoint, and while a local model streams, so a stopped request stops generating instead of finishing a discarded answer.
  • Stopped imports show a cancelled state and API status (treated as terminal), can be read again, and aren't reused when the statement is uploaded again.
  • Stopping requires write access to the statement or account, or statement-manager permission for imports with neither.
  • Fixes PDF reading so a page whose text layer holds only Unicode spaces counts as blank.
  • Known limit: a Stop that lands inside the vector-store upload still uploads the statement's search copy.

Summary by CodeRabbit

  • New Features
    • You can stop an in-progress PDF import when you have permission to manage its statement. Pending imports cannot be stopped.
    • Stopped imports display a stopped status on the import screen and in the import list. The imports API also reports stopped status and supports filtering by it.
  • Bug Fixes
    • Results received after an import is stopped no longer update the import or trigger follow-up actions. Stopped imports remain stopped rather than being marked as failed.