47 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5.5 87dcb3452f fix(spikes): scrub progress bars line by line, not with a backtracking regex
SonarCloud's PR analysis flagged the progress-bar regex in capture.py's redaction again (S8786,
super-linear backtracking) — the second regex form of this rule it has flagged. A per-line test
cannot backtrack at all. It replaces exactly the lines the regex did on the LF text
`subprocess.run(text=True)` produces, checked against seventeen sample lines including the edge
cases (no space after the dashes, trailing whitespace, several "eta"s, a final line without a
newline); no committed fixture changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 6cd7e99385 chore(release): 1.4.0
The version in all five places it lives — Cargo.toml, Cargo.lock, package.json,
package-lock.json and tauri.conf.json — checked with `cargo metadata --locked` and with the
release workflow's own tag check run locally against v1.4.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 7124227262 docs: the specs say what the code does; 1.4.0 recorded, with its audit backlog
Every spec checked against the code rather than against itself, in four passes that each read the
branch's commits and then the source:
- CLI-SPEC/CLI-GUIDE: one JSON document per command (with the per-command table and the paths
  that print nothing), environment selection, logging, Ctrl-C and exit 130, the prompts as they
  are rather than the [A]bort and countdown that never existed, `.heldBack`, a `pipdock audit`
  section, and the rules every mutating command now follows.
- ARCHITECTURE/DATA-FLOW/ERROR-CATALOG: the Engine trait's real signatures, Requires-Python's
  three checkpoints, store v4 and the log folder, §7's return types and events, the state machine
  with re-probing and Force latest, where each §9 invariant is enforced, and 35 codes in 32 rows.
- SECURITY/TESTING/RELEASE-CI/CODE-HEALTH-SPEC: the PEP 668 override as built, four browser hosts
  and the exact capability set, attested releases, the new CI, the tools constraints, and test
  tiers that describe what runs rather than what was planned.
- UI-SPEC/PRD/README/I18N: the screens as they render, the keyboard, tokens and their contrast
  sweep, the feature matrix's status, attestation instructions, and I18N's one stated exception.

ROADMAP gets the 1.4.0 record — what was wrong, what running found that reading did not, what was
deliberately not done — and the **Audit backlog**: every finding not fixed, with where it is and
why it waited. CLAUDE.md's counts and contradictions are corrected, with the rules this release
left behind. changelog/1.x.md has the 1.4.0 entry, including "Changed for scripts" and "You will
see this once". AI-DISCLOSURE, README and About say which model and who released what. The legal
documents' effective date moves to the release date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 42f227c1aa fix: what installing the build found, and what the doc pass turned up
The release build was installed and driven before tagging. Two defects showed up that no suite
could see:
- Every dialog opened in the window's top-left corner. Tailwind's preflight sets `margin: 0` on
  everything, which removes the `margin: auto` a modal <dialog> is centred by; PdDialog (and so the
  uninstall guard, since it was written) and the Ctrl+K palette were both affected. `m-auto` /
  `mx-auto`, measured in the dev server: (0,0) before, centred after.
- On a profile that had never downloaded the index, Search said "preparing the package index"
  for ever and never offered the download. Moving the load into the background let a failed load
  restart on the next search, which reset the slot to Warming before the failure could be read,
  and the screen asked again every 150 ms. A failed load now stays failed until a refresh; a test
  in state.rs failed first against the old rule.

From the documentation pass, each checked against the code:
- The GUI's snapshot diff used the plain diff while the CLI's and the rollback used the
  engine-aware one, so the two heads disagreed about pip and setuptools across engines (G5).
- `--json`'s help still promised NDJSON; `--yes`, `--quiet`, `--verbose`, `--log-file`, the
  install spec and `engine` described behaviour they did not have. Corrected, and the 32 help
  goldens re-blessed for exactly those lines. `pipdock engine` now marks the configured engine,
  as its help always said; `health --fix` printed a dirty-tree warning to stdout before its JSON;
  the text preview now lists withdrawn releases, as the GUI's does.
- Copy that promised what the code does not do: a pinned package "can still be updated on its
  own" (an Exclude pin filters a named package too), a held pin left only "out of bulk updates",
  and an empty Environments screen pointing at a Browse… button that does not exist.
- Stale comments in exec, the pip and uv parsers, index refresh, health, the pin screen, the
  status line, the settings store and i18n.ts (whose missing-key warning never fires). The
  ExecutionSummary.cancelled description is part of the public schema, so that golden and the
  TypeScript bindings move with it.
- Metadata lookups reuse the shared HTTP client (M37 had been half done); insta was a dev
  dependency of core that nothing in core used; the integration workflow's checkouts no longer
  persist credentials; the capability file cites SECURITY §4, where the rule lives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 310436552c fix: a bug-report link GitHub will open; uninstall output that finishes printing
- report.rs: the excerpt was capped at 6000 characters *before* percent-encoding, which is what
  decides the length GitHub sees - an accented letter costs up to nine bytes, a path separator
  three - so a log full of Vietnamese paths built a ~20 KB link and GitHub answered with an error
  page instead of the form (M51). Lines are now dropped from the front until the encoded excerpt
  fits; a single enormous line is trimmed rather than dropped. Two tests, both failing first.
- run.rs: `pipdock uninstall` dropped its output pump's handle instead of awaiting it, so the
  summary could print over the last engine lines - the ones that say how the removal ended (X38).
  The other three pumps already waited.
- bug_report.yml: the version placeholder read "1.0.0", which every release since made wrong; it
  now says where to find the version instead (X48).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 25f0269631 fix(build): the legal hash ignores line endings; the privacy policy says what is stored
build.rs hashed each document's raw length two lines above the normalisation that existed so a
CRLF checkout would hash like an LF one (X25). It did not: a build from a Windows checkout with
autocrlf - the runner's default - carried a different hash from an LF build of the same commit.
The algorithm moves to src/legal_hash.rs, which build.rs includes by #[path] and the library
compiles under cfg(test), so the tests exercise the function that runs at build time: a CRLF pair
hashes like its LF pair (this failed against the old code), a changed document or text moved
between documents changes the hash, and the hand-rolled SHA-256 agrees with sha2 across block
boundaries.

legal/, as users read it (X26):
- PRIVACY §2 names what is now stored: the log files exist (they record the commands PipDock ran,
  so they hold package names and paths), PipDock's own tools/ and audit/ environments, and the
  per-release Python ranges. §3 says what the one destination, PyPI, is asked for - including
  pip-audit's advisory data, which comes from PyPI's own service - and adds osv.dev to the pages
  handed to the browser. The Vietnamese summary follows.
- THIRD-PARTY §A gains rfd (the startup-failure dialog), §C osv.dev: four browser destinations,
  not three.

Both documents are hashed into the consent record, so the legal gate is shown once more after
updating - the mechanism working, as CLAUDE.md says.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 12bf723daa ci: failures reach someone, audits run on what is merged, releases are attested
- notify-ci-failure.yml lists its workflows by name. `workflows: ['*']` is not a wildcard to
  workflow_run: it matched nothing, so `main` was red from 2026-09-23 with no one told.
- cargo audit runs a prebuilt cargo-audit (taiki-e/install-action, pinned by commit) with
  `--deny warnings`, replacing rustsec/audit-check@v2 - Node 20, a check-run write token, and on a
  pull request a failure only for "critical", which is how September's advisories passed every PR.
  .cargo/audit.toml's contract (a new informational advisory fails CI) is now what runs.
- security-scan.yml: both audits daily against `main`, so an advisory against something already
  merged is reported the day it is published, not at the next PR.
- cargo deny (licences, sources, bans) with deny.toml: the licence allowlist makes "every bundled
  licence is GPL-3.0-compatible" a test. The workspace declares `publish = false`, which it never
  had - and without which cargo-deny judged the app crates as published ones.
- CodeQL analyses rust and actions as well as javascript-typescript. The comment saying CodeQL had
  no Rust support stopped being true in 2025.
- ci-node.yml: Pages and id-token write move from the workflow to the one job that needs them
  (Sonar S8233); the audit installs with --ignore-scripts (S6505); a new `tauri lockstep` job
  fails when a Tauri crate and its npm package drift apart on Cargo.lock and package-lock.json.
- release.yml: build (read-only token, no persisted credentials) and publish (attest + draft) are
  separate jobs; the tag must match all five version fields; SHA256SUMS.txt is LF, which
  `sha256sum -c` elsewhere needs; actions/attest-build-provenance attests the .exe and .msi;
  softprops/action-gh-release is pinned by commit; `workflow_dispatch` with `dry_run` builds any
  ref without attesting or drafting.
- ci-integration.yml also runs for the CLI, exec, audit, release metadata, errors, store, index,
  Cargo.lock and rust-toolchain.toml - every one of which its end-to-end steps run through.
- dependabot.yml: cooldowns, a group per ecosystem for Tauri packages and for actions and pip,
  TypeScript held below 6.1 (typescript-eslint's peer range), and the rust-toolchain ecosystem.
  A multi-ecosystem group would put both Tauri halves in one PR, but what it does to dependencies
  outside its patterns is undocumented; the lockstep job covers the gap instead.
- Sonar: NOSONAR with reasons on the dev scripts' argv and PATH lookups; bundle-cli.mjs no longer
  claims to run from beforeBuildCommand. The dev CSP moves out of index.html into a Vite plugin
  that reads devCsp from tauri.conf.json, so a release build carries one policy, the strict one
  (S7039); checked in the dev server, where React Refresh's preamble still runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 7c6a506652 chore: remove what nothing uses, and finish what was half-wired
Dead code, each checked for callers first:
- graph::ReverseDeps::leaves (only its own test called it), health::run::sink_for (no caller,
  and a doc describing something else), SnapshotProof::id and is_waived (no caller).
- Two whitespace collapsers become one, errors::catalog::collapse_whitespace; the classifier's
  normalize is that plus lowercase. Three hand-folded SHA-256 hex digests become
  model::sha256_hex (build.rs keeps its own: a build script cannot use the crate it builds).
- Six copies of asPdError become one, beside isPdError in ipc/errors.ts.
- Thirteen strings no screen renders, from both catalogs (status.resolving/executing/ready,
  actions.confirm/browse/retry/openLogs, env.requiresPython/unusable,
  packages.updateSelectedSoon, health.notInstalled, settings.localeSystem/saved).
- fixtures.rs is compiled only for tests and for xtask (feature `fixtures`), not into release.

Half-wired, finished rather than deleted: engine_info had a typed wrapper and no caller, while
ARCHITECTURE §7 promised a version beside each engine radio. Settings now shows it for the
selected environment, and says "not found" for an engine that is not installed.

Docs that described another project: core's "Phase 0" status, model.rs's specta, pip.rs's "lands
in M1", snapshot.rs's "execute takes a Snapshot" (it takes a SnapshotProof), declared_source's
doc stranded on validate_project, the pin validators' "character-class check" (they share
pep440::is_version now), three health wrappers in ipc/index.ts each under another's doc, and
three %LOCALAPPDATA% paths missing the data\ folder.

Repo: production builds carry no source maps - Tauri embeds dist/ in the executable, so
`sourcemap: true` shipped 2 MB of them to every user (X51). .gitignore covers insta's pending
snapshots and a downloaded SHA256SUMS.txt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 4da4c0f3ec fix(ui): the shell - window, grants, CSP, language, keys, table, contrast
The window (U21). It may now be maximized and snapped; the 1600x1100 cap is gone, and the content
column stops at max-w-content (87.5rem) instead, centred in what is left. The window is created
hidden and src-tauri/src/window.rs fits it to the monitor's work area before showing it: 1180x760
is taller than the work area of a 1920x1080 panel at 150% and of a 1366x768 laptop, so the status
line and the plan panel's Confirm opened under the taskbar. Never below 900x560; pinned to the
corner rather than centred off-screen when even that does not fit. UI-SPEC §5 says so.

The webview's grants (U1, U32). core:default granted some sixty core commands nothing called and
not core:window:allow-close, so Decline on the legal gate did nothing in the installed app while
its component test - which mocks close() - passed. default.json now holds exactly the five the
frontend calls, and a test in lib.rs pins the union of every capability file, plus the opener's
four hosts.

CSP (U56): object-src, base-uri and form-action 'none'. A release build's style-src drops
'unsafe-inline' - React sets styles through CSSOM, which CSP does not govern. index.html keeps it
for `npm run dev`, where Vite injects <style> elements; both policies are enforced, so the
stricter decides. To be confirmed on the installed build.

Language (U3): the choice is stored and applied at start. save() sent locale: null every time, so
choosing Vietnamese lasted until the window closed. Settings now load before the legal gate, so the
gate is in the chosen language too, and <html lang> follows the UI.

Keys: a screen's data-autofocus wins over the heading (U12) - Search's field lost focus to the
shell's effect, which runs after its children's - and `/` works from Search itself. Ctrl+1..9 by
e.code (U49): on AZERTY Ctrl+3 reports `"`. A release build swallows F5, Ctrl+R, Ctrl+P, Ctrl+F,
F3 and Alt+arrows (U20), which reloaded, printed and found in a single-page app.

Also: Security scrolls (U2); the legal gate shows a consent that cannot be recorded (U29); Report
bug asks for the link again with the environment, so the issue carries the Python and engine
versions, at one subprocess per click rather than per row (U31); the package table's header and
rows share one set of widths and one gutter, and narrow tables drop Size so names stay visible at
900px (U22, U23); the grid is focusable (Sonar S6852); --color-danger is #F26A63 and danger badges
use a 15% tint, with tokens.test.ts now compositing every badge tint over every surface (U46 -
3.92:1 before); test seeds typecheck instead of `as never`, the IPC mock uses the real isPdError
and has the audit cache entry (U10).

U14 and U26 were already fixed by earlier commits in this release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 8e4b87e4ab feat(ui): the PEP 668 override asks first and is shown; the preview says what the report says
SECURITY §3 asks for two things the override never had: a confirmation before it turns on, and a
persistent chip on every mutating screen while it applies. Turning it on now opens PdDialog with
Cancel focused; turning it off saves at once. PdOverrideChip shows on Installed/Updates, Search's
dock bay, the plan panel and an environment's detail - only where the override applies: the
setting is on and the environment carries the EXTERNALLY-MANAGED marker. A venv never does, and a
chip there would claim the flag is being sent.

The preview renders the three fields ResolutionReport gained in this release, which nothing showed:
- forced: "Will break (n)" in danger, each dependent named with the constraint the forced version
  violates; the Confirm button carries the count and the danger treatment (DISCLAIMER §2).
- incompatible: left out for Requires-Python, with the range against this interpreter (invariant
  10). A plan whose only content is one is no longer "nothing to change".
- yanked: PD-PKG-003 as a warning row beside the change it belongs to.

The summary says when the post-run check could not run (CheckReport.error) instead of showing
nothing, which read as a pass (M30). The same defect survived on the empty-plan path of
plan::execute, which kept its own unwrap_or(ok: true); it now goes through post_check like every
other path, with a test that failed first.

Also: settings load at app start once the documents are accepted, so the status line's engine and
the chip are right before anyone opens Settings (U13); the plan panel names the interpreter it
changes (part of U15); pins.suggestIntro no longer claims a pinned package can still be updated one
at a time - an Exclude pin filters a named package too (DATA-FLOW §9.5).

flow_step_forced.json is computed by derive_forced and release::mismatch over the scenario rows
rather than written, for the reason fixtures.rs gives for its other computed fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 73e65303ca fix(ui): an answer for what the user has left is dropped
Every store awaited a command and then wrote what came back, without asking whether the question
was still the one being asked. A slow answer for the environment the user had just left landed on
the one they switched to:
- the package list and the outdated badges (U5), pin suggestions (U43) and the snapshot timeline
  check the environment after each await;
- a pin write re-joins the rows from the store as it is after the write, not as it was before
  two awaits (U6);
- two clicks down the timeline show the second entry's diff whichever answers first (U42);
- the dependency view loads the environment switched to while the previous one was loading,
  rather than bailing on "already loading" and showing nothing (U34).

The plan store counts generations. Leaving a plan the backend is still working on - Back during
a resolve or a guard, or out of a parked preview - now stops it there with plan_cancel, and its
late answer no longer re-opens the panel the user closed (U9). A failed decision round keeps the
preview (U24, the UI half). The progress subscription stays open 50 ms past the command's reply,
which arrives separately from its last events and in no promised order. The uninstall guard's
probe has its own phase, so the table is not swapped for the plan panel for half a second and its
scroll position kept (U14).

- Back from a preview is not a finished run: the selection is kept and nothing is refetched (U11).
- Search asks again while the index warms instead of waiting for another keystroke (U7); the
  backend now always answers the first search at once.
- Install from the dock bay keeps the queue until the resolve answers (U30).

ui/src/stores/races.test.ts holds a command open, moves on, then lets it answer: six of its seven tests
fail on the previous stores.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 a9f476a2ae fix(app): a claimed slot releases itself; IO errors say what happened; quieter locks
- The session slot is claimed through a guard that releases it on drop unless it was parked
  (U4). Release was a call every exit path had to remember, and plan_resolve, uninstall_guard and
  the rollback preview each had a `?` between claim and release: one failed settings read left the
  slot Busy and every later plan answered PD-RES-003 until a restart. The slot is a std mutex now,
  held only to swap a value, so the drop can take it; a test returns early through a claim and
  finds the slot free and the token gone.
- A guard refusal in uninstall_execute keeps the flow parked: the dialog is still on screen and
  Force remove is still a choice, and its buttons used to answer "no plan".
- A file the user chose - an export, a saved report, a requirements file - fails with the code
  that fits: read-only is PD-PRM-003, in use is PD-PRM-002, a full disk is still PD-SYS-002. Every
  one of them was PD-SYS-002, "not enough free disk space" (U25).
- cache_clear holds the slot of the feature that owns the target - Health for the tools venv, the
  Security tab for the audit venv, the plan slot for snapshots - so a clear is refused while that
  feature runs instead of deleting the venv in use, and a parked preview is put back (U36). The
  deletion runs off the async workers.
- The name index loads in the background on its own connection (U35). The load held the store's
  lock for 140 ms - every command that wanted the store waited behind a keystroke - on a worker
  the app shares; the triggering search answers ready:false, as the command's doc always said.
- Environment probes run four at a time instead of in series (U19, part).
- The audit's cancellation token is registered before the freeze, so Stop during it is honoured
  (U37); a run stopped that early skips the venv sync and reports itself cancelled.
- A cache test named its scratch folder after the clock alone, so two tests in one tick shared it
  and the fresh-install test read the other's files. It failed once in this run; a counter fixes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 040571c7f7 fix(cli)!: one JSON document per command, env use is honoured, Ctrl-C stops the run
Changed for scripts: every `--json` invocation now prints exactly one document on stdout
(CLI-SPEC §6), with prompts, previews-before-a-prompt and prose on stderr (X5). The preview and
then the summary used to be two documents, so `pipdock install x --json | ConvertFrom-Json`
failed on the second. The document is: the ResolutionReport when nothing runs (a dry run, an
empty plan, a declined prompt - exit 2), the ExecutionSummary when something does, the FlowStep
when there is nothing to plan, the GuardReport for a refused removal (with --force, only the
summary), and the entity itself for env use, pin add/remove, snapshot create, engine and
pip-upgrade ({before, after}). Prompts moved to stderr in both modes.

- `env use` is honoured (X3): --env, then the default it set, then a .venv here - as --env's help
  always said. It was written and never read. A default whose interpreter is gone is said and
  skipped. The help line says "the one `env use` set" now (32 help snapshots re-blessed for that
  line alone).
- Ctrl-C (and Ctrl-Break, which a supervisor can send) trips the flow's token (X6): the engine's
  process tree is killed, what ran is summarized with the snapshot to roll back to, and the exit
  is 130; a second press quits at once. Verified against a resolve hung on a server that never
  answers: exit 130 the instant the signal arrived, no python left running.
- `update` with neither names nor --all exits 2 instead of planning nothing (X16); `audit` uses
  --engine (X14); `engine` needs no environment (X15); `doctor` judges the configured engine, not
  pip, so a uv-only venv passes (no pip is the uv default); an impossibility skipped off a TTY says
  what and why (X26); `list` probes once instead of twice (X28); names and versions honour
  `{:<32}` (X27); `snapshot diff` compares the way a rollback would across engines.

Verified with a script driving the real binary through each of these: every stdout parses as one
JSON document and every exit matches CLI-SPEC §5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 77ca18cc33 feat(app): the GUI logs, says when it cannot start, and shows where the log is
- The GUI writes data\logs\pipdock.<date>.log through the same core::logging the CLI uses, with
  the panic hook installed, so a crash leaves a record where it used to leave nothing.
- A data folder that cannot be opened is said in a dialog before any window exists (U18). The
  store was opened inside Tauri's setup hook, whose failure is a panic in the event loop: a
  release build has no console, so the user double-clicked and nothing happened. It now opens
  before Tauri starts, and the failure shows the code, the message and the log path through
  rfd - already in the tree via tauri-plugin-dialog, so Cargo.lock gains one dependency edge and
  no crate. It is the one place GUI copy is written in Rust (both languages at once), because no
  webview exists yet to load a catalog.
- logs_tail returns LogTail { dir, lines } - a new schema, so schema-LogTail is blessed and
  schema-unknown-type lists one more type. NOT_YET is down to one entry, env_add_manual.
- Settings gains a Logs row: the folder, as a path, and "Copy recent log", which re-reads the tail
  at the moment of copying so the clipboard holds the run that just went wrong. The clipboard
  permission "Copy full log" already had is enough; no capability changes. en + vi copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 b7fa16a281 feat(logging): a log exists, and the CLI's logging flags do something
There was no log. tracing was a dependency of three crates and called zero times, --verbose and
--log-file were parsed and ignored, LOG_RETENTION_DAYS had no reader, and the privacy policy
described "log files (14-day rotation)" that did not exist. A bug report could attach the last
run's engine output and nothing about what PipDock itself had done.

core::logging owns what both heads share: one file per UTC day under data\logs
(<prefix>.<date>.log, so the GUI and CLI never interleave), a sweep that keeps
LOG_RETENTION_DAYS and never touches a file it did not name, tail() for reading it back, and a
panic hook. What is logged: every spawn's argv, exit code and duration, every stop and its
reason (exec); each resolve's outcome, each snapshot, each run's counts or refusal (flows); and
the engine's own lines at DEBUG.

The CLI always writes its file, at PIPDOCK_LOG or INFO; --verbose adds stderr at DEBUG;
--log-file adds a copy; an internal error (exit 10) prints the log's path on stderr. Nothing goes
to stdout - verified: `install --dry-run --json --log-file x` leaves one JSON document on stdout
and nothing on stderr. The golden suite runs under a scratch LOCALAPPDATA now, and no golden
changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 f4cf9e4959 build(tools): pin the tools venvs' whole dependency tree, not just the tools
tools-requirements.txt pins four tools and nothing beneath them, so every sync resolved their
thirty-odd dependencies against whatever PyPI held that day: a Code Health report was
reproducible for a build only as far as the top of the tree, and a broken or compromised release
of requests, rich or msgpack reached every user on their next sync (H27).

tools/tools-constraints.txt is that tree, compiled once with
`uv pip compile --universal --python-version 3.10 --only-binary :all: --no-emit-package pip`
(the command is in its header), embedded in the binary and passed to the bootstrap as `-c`. One
file serves both venvs because a constraint does not install anything. pip is left out on purpose:
it is the installer, and pip-audit's dependency on it would otherwise make pip replace itself
half-way through installing pip-audit. A test refuses a ledger pin the constraints do not match,
with the command to fix it, so a Dependabot bump cannot ship half-applied.

The manifest hash still covers the tool pins alone, so no existing venv is forced to re-sync.
Verified by syncing both venvs from nothing: every installed package is the constrained version.
Hashes (`--require-hashes`) remain in the backlog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 535b4c8707 fix(health, audit, index, snapshot): what was previewed is what is fixed, and smaller holes
Code Health
- ruff --fix ran `check . --fix` with none of the exclusions the previewed run used (C4). Real
  ruff 0.17.1, verified: it rewrote every .ipynb in the tree - the preview excludes notebooks -
  and, in a project whose pyproject sets its own `exclude` (which replaces ruff's defaults), the
  files under .venv as well. The fix argv is now the read-only argv plus --fix, by construction;
  re-run against both cases, neither file changes.
- git status runs with -c core.fsmonitor=false (M40): a project folder that carries its own
  .git/config could name a program for `git status` to run, and asking "is it safe to write
  here" would have run it.
- One tool whose output cannot be read is that tool's problem, not the run's (H24). A `?` at the
  last step returned from the whole run, taking the other tools' findings with it.
- The fix's own failures speak Code Health's codes, and a timeout says files may already have
  been rewritten (M39). Project paths lose Windows' \?\ prefix, which every filename in the
  report carried (M47).

Security tab
- pip-audit is given pins, not the raw freeze (H21): one editable install failed the whole audit.

Index
- TLS failures read the error's source chain (M32): reqwest's top-level message never mentions
  the certificate, so PD-NET-002's guidance never showed.
- Typed, borrowing parse instead of a Value tree of 700k objects; the ingest runs on a blocking
  thread; connect/read timeouts replace a single 120 s total a slow link could exceed while
  making progress (M36). An empty project list is refused rather than ingested over the index
  (L55).

Snapshots
- Ids are fixed width and the list orders by created_at (M43): the timestamp's trimmed fraction
  made `…09-42Z` sort after `…09-4235606Z`. A sidecar whose id is not a PipDock id is ignored
  rather than used to build a freeze-file path (L54).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 545e86bd31 fix(flow): rollback across engines keeps pip; Hold pins hold; a failed round keeps the preview
- A rollback never removes pip, and across engines leaves pip, setuptools and wheel out of the
  comparison (C7). uv's freeze has no --all, so a uv snapshot never lists them; compared with
  pip's freeze every one looked added since, and the restore uninstalled pip from the
  environment. Meta::engine was recorded for exactly this and read by nothing. Verified: a uv
  snapshot previewed for a pip rollback now reports the environment already matches.
- Hold pins are restated at their version in every resolve (H17). hold_requirements existed and
  nothing called it, so a held package was only left out of the upgrade list and free to move as
  anyone's dependency. A hold never releases the packages it collides with - only a forced pin
  does - so its impossibility is shown as it stands.
- PinMode::Exclude's doc promised one-at-a-time updates that filter_upgrades never allowed. The
  rule stays DATA-FLOW §9.5 and the doc now says so (schema-Pin re-blessed for the wording).
- decide() is transactional and the GUI keeps the flow parked when it fails (U24): a failed
  re-resolve used to leave the new request beside the old report, and plan_decide dropped the
  flow, so the preview on screen had a Confirm that answered "no plan".
- An install no longer runs `list --outdated`, a network sweep of every installed package that
  nothing in an install reads (M28).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 e2e75f63fb feat(flow): PipDock enforces Requires-Python itself, as hard invariant 10 says
Invariant 10 says PipDock enforces Requires-Python because the engines disagree, and nothing
did (C2): PD-PKG-001 existed in the catalog and was never raised. pip refused an incompatible
exact pin with the "No matching distribution" it gives a typo (PD-PKG-002); uv honours the
lower bound, ignores the upper one, planned scipy==1.7.3 on Python 3.14 and failed at install
time building it from source.

The update flow now checks three places:
- exact pins the user typed (name==v, name===v), before any engine sees them. A request that is
  nothing but such pins is PD-PKG-001 with the range and the interpreter; otherwise the pin is
  left out and the preview says so (report.incompatible).
- forced pins: forcing a release this Python cannot run stays held back, with the reason.
- what the engine planned. pip's report already says what each release requires, so nothing is
  asked; for uv's plan PyPI is, and each release that excludes this Python is ruled out by name
  (`name!=v`) and the engine asked again, at most twice - it, not PipDock, picks what is next.

crate::release asks https://pypi.org/pypi/{name}/{version}/json for info.requires_python, at most
eight at once with a 15 s watchdog each, and remembers every answer forever in a new store table
(an uploaded release's metadata never changes). A failure is asked again; unknown never blocks.
The PyPI client is shared per process now, rather than rebuilt for every request (M37, part).

Store v4. Migrations ran on every open - a journal_mode write and eight CREATE TABLEs, on a store
some paths open twice per lookup - and an older build set user_version back down, so the next
newer build re-ran them (M38). Both fixed, with tests.

Verified on Python 3.14: `install scipy==1.7.3` is PD-PKG-001 under pip and uv alike, and
`install scipy==1.7.3 six==1.17.0` plans six and says why scipy was left out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 6ff2a10631 fix(flow): Force latest forces, and says what it breaks before it runs
Choosing Force latest recorded the decision in the request and nothing read it, so the "forced"
resolve was the held-back one again (C6). forced_requirements had existed since M2 with no
production caller. The flow now turns Strategy::ForceLatest into the resolve's GuardAdjust: the
forced package pinned to its latest, and the packages whose constraints held it back released
from the guard set.

Forcing still failed in the canonical case, because the guard set pins every installed package
the plan does not move - the forced package's own dependencies included: httpcore 1.0.9 needs
h11>=0.16 and the guard had h11==0.12.0. Which pins collide is resolution, and PipDock does not
resolve (invariant 3), but the engine names them in its impossibility; forced_collisions
releases exactly those, installed and still pinned, and asks again, at most three times.

report.forced carries each forced package with its blockers - the "Will break" rows DISCLAIMER
§2 requires before anything runs - and the CLI prints them. Verified on a venv seeded with
httpx 0.23.0: under pip and uv both, httpcore -> 1.0.9 and h11 -> 0.16.0, breaking httpx, named.

The underlying over-pinning (a selective upgrade cannot move its target's dependencies) is
recorded in the audit backlog rather than changed here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 3cfb8f82ec fix(flow): PEP 668 is decided on a fresh probe, and the override works
The gate read env.externally_managed - whatever the caller last cached - before anything was
probed, and the rollback flow had no gate at all (H12). The Settings override saved and nothing
read it, so turning it on changed nothing (H11). Every mutating flow now starts with one
preamble: probe, then decide on what the probe says. Without the override a managed
environment is PD-ENV-002 before any engine command; with it, the flow carries
SystemPackages::OverrideAllowed to every mutating engine call.

SystemPackages is a named value, not a bool, for the reason SnapshotProof is a named waiver:
hard invariant 5 says the flag is never passed implicitly, and this makes "implicitly"
greppable. It reaches pip and uv installs and removals, and uv's dry run, which refuses a
managed environment without it (verified, uv 0.13.1); pip's --dry-run --report is exempt and is
never given it. pip implemented PEP 668 in 23.0 and added the flag in 23.0.1, so below 23.0
nothing is passed and pip 23.0 itself is PD-ENV-002.

The CLI reads the override from the store both heads share - deliberately with no flag of its
own - and says on stderr, every run, that it is in force. Verified against a uv-managed
CPython 3.13 with an EXTERNALLY-MANAGED marker: refused without the override (exit 3); with it,
pip installed and uv dry-ran and removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 5d63b31098 fix(flow): a stale or drifted preview is refused, before the snapshot
DATA-FLOW §9.3 refuses a preview older than ten minutes or one whose environment changed. Both
checks existed in AcceptedPlan::verify and neither could fire (C1): the flow created the plan
inside execute() with the current time, so its age was always zero; it passed the resolve-time
listing as the "current" one, so the fingerprint always matched; and plan::execute compared the
plan's env hash with itself.

AcceptedPlan::accept now takes the basis the report was resolved over - the listing and the
resolve time - and the flow re-probes in take_snapshot, after the user confirmed and before
anything is written, so a refusal costs no snapshot. plan::execute verifies against the hash of
the environment it is actually changing, and acts on the re-probed listing.

The same rule reaches the other two flows (M44): an uninstall re-probes before its snapshot, since
a package installed after the guard ran may depend on what is about to go, and a rollback compares
the freeze it takes with the one its restore plan was diffed against.

One plan id (M31): the snapshot said "update-<env>" for every plan ever made in an environment and
the summary carried a different id. Both now carry the flow's, which is unique per plan.

Five new flow tests fail on the previous code and pass on this one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 f9984fa4fb refactor(flow): FlowOptions and an Engine::probe seam
Every flow probed through a free function, so nothing `start` decides - the PEP 668 gate, the
graph, the drift basis, what reaches the resolver - could be reached by a test without a real
interpreter, and the bugs the next commits fix were all there. Engine::probe is a provided
method (it is probe.py, not an engine command; no adapter overrides it), and tests/flows.rs
drives whole flows against a scripted engine that owns a small, mutable world.

FlowOptions carries what the caller decides before a flow starts: the cancellation token and a
clock. The token is the caller's because the first resolve runs inside `start`, and a token
made there could only be handed out after the resolve it was needed to stop. The GUI
registered a token of its own for that window which nothing listened to, so Stop during a first
resolve did nothing at all (H13); plan_resolve now hands its token to the flow, and a test
proves a hung resolve ends on Stop rather than on its watchdog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 7e6ad52b4f fix(graph): platform markers are read, and the lexer is safe on any text
The marker evaluator knew python_version and python_full_version and treated every other
variable as unknown, which keeps the requirement in force. The platform markers had been left
out as "constants for a Windows-only v1" - but a constant still has to be read. Unread,
ipython's `pexpect; sys_platform != "win32"` was in force on Windows, so the dependency view
reported pexpect missing from every Windows environment with ipython in it, and the uninstall
guard and pin suggestions counted edges that do not exist there (H25).

ReverseDeps::for_probe evaluates against probe schema 3's marker environment: platform
variables compare as strings with ==, != and PEP 508's `in` / `not in`, which the lexer now
reads. Whatever the probe did not report - platform_release on Windows - still keeps the
requirement. Every production graph (update and uninstall flows, deps_graph, pin suggestions)
is built this way; build_for remains for callers that know only the Python version.

The lexer skipped whitespace a byte at a time and sliced a word's length before checking the
prefix, so a no-break or ideographic space in some installed package's Requires-Dist cut a
character in half and panicked the command (H19).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 53dedf8625 fix(probe): one METADATA parse, a marker environment, and paths with spaces
probe.py read each distribution's METADATA three times - dist.metadata, then dist.version and
dist.requires, which each re-parse it - on the path every environment open pays (M42). One
parse now; an .egg-info still gets its requires.txt. On CPython 3.14 with 64 distributions the
probe went from 154 ms to 118 ms (median of 15, twice), and the dists array is byte-identical.

Probe schema 3 adds the PEP 508 marker environment, so the graph can tell a requirement in
force from one gated to another platform (H25, consumed in the next commit). It is built from
sys and os: platform.uname() is a WMI query on Windows (55 ms on 3.14) for two values almost no
requirement mentions, which are left out there and stay unevaluated.

Discovery:
- py -0p and uv python list rows are "<key> [*] <path>", and the path may contain spaces
  (H26). Taking the last token turned C:\Program Files\Python312\python.exe - where every
  all-users python.org install goes - into a relative path the existence check dropped.
- A 32-bit all-users Python registers under Wow6432Node, which a 64-bit process does not see
  through the default registry view (M48). HKLM is now read in both views.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 c0301fa3e8 fix(parse): uv is read by its exit status; check findings name the right package
uv's adapter handed every outcome to the plan parser, which looked for the words of a plan
(C3). A build that failed still printed "Resolved 1 package", so it previewed as "no changes";
a refused connection matched nothing and was reported as a uv newer than PipDock (PD-ENG-003);
an unknown name came through the resolver as an impossibility and was auto-skipped as a
conflict. uv_resolution and pip_resolution now decide by exit status first: zero is a plan, an
impossibility is a report, anything else is classified like every other engine failure. A new
corpus test asks that function - the one each resolve returns through - about every failed
capture; classifier_corpus.rs had proved each stderr classifies correctly while the adapter
never asked the classifier. Verified against real uv 0.13.1: PD-PKG-002 and PD-NET-001 (exit 6).

check_text read one of the three shapes real engines print (H18, and one found by breaking an
environment on purpose): pip's version conflicts say "has requirement" and were dropped - the
case a post-run check exists for - and every uv finding ("The package `httpx` requires ...")
was filed under a package called "the".

- A pip yank reason is the one line after the warning that names the package (H23). Flattening
  the whole stderr ran it over pip's [notice] lines, which carry the user's home directory, and
  gave the first of two yanked packages both reasons.
- pip's unreadable output is PD-ENG-999, not PD-ENG-003, whose advice is to switch to pip (M34).
- A pip below 22.2 stops at --dry-run, the first option it does not know, so that line is
  PD-ENG-002 too.
- uv 0.11 (miette glyphs) and 0.13 ("cause:" labels) now explain one conflict in the same words.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 8b18dc4795 feat(engine): a resolve can be stopped, and pip's impossibility is a report
Engine::resolve takes a ResolveCtx: the flow's cancellation token, which now reaches the dry-run
command, and a GuardAdjust the flow will use for Force latest, Hold pins and Requires-Python
exclusions (pins replace a name in the request and the guard set, releases leave the guard set,
exclusions ride as `name!=v`). A stopped resolve is FlowStep::Nothing(Cancelled) - nothing
planned, nothing ran - instead of an error (H13).

pip's ResolutionImpossible was a hard error, so under pip one unsatisfiable package failed the
whole preview while uv offered a per-package Skip. The pip adapter now returns
report.impossible, built from pip's "Cannot install A and B" line (H15). The same request now
exits 2 under both engines.

Running it found a defect the requirement files introduced: pip names a requirement that came
from a file as "-r <temp path> (line N)", so the impossibility lost the package the user asked
for and every error row showed a temp path that had already been deleted.
RequirementFiles::humanize puts the line back; uv names requirements by their text and needs
none of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 d2993bbd7d feat(wire)!: the preview carries what it was missing, and stops carrying the engine's output
A contract change, deliberately in one commit; four schema goldens re-blessed for it
(`ResolutionReport`, `FlowStep`, `CheckReport`, `ExecutionSummary`).

**`ResolutionReport.raw` leaves the wire.** It was pip's whole `--report` document — every
package's README — cloned into each `FlowStep`, serialized over IPC on every round and printed by
`--json` (33 KB for two packages, megabytes for "update all"). Nothing in the UI ever read it. It
stays in Rust (`#[serde(skip)]`) for the log, and for pip it now holds stderr — pip's warnings —
rather than the report the parser already consumed.

**New fields, all omitted when empty, so existing JSON reads the same:**
- `incompatible: [PythonMismatch]` — pins whose `Requires-Python` excludes this environment
  (PD-PKG-001), as structured data: the preview shows the required range against the
  environment's version, which a sentence assembled in Rust could not let it do (invariant 4).
  Filled by a later commit.
- `forced: [HeldBack]` — what "Force latest" will break. Filled by a later commit.
- `yanked: [YankWarning]` — **both adapters parsed yank warnings and then dropped them**
  (`.map(|p| p.report)`), so PD-PKG-003's preview warning has never been shown.
  `ParsedPlan::into_report` keeps them.

**`CheckReport.error`.** A post-execution check that could not run was reported as
`ok: true` — "verified" exactly when nothing was, for instance when the run had broken pip
itself. It is now `ok: false` with the reason's code; the rows still carry the per-package truth.
`CheckReport` therefore embeds `Code`, which makes it the sixth schema that does.

**`NothingReason::Cancelled`**, for a resolve the user stopped (wired in a later commit); the
CLI maps it to exit 130.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 80b2cee9e7 fix(engine): requirements and constraints reach the engine as files
**The command line no longer grows with the environment.** Every plan restates the whole
installed set as requirements (SP-1), and it did so as one argv entry per package — at about 1,300
packages that passes Windows' 32,767-character command line, the spawn fails with os error 206,
and the user was told to install an engine. Resolves and installs now pass `-r <file>` (and
`-c <file>`), written under fresh random names with `TempFile` and deleted on drop. The files hold
exactly the tokens argv held: rendered `PinnedSpec`s and validated `Spec`s. A test restates 2,000
long names and asserts the command line stays under 1,000 characters.

**Every install step holds the rest of the environment still.** SP-1's rule was applied to the
resolve only. Phase B then ran `pip install alpha==2` bare, free to move any dependency — pip warns
and exits 0 when it breaks an installed package's bound — so a failed batch could leave a state
the preview never showed. `Engine::install` now takes an `InstallSet { specs, constraints }`:
Phase A constrains everything the plan does not touch to its current version; a Phase B step adds
the rest of the plan at its planned versions; a rollback restore holds the rest of the restore at
the snapshot's.

Verified against real engines in a throwaway venv (pip 26.2.1 and uv 0.13.1): `-r`/`-c` dry
runs, the SP-1 held-back case and a real install all behave as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 6559ebcc84 feat(model): PEP 440 at the boundary where text becomes argv
SECURITY §2 has always said names *and versions* are validated before argv. Names were; versions
were plain strings, so a dock-bay entry of `2.0 ; python_version<'0'` reached argv as one token pip
read as a requirement whose marker is false — a silent no-op install — and requirements import
failed outright on any range, because `build_request` split on `==` alone (`django>=5.0,<6`
became a "package name"; `pkg===1.0` became version `=1.0`).

New `pep440` module, the one place that says what a version and a specifier set may look like: a
hand-written reader of `packaging`'s `VERSION_PATTERN` (epochs, every pre/post/dev spelling, local
labels — nothing legitimate is refused), a specifier-set grammar (`===`, `.*` prefixes, whitespace
only between an operator and its version), and `is_argv_safe` for installed versions that are not
PEP 440, which the guard set now restates with `===` (packaging dropped `LegacyVersion`, so `==`
would be refused).

Wired in at every way text arrives:
- `Spec::parse` for CLI/GUI install specs and imported requirements; `Spec` and `PinnedSpec` now
  deserialize through the same checks, closing the IPC door the way `PkgName` already did.
- The guard set skips an installed version that could be read as more than one token.
- uv's `+ pkg==0.1.0 (from file:///…)` keeps only the version (it reached argv whole).
- pip report changes and freeze lines with such versions are dropped / unrestorable.
- `pins::validated_hold` and `health::validated_version` were the same charset check twice; both
  use `pep440::is_version` now, which also rejects `1.0--break-system-packages`, a string whose
  every character is in a version's alphabet.

`version_req` is normalized to an operator form (`==0.28.1`), which `plan_argv_specs` already
rendered identically. The one golden that moved is `schema-PlanRequest`, for its doc text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 3e4f3d0243 fix(plan): Phase A under Stop, a watchdog and an environment-wide failure
`plan::execute` ran the batch with `engine.install(...).await?`. The real adapters return `Err`
when the batch is stopped or cannot start, so that `?` sent all of these out of `execute` as
PD-INT-001 — no summary, no "cancelled", no rollback offer:

- **Stop during Phase A**, which is most of any run: the cancelled-Phase-A branch right below was
  unreachable outside a test whose fake engine returned `Ok` on cancel.
- **The watchdog** on a long sdist build: the whole run aborted, contradicting the
  skip-and-continue requirement it exists to keep.
- **An engine that will not start**.

Now an `Err` is an outcome: a user's cancel marks every row Skipped with `cancelled: true`; any
other failure becomes the batch's code on every row.

**Phase B only runs when it could help.** Isolating re-ran every package one at a time after
*any* batch failure — offline, read-only site-packages, a full disk, a missing or too-old pip, a
watchdog — each meeting the same wall after pip's own retry backoff. `isolates()` keeps those in
Phase A, with the stderr tail on the first row only instead of N copies of one network trace.

**Rows say what they moved from** (`StepResult.from`), taken from the plan's changes; the
engines cannot know it, so every row carried `None` and the summary and `--json` called every
upgrade a fresh install.

A rollback no longer runs `pip check` between its removals and its restores — it nested
`execute_uninstall`, post-check included; both now share the removal loop.

Five new tests, each failing before this: a fake engine that returns `Err(Stop::Cancelled)`,
`Err(Stop::TimedOut)` and a spawn failure the way the adapters do, an offline batch that must not
be isolated, and `from` through both phases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 8ddb2317f4 refactor(exec): a stopped run says why in its type; the pump survives any bytes
**Typed stops.** A cancelled or watchdog-killed command now returns a `PdError` carrying
`stop: Some(Stop::Cancelled | Stop::TimedOut(_))` (never on the wire). Three modules decided
"was this a cancel or a timeout?" by matching the `"cancelled:"` / `"timed out"` prefixes
`Command::stopped` happened to write — so pip's own "Read timed out" network error was relabelled
a watchdog by Code Health's remap. They ask `is_cancelled()` / `is_timeout()` now. A timeout
carries PD-ENG-004 at this layer; Code Health and the audit still remap it to their own codes.

**The pump reads bytes.** tokio's `lines()` errors at the first byte that is not UTF-8, and the
loop treated that as end of stream: it stopped reading and dropped the pipe, so the child died on
a broken pipe mid-install and the stderr the classifier needed was cut short. MSVC prints in the
OEM code page, so a non-English Windows was one failed source build away. Lines are now read
with `read_until` and decoded lossily; a test writes raw cp-1252/cp-932 bytes through
`cmd /C type` and asserts the line after them arrives.

**Watchdogs per kind of work** (`exec::watchdog`): install 30 min, resolve and `--outdated`
10 min, local queries 3 min, `probe.py` 60 s, `py -0p` / `uv python list` 30 s. One 600 s budget
let a hung `py -0p` hold the Environments screen for ten minutes and killed a slow scipy build.

**Spawn failures map by cause**: a missing interpreter is PD-ENV-001 (it was PD-ENG-001,
"install the engine"), a command line past 32,767 characters is PD-SYS-001.

**`TempFile`** replaces `write_temp`: `create_new` with retry, deleted on drop. The old function
documented that an overwritten temp file would be harmful and then called `fs::write`, and its
comment described a nonce scheme the code did not use. `io_error` maps filesystem failures to
the code whose advice fits (disk full, path too long, permission) instead of always "disk full".

**`Command::python_tool`** gives vulture, deptry and pip-audit the UTF-8 environment
`Command::python` gives interpreters; they are Python launchers and were spawned without it.

**`probe.py` runs with `-X utf8`.** `-I` implies `-E`, which ignores PYTHONUTF8 and
PYTHONIOENCODING, so the probe wrote through the ANSI code page: a venv under a folder named with
Vietnamese diacritics crashed it with UnicodeEncodeError (PD-ENV-003, reproduced) and a Latin-1
path came back as mojibake. `-X` is a command-line option, which isolated mode honours.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 9409a82e84 test(fixtures): pip 26.2.1 and uv 0.13.1 captures, both uv renderings under test
Re-captured by the drift job itself (workflow_dispatch on this branch, Python 3.12.10, artifact
`captured-fixtures`) rather than on a dev machine, so next Monday's run compares like with like.
Copied byte for byte; CRLF counts unchanged where the engine's output did not change.

What actually moved:

- **uv 0.13.1** renders every failure as `error: …` / `cause: …` instead of miette's `× …`,
  `╰─▶` and "Caused by:". The phrases the classifiers key on survived, so nothing reclassified —
  `both_uv_renderings_classify_identically` now pins that, against the frozen `uv-0.11/` corpus.
  The build failure also moved from `build_wheel` to `get_requires_for_build_wheel` and gained a
  `hint:` line.
- **pip 26.2.1** (it was 25.0.1 all along — the capture never upgraded it) prints no release
  notice, and for an unsatisfiable `scipy==1.7.3` now says *which* versions it ignored and why:
  "Ignored the following versions that require a different python version: … 1.7.3
  Requires-Python >=3.7,<3.11". pip 25 said only "No matching distribution found", which is why
  ERROR-CATALOG calls PD-PKG-001 unclassifiable from stderr. On pip ≥ 26 it no longer is.
- `clean-upgrade` now upgrades to the pinned idna 3.10 in both live corpora.

`plan_parsers.rs` and `classifier_corpus.rs` run over `pip/`, `uv/` and `uv-0.11/`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 2b4681954b feat(errors): PD-ENG-004 for an engine watchdog; WinError rules match exactly
**PD-ENG-004 `EngTimedOut`.** Every engine command shares one watchdog, and when it fired the run
reported PD-INT-001 — "PipDock hit an internal error" — for an sdist build that was simply still
compiling, and in the batch phase that error aborted the whole run with no summary and no
per-package retry. A timeout is a fact about the engine, not a PipDock bug, so it gets its own
code. Raised by PipDock, never classified from stderr, so it joins the `internally_raised` table of
the corpus gate. The exec layer starts producing it in the next commit.

The nine places: the catalog variant (`as_str`, `area`, `ALL`), both count tests (34 → 35), the
corpus gate, both `errors.json` catalogues, `codes.json` and `generated.ts` (regenerated, not
edited), the ERROR-CATALOG row (31 → 32 rows), and the five schema goldens that embed `Code` —
`Code`, `StepResult`, `ExecutionSummary`, `HealthReport`, `AuditReport` — each re-blessed for
exactly one new `const`, which is the contract change this is.

**WinError needles include the closing bracket.** Python prints `[WinError N]`, and the bare
"winerror 5" also matched 50, 53 and 59: `[WinError 53] The network path was not found` came out
as PD-PRM-001, "use a venv". `[WinError 53]` and `[WinError 10013]` (a firewall refusing the
socket, raised *as* a PermissionError) now classify as network failures, ahead of the permission
rules that would otherwise take them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 2b07d4057b test(fixtures): the drift gate measures engines, not PyPI
The weekly re-capture has failed seven Mondays running (since 2026-08-31), and for most of them no
engine had changed at all:

- `clean-upgrade` asked for the *latest* idna, so 3.18 → 3.20 was "drift". Pinned to idna==3.10.
- pip's "(from versions: …)" listed every scipy release, so the requires-python fixture grew with
  each one. Redacted, like the release notice before it; no classifier reads it.
- The capture never upgraded pip: every venv ran the CPython-bundled 25.0.1 while 26.2.1 was
  current, so the job meant to catch a pip output change could not see one. `venv.create(...,
  upgrade_deps=True)`, and the report's `pip_version` is redacted because it now moves with each
  pip release (provenance still records it).
- `python-version: '3.12'` floated with the runner image, and the Python patch is recorded in both
  engines' output. Pinned to 3.12.10, the version every committed fixture was captured with.

The job now uploads what it captured whether or not the gate passes, so a real drift is fixed by
reviewing and committing exactly those bytes. `capture.py` also refuses an unknown `--only` name
(it used to capture nothing and exit 0) and exits 1 when nothing was captured; its two
backtracking-prone patterns (SonarCloud S8786) became a `[ \t]` class and a `partition`.

The other half of the red was real: uv 0.13.0 (2026-10-09) replaced its miette rendering — `×`,
`╰─▶`, "Caused by:" — with "error:" / "cause:". `UV_MIN_VERSION` is 0.10, so both renderings stay
under test: the current captures are frozen as `uv-0.11/` (uv 0.11.32, byte-identical copy) before
`uv/` is re-captured against the newest uv. The disposable-venv suite also stops running twice on
Monday mornings (the drift cron matched it too).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 91a846c0fd build(deps): every dependency to its latest release
Supersedes Dependabot #75, #76 and #77, which could not merge while `main`'s audits were red.

Rust (floors raised to what is locked, so the manifests say what is built):
- tauri 2.11.5 → 2.12.4 and tauri-build 2.7.3, with the plugins dialog 2.8.3, opener 2.7.2,
  clipboard-manager 2.5.0 and single-instance 2.5.4 — in lockstep with `@tauri-apps/*` 2.12, which
  Tauri's own version check requires.
- **rusqlite 0.37 → 0.40.2** (libsqlite3-sys 0.38.2, SQLite 3.53.2). ARCHITECTURE §10 held it
  because libsqlite3-sys used the then-unstable `cfg_select!`; that is stable since 1.95 and the
  toolchain is now 1.99.1. Nothing here used `u64`/`usize` `ToSql` (disabled by default since
  0.38) or `prepare_cached` (optional since 0.38), and 0.40.1 fixes a SAVEPOINT-name injection.
- reqwest 0.13.5, tokio 1.53.3, tokio-util 0.7.20, jiff 0.2.38, clap 4.6.7, schemars 1.2.3,
  sha2 0.11.1, thiserror 2.0.21, serde_json 1.0.154, async-trait 0.1.92, insta 1.49.0, and 211
  transitive updates (h2 0.4.20 among them).

npm: React 19.3.1, Vite 8.3.4, @vitejs/plugin-react 6.1.2, **Vitest 5.0.5** (all 18 `vi.mock`
calls were already top-level), ESLint 10.12.0, typescript-eslint 8.71.2, jsdom 30.1.3,
@tanstack/react-virtual 3.14.21, i18next 26.4.7, react-i18next 17.0.19, @types/* current.
**TypeScript stays 6.0.3**: typescript-eslint 8.71.2 still peers `>=4.8.4 <6.1.0`.

Code Health pin: ruff 0.16.3 → 0.17.1. Verified by running it, not by reading its changelog:
`health/sample/capture.py` reproduces all four committed `ruff/*.json` byte for byte, and exit
codes 0/1/2 still mean clean/findings/error.

Two things the upgrade surfaced in the frontend, both real:

- virtual-core 3.19 measures the scroll element with `clientWidth`/`clientHeight` (it used
  `getBoundingClientRect()`), and that first reading replaces `initialRect`. jsdom reports 0, so 13
  table tests and 5 App-level ones went back to rendering an empty grid; the setup now stubs the
  two properties beside the `offset*` ones.
- jsdom 30.1 implements "a closed `<dialog>`'s contents cannot take focus", which is the spec.
  React applies `autoFocus` by calling `focus()` during commit — *before* PdDialog's effect calls
  `showModal()` — and never writes the `autofocus` attribute, so neither path focused Cancel. It
  worked in WebView2 only because Cancel is the first focusable element. PdDialog and the palette
  now focus explicitly after `showModal()`, and return focus to whatever opened them on close
  (it fell to `<body>` before).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 d9c62ec6c9 fix(deps): rustls 0.23.46, quinn-proto 0.11.19, and the npm highs — main is green again
`main` has failed `cargo audit` since 2026-09-23 and every PR with it, because both audit checks are
required:

- rustls 0.23.42 → 0.23.46 (RUSTSEC-2026-0285, TLS 1.3 handshake messages accepted across key
  changes). `cargo update -p rustls` alone stops at 0.23.43: the fix needs aws-lc-rs 1.18 and
  rustls-webpki 0.103.15, which a conservative update will not move, so it is pinned with
  `--precise`.
- quinn-proto 0.11.16 → 0.11.19 (RUSTSEC-2026-0338..0342). Lockfile-only — nothing compiles quinn
  — but `cargo audit` scans the whole lockfile.
- chacha20 0.10.1 → 0.10.2 (the old one is yanked).
- npm: undici 8.9.0 → 8.12.2 (via jsdom), source-map-js 1.2.1 → 1.2.2, brace-expansion → 5.0.12, all
  dev-only. `npm audit fix` without `--force`; `npm audit --audit-level=high` reports 0.

Dependabot could not have done this: there are no Dependabot alerts for rustls, and its grouped PRs
only move direct dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
poli0981andClaude Opus 5.5 1af0ec127b build(toolchain): Rust 1.99.1
Five stable releases behind (1.94.1, 2026-03-25). Two reasons to move now rather than on the next
Dependabot nudge:

- The rustls fix for RUSTSEC-2026-0285 (>= 0.23.45) does not resolve under `rust-version = "1.94"`:
  resolver 3 is MSRV-aware and stops at 0.23.43, so `main`'s red `cargo audit` cannot be fixed on
  the old pin at all.
- `cfg_select!` is stable since 1.95, which is the condition ARCHITECTURE §10 set for lifting the
  rusqlite 0.37 hold.

`rust-version` moves with the pin, so the workspace never claims a floor it is not built with.
Clippy 1.99 adds `chunks_exact_to_as_chunks`; the build script's SHA-256 now uses `as_chunks`, which
also removes two `try_into().unwrap_or` fallbacks that could never fire.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:55:27 +07:00
dependabot[bot] 2300b637a9 build(deps): Bump @vitest/mocker and vitest
Bumps [@vitest/mocker](https://github.com/vitest-dev/vitest/tree/HEAD/packages/mocker) to 4.1.11 and updates ancestor dependency [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest). These dependencies need to be updated together.


Updates `@vitest/mocker` from 4.1.10 to 4.1.11
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/mocker)

Updates `vitest` from 4.1.10 to 4.1.11
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/vitest)

---
updated-dependencies:
- dependency-name: "@vitest/mocker"
  dependency-version: 4.1.11
  dependency-type: indirect
- dependency-name: vitest
  dependency-version: 4.1.11
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-23 07:32:37 +07:00
poli0981andClaude Opus 5 f770e9c85f fix(deps): h2 0.4.16 — RUSTSEC-2026-0258
Unrelated to this slice, and blocking its required `cargo audit` gate.
`main` is equally affected: the advisory was published 2026-08-17 and
reached the RustSec database at 10:23+02:00 on the 18th, while main's
last audit ran at 07:08 that morning and passed. The next push to main
would have failed on it regardless of this branch.

Low severity, denial-of-service: h2 accepted and queued empty DATA
frames without limit, so an undrained stream could grow memory without
bound or panic on length overflow. Reached transitively through
reqwest and hyper; PipDock's only network use is the package index and
metadata fetches, both to pypi.org, so nothing here is exposed to an
attacker-chosen peer. Fixed rather than ignored anyway, because
SECURITY.md is explicit that the vulnerability gate is never relaxed —
the `.cargo/audit.toml` ignore list is for *informational* advisories
on crates we cannot influence, and this one has a patch release.

`cargo update -p h2 --precise 0.4.16` and nothing else. The lockfile
diff looks alarming and is not: sixteen of its eighteen lines are
dependency *edges* re-pointing between `windows-sys` copies that
already coexist in the lock — five of them before this change and five
after. No package is added, removed or downgraded, and the only version
that moves is h2's own. `cargo check --workspace --all-targets` and the
full test suite pass on it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 02cc17d95d docs: the dependency view recorded, and 1.3.0
UI-SPEC §4 gains the screen and **loses the sentence it contradicted**.
It said the third row action folds all three into a `⋮` menu "with the
budget intact"; that makes uninstall four clicks where §5's table
records three, hand-counted. The correction is written as a correction
rather than an overwrite, because the reason it slipped through is the
useful part: four is under the ceiling of five, and a ceiling is not a
ratchet — a table of measured counts is. §5 gains the row, §6 the
component, ARCHITECTURE §4 the forward direction and the whole-graph
value.

**The dangling cross-reference is repaired by writing what it promised.**
`ROADMAP.md` has pointed at "the analysis above" for what blocks P1-6
and P1-7 since 1.2.0, and no such analysis was anywhere in the document
— the survey lived only outside the repository, and the sentence had
been copied into CLAUDE.md as well. P1-6's half is its slice record.
P1-7's is now written too, and counted against the tree rather than
recalled: no toast component, no notification/autostart/tray dependency,
one plan-scoped `tokio::spawn` and zero intervals in either head, and no
surface that can report a failure at 03:00 while `logs_tail` is still
`NOT_YET`. Drafting this commit I nearly shipped a CLAUDE.md line
claiming that survey existed before I had written it, which is the same
defect one layer up.

Version in five places, moved together: the workspace inherits it, so
`Cargo.toml`, `package.json` and `tauri.conf.json` are the only hand
edits and the two lockfiles are regenerated. Hand-editing `Cargo.lock`
would have been wrong twice over — `scopeguard` and `simd_cesu8` are
also at 1.2.0 and `fs_extra` was already at 1.3.0. `cargo metadata
--locked` passes, which is the one-command check.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 8609518a37 test(ui): drive the shell against a logging bridge
The jsdom form of the recipe that has found more real defects here than
any suite: render the app, log every command that crosses, read back
what actually happened. Stage 2 found every screen fetching twice this
way and Stage 4 found a plan resolving into a screen that does not
render it — both faults *between* components, which is the one place a
component suite cannot look.

It proves the premise the slice is built on where it can actually be
observed: `deps_graph` crosses **once** when the view opens and **zero**
times on a re-centre. It also covers the seam nothing else did — the
row's new button through the table, the screen, the store and out to the
bridge — and pins the three row actions with none of them a tab stop.

Writing it found the trap the browser recipe already records, in its
jsdom form. `App` calls `checkConsent()` on mount and
`useLegalStore.check` **fails closed**, so setting `accepted: true` in
the store is undone a tick later by the real command rejecting and the
legal gate replaces the entire shell. The store reached `phase: 'ready'`
with the graph in hand and every assertion was reading a licence
agreement. Both halves have to be stubbed; the comment says so.

The browser pane could not reach localhost in this session, so this
stands in for the live drive rather than replacing it — the Rust side
of a command and the real window still want a human.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 6ef677bc01 feat(ui): the dependency view, drawn at the one depth that survives the data
A mode of the package screen, not a tenth tab. `PdEnvironments` switches
to `PdEnvDetail` on `openFor`; this switches on `focus`, for UI-SPEC §4's
reason: `Ctrl+1..9` is positional over `NAV_KEYS`, appending is free and
inserting is not, and a Dependencies tab would have to sit beside
Installed to read as related. `NAV_KEYS` is already nine, so a tenth
entry would have no digit at all.

Three columns at depth 1, and depth is navigated by re-centring rather
than drawn. That is a measurement, not a preference: on the 352-package
fixture a depth-1 neighbourhood is a median of 7 nodes, and depth 2 is a
median of 172 and exceeds 60 for 212 of 352 packages. No layout
algorithm makes 172 nodes legible, so the eleventh runtime dependency, a
THIRD-PARTY-NOTICES edit that re-shows the legal gate, and a CSP
argument all buy a picture nobody can use. Transitive reach is two
numbers instead, and paths are not offered at all — `setuptools` has
more than 2000 distinct paths to a root in that environment.

**UI-SPEC §4 said the third row action folds all three into a `⋮` menu.
It does not.** A menu spends one click opening and one choosing, so
uninstall becomes four clicks where §5's table records three,
hand-counted. Four is under the ceiling of 5, which is exactly why the
budget alone would have let it through. A third inline button costs
nothing: the row is the only tab stop, so the controls are a roving
sequence and a third is one more arrow step, not 200 more stops.

Nothing is carried by colour. `styles.css` rebinds every `--color-*` to
a system keyword in forced-colors, so every edge states its specifier as
text and the columns are told apart by heading and position.

`deps_graph.json` is computed by `fixtures::deps_graph`, never written —
`numpy_blockers`' lesson. It turned out to carry two dependents with two
different specifiers *and* two packages with unsatisfied requirements,
which is more than a hand-written one would have thought to include.

Two defects the tests found by being run against mutations rather than
by being written: a column helper keyed on copy silently matched nothing
once the heading pluralised ("2 packages require this", not "requires"),
and a name-only comparison of the dependents column passed a mutation
that dropped the version and the specifier from every row.

The invalidation is the one this slice was warned about: `freshGraph`
keys on `envHash`, which a mutation does not change, so `App.tsx` resets
the slice in `onFinished`. Health and Security guard and never reset
because nothing they read is altered by an install. Edges are exactly
what an install alters.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 c58fcac523 feat: deps_graph, and the shape it deliberately is not
`pin_suggestions`' shape, not `audit_run`'s. No `Sessions` slot, no
progress channel, no cancellation: those exist because an audit is
18-68 seconds, and a probe is 605 ms. Borrowing them here would be a
constant carrying its original units — the mistake `AUDIT_TIMEOUT`
already records.

One call per environment rather than one per package, which is the
whole reason the value is shaped this way. The view re-centres on a
click; a `deps_for(pkg)` command would read more naturally and pay a
probe for every click to answer a question the previous probe already
held the data for.

No store read, so there is no guard to drop — `pkg_list` is the same
and for the same reason. All five sites: the command, the handler list,
`COMMANDS`, the wrapper with `DepsGraph` added to the `import type`
list (`export type *` does not bring it into scope for a wrapper's own
signature), the `test/ipc.ts` mock, and ARCHITECTURE §7 — with its
trailing pipe, which the test added two commits ago now checks.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 4ddec61ebb feat(wire): DepsGraph is a schema type
Registered in `schema_for!` and `SCHEMA_TYPES`, and in `golden.rs`'s own
copy of that list — the deliberate second list, which
`schema_lists_exactly_the_documented_types` holds in step by reading the
real one back out of the binary.

Only the root type, as the comment beside `HealthReport` says: the
generator hoists every `$defs` entry, so `DepEdge` and `DepsNode` arrive
as their own TS declarations without being listed, and listing them
would emit each twice.

`golden__schema-unknown-type.snap` churns because the error message
enumerates every known type, which is a real behaviour change rather
than noise. 67 snapshots.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 bf2947b6c3 feat(core): the forward direction, and the graph as one value
`ReverseDeps` has been reverse-only since S3. Three features read it and
all three look exactly one edge out, so nothing ever needed to ask what
a package requires. PRD P1-6 does.

`forward` is built in the same pass, from the same parse, and filtered
by the same `applies_in` rule — a second traversal is how the two
directions would come to disagree. `edges_to` goes further and projects
`breaking_dependents` rather than walking `edges` again, so the
dependents column and the uninstall guard are the same set by
construction; the test asserts it whole rather than by name, after a
mutation that dropped the version and the constraint passed a name-only
comparison.

`unsatisfied` is the one thing this can say that the package list
cannot, and it is only trustworthy because the markers are evaluated.
Measured on the 352-package fixture: counting raw `Requires-Dist` names
reports **7** missing packages; evaluating markers reports **1**. The
other six are backports gated on a Python this environment is not. That
gap is the whole argument for this living in Rust.

`view` crosses the bridge whole rather than a package at a time,
because the alternative pays a 605 ms probe on every re-centring click.
Uncapped on purpose: the window is bounded in the view, but the
"+ N more" count has to come from the full set or a capped view
misreports a total.

Measured in --release against C:\Python314, 352 packages: build 1.8 ms,
view 42.9 ms, payload 249 KB, 1858 in-force edges, impact median 20 /
p90 111 / max 178. Having `reach` walk `forward` itself takes the view
to 31.4 ms — 1.8% of the probe the user is already waiting for, bought
with a second copy of the in-force rule. Declined, and the number is in
the doc so it is not re-litigated.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 3152c55eaa fix(docs): three things main was carrying, and the gate that missed one
Found while surveying P1-6. None is caught by any suite, which is the
common thread rather than a coincidence.

`docs/ARCHITECTURE.md`'s `audit_run` row was the only row in the §7
command table missing its trailing pipe, so the table rendered wrong
from 1.2.0. Every gate passed: the command is registered, declared and
documented, and `documented()` strips only the *leading* pipe, so the
row parsed correctly and nothing looked at its shape. A spec sentence
is not a test — and neither is a spec table. The new
`the_architecture_table_is_well_formed` asserts the shape as well as the
contents, and was mutation-checked against the row it was written for.

`catalog.rs`'s comment read "Rust has 33; docs tabulates 30" three
lines above `assert_eq!(Code::ALL.len(), 34)`. Both numbers were one
behind; the doc tabulates 31, folding PD-HLT-001..004 into one row.

CLAUDE.md's error-code checklist named three schemas embedding `Code`
while saying "four", and 1.2.0 made it genuinely four by adding
`AuditReport` via `ToolProblem.code` — five snapshot files in all. So
anyone adding a code today would leave `golden__schema-AuditReport.snap`
stale. The line now says to grep `PD-ENV-001` across the snapshots
rather than trust the list, because that is how the omission was found.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
293 changed files with 17003 additions and 4191 deletions

No files matched your search

+2 -4
View File
@@ -29,10 +29,8 @@ ignore = [
"RUSTSEC-2024-0419", # gtk3-macros — unmaintained
"RUSTSEC-2024-0420", # gtk-sys — unmaintained
"RUSTSEC-2024-0429", # glib — unsound (VariantStrIter::impl_get); same GTK3 stack
# --- Build-time only -----------------------------------------------------
# A proc-macro helper pulled in by a build dependency. It never reaches a shipped binary, and
# the advisory is "unmaintained", not a defect.
# A proc-macro, reached through glib-macros: the same stack, not a build dependency of
# PipDock's as this file used to say (`cargo tree -i proc-macro-error --target all`).
"RUSTSEC-2024-0370", # proc-macro-error — unmaintained
# --- unic-* Unicode tables ----------------------------------------------
+2 -1
View File
@@ -13,7 +13,8 @@ body:
id: pd-version
attributes:
label: PipDock version
placeholder: "1.0.0"
# Not a version number: any example goes stale with the next release, as "1.0.0" did.
placeholder: "x.y.z — shown under About → This build"
validations:
required: true
- type: input
+55 -7
View File
@@ -4,10 +4,22 @@
# ops repo, and that repo ships a dependabot-summary.yml, which makes Dependabot the portfolio
# standard.
#
# Grouping intent carried over from the original spec: weekly grouped minor/patch PRs per
# ecosystem, and Code Health pins kept in their own group so they stay reviewable in isolation.
# Security advisories bypass grouping and schedule automatically — that is Dependabot's default
# for security updates and cannot be configured away here.
# Weekly grouped PRs per ecosystem, with Code Health's pins kept apart so a tool bump is reviewed
# on its own. Security advisories bypass grouping and schedule — that is Dependabot's default for
# security updates and cannot be configured away here.
#
# **Cooldown**: a release has to be a few days old before it is proposed. Most yanked or
# compromised releases are pulled within that window, and nothing here needs a dependency the day
# it ships.
#
# **Tauri moves in lockstep**: the `tauri` crate and `@tauri-apps/api` must share a minor or the
# app will not start, and Dependabot cannot bump Cargo and npm in one pull request — a
# multi-ecosystem group can, but what it does to the dependencies outside its patterns is not
# documented, and guessing wrong would silently stop every other update. So each ecosystem groups
# its Tauri packages into one PR, and ci-node.yml's `tauri lockstep` job fails either PR until its
# counterpart is merged beside it.
#
# The labels below must exist in the repository, or Dependabot opens its PRs without them.
version: 2
@@ -18,7 +30,13 @@ updates:
interval: weekly
day: monday
open-pull-requests-limit: 5
cooldown:
default-days: 3
semver-major-days: 14
groups:
# First, so a Tauri crate never lands in the catch-all group below.
tauri:
patterns: ['tauri', 'tauri-*']
cargo-minor-patch:
update-types: [minor, patch]
labels: [dependencies, rust]
@@ -29,7 +47,17 @@ updates:
interval: weekly
day: monday
open-pull-requests-limit: 5
cooldown:
default-days: 3
semver-major-days: 14
ignore:
# typescript-eslint 8.71 peers `typescript >=4.8.4 <6.1.0`, so a 6.1 bump fails `npm ci` with
# ERESOLVE before a single check runs. Remove once typescript-eslint widens its range.
- dependency-name: typescript
versions: ['>=6.1.0']
groups:
tauri:
patterns: ['@tauri-apps/*']
npm-minor-patch:
update-types: [minor, patch]
labels: [dependencies, frontend]
@@ -39,14 +67,34 @@ updates:
schedule:
interval: weekly
day: monday
cooldown:
default-days: 7
groups:
actions:
patterns: ['*']
labels: [dependencies, ci]
# Code Health tool pins (deptry / vulture / ruff), shipped with the app and resolved at release
# time — CODE-HEALTH-SPEC §2. Kept as its own ecosystem so a bump here is never bundled with
# application dependencies.
# Code Health tool pins (deptry / vulture / ruff / pip-audit), shipped with the app and resolved
# at release time — CODE-HEALTH-SPEC §2. Its own ecosystem, so a bump here is never bundled with
# application dependencies. A bump also needs tools-constraints.txt regenerated (the command is
# in its header); `cargo test` fails until it is.
- package-ecosystem: pip
directory: /tools
schedule:
interval: weekly
day: monday
cooldown:
default-days: 7
groups:
code-health:
patterns: ['*']
labels: [dependencies, code-health]
# rust-toolchain.toml's pinned channel. A toolchain bump brings new clippy lints, which is why
# it gets a PR of its own rather than arriving with a cargo update.
- package-ecosystem: rust-toolchain
directory: /
schedule:
interval: weekly
day: monday
labels: [dependencies, rust]
+36 -1
View File
@@ -23,7 +23,19 @@ on:
# against a real interpreter is only ever exercised here.
- 'crates/pipdock-core/src/probe.py'
- 'crates/pipdock-core/src/health/**'
# Every end-to-end step drives the CLI, and these are what it runs through. A change to
# any of them reached `main` without this job ever seeing it.
- 'crates/pipdock-cli/**'
- 'crates/pipdock-core/src/exec.rs'
- 'crates/pipdock-core/src/audit.rs'
- 'crates/pipdock-core/src/release.rs'
- 'crates/pipdock-core/src/errors/**'
- 'crates/pipdock-core/src/store/**'
- 'crates/pipdock-core/src/index/**'
- 'crates/pipdock-core/tests/**'
# A dependency or toolchain bump is a change to all of the above at once.
- 'Cargo.lock'
- 'rust-toolchain.toml'
- 'spikes/capture.py'
# A Dependabot bump to the Code Health pins has to re-run the bootstrap: whether the new
# pin set still resolves to wheels on 3.10 and 3.14 is exactly what this job can answer
@@ -57,6 +69,9 @@ env:
jobs:
disposable-venvs:
name: Real engines, throwaway venvs
# The Monday cron exists for the drift job below. Without this the whole suite ran twice every
# Monday morning, an hour apart, against the same commit.
if: github.event_name != 'schedule' || github.event.schedule != '17 4 * * 1'
runs-on: windows-latest
timeout-minutes: 45
strategy:
@@ -67,6 +82,8 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Setup Python ${{ matrix.python }}
uses: actions/setup-python@v7
@@ -384,11 +401,16 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
# An exact patch, on purpose. pip's report records `python_full_version` and uv prints "Using
# Python 3.12.x environment", so a floating `3.12` turns every runner-image Python bump into
# a fixture diff that says nothing about pip or uv. Bump it deliberately, and re-capture.
- name: Setup Python
uses: actions/setup-python@v7
with:
python-version: '3.12'
python-version: '3.12.10'
- name: Install the newest uv
run: |
@@ -402,6 +424,19 @@ jobs:
python spikes\capture.py --engine pip
python spikes\capture.py --engine uv --uv-exe .uvtools\Scripts\uv.exe
# Uploaded whether or not the gate below passes: when it fails, the fix is to review and
# commit exactly these bytes, and re-running the capture elsewhere produces different ones
# (another interpreter, another network, another day's index).
- name: Upload the captured fixtures
if: always()
uses: actions/upload-artifact@v7
with:
name: captured-fixtures
path: |
crates/pipdock-core/tests/fixtures/pip
crates/pipdock-core/tests/fixtures/uv
if-no-files-found: error
# A diff means an engine changed its output. That is exactly the PD-ENG-003 situation the
# adapters degrade into, and catching it here is what stops a user meeting it first.
#
+29 -7
View File
@@ -1,4 +1,4 @@
# Caller into the ops repo's React reusable, plus one local job.
# Caller into the ops repo's React reusable, plus local jobs.
#
# The reusable runs Node 24, `npm ci`, then lint / typecheck / test when the matching npm script
# exists, then the build. It has no `npm audit` step, so that gate lives here — see
@@ -14,13 +14,8 @@ on:
push:
branches: [main]
# The reusable declares a Pages-deploy job needing `pages: write` and `id-token: write`. It is
# skipped here (`deploy-pages: false`), but permissions are validated at startup regardless of
# `if:`, so a caller that grants less than the callee declares is rejected before it runs.
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: ci-node-${{ github.ref }}
@@ -29,6 +24,14 @@ concurrency:
jobs:
web:
name: lint · typecheck · test · build
# The reusable declares a Pages-deploy job needing `pages: write` and `id-token: write`. It is
# skipped here (`deploy-pages: false`), but permissions are validated at startup regardless of
# `if:`, so a caller that grants less than the callee declares is rejected before it runs.
# Granted on this job only, not the workflow: the other jobs here never need to write.
permissions:
contents: read
pages: write
id-token: write
uses: poli0981/.github/.github/workflows/reusable-web-react.yml@main
with:
node-version: '24'
@@ -44,6 +47,8 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@v7
@@ -51,8 +56,25 @@ jobs:
node-version: '24'
cache: npm
# The audit reads the lockfile; nothing is built, so no install script has a reason to run.
- name: Install
run: npm ci
run: npm ci --ignore-scripts
- name: Audit
run: npm audit --audit-level=high
lockstep:
name: tauri lockstep
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
# Tauri refuses to run when the `tauri` crate and `@tauri-apps/api` are on different minors,
# and Dependabot bumps the two ecosystems in separate PRs — so either one, merged alone,
# leaves a `main` that builds and does not start. The script reads both lockfiles.
- name: Crate and npm package on one minor
run: node scripts/check-tauri-lockstep.mjs
+41 -11
View File
@@ -30,6 +30,8 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
# rust-toolchain.toml pins the exact version, so no toolchain action is needed — rustup
# honours it on first invocation and installs rustfmt and clippy with it.
@@ -62,19 +64,47 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
env:
# The action builds cargo-audit from source, and rust-toolchain.toml would otherwise pin
# that build to PipDock's toolchain. cargo-audit's own dependency tree already requires a
# newer rustc than we pin (kstring needs 1.96), so the audit failed to compile rather than
# finding anything. It only reads Cargo.lock, so building it with stable is correct — the
# pin exists to make *PipDock* reproducible, not its tooling.
# cargo-audit only reads Cargo.lock, so it runs under the runner's stable cargo rather than
# making rustup install the toolchain rust-toolchain.toml pins — that pin exists to make
# PipDock reproducible, not its tooling.
RUSTUP_TOOLCHAIN: stable
steps:
- name: Checkout
uses: actions/checkout@v7
# RustSec advisories against the committed Cargo.lock. Split from the Windows job because
# it needs no target build — it is a lockfile scan.
- name: Audit
uses: rustsec/audit-check@v2
with:
token: ${{ secrets.GITHUB_TOKEN }}
persist-credentials: false
# A prebuilt cargo-audit, pinned by commit. This replaced rustsec/audit-check@v2, which ran
# on Node 20, needed a check-run write token, and on a pull request failed only on
# "critical" — so the advisories that turned `main` red in September passed every PR.
- name: Install cargo-audit
uses: taiki-e/install-action@83ac0ad63c0167e6f06796fab0fce28db1bf3db0 # v2.87.22
with:
tool: cargo-audit
# RustSec advisories against the committed Cargo.lock. `--deny warnings`, because
# .cargo/audit.toml's contract is that a *new* informational advisory fails CI and is looked
# at; the known ones are ignored there one by one, with reasons.
- name: Audit
run: cargo audit --deny warnings
deny:
name: cargo deny
runs-on: ubuntu-latest
timeout-minutes: 15
env:
RUSTUP_TOOLCHAIN: stable
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Install cargo-deny
uses: taiki-e/install-action@83ac0ad63c0167e6f06796fab0fce28db1bf3db0 # v2.87.22
with:
tool: cargo-deny
# Licences, sources and bans — deny.toml says why each. Advisories stay cargo audit's.
- name: Licences, sources, bans
run: cargo deny --locked check licenses sources bans
+7 -5
View File
@@ -1,9 +1,11 @@
# Caller into the ops repo's CodeQL reusable.
#
# JavaScript/TypeScript only: CodeQL has no Rust analyzer, and the reusable's supported set is
# csharp, python, javascript-typescript, ruby, c-cpp, java-kotlin, go and swift. Rust's static
# analysis is clippy `-D warnings` plus `cargo audit`, both blocking in ci-rust.yml.
# See docs/RELEASE-CI.md §1 and docs/SECURITY.md §7.
# Three languages. **Rust** — CodeQL analyses it without a build (`build-mode: none`, which the
# reusable passes for every language outside its autobuild list); this file said for six releases
# that CodeQL had no Rust support, which stopped being true in 2025. **Actions** — the workflows
# themselves: the class of mistake SonarCloud kept finding by hand (write permissions at workflow
# level, unpinned third-party actions). **JavaScript/TypeScript** — the frontend, and the one
# whose check name `main`'s protection requires, so it keeps its exact name.
#
# The reusable notes that repo Settings → Advanced Security → CodeQL "Default setup" must be
# DISABLED, or this advanced-setup workflow is rejected at upload time.
@@ -32,4 +34,4 @@ jobs:
analyze:
uses: poli0981/.github/.github/workflows/reusable-codeql.yml@main
with:
languages: '["javascript-typescript"]'
languages: '["javascript-typescript", "rust", "actions"]'
+12 -3
View File
@@ -1,13 +1,22 @@
# Caller into the ops repo's Discord CI-failure notifier.
#
# The reusable skips workflows that have their own dedicated notifier (release, CodeQL,
# Dependabot), so this does not double-report.
# **Listed by name.** `workflows: ['*']`, which the ops repo's own example suggests, is not a
# wildcard to `workflow_run`: it matched nothing, so `main` stayed red from 2026-09-23 with every
# failure unreported — the only runs this ever saw were Dependabot's. Adding a workflow means
# adding its `name:` here, exactly.
#
# CodeQL and Release are deliberately absent: the reusable skips workflows with dedicated
# notifiers by name ('odeQL', 'elease', …), so listing them would only create skipped runs.
name: Notify CI Failure
on:
workflow_run:
workflows: ['*']
workflows:
- CI / Rust
- CI / Node
- CI / Integration
- Security scan
types: [completed]
permissions:
+109 -16
View File
@@ -1,11 +1,20 @@
# Project-local: the ops repo has no reusable Tauri/build workflow (docs/RELEASE-CI.md §1).
#
# Produces the NSIS .exe and .msi, publishes SHA256SUMS.txt and leaves a DRAFT release for owner
# review. Publishing is manual on purpose — RELEASE-CI.md §3.4 — and announce-release.yml fires on
# `release: published`.
# Builds the NSIS .exe and .msi, attests where they were built, publishes SHA256SUMS.txt and leaves
# a DRAFT release. Publishing is a separate, human-directed step (RELEASE-CI.md §3.4), and
# announce-release.yml fires on `release: published`.
#
# **Two jobs, so the token that can write releases never runs the build.** Building executes
# third-party code — every crate's build script, every npm package's — and gets a read-only token
# with no credentials left in the checkout. The publish job only attests and uploads what the build
# produced.
#
# `workflow_dispatch` with `dry_run` builds and checksums any ref — a branch before it merges —
# without attesting or drafting anything: the release recipe is tested before a tag depends on it.
#
# PipDock does not update itself, so there is no signing key and no `latest.json` here. Users get
# new versions from the GitHub Releases page. The checksums below are what they verify against.
# new versions from the GitHub Releases page; the checksums and the attestation are what they
# verify against (docs/SECURITY.md §5).
name: Release
@@ -15,12 +24,17 @@ on:
workflow_dispatch:
inputs:
tag:
description: Tag to build (for re-runs)
required: true
description: Tag to build (for re-runs). Empty builds the selected ref.
required: false
type: string
dry_run:
description: Build and checksum only — no attestation, no draft release.
required: false
type: boolean
default: false
permissions:
contents: write # release assets
contents: read
concurrency:
group: release-${{ github.ref }}
@@ -31,14 +45,51 @@ env:
jobs:
build:
name: Build · checksum · draft
name: Build · checksum
runs-on: windows-latest
timeout-minutes: 90
permissions:
contents: read
outputs:
tag: ${{ steps.version.outputs.tag }}
steps:
- name: Checkout
uses: actions/checkout@v7
with:
ref: ${{ inputs.tag || github.ref }}
persist-credentials: false
# The version lives in five places and they move together (CLAUDE.md), and a tag names the
# one they must all carry. A tag pushed before the bump commit, or a bump that missed one
# file, would otherwise build an installer whose About states another version.
- name: The tag and all five versions agree
id: version
shell: pwsh
env:
REF: ${{ inputs.tag || github.ref_name }}
DRY_RUN: ${{ inputs.dry_run || false }}
run: |
$ErrorActionPreference = 'Stop'
$found = [ordered]@{}
$found['Cargo.toml'] = (Select-String -Path Cargo.toml -Pattern '^version = "([^"]+)"' |
Select-Object -First 1).Matches[0].Groups[1].Value
$lock = Get-Content Cargo.lock -Raw
if ($lock -notmatch '(?m)^name = "pipdock-core"\r?\nversion = "([^"]+)"') { throw 'pipdock-core is not in Cargo.lock' }
$found['Cargo.lock'] = $Matches[1]
$found['package.json'] = (Get-Content package.json -Raw | ConvertFrom-Json).version
# -AsHashtable: package-lock.json has a property named "", which plain ConvertFrom-Json refuses.
$found['package-lock.json'] = (Get-Content package-lock.json -Raw | ConvertFrom-Json -AsHashtable)['version']
$found['tauri.conf.json'] = (Get-Content src-tauri/tauri.conf.json -Raw | ConvertFrom-Json).version
$found.GetEnumerator() | ForEach-Object { Write-Host ("{0,-18} {1}" -f $_.Key, $_.Value) }
$versions = @($found.Values | Sort-Object -Unique)
if ($versions.Count -ne 1) { throw "the five versions disagree: $($versions -join ', ')" }
$v = $versions[0]
if ($env:REF -match '^v\d') {
if ($env:REF -ne "v$v") { throw "tag $env:REF does not match version $v" }
} elseif ($env:DRY_RUN -ne 'true') {
throw "$env:REF is not a version tag; only a dry run builds a branch"
}
"tag=v$v" >> $env:GITHUB_OUTPUT
- name: Setup Node.js
uses: actions/setup-node@v7
@@ -79,21 +130,63 @@ jobs:
ForEach-Object { Copy-Item $_.FullName $out }
Get-ChildItem $out
- name: Publish checksums
- name: Checksums
shell: pwsh
run: |
# SmartScreen warns on first run because the binaries are not EV-code-signed, so the
# README tells users to verify these instead (docs/SECURITY.md §5).
Get-ChildItem release-artifacts -File |
#
# LF line endings, written byte for byte: `Set-Content` wrote CRLF, and `sha256sum -c`
# on any other platform reads the CR as part of the file name and reports it missing.
$lines = Get-ChildItem release-artifacts -File |
Where-Object { $_.Name -ne 'SHA256SUMS.txt' } |
ForEach-Object { "$((Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLower()) $($_.Name)" } |
Set-Content release-artifacts\SHA256SUMS.txt -Encoding ascii
Sort-Object Name |
ForEach-Object { "$((Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLower()) $($_.Name)" }
[IO.File]::WriteAllText(
(Join-Path $PWD 'release-artifacts\SHA256SUMS.txt'),
(($lines -join "`n") + "`n"),
[Text.Encoding]::ASCII)
Get-Content release-artifacts\SHA256SUMS.txt
- name: Draft GitHub release
uses: softprops/action-gh-release@v3
- name: Upload the build
uses: actions/upload-artifact@v7
with:
tag_name: ${{ inputs.tag || github.ref_name }}
draft: true # owner reviews, then publishes; publishing triggers the announcement
name: release-artifacts
path: release-artifacts/*
if-no-files-found: error
publish:
name: Attest · draft
needs: build
if: ${{ !inputs.dry_run }}
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: write # the draft release and its assets
id-token: write # Sigstore, for the attestation
attestations: write
steps:
- name: Download the build
uses: actions/download-artifact@v8
with:
name: release-artifacts
path: release-artifacts
# Build provenance for the two installers: `gh attestation verify <file> --repo
# poli0981/pipdock` proves an installer came from this workflow, at this commit — which a
# checksum published beside the file cannot, since whoever could replace one could replace
# both.
- name: Attest provenance
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
with:
subject-path: |
release-artifacts/*.exe
release-artifacts/*.msi
- name: Draft GitHub release
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
with:
tag_name: ${{ needs.build.outputs.tag }}
draft: true # reviewed, then published; publishing triggers the announcement
generate_release_notes: true
files: release-artifacts/*
+64
View File
@@ -0,0 +1,64 @@
# Daily advisory scans of `main` — docs/SECURITY.md §7.
#
# The PR gates (ci-rust.yml's `cargo audit`, ci-node.yml's `npm audit`) only run when something
# changes. An advisory published against a dependency already on `main` therefore sat unnoticed
# until the next pull request happened to fail on it: that is how `main` went red in September
# with no PR open to say so. This runs the same two scans every day against what is merged, and a
# failure reaches Discord through notify-ci-failure.yml.
#
# Not a required check — it runs on no pull request.
name: Security scan
on:
schedule:
# Daily, off the hour.
- cron: '41 5 * * *'
workflow_dispatch:
permissions:
contents: read
jobs:
cargo:
name: cargo audit
runs-on: ubuntu-latest
timeout-minutes: 15
env:
RUSTUP_TOOLCHAIN: stable
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Install cargo-audit
uses: taiki-e/install-action@83ac0ad63c0167e6f06796fab0fce28db1bf3db0 # v2.87.22
with:
tool: cargo-audit
- name: Audit
run: cargo audit --deny warnings
npm:
name: npm audit
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@v7
with:
node-version: '24'
cache: npm
# Nothing is built here, so no package's install script has a reason to run.
- name: Install
run: npm ci --ignore-scripts
- name: Audit
run: npm audit --audit-level=high
+5
View File
@@ -51,6 +51,11 @@ tauri-signing-private.key*
# Logs & scratch
*.log
# insta's pending snapshots: review them with `cargo insta review`, never commit them.
*.snap.new
*.pending-snap
# A release's checksums, when downloaded beside the checkout to verify an installer.
/SHA256SUMS.txt
/spikes/out/
# Spike tooling venvs (SP-1 needs several uv versions side by side)
+66 -26
View File
@@ -1,7 +1,7 @@
# PipDock — working notes for Claude
Windows GUI + CLI for bulk-managing Python packages. Tauri 2 + Rust core + React 19.
Repo `poli0981/pipdock` · GPL-3.0-only · **Status: 1.2.0. M1, M2, Phase 3, Phase 4, the P1 wave and the Security tab are all complete.** 1.0.0 shipped the release pipeline, a protected `main`, the manual charter and legal documents that match the code; 1.1.0 added pin auto-suggest, requirements export/import, the cache manager and the `Ctrl+K` palette; 1.2.0 added the Security tab (PRD P1-1), which was the last major P1 item. **What is left of Post-1.0 is two things** — the dependency-graph view (P1-6) and the scheduled check (P1-7) — and neither is near P1-1's readiness; see `docs/ROADMAP.md`.
Repo `poli0981/pipdock` · GPL-3.0-only · **Status: 1.4.0. M1, M2, Phase 3, Phase 4, the P1 wave, the Security tab and the dependency view are all complete.** 1.0.0 shipped the release pipeline, a protected `main`, the manual charter and legal documents that match the code; 1.1.0 added pin auto-suggest, requirements export/import, the cache manager and the `Ctrl+K` palette; 1.2.0 added the Security tab (PRD P1-1); 1.3.0 added the dependency view (P1-6), which is a *mode of the package screen* rather than a tab and adds no runtime dependency — read its ROADMAP record before touching `graph/`, because the shape of the screen is a consequence of measurements rather than of taste. 1.4.0 added no feature: it is the audit release — about 170 findings, every Critical and High fixed with a test that failed first, and the rest in ROADMAP's **Audit backlog**, with file:line and a reason each. Read that table before starting a slice; most of what is wrong with the codebase is already written down there. **What is left of Post-1.0 is one thing** — the scheduled check (P1-7) — and `docs/ROADMAP.md` now carries the survey of what blocks it, which for two versions it was cited for and did not contain: no toast component, no notification/autostart/tray plugin, nothing on a timer, and no surface that can report a background failure.
## Read the docs before changing anything
@@ -12,15 +12,19 @@ The design is fully specified. Read in this order; do not invent behaviour that
3. `docs/DATA-FLOW.md` — update/install/uninstall/rollback state machines, engine command mapping, **invariants §9**
4. `docs/UI-SPEC.md` — design tokens, screens, click budgets, keyboard map
5. `docs/CLI-SPEC.md` — commands, flags, exit codes, JSON contracts
6. `docs/ERROR-CATALOG.md` — the launch codes and their stderr classifiers. **34 in Rust**
6. `docs/ERROR-CATALOG.md` — the launch codes and their stderr classifiers. **35 in Rust**
(`Code::ALL`, pinned by two tests); the doc tabulates fewer rows because it folds
`PD-HLT-001..004` into one. Adding a code means the catalog, `Code::ALL`, both counts, the
"no code without a fixture" gate in `classifier_corpus.rs`, **both `locales/*/errors.json`**,
a regenerated `codes.json` (`cargo run -p xtask -- ipc-fixtures`), regenerated bindings, and
re-blessed goldens — `golden__schema-Code.snap` **and every schema that embeds it**, which
since P3 is **four**: `StepResult`, `ExecutionSummary` and `HealthReport`, the last via
`ToolProblem.code`. Nine places; the gates will tell you which you forgot, including
`i18n.test.ts`, which fails on a code with no copy in either language
`PD-HLT-001..004` into one, so it shows **32 rows**. Adding a code means the catalog,
`Code::ALL`, both counts, the "no code without a fixture" gate in `classifier_corpus.rs`,
**both `locales/*/errors.json`**, a regenerated `codes.json`
(`cargo run -p xtask -- ipc-fixtures`), regenerated bindings, and re-blessed goldens —
`golden__schema-Code.snap` **and every schema that embeds it**, which since 1.4.0 is
**five**: `StepResult`, `ExecutionSummary`, `CheckReport` (its `error`), `HealthReport` and
`AuditReport`, the last two via `ToolProblem.code`. **Six snapshot files in all.** This line
has been wrong about the count twice — grep `PD-ENV-001` across
`crates/pipdock-cli/tests/snapshots/` rather than trusting the list. Nine places; the
gates will tell you which you forgot, including `i18n.test.ts`, which fails on a code with
no copy in either language
7. `docs/CODE-HEALTH-SPEC.md`, `docs/SECURITY.md`, `docs/TESTING.md`, `docs/RELEASE-CI.md`, `docs/I18N.md`, `docs/ROADMAP.md`
8. `legal/` — EULA, Disclaimer, Privacy, Third-Party Notices (public; the in-app legal gate links to these GitHub URLs)
@@ -58,7 +62,7 @@ failed package never aborts a batch (skip-and-continue, then a `"13 successful,
minor range at roughly 600 lines and never renumber an existing range file —
`changelog/README.md` is the authority.
- Crates `pipdock-*`; React components prefixed `Pd` (`PdPackageRow`, `PdConflictDialog`)
- Crates `pipdock-*`; React components prefixed `Pd` (`PdPackageRow`, `PdConflictRow`)
- Tauri identifier `com.skullmute.pipdock`; CLI binary `pipdock`
- Frontend lives in `ui/`, but `package.json` sits at the **repo root** so the ops-repo
`reusable-web-react.yml` (which has no `working-directory` input) works unmodified; Vite is
@@ -72,9 +76,18 @@ failed package never aborts a batch (skip-and-continue, then a `"13 successful,
`docs/RELEASE-CI.md` is authoritative *as corrected*: the ops repo `poli0981/.github` has **no
reusable Rust or Tauri workflow**, its notifiers are **Discord-only**, dependency bumps are
**Dependabot** (not Renovate), and its CodeQL reusable has **no Rust support**. So `ci-rust.yml` and
`release.yml` are project-local; `ci-node.yml`, `codeql.yml` and the notifiers are callers.
Every caller needs an explicit `permissions:` block — callers without one default to `none`.
**Dependabot** (not Renovate), and its CodeQL reusable *lists* no Rust but passes `languages`
straight to codeql-action, which analyses Rust and Actions without a build — `codeql.yml` asks for
both. So `ci-rust.yml`, `release.yml` and `security-scan.yml` are project-local; `ci-node.yml`,
`codeql.yml` and the notifiers are callers. Every caller needs an explicit `permissions:` block —
callers without one default to `none` — and a write permission belongs on the job that needs it,
not the workflow.
**`notify-ci-failure.yml` lists its workflows by name, and a new workflow has to be added to it.**
`workflows: ['*']` — the ops repo's own example — is not a wildcard to `workflow_run`: it matched
nothing, and `main` was red from 2026-09-23 for three weeks with no one told. Start any CI
question with `gh run list --branch main`, and remember that `security-scan.yml` exists for the
case no PR will catch: an advisory against something already merged.
## Current state
@@ -89,7 +102,7 @@ has a table per stage and says where to pick up; read it before starting a slice
**Phase 3 is complete** — six slices, exit criteria met and recorded. P4 put Code Health on screen: `PdHealthReport` is UI-SPEC §6's
fifteenth of sixteen, `EnvRow.healthProject` remembers the folder per environment, and
`health_save_report` writes Markdown + JSON. **`NOT_YET` is down to two**, both M3-general — P5 landed the
`health_save_report` writes Markdown + JSON. `NOT_YET` was down to two after it, both M3-general — P5 landed the
gated `ruff --fix`, PipDock's first write outside site-packages and `%LOCALAPPDATA%`. P4 *did* need new commands, contrary to the earlier claim — one shipped, and
cancellation was deferred on a measurement (a warm three-tool run is 1.3 s in release).
@@ -107,16 +120,44 @@ P2 built the tools venv — `health::sync_tools_venv` fills
`%LOCALAPPDATA%\PipDock\data\tools\.venv` from the shipped pins over `pipdock tools sync`, and there is
no `TOOLS_PYTHON_MAX` because deptry ships an abi3 wheel (ROADMAP's premise for that const was
wrong; the record says why). P1 closed **P0-10**: pip's version is on every Environments row and
*Upgrade pip* is 2 clicks. **Next is P3** (the three runners + `HealthReport`), then P4 (the Health
screen) and P5 (the gated `ruff --fix`); `~/.claude/plans/b-n-c-th-b-t-snappy-rabin.md` has all
four decomposed, including six corrections to the specs found by running the pinned tools.
P2 touched no `NOT_YET` entry: it is CLI-only on purpose, so P3's `health_run` owns the
*Upgrade pip* is 2 clicks. P3–P5 followed — the three runners and `HealthReport`, the Health
screen, the gated `ruff --fix` — and are recorded in ROADMAP. P2 touched no `NOT_YET` entry: it is CLI-only on purpose, so P3's `health_run` owns the
implicit sync rather than the frontend getting two ways to reach one operation.
**`NOT_YET` is two**, and only two: `env_add_manual` and `logs_tail`, both M3-general.
`src-tauri/src/lib.rs:25-28` is the authority and three tests keep it honest in both directions —
this file used to say "four" in one paragraph and "two" in another, each true when written and
neither updated.
**`NOT_YET` is one**: `env_add_manual` — *Browse…*, and the next slice. `logs_tail` shipped in
1.4.0 together with the log it tails. `NOT_YET` in `src-tauri/src/lib.rs` is the authority and
three tests keep it honest in both directions — this file has said "four", "two" and "two" in
different paragraphs at once, each true when written and none updated.
**1.4.0, the audit release, left these behind** — most found by running rather than by reading, and each
rule below backed by a test where a test can hold it:
- **A flow is only as safe as what can drive it.** The stale-plan and drift checks (DATA-FLOW
§9.3) never fired, because nothing could run a flow without a real engine, so nothing did.
`FlowOptions`, the `Engine::probe` seam and `tests/flows.rs`'s scripted engine exist so that
every flow decision has a test needing no pip. A new flow decision without one is a regression.
- **A check that cannot run must not report a pass.** `unwrap_or(ok: true)` said "verified"
exactly when nothing was — a pip broken by the run it was checking. `CheckReport.error` says so.
The empty-plan path kept its own copy of the bug until the last UI commit of the release.
- **`python -I` ignores `PYTHONUTF8` and `PYTHONIOENCODING`** (it implies `-E`), so invariant 7's
variables did nothing for the probe, and every venv under a folder named in Vietnamese crashed
it. `-X utf8` survives isolation; `probe.py` runs under it.
- **A grant is a contract no frontend test can see.** Decline on the legal gate did nothing in the
installed app while its test passed: the test mocks `close()`, and `core:default` never granted
`core:window:allow-close`. `lib.rs` pins the webview's exact permissions now — widening them is
a test change, on purpose.
- **Data drift and format drift look identical in a red drift job.** Seven weeks of red were two
causes: PyPI data (idna's newest release, scipy's version list) and uv 0.13 rewriting its error
rendering. Data is redacted in `capture.py`; a format change gets a frozen corpus of its own
(`tests/fixtures/uv-0.11/`, the last miette-style uv) beside the live one (`uv/`).
- **Normalise everything you hash, not most of it.** The legal-docs hash normalised CRLF in the
content and hashed the raw length, so a Windows checkout re-showed the gate for nothing.
- **`--json` is one document.** Scripts parse stdout with one `ConvertFrom-Json`; prose, prompts
and warnings go to stderr. Every command's shape is in CLI-SPEC §6, and the goldens hold it.
- **Never put a backslash in a Bash heredoc** that becomes source code: the tool collapses `\\`
to `\`, which turned `b"\r\n"` test strings into real line breaks and a CRLF test into one that
could not fail. Write such files with the Write/Edit tools, then check the failing-first run
actually failed.
Three rules P1 left behind, all found by running rather than reading:
@@ -197,7 +238,7 @@ Things worth knowing before you change any of it:
- **`cargo test` fails when `ui/src/ipc/generated.ts` is stale.** Fix with
`cargo run -p xtask -- bindings`; the failure names that command and the first differing line.
- **The L4 goldens (`crates/pipdock-cli/tests/golden.rs`, 64 snapshots at 1.1.0) are the CLI's output
- **The L4 goldens (`crates/pipdock-cli/tests/golden.rs`, 68 snapshots at 1.4.0) are the CLI's output
contract.** A diff there is a real behaviour change — re-bless deliberately, never reflexively.
They are what made the `core::flow` refactor provably behaviour-preserving.
- **Two tests hold the wire format**: `Code::ALL` must serialize as `as_str()`, and no
@@ -336,6 +377,5 @@ Things worth knowing before you change any of it:
id before execution and the GUI can draw DATA-FLOW §3's distinct states. The cost is that
skipping the snapshot becomes expressible, which is why `flow::proof_from` refuses `NotTaken`
with `PD-SNP-001`. Do not "simplify" them back into one.
- **Fixtures under `tests/fixtures/{pip,uv}/` are not literal engine bytes** — see the redaction
note above. Related: `ScanProgress.label` and every path, version and engine id in the UI are
data and are never translated (I18N §2).
- `ScanProgress.label` and every path, version and engine id in the UI are data and are never
translated (I18N §2).
Generated
+716 -677
View File
File diff suppressed because it is too large. Load diff
+5 -2
View File
@@ -3,12 +3,15 @@ resolver = "3"
members = ["crates/pipdock-core", "crates/pipdock-cli", "src-tauri", "xtask"]
[workspace.package]
version = "1.2.0"
version = "1.4.0"
edition = "2024"
rust-version = "1.94"
rust-version = "1.99"
license = "GPL-3.0-only"
repository = "https://github.com/poli0981/pipdock"
authors = ["Kokone (poli0981)"]
# Applications, not libraries: nothing here belongs on crates.io, and cargo-deny treats a
# publishable crate's licence and path dependencies as a published one's (deny.toml).
publish = false
[workspace.lints.rust]
unsafe_code = "forbid"
+24 -12
View File
@@ -50,22 +50,26 @@
| Area | What you get |
|---|---|
| Environments | Auto-discovery of venvs / uv venvs / system Pythons (PEP 514 + `py` launcher), manual add, PEP 668 guard |
| Environments | Auto-discovery of installed Pythons — the Windows registry (PEP 514), the `py` launcher and the Pythons `uv python list` reports — plus a `.venv`, `venv`, `env` or `.env` folder in the folder PipDock was started from. Adding an environment by path is not in the app yet; the CLI takes any interpreter or environment folder with `--env` |
| PEP 668 guard | Pythons marked externally managed are refused by default. An override in Settings, off by default, asks before it turns on, and while it applies every screen that can change that Python says so |
| Installed | Full package list per env; up-to-date packages dimmed, outdated badged |
| Updates | Bulk update with group dry-run resolve, held-back explanations, 3-way conflict choices |
| Updates | Bulk update with group dry-run resolve, held-back explanations, 3-way conflict choices. The preview names every package *Force latest* would break, anything left out because it needs a different Python, and withdrawn (yanked) releases |
| Search & Install | Instant fuzzy search over a locally cached PyPI name index (PEP 691), metadata on demand, install queue |
| Uninstall | Bulk uninstall with reverse-dependency warnings |
| Pins | Exclude packages from bulk updates, with a reason. The Pins screen suggests packages a lot of your others depend on, and the threshold is configurable |
| Dependencies | For any package on the Installed list: what requires it and what it requires, with the version constraint on each, how many packages removing it would leave broken, and any requirement nothing installed satisfies |
| Pins | Keep packages out of every update until you unpin them, with a reason. The Pins screen suggests packages a lot of your others depend on, and the threshold is configurable |
| Snapshots | Automatic pre-batch snapshots, diff view, one-click rollback |
| Engine | pip **or** uv, selectable in Settings (uv auto-detected on first run) |
| Engine | pip **or** uv, chosen in Settings, which shows each one's version for the selected environment (or *not found*). pip is the default; uv has to be on your `PATH` |
| Code Health | deptry + vulture + ruff against a project folder — unused deps, dead code, style — run from PipDock's own isolated tools env |
| Security | pip-audit against an environment's packages: each known advisory with the versions that fix it (or *no fix*), its CVE aliases and a link to its OSV entry, run from PipDock's own isolated audit environment |
| pip upkeep | Check & update pip itself per environment |
| CLI | `pipdock` — full parity for core operations, JSON output, CI-friendly exit codes |
| Requirements | Export an environment as `requirements.txt`; import one and preview what it would install, with every line it will not use reported by number |
| Disk usage | See and clear what PipDock has written — snapshots and the Code Health tools environment |
| Keyboard | `Ctrl+K` command palette, `Ctrl+1`–`Ctrl+9` tabs, full keyboard traversal |
| i18n | English + Tiếng Việt |
| Privacy | No telemetry. **PyPI is the only host PipDock connects to.** It does not check for updates, so it never calls home — GitHub and the ruff docs are only ever handed to your browser as a link you clicked |
| Disk usage | Everything PipDock writes is under `%LOCALAPPDATA%\PipDock\data\`. Settings shows it and clears the parts that are safe to clear — snapshots (`snapshots\`), the Code Health tools environment (`tools\`) and the Security tab's audit environment (`audit\`). `index.db` (package index, settings, pins, your acceptance of the legal documents) is shown but never cleared; the logs (`logs\`) are deleted automatically after 14 days |
| Logs | PipDock keeps its own log, one file per day in `data\logs\`, and never sends it anywhere. It records the commands PipDock ran, so it holds package names and file paths. Settings shows the folder and copies the recent lines for a bug report |
| Keyboard | `Ctrl+K` command palette, `Ctrl+1`–`Ctrl+9` tabs (by key position, so AZERTY and other layouts work too), `/` for Search, full keyboard traversal |
| i18n | English + Tiếng Việt, remembered across restarts |
| Privacy | No telemetry. **PyPI is the only host PipDock connects to.** It does not check for updates, so it never calls home — GitHub, the ruff docs, OSV's advisory pages and the author's links page are only ever handed to your browser as a link you clicked |
## Install
@@ -73,17 +77,25 @@ Download the installer (NSIS `.exe` or `.msi`) from [GitHub Releases](https://gi
PipDock does not update itself — grab a new build from the same page when you want one. That is deliberate: a self-updater is a standing remote-code-execution path into a tool that already runs subprocesses against your interpreters, and it is not worth the convenience (see [docs/SECURITY.md](docs/SECURITY.md) §5).
> Windows SmartScreen may warn on first run because the binaries are not EV-code-signed. Every release publishes `SHA256SUMS.txt`; verify your download against it before running:
> Windows SmartScreen may warn on first run because the binaries are not EV-code-signed. Every release publishes `SHA256SUMS.txt`; verify your download against it before running (replace `<version>` with the version in the file name you downloaded):
>
> ```powershell
> (Get-FileHash .\PipDock_1.0.0_x64-setup.exe -Algorithm SHA256).Hash.ToLower()
> (Get-FileHash .\PipDock_<version>_x64-setup.exe -Algorithm SHA256).Hash.ToLower()
> ```
>
> Compare that against the matching line in `SHA256SUMS.txt`. If they differ, do not run the file.
>
> From 1.4.0 the `.exe` and `.msi` also carry a build-provenance attestation. A checksum published beside a file cannot prove where the file came from — whoever could replace one could replace both — but the attestation proves the installer was built by this repository's release workflow. With the [GitHub CLI](https://cli.github.com/):
>
> ```powershell
> gh attestation verify .\PipDock_<version>_x64-setup.exe --repo poli0981/pipdock
> ```
>
> It succeeds only when GitHub holds an attestation from this repository for that exact file. If it fails, do not run the file.
## Quick start
**GUI:** launch PipDock → accept the first-run legal gate → pick an environment (auto-discovered or *Browse…*) → the *Updates* tab shows what's outdated → *Select all* → *Update* → review the preview → *Confirm*. Four clicks.
**GUI:** launch PipDock → accept the first-run legal gate → pick an environment from the discovered list (the first usable one is already selected; *Use* picks another) → the *Updates* tab shows what's outdated → *Select all* → *Update* → review the preview → *Confirm*. Four clicks.
**CLI:** the installer puts `pipdock.exe` next to the GUI, in `%LOCALAPPDATA%\PipDock\`.
**PipDock does not edit your `PATH`**; add that folder yourself if you want to type `pipdock`
@@ -129,7 +141,7 @@ just stating them. Everything below is for reading the code.
## How this was built
PipDock was written with substantial help from an AI coding assistant — **Claude Opus 5**, made by [Anthropic](https://www.anthropic.com), through [Claude Code](https://claude.com/claude-code) — under human review. It wrote source code, tests, debugging work and the Vietnamese translation. Every change reached `main` through a pull request the maintainer read and merged, `main` is protected and cannot be bypassed, and the built application was driven by hand on three machines before 1.0.0 shipped.
PipDock was written with substantial help from an AI coding assistant — **Claude Opus 5** through 1.3.0 and **Claude Opus 5.5** from 1.4.0, made by [Anthropic](https://www.anthropic.com), through [Claude Code](https://claude.com/claude-code) — under human review. It wrote source code, tests, debugging work and the Vietnamese translation. Every change reached `main` through a pull request, and `main` is protected and cannot be bypassed. Through 1.3.0 the maintainer read and merged each one, and drove the built application by hand on three machines before 1.0.0 shipped; 1.4.0 was released by the assistant on the maintainer's written instruction, once its checks had passed.
That review mattered: **thirty-five defects** reached or nearly reached `main`, and not one was caught by the test suite that was green at the time. They were found by running the thing.
+137
View File
@@ -3,6 +3,143 @@
Newest first. See [`README.md`](README.md) for the conventions, and `docs/ROADMAP.md` for what each
slice cost and what it taught — that is a different document for a different reader.
## 1.4.0 — 2026-10-17
**No new feature: everything PipDock already did, made to do what it said.** A review of the whole
codebase found about 170 problems, and this release fixes every serious one. Several were in the
part that matters most — checking a change before it happens — so if you skip release notes as a
rule, read the first section.
### Fixed — the safety checks
- **A preview that is out of date is refused.** A plan confirmed more than ten minutes after it was
made, or for an environment something else changed in the meantime, is refused before anything
is written (`PD-RES-002`). This check existed and never ran.
- **A version your Python cannot run is never planned.** PipDock now checks every release's
`Requires-Python` itself, for pip and for uv alike. A package that cannot be updated for that
reason is listed under *Left out — needs a different Python*, with the range it needs and the
Python you have, instead of pip's misleading "not found" — or uv quietly planning it anyway.
- **Force latest forces.** It used to change nothing. It now installs the newest release, and the
preview has a **Will break** section naming each package that will stop working and the
requirement of its that is being overridden; the Confirm button counts them.
- **Restoring a snapshot with the other engine no longer removes pip.**
- **`ruff --fix` only changes the files the report showed you.** It used to fix everything it could
reach, including files inside `.venv` and notebooks the report had excluded.
- **A failed build is a failure.** With uv, a package whose build failed showed as "nothing to
change".
- **Stop, a timeout or a network outage mid-install** now ends with a summary of what happened and
the snapshot to restore from, instead of an internal error and nothing else.
- **After a run, a check that could not run says so**, instead of showing nothing — which read as
everything being fine.
### Fixed — everything else
- PipDock **crashed on any environment inside a folder with accented characters in its name** —
every Vietnamese-named folder, for one. It no longer does.
- Interpreters installed under a path with a **space** in it are found.
- Requirements that only apply on another platform (`pexpect; sys_platform != "win32"`) are no
longer reported as missing.
- **The PEP 668 setting now does what it says.** It was a checkbox nothing read. Turning it on asks
you first; while it is on, a red *PEP 668 override* chip shows on every screen where it applies,
and only there.
- **Decline on the first-run screen closes PipDock.** It did nothing.
- **The language you choose is kept** after a restart.
- **The window can be maximized and snapped**, and opens at a size that fits your screen — on a
laptop it used to open with the status line under the taskbar. The content stops widening at a
readable width.
- **Switching environment quickly no longer shows the previous one's data** — package lists,
update badges, snapshot diffs, the dependency view and pin suggestions could all land on the wrong
environment.
- A run that failed to start could leave PipDock refusing every other change ("another change is in
progress") until restart.
- **Back** while a preview is still being worked out now stops the engine, rather than leaving it
running.
- The **Security** tab scrolls.
- Typing `/` puts the cursor in Search from any screen — including Search itself, where it did nothing.
- `Ctrl+1`…`Ctrl+9` work on keyboard layouts where the digits need Shift, such as French.
- F5, Ctrl+R, Ctrl+P and Ctrl+F no longer reload, print or search the app as if it were a web page.
- The package table's headings line up with their columns, and names stay visible at the smallest
window size.
- Text on red badges is easier to read.
- A file PipDock cannot write — read-only, or open in another program — is reported as that, not as
a full disk.
- *Report bug* includes your Python and engine versions, and still opens when the log is full of
accented paths.
- Withdrawn ("yanked") releases in a plan are listed in the preview. They were detected and then
never shown.
- Dialogs open in the middle of the window. They opened in its top-left corner.
- On a fresh install, Search offers to download the package index instead of saying it is
"preparing" indefinitely.
### Added
- **PipDock keeps a log** — one file a day in `%LOCALAPPDATA%\PipDock\data\logs\`, kept for 14
days. **Settings → Logs** shows where, and copies the recent part for a bug report. The privacy
policy has described this log since 1.0; now it exists. Nothing in it is sent anywhere.
- If PipDock cannot open its data folder, it **says so in a dialog**, with the log's location,
instead of not starting.
- **Settings shows each engine's version** for the selected environment, and *not found* when one
is missing.
- The plan panel names the environment it is about to change.
### Changed for scripts (`pipdock` CLI)
- **`--json` prints exactly one JSON document** per command, on stdout. Prompts, warnings and
progress go to stderr. Scripts that read several documents, or skipped a leading line, need
updating — `docs/CLI-SPEC.md` §6 lists every command's document.
- **`pipdock env use` is honoured.** The environment is `--env` if given, then the one `env use`
chose, then a `.venv` in the current folder. Before, `env use` was saved and ignored.
- **Ctrl-C stops a run**: the engine is stopped, what completed is printed with the snapshot to
restore from, and the exit code is 130.
- `--verbose` and `--log-file` work. On an internal error, the log's path is printed.
- `pipdock update` with no package and no `--all` is a usage error (exit 2) rather than a silent
no-op. `pipdock audit` follows `--engine`; `pipdock doctor` no longer requires pip when uv is the
configured engine.
### You will see this once
**The first-run legal screen appears again.** The privacy policy now describes the log and the tool
environments PipDock keeps, and the third-party notices name osv.dev; PipDock also stopped
computing the documents' version differently depending on how the files were checked out. Your
acceptance is recorded against that version, so it asks once more. Nothing else resets.
### Verifying a download
Each installer now carries a **build attestation** as well as its checksum:
`gh attestation verify <installer> --repo poli0981/pipdock` proves it was built by this
repository's release workflow from the tagged commit. `SHA256SUMS.txt` is also readable by
`sha256sum -c` on any system now.
## 1.3.0 — 2026-08-20
The **dependency view** — what depends on a package, what it depends on, and what a removal would
cost.
### Added
- **Dependencies**, from any package row: the `⇄` button beside pin and remove. The package sits
between two columns — everything that requires it and everything it requires — and every row
carries the version specifier written on that edge, so you can see *why* something is held where
it is rather than only *that* it is. Click any neighbour to move the view onto it.
- **The two numbers underneath**: how many packages a removal would leave with a missing
dependency, counted all the way through rather than one hop, and how many packages this one
pulls in itself. This is the part the package list could never tell you.
- **Requirements nothing satisfies.** If something in the environment declares a dependency that
is not installed, the view says so. Nothing else in PipDock reports this, and it only counts
requirements that actually apply to your Python — a backport gated on 3.9 is not a hole.
- The environment's dependencies are read **once** when you open the view, so moving from package
to package is instant.
### Changed
- **Package rows now have three buttons instead of two.** Removing a package is still three
clicks; the new one does not sit in front of it.
- **There is no node-link diagram, and there was never going to be a useful one.** Drawn as a
picture, a real environment is unreadable: on a 352-package install the average package has 172
others within two steps, and more than 200 of them exceed 60. So the view shows one step at a
time and lets you walk it, and answers the "everything downstream" question with a number
instead. No new third-party code was added to the application for this.
## 1.2.0 — 2026-08-18
The **Security tab**, which the sidebar has shown greyed out since M2.
+7 -5
View File
@@ -5,6 +5,7 @@ version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
repository.workspace = true
authors.workspace = true
@@ -16,11 +17,12 @@ path = "src/main.rs"
workspace = true
[dependencies]
clap = { version = "4.6.4", features = ["derive"] }
jiff = "0.2.35"
clap = { version = "4.6.7", features = ["derive"] }
jiff = "0.2.38"
pipdock-core = { path = "../pipdock-core" }
serde_json = "1.0.151"
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros"] }
serde = "1.0.229"
serde_json = "1.0.154"
tokio = { version = "1.53.3", features = ["rt-multi-thread", "macros", "signal"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
@@ -28,4 +30,4 @@ tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
assert_cmd = "2.2.2"
# `filters` gives `Settings::add_filter`, used to keep the crate version out of the help
# snapshots so a release bump does not churn every golden in tests/golden.rs.
insta = { version = "1.48.0", features = ["filters"] }
insta = { version = "1.49.0", features = ["filters"] }
+80
View File
@@ -0,0 +1,80 @@
//! The CLI's subscriber: which log lines go where.
//!
//! - **Always** the daily file, `data\logs\pipdock-cli.<date>.log`, at `PIPDOCK_LOG` or INFO.
//! - `--verbose` adds **stderr**, at DEBUG — every engine line as it was printed.
//! - `--log-file <path>` adds a copy of the file's lines there, for a CI job's artefacts.
//!
//! **Never stdout**, which is the CLI's contract (CLI-SPEC §6): a script reading `--json` gets a
//! document and nothing else, verbose or not. `--quiet` adds nothing, and turns nothing off that
//! is not already off — the file is for after the fact, not for the terminal.
//!
//! Both flags were parsed and ignored before 1.4.0.
use std::path::PathBuf;
use pipdock_core::logging::{self, DailyFile};
use tracing_subscriber::layer::SubscriberExt as _;
use tracing_subscriber::util::SubscriberInitExt as _;
use tracing_subscriber::{EnvFilter, Layer as _, fmt};
use crate::GlobalOpts;
/// Set up logging for one invocation. Returns today's log file, for the line an internal error
/// prints (CLI-SPEC §5: exit 10 says where the log is).
pub fn init(opts: &GlobalOpts) -> PathBuf {
let dir = logging::log_dir(&pipdock_core::store::default_app_data());
// The first reader `LOG_RETENTION_DAYS` has had since it was written.
logging::sweep(
&dir,
pipdock_core::LOG_RETENTION_DAYS,
jiff::Timestamp::now(),
);
let file = DailyFile::new(&dir, "pipdock-cli");
let path = file.current_path();
let level =
|| EnvFilter::try_from_env("PIPDOCK_LOG").unwrap_or_else(|_| EnvFilter::new("info"));
let to_file = fmt::layer()
.with_ansi(false)
.with_writer(move || file.clone())
.with_filter(level());
let to_stderr = opts.verbose.then(|| {
fmt::layer()
.with_ansi(false)
.with_writer(std::io::stderr)
.with_filter(EnvFilter::new("debug"))
});
let to_copy = opts
.log_file
.as_ref()
.and_then(|p| {
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(p)
.map_err(|e| eprintln!("warning: --log-file {}: {e}", p.display()))
.ok()
})
.map(|f| {
fmt::layer()
.with_ansi(false)
.with_writer(std::sync::Mutex::new(f))
.with_filter(level())
});
// A second init (a test harness, say) keeps the first; logging is never worth failing over.
let _ = tracing_subscriber::registry()
.with(to_file)
.with(to_stderr)
.with(to_copy)
.try_init();
logging::install_panic_hook();
tracing::info!(
target: "pipdock::cli",
version = env!("CARGO_PKG_VERSION"),
args = ?std::env::args().skip(1).collect::<Vec<_>>(),
"start"
);
path
}
+23 -10
View File
@@ -90,7 +90,7 @@ impl ToolArg {
/// Options accepted by every command (CLI-SPEC §2).
#[derive(Debug, Args)]
pub struct GlobalOpts {
/// Interpreter or environment directory. Defaults to the last used env, else an
/// Interpreter or environment directory. Defaults to the one `env use` set, else an
/// auto-detected `.venv` in the working directory.
#[arg(long, global = true, value_name = "PATH")]
pub env: Option<PathBuf>,
@@ -99,23 +99,27 @@ pub struct GlobalOpts {
#[arg(long, global = true, value_enum)]
pub engine: Option<EngineArg>,
/// Machine-readable output; NDJSON for streaming commands.
/// Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
///
/// Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming
/// commands" until 1.4.0, when several commands printed several documents.
#[arg(long, global = true)]
pub json: bool,
/// Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*.
/// Assume the default at every prompt: a held-back package keeps its compatible version and
/// an impossible one is skipped. Only `--strategy latest` forces.
#[arg(long, short = 'y', global = true)]
pub yes: bool,
/// Reduce log output.
/// Do not stream engine output to stderr. (The log file is written regardless.)
#[arg(long, global = true, conflicts_with = "verbose")]
pub quiet: bool,
/// Increase log output.
/// Also write the log to stderr, at debug level.
#[arg(long, global = true)]
pub verbose: bool,
/// Tee logs to a file.
/// Also write the log to this file. The daily log in `data\logs\` is always kept.
#[arg(long, global = true, value_name = "PATH")]
pub log_file: Option<PathBuf>,
@@ -174,7 +178,7 @@ enum Command {
/// Install packages.
Install {
/// `name` or `name==version`.
/// A name with an optional PEP 440 specifier: `six`, `six==1.16.0`, `"six>=1.16,<2"`.
#[arg(required = true)]
specs: Vec<String>,
/// Print the resolution report and exit without changing anything.
@@ -246,7 +250,7 @@ enum Command {
/// Show or set the configured engine.
Engine {
/// Engine to switch to; omit to print the current one.
/// Engine to switch to; omit to list both, with versions, marking the configured one.
engine: Option<EngineArg>,
},
@@ -344,11 +348,13 @@ enum SelfCommand {
ReportBug,
}
mod log;
mod run;
#[tokio::main]
async fn main() -> ExitCode {
let cli = Cli::parse();
let log_path = log::init(&cli.global);
let result = match &cli.command {
Command::Env(EnvCommand::List) => run::env_list(&cli.global).await,
@@ -422,6 +428,8 @@ async fn main() -> ExitCode {
match result {
Ok(exit) => exit.into(),
Err(e) => {
tracing::error!(target: "pipdock::cli", code = %e.code, message = %e.message, "failed");
let exit = run::exit_for(e.code);
// ERROR-CATALOG §3: `error[PD-XXX-NNN]: <one-liner>` on stderr, or the JSON envelope.
if cli.global.json {
println!(
@@ -438,7 +446,12 @@ async fn main() -> ExitCode {
eprintln!("{tail}");
}
}
run::exit_for(e.code).into()
// CLI-SPEC §5: an internal error says where the log is. On stderr in both modes, so
// `--json`'s stdout stays the one envelope.
if exit == Exit::Internal {
eprintln!("log: {}", log_path.display());
}
exit.into()
}
}
}
@@ -494,7 +507,7 @@ mod tests {
"--yes",
"--json",
"--log-file",
r"C:\logs\pd.json",
r"C:\logs\pd.log",
])
.expect("nightly maintenance example");
+458 -150
View File
@@ -13,7 +13,8 @@ use pipdock_core::engine::{
use pipdock_core::envs::{self, Candidate};
use pipdock_core::errors::{Code, PdError, Result};
use pipdock_core::flow::{
FlowStep, GuardAck, NothingReason, RollbackFlow, SnapshotPolicy, UninstallFlow, UpdateFlow,
FlowOptions, FlowStep, GuardAck, NothingReason, RollbackFlow, SnapshotPolicy, UninstallFlow,
UpdateFlow,
};
use pipdock_core::model::{EngineId, EnvSource, PkgName, PyEnv, StepStatus};
@@ -25,10 +26,10 @@ use pipdock_core::{health, index, pins, plan, report, settings, snapshot};
use crate::{EngineArg, Exit, GlobalOpts, ToolArg};
/// Resolve which engine to drive.
/// Resolve which engine to drive: `--engine` for one invocation, else the configured one.
///
/// ARCHITECTURE §3: first run probes `uv --version` on PATH and preselects uv when present. The
/// `--engine` flag overrides for one invocation.
/// ARCHITECTURE §3 describes a first run that probes for uv and preselects it; neither head does
/// that yet (Audit backlog X19), and this deliberately does not — see the comment below.
#[must_use]
pub fn engine_for(opts: &GlobalOpts) -> Box<dyn Engine> {
let id = match opts.engine {
@@ -48,6 +49,73 @@ pub fn engine_for(opts: &GlobalOpts) -> Box<dyn Engine> {
engine::for_id(id)
}
/// What every mutating flow is started with: the stored PEP 668 override (SECURITY §3).
///
/// Read from the store both heads share. The CLI has deliberately no flag to turn it on — the
/// override is meant to be hard to reach, and a flag would put it one shell-history search away.
fn flow_options() -> FlowOptions {
FlowOptions {
cancel: stop_on_ctrl_c(),
allow_externally_managed: Store::open(&app_data_dir())
.and_then(|store| settings::load(&store))
.is_ok_and(|s| s.allow_externally_managed),
releases: Some(std::sync::Arc::new(
pipdock_core::release::PyPiReleases::new(app_data_dir()),
)),
..FlowOptions::default()
}
}
/// Ctrl-C stops the run rather than the process (CLI-SPEC §5: 130, a partial summary, no orphans).
///
/// The first press trips the flow's token: `exec`'s job object kills the engine's whole process
/// tree, what already ran is summarized with the snapshot to roll back to, and the exit is 130. A
/// second press exits at once, for a step that is not listening — a probe, a snapshot write. The
/// CLI installed no handler before 1.4.0, so Ctrl-C killed PipDock mid-batch with no summary and
/// no word about the snapshot it had just written (X6).
fn stop_on_ctrl_c() -> CancellationToken {
let token = CancellationToken::new();
let trip = token.clone();
tokio::spawn(async move {
if interrupted().await.is_err() {
return;
}
eprintln!("\nstopping — press Ctrl-C again to quit now");
trip.cancel();
if interrupted().await.is_ok() {
std::process::exit(130);
}
});
token
}
/// The next Ctrl-C — or, on Windows, Ctrl-Break, which is the one a supervising process can send
/// to a single process group (and the one a terminal's *Break* key sends).
async fn interrupted() -> std::io::Result<()> {
#[cfg(windows)]
{
let mut brk = tokio::signal::windows::ctrl_break()?;
tokio::select! {
r = tokio::signal::ctrl_c() => r,
_ = brk.recv() => Ok(()),
}
}
#[cfg(not(windows))]
{
tokio::signal::ctrl_c().await
}
}
/// Say, on every run, that the PEP 668 override is in force. The GUI's warning chip, as text.
fn warn_pep668(overrides: bool) {
if overrides {
eprintln!(
"warning: this Python is externally managed (PEP 668) and the Settings override is \
on, so --break-system-packages will be passed. Prefer a virtual environment."
);
}
}
/// `pipdock engine <pip|uv>` — set the configured engine.
///
/// # Errors
@@ -95,14 +163,26 @@ pub async fn engine_set(opts: &GlobalOpts, engine: EngineArg) -> Result<Exit> {
let mut settings = settings::load(&store)?;
settings.engine = id;
settings::save(&store, &settings)?;
println!(
"engine set to {} {}",
id.as_str(),
info.version.unwrap_or_default()
);
if opts.json {
print_json(&info);
} else {
println!(
"engine set to {} {}",
id.as_str(),
info.version.unwrap_or_default()
);
}
Ok(Exit::Success)
}
/// The one document a `--json` command prints (CLI-SPEC §6).
fn print_json<T: serde::Serialize + ?Sized>(value: &T) {
println!(
"{}",
serde_json::to_string_pretty(value).unwrap_or_default()
);
}
/// Map a catalog code onto the exit code CLI-SPEC §5 assigns it.
///
/// Scripts branch on these numbers, so the mapping is part of the public contract — and it is
@@ -126,30 +206,54 @@ pub fn exit_for(code: Code) -> Exit {
/// Select the environment to act on.
///
/// CLI-SPEC §2: `--env` wins; otherwise an auto-detected `.venv` in the working directory; the
/// "last used" fallback arrives with the settings store.
/// # Errors
/// As [`select`].
pub async fn select_env(opts: &GlobalOpts) -> Result<PyEnv> {
select(opts).await.map(|p| p.env)
}
/// Select the environment to act on, and the probe that found it.
///
/// CLI-SPEC §2 and `--env`'s own help text: `--env` wins; then the default `env use` set; then a
/// `.venv` in the working directory. The default was written by `env use` and read by nothing, so
/// `env use` reported success and every later command ignored it (X3). A default whose interpreter
/// is gone is said on stderr and skipped, rather than failing a command the user ran somewhere a
/// `.venv` would have answered.
///
/// Returns the probe, not just the `PyEnv`, so a command that needs the listing does not probe a
/// second time — `list` did, and paid twice on every invocation (X28).
///
/// # Errors
/// `PD-ENV-001` when nothing usable can be found, so the user gets a code rather than a silent
/// default that mutates the wrong environment.
pub async fn select_env(opts: &GlobalOpts) -> Result<PyEnv> {
pub async fn select(opts: &GlobalOpts) -> Result<envs::ProbeResult> {
if let Some(path) = &opts.env {
let interpreter = interpreter_in(path);
return envs::probe(&interpreter, EnvSource::Manual)
.await
.map(|p| p.env);
return envs::probe(&interpreter_in(path), EnvSource::Manual).await;
}
let stored = Store::open(&app_data_dir())
.ok()
.and_then(|store| store.default_env().ok().flatten());
if let Some(default) = stored {
let interpreter = PathBuf::from(&default.interpreter);
if interpreter.is_file() {
return envs::probe(&interpreter, EnvSource::Manual).await;
}
eprintln!(
"warning: the default environment ({}) no longer exists; `pipdock env use` sets another",
default.interpreter
);
}
let cwd = std::env::current_dir().unwrap_or_default();
if let Some(found) = envs::venv_scan(&cwd).into_iter().next() {
return envs::probe(&found, EnvSource::VenvScan)
.await
.map(|p| p.env);
return envs::probe(&found, EnvSource::VenvScan).await;
}
Err(PdError::new(
Code::EnvInterpreterMissing,
"no environment selected: pass --env, or run from a directory containing a .venv",
"no environment selected: pass --env, set a default with `pipdock env use`, or run from a \
directory containing a .venv",
))
}
@@ -253,7 +357,8 @@ pub async fn env_list(opts: &GlobalOpts) -> Result<Exit> {
/// # Errors
/// Propagates environment and engine failures with their catalog codes.
pub async fn list(opts: &GlobalOpts, outdated: bool) -> Result<Exit> {
let env = select_env(opts).await?;
let probed = select(opts).await?;
let env = probed.env.clone();
let engine = engine_for(opts);
if outdated {
@@ -274,8 +379,7 @@ pub async fn list(opts: &GlobalOpts, outdated: bool) -> Result<Exit> {
}
// The probe is the richer source: it carries requires_dist, which `list --format=json` does
// not, and it is what the reverse-dependency graph is built from.
let probed = envs::probe(&env.interpreter, env.source).await?;
// not, and it is what the reverse-dependency graph is built from. It is the one `select` made.
if opts.json {
println!(
"{}",
@@ -307,9 +411,16 @@ pub async fn doctor(opts: &GlobalOpts) -> Result<Exit> {
let env = select_env(opts).await?;
let pip = PipEngine.info(&env).await;
let uv = UvEngine.info(&env).await;
let check = engine_for(opts).check(&env).await;
let engine = engine_for(opts);
let check = engine.check(&env).await;
let pip_ok = pip.available;
// The configured engine is what has to work. Requiring pip failed `doctor` on every uv-only
// environment — `uv venv` makes them without pip by default — for a tool the user had told
// PipDock not to use.
let engine_ok = match engine.id() {
EngineId::Pip => pip.available,
EngineId::Uv => uv.available,
};
let check_ok = check.as_ref().map(|c| c.ok).unwrap_or(false);
// Whether Code Health can run at all. Deliberately **not** part of the exit rule below: Health
@@ -382,7 +493,7 @@ pub async fn doctor(opts: &GlobalOpts) -> Result<Exit> {
}
// A doctor that found real problems should say so in its exit code, or scripts cannot use it.
Ok(if pip_ok && check_ok {
Ok(if engine_ok && check_ok {
Exit::Success
} else {
Exit::PartialFailure
@@ -451,10 +562,14 @@ pub async fn snapshot_create(opts: &GlobalOpts) -> Result<Exit> {
jiff::Timestamp::now(),
)?;
println!(
"snapshot {} written ({} packages)",
snap.meta.id, snap.meta.package_count
);
if opts.json {
print_json(&snap.meta);
} else {
println!(
"snapshot {} written ({} packages)",
snap.meta.id, snap.meta.package_count
);
}
Ok(Exit::Success)
}
@@ -469,7 +584,9 @@ pub async fn snapshot_diff(opts: &GlobalOpts, id: &str) -> Result<Exit> {
let snap = snapshot::load(&app_data_dir(), &hash, id)?;
let current = snapshot::parse_freeze(&engine.freeze(&env).await?);
let d = snapshot::diff(&current, &snap.entries());
// What a rollback with this engine would see, so `diff` and `rollback` cannot disagree about
// pip and setuptools across engines (C7).
let d = snapshot::restorable_diff(&current, &snap.entries(), snap.meta.engine, engine.id());
if opts.json {
println!("{}", serde_json::to_string_pretty(&d).unwrap_or_default());
@@ -514,13 +631,25 @@ pub async fn snapshot_diff(opts: &GlobalOpts, id: &str) -> Result<Exit> {
/// otherwise propagates environment and engine failures. Per-package failures are not errors —
/// they appear in the summary.
pub async fn plan_and_run(opts: &GlobalOpts, intent: Intent, dry_run: bool) -> Result<Exit> {
// `update` with neither names nor `--all` is a usage mistake, not a plan with nothing in it:
// it used to resolve an empty request and exit 0 saying "nothing to do" (X16).
if let Intent::Update {
all: false, pkgs, ..
} = &intent
&& pkgs.is_empty()
{
eprintln!("error: name the packages to update, or pass --all");
return Ok(Exit::PlanAborted);
}
let env = select_env(opts).await?;
let store = Store::open(&app_data_dir())?;
// Read before the flow starts: `UpdateFlow` takes the pins rather than the store they came
// from, so its future stays `Send` for the GUI's sake.
let env_pins = pins::list(&store, &envs::env_hash(&env.interpreter))?;
let (mut flow, mut step) = UpdateFlow::start(env, engine_for(opts), &intent, &env_pins).await?;
let (mut flow, mut step) =
UpdateFlow::start(env, engine_for(opts), &intent, &env_pins, flow_options()).await?;
warn_pep668(flow.overrides_pep668());
// The flow returns the exclusion as data; the wording is the head's business (I18N §1).
if !flow.excluded_pins().is_empty() && !opts.json {
@@ -547,15 +676,28 @@ pub async fn plan_and_run(opts: &GlobalOpts, intent: Intent, dry_run: bool) -> R
let report = loop {
match step {
FlowStep::Nothing { reason } => {
// The step itself is the document: a script reads `reason` rather than a sentence.
if opts.json {
print_json(&FlowStep::Nothing { reason });
}
return Ok(match reason {
NothingReason::NothingToDo => {
println!("nothing to do");
if !opts.json {
println!("nothing to do");
}
Exit::Success
}
NothingReason::EverythingSkipped => {
println!("every package was skipped; nothing to do");
if !opts.json {
println!("every package was skipped; nothing to do");
}
Exit::PlanAborted
}
// CLI-SPEC §5: a user cancel is 130, and nothing ran.
NothingReason::Cancelled => {
eprintln!("stopped before anything was planned; nothing ran");
Exit::Cancelled
}
});
}
FlowStep::NeedsConfirm { report } | FlowStep::RoundsExhausted { report } => {
@@ -568,17 +710,35 @@ pub async fn plan_and_run(opts: &GlobalOpts, intent: Intent, dry_run: bool) -> R
}
};
print_preview(opts, &report);
if dry_run {
// **One document per command under `--json`** (CLI-SPEC §6, X5). This printed the report and
// then the summary, so `pipdock install x --json | ConvertFrom-Json` failed on the second
// document. The report is the document when nothing runs — a dry run, an empty plan, a
// declined prompt — and the summary when something does. A person at a terminal still sees the
// preview before the prompt: on stderr, beside the prompt itself.
if dry_run || report.changes.is_empty() {
if opts.json {
print_json(&report);
} else {
print!("{}", preview_text(&report));
if !dry_run {
println!("no changes to apply");
}
}
return Ok(Exit::Success);
}
if report.changes.is_empty() {
println!("no changes to apply");
return Ok(Exit::Success);
if opts.json {
if !opts.yes {
eprint!("{}", preview_text(&report));
}
} else {
print!("{}", preview_text(&report));
}
if !opts.yes && !confirm(&report) {
println!("aborted");
if opts.json {
print_json(&report);
} else {
println!("aborted");
}
return Ok(Exit::PlanAborted);
}
@@ -593,7 +753,8 @@ pub async fn plan_and_run(opts: &GlobalOpts, intent: Intent, dry_run: bool) -> R
} else {
SnapshotPolicy::Take
};
if let Some(meta) = flow.take_snapshot(policy, &app_data_dir()).await?
let snap = flow.take_snapshot(policy, &app_data_dir()).await?;
if let Some(meta) = &snap
&& !opts.json
{
println!("snapshot {} written", meta.id);
@@ -613,11 +774,29 @@ pub async fn plan_and_run(opts: &GlobalOpts, intent: Intent, dry_run: bool) -> R
let summary = flow.execute(tx).await?;
print_summary(opts, &summary);
Ok(if summary.counts.failed > 0 {
Ok(finished(&summary, snap.as_ref().map(|m| m.id.as_str())))
}
/// The exit a finished run earns, and — when it was stopped — how to undo what it did.
///
/// CLI-SPEC §5: 130 when the user stopped it, after the partial summary; the snapshot taken before
/// it is the way back, so its id is said rather than left to `snapshot list`.
fn finished(summary: &plan::ExecutionSummary, snapshot: Option<&str>) -> Exit {
if summary.cancelled {
match snapshot {
Some(id) => eprintln!(
"stopped. What ran is above; `pipdock snapshot rollback {id}` puts back the state \
from before this run."
),
None => eprintln!("stopped. What ran is above."),
}
return Exit::Cancelled;
}
if summary.counts.failed > 0 {
Exit::PartialFailure
} else {
Exit::Success
})
}
}
/// Decide what to do about each package needing a decision.
@@ -641,6 +820,21 @@ fn decide(
out.insert(held.pkg.clone(), decision);
}
if let Some(detail) = &report.impossible {
// Said before it is done: off a TTY the default for an impossibility is *skip*, and a
// skip that names nothing left the user with "every package was skipped" and no idea
// why (X26). On stderr, so `--json`'s stdout stays one document.
if !interactive {
eprintln!("{}", detail.explanation);
eprintln!(
"skipping: {}",
detail
.packages
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
);
}
for pkg in &detail.packages {
let decision = plan::default_decision(true, false);
out.insert(pkg.clone(), decision);
@@ -669,15 +863,16 @@ fn blocker_line(b: &plan::Blocker) -> String {
fn prompt_decision(held: &plan::HeldBack) -> plan::Decision {
use std::io::Write as _;
println!(
// Prompts go to stderr, with the question, so stdout is only ever the result (CLI-SPEC §6).
eprintln!(
"\n{} held back at {} (latest {})",
held.pkg, held.resolved, held.latest
);
for blocker in &held.blockers {
println!(" — {}", blocker_line(blocker));
eprintln!(" — {}", blocker_line(blocker));
}
print!(" [C]ompatible (default) [S]kip [F]orce latest: ");
let _ = std::io::stdout().flush();
eprint!(" [C]ompatible (default) [S]kip [F]orce latest: ");
let _ = std::io::stderr().flush();
let mut line = String::new();
if std::io::stdin().read_line(&mut line).is_err() {
@@ -693,7 +888,7 @@ fn prompt_decision(held: &plan::HeldBack) -> plan::Decision {
.filter_map(|b| b.by.as_ref().map(ToString::to_string))
.collect();
if !breaks.is_empty() {
println!(" this will break: {}", breaks.join(", "));
eprintln!(" this will break: {}", breaks.join(", "));
}
plan::Decision::ForceLatest
}
@@ -701,53 +896,91 @@ fn prompt_decision(held: &plan::HeldBack) -> plan::Decision {
}
}
/// Render the preview (UI-SPEC §4's three groups, in text).
fn print_preview(opts: &GlobalOpts, report: &plan::ResolutionReport) {
if opts.json {
println!(
"{}",
serde_json::to_string_pretty(report).unwrap_or_default()
);
return;
/// The preview as text (UI-SPEC §4's groups). A string, so the caller decides the stream: stdout
/// normally, stderr beside the prompt under `--json`.
fn preview_text(report: &plan::ResolutionReport) -> String {
use std::fmt::Write as _;
let mut out = String::new();
// Infallible: writing to a String cannot fail.
macro_rules! line {
($($arg:tt)*) => {{
let _ = writeln!(out, $($arg)*);
}};
}
let upgrades: Vec<_> = report.changes.iter().filter(|c| c.from.is_some()).collect();
let fresh: Vec<_> = report.changes.iter().filter(|c| c.from.is_none()).collect();
if !upgrades.is_empty() {
println!("\nWill upgrade:");
line!("\nWill upgrade:");
for c in upgrades {
let from = c.from.as_ref().map(ToString::to_string).unwrap_or_default();
println!(" {:<32} {} -> {}", c.name, from, c.to);
line!(" {:<32} {} -> {}", c.name, from, c.to);
}
}
if !fresh.is_empty() {
println!("\nNew:");
line!("\nNew:");
for c in fresh {
println!(" {:<32} {}", c.name, c.to);
line!(" {:<32} {}", c.name, c.to);
}
}
if !report.held_back.is_empty() {
println!("\nNeeds decision — held back:");
line!("\nNeeds decision — held back:");
for h in &report.held_back {
println!(" {:<32} {} (latest {})", h.pkg, h.resolved, h.latest);
line!(" {:<32} {} (latest {})", h.pkg, h.resolved, h.latest);
for b in &h.blockers {
println!(" {}", blocker_line(b));
line!(" {}", blocker_line(b));
}
if h.blockers.is_empty() {
// ARCHITECTURE §3: no culprit is invented, and the row says so plainly rather
// than looking like a rendering bug.
println!(" (nothing installed explains this)");
line!(" (nothing installed explains this)");
}
}
}
if !report.incompatible.is_empty() {
// Hard invariant 10: left out, and why, rather than a "not found" for a version that
// exists.
line!("\nLeft out — needs a different Python:");
for m in &report.incompatible {
line!(
" {} {} requires Python {} (this is {})",
m.pkg,
m.version,
m.requires_python,
m.python
);
}
}
if !report.forced.is_empty() {
// DISCLAIMER §2: what forcing breaks is said before anything runs, not discovered after.
line!("\nForced — will break:");
for f in &report.forced {
line!(" {:<32} -> {}", f.pkg, f.latest);
for b in &f.blockers {
line!(" {}", blocker_line(b));
}
}
}
if !report.yanked.is_empty() {
// PD-PKG-003 is a warning, not a failure (SP-2). Shown in JSON only until 1.4.0.
line!("\nWithdrawn releases (yanked):");
for y in &report.yanked {
match &y.reason {
Some(reason) => line!(" {} {} — {reason}", y.pkg, y.version),
None => line!(" {} {}", y.pkg, y.version),
}
}
}
if let Some(detail) = &report.impossible {
println!("\nImpossible:");
println!(" {}", detail.explanation);
line!("\nImpossible:");
line!(" {}", detail.explanation);
}
if report.changes.is_empty() && report.held_back.is_empty() {
println!("\nno changes");
line!("\nno changes");
}
out
}
/// Ask before touching anything (DATA-FLOW §3's Confirm step).
@@ -759,8 +992,8 @@ fn confirm(report: &plan::ResolutionReport) -> bool {
eprintln!("error[PD-RES-002]: not a terminal; pass --yes to apply without confirming");
return false;
}
print!("\nApply {} change(s)? [y/N]: ", report.changes.len());
let _ = std::io::stdout().flush();
eprint!("\nApply {} change(s)? [y/N]: ", report.changes.len());
let _ = std::io::stderr().flush();
let mut line = String::new();
if std::io::stdin().read_line(&mut line).is_err() {
return false;
@@ -798,7 +1031,9 @@ pub async fn env_use(opts: &GlobalOpts, path: &Path) -> Result<Exit> {
true,
)?;
if !opts.quiet {
if opts.json {
print_json(&probed.env);
} else if !opts.quiet {
println!(
"default environment set: {} (Python {})",
interpreter.display(),
@@ -861,8 +1096,8 @@ pub async fn tools_sync(opts: &GlobalOpts, force: bool, python: Option<&Path>) -
}
});
// A fresh token nothing trips, matching every other CLI path: the CLI installs no Ctrl-C
// handler, and the flows build their own tokens for the GUI's `plan_cancel` to reach. Killing
// A fresh token nothing trips: only the mutating commands install a Ctrl-C handler, and a
// sync is not one of them, so Ctrl-C ends the process and the sync with it. Killing
// the process still tears the tree down — `exec::TreeGuard`'s job object closes with the last
// handle — which is verified rather than assumed: a killed sync leaves no orphan pip.
let sink = engine::ProgressSink::new(
@@ -903,9 +1138,9 @@ pub async fn audit(opts: &GlobalOpts) -> Result<Exit> {
let env = select_env(opts).await?;
let app_data = app_data_dir();
let store = Store::open(&app_data)?;
let engine = engine::for_id(settings::load(&store)?.engine);
drop(store);
// `--engine` decides, like everywhere else: pip freezes with `--all` and uv does not, so the
// engine changes what is audited, and the flag was being read by everything but this (X14).
let engine = engine_for(opts);
// Taken before the venv is touched, so an unreadable environment fails before a 15-second
// bootstrap rather than after one.
@@ -943,7 +1178,7 @@ pub async fn audit(opts: &GlobalOpts) -> Result<Exit> {
if !opts.quiet && !opts.json {
println!(
"checking {} packages against the advisory database…",
freeze.lines().count()
snapshot::parse_freeze(&freeze).len()
);
}
audit::run(&dir, &env, &freeze, &sink.at(synced)).await
@@ -1139,7 +1374,7 @@ pub async fn health(
print_health(opts, &report);
}
if fix {
return apply_fix(opts, &tools_dir, &project, &report).await;
return apply_fix(opts, &tools_dir, &project, &report, &run_opts).await;
}
Ok(if health::has_findings(&report) {
Exit::PartialFailure
@@ -1158,8 +1393,10 @@ pub async fn health(
/// `--yes` means "assume defaults", and **the default over uncommitted work is don't**. A clean
/// tree proceeds: one `git checkout .` puts it back, so an unattended fix there is recoverable,
/// and refusing would make `--fix` useless in the pre-commit hook the exit-code rule was written
/// for. A dirty tree — or no repository at all — refuses with exit 2, because those are the cases
/// where a script could destroy work with no way back.
/// for. A dirty tree refuses with exit 2, because that is where a script could destroy work with
/// no way back. **Outside a repository `--yes` proceeds**: `fix::dirty` answers `None` both for a
/// clean tree and for no repository, so the two cannot be told apart here. Refusing there too is in
/// ROADMAP's Audit backlog; this comment used to claim it already did.
///
/// The escape hatch is deliberately **not a flag**. It is `git commit` or `git stash`, which is the
/// actual remedy and leaves the user something to return to; a `--force-fix` would exist only to be
@@ -1174,6 +1411,7 @@ async fn apply_fix(
tools_dir: &Path,
project: &Path,
report: &health::HealthReport,
run_opts: &health::RunOptions,
) -> Result<Exit> {
use pipdock_core::health::fix;
@@ -1203,7 +1441,8 @@ async fn apply_fix(
true
} else if interactive {
if let Some(tree) = dirty {
println!(
// stderr, with the prompt it introduces: under `--json` stdout carries one document.
eprintln!(
"\n{} uncommitted change(s) in this repository. PipDock cannot undo a fix, and \
`git checkout .` would take your own edits with it.",
tree.entries
@@ -1231,7 +1470,7 @@ async fn apply_fix(
// process produced seconds ago, so there is no window between confirming and fixing for the
// tree to drift in. The consent is still built from what was actually observed.
let consent = fix::consent_ok(report.ruff.fixable_files, dirty.is_some(), dirty)?;
let fixed = fix::apply(tools_dir, project, &report.ruff, consent).await?;
let fixed = fix::apply(tools_dir, project, &report.ruff, consent, run_opts).await?;
if opts.json {
println!(
@@ -1406,11 +1645,15 @@ pub async fn pip_upgrade(opts: &GlobalOpts) -> Result<Exit> {
PipEngine.upgrade_pip(&env).await?;
let after = PipEngine.info(&env).await;
println!(
"pip {} -> {}",
before.version.unwrap_or_else(|| "?".into()),
after.version.unwrap_or_else(|| "?".into())
);
if opts.json {
print_json(&serde_json::json!({ "before": before, "after": after }));
} else {
println!(
"pip {} -> {}",
before.version.unwrap_or_else(|| "?".into()),
after.version.unwrap_or_else(|| "?".into())
);
}
Ok(Exit::Success)
}
@@ -1426,35 +1669,36 @@ pub async fn snapshot_rollback(opts: &GlobalOpts, id: &str) -> Result<Exit> {
let env = select_env(opts).await?;
let app_data = app_data_dir();
let (mut flow, preview) = RollbackFlow::start(env, engine_for(opts), &app_data, id).await?;
let (mut flow, preview) =
RollbackFlow::start(env, engine_for(opts), &app_data, id, flow_options()).await?;
warn_pep668(flow.overrides_pep668());
// One document under `--json`, as everywhere (X5): the preview when nothing runs, the summary
// when something does.
if preview.restore.is_empty() {
println!("environment already matches snapshot {}", preview.target.id);
if opts.json {
print_json(&preview);
} else {
println!("environment already matches snapshot {}", preview.target.id);
}
return Ok(Exit::Success);
}
println!("Rolling back to {}:", preview.target.id);
for name in &preview.restore.uninstall {
println!(" remove {name}");
}
for spec in &preview.restore.install {
println!(" restore {} {}", spec.name, spec.version);
}
// Honesty about what cannot come back, rather than reporting a success that is not one.
if !preview.unrestorable.is_empty() {
println!(
"\nwarning[PD-SNP-002]: {} entr(y/ies) in this snapshot cannot be restored from an \
index and will be left as they are:",
preview.unrestorable.len()
);
for line in &preview.unrestorable {
println!(" {line}");
let text = rollback_text(&preview);
if opts.json {
if !opts.yes {
eprint!("{text}");
}
} else {
print!("{text}");
}
if !opts.yes && !confirm_text(&format!("Apply {} operation(s)?", preview.restore.len())) {
println!("aborted");
if opts.json {
print_json(&preview);
} else {
println!("aborted");
}
return Ok(Exit::PlanAborted);
}
@@ -1479,11 +1723,34 @@ pub async fn snapshot_rollback(opts: &GlobalOpts, id: &str) -> Result<Exit> {
let summary = flow.execute(tx).await?;
print_summary(opts, &summary);
Ok(if summary.counts.failed > 0 {
Exit::PartialFailure
} else {
Exit::Success
})
Ok(finished(&summary, Some(&pre.id)))
}
/// What a rollback would do, as text.
fn rollback_text(preview: &pipdock_core::flow::RollbackPreview) -> String {
use std::fmt::Write as _;
let mut out = String::new();
let _ = writeln!(out, "Rolling back to {}:", preview.target.id);
for name in &preview.restore.uninstall {
let _ = writeln!(out, " remove {name}");
}
for spec in &preview.restore.install {
let _ = writeln!(out, " restore {} {}", spec.name, spec.version);
}
// Honesty about what cannot come back, rather than reporting a success that is not one.
if !preview.unrestorable.is_empty() {
let _ = writeln!(
out,
"\nwarning[PD-SNP-002]: {} entr(y/ies) in this snapshot cannot be restored from an \
index and will be left as they are:",
preview.unrestorable.len()
);
for line in &preview.unrestorable {
let _ = writeln!(out, " {line}");
}
}
out
}
/// `pipdock self report-bug`
@@ -1517,7 +1784,11 @@ pub async fn report_bug(opts: &GlobalOpts) -> Result<Exit> {
&os_description(),
);
println!("{url}");
if opts.json {
print_json(&serde_json::json!({ "url": url }));
} else {
println!("{url}");
}
if !opts.quiet {
// Concatenated rather than a multi-line literal: a bare string literal keeps the source
// indentation, which shipped this line with fourteen stray spaces in the middle of a
@@ -1545,8 +1816,8 @@ fn confirm_text(question: &str) -> bool {
eprintln!("error[PD-RES-002]: not a terminal; pass --yes to proceed without confirming");
return false;
}
print!("\n{question} [y/N]: ");
let _ = std::io::stdout().flush();
eprint!("\n{question} [y/N]: ");
let _ = std::io::stderr().flush();
let mut line = String::new();
if std::io::stdin().read_line(&mut line).is_err() {
return false;
@@ -1724,16 +1995,18 @@ pub async fn pin_add(opts: &GlobalOpts, pkg: &str, reason: Option<&str>) -> Resu
let store = Store::open(&app_data_dir())?;
let name = PkgName::parse(pkg)?;
pins::add(
&store,
&envs::env_hash(&env.interpreter),
&pins::Pin {
pkg: name.clone(),
mode: pins::PinMode::Exclude,
reason: reason.map(str::to_owned),
},
)?;
println!("pinned {name} (excluded from bulk updates)");
let pin = pins::Pin {
pkg: name.clone(),
mode: pins::PinMode::Exclude,
reason: reason.map(str::to_owned),
};
pins::add(&store, &envs::env_hash(&env.interpreter), &pin)?;
if opts.json {
print_json(&pin);
} else {
// DATA-FLOW §9.5: every update, not only bulk ones.
println!("pinned {name} (left out of updates until unpinned)");
}
Ok(Exit::Success)
}
@@ -1746,7 +2019,10 @@ pub async fn pin_remove(opts: &GlobalOpts, pkg: &str) -> Result<Exit> {
let store = Store::open(&app_data_dir())?;
let name = PkgName::parse(pkg)?;
if pins::remove(&store, &envs::env_hash(&env.interpreter), &name)? {
let removed = pins::remove(&store, &envs::env_hash(&env.interpreter), &name)?;
if opts.json {
print_json(&serde_json::json!({ "pkg": name, "removed": removed }));
} else if removed {
println!("unpinned {name}");
} else {
println!("{name} was not pinned");
@@ -1770,15 +2046,15 @@ pub async fn uninstall(opts: &GlobalOpts, pkgs: &[String], force: bool) -> Resul
let env = select_env(opts).await?;
let engine = engine_for(opts);
let (mut flow, report) = UninstallFlow::start(env, engine, pkgs).await?;
let (mut flow, report) = UninstallFlow::start(env, engine, pkgs, flow_options()).await?;
warn_pep668(flow.overrides_pep668());
if !report.is_clear() {
if opts.json {
println!(
"{}",
serde_json::to_string_pretty(&report).unwrap_or_default()
);
} else {
// Under `--json` the guard report is the document only when it ends the command; with
// `--force` the summary is, and printing both was two documents (X5).
if opts.json && !force {
print_json(&report);
} else if !opts.json {
for (pkg, broken) in &report.breaks {
// Names alone say what breaks; the specifier says whether the user can live with
// it. `pandas 2.1.4 (<2,>=1.26.0)` is checkable against what they know.
@@ -1836,7 +2112,8 @@ pub async fn uninstall(opts: &GlobalOpts, pkgs: &[String], force: bool) -> Resul
} else {
SnapshotPolicy::Take
};
if let Some(meta) = flow.take_snapshot(policy, &app_data_dir()).await?
let snap = flow.take_snapshot(policy, &app_data_dir()).await?;
if let Some(meta) = &snap
&& !opts.json
{
println!("snapshot {} written before removing", meta.id);
@@ -1863,14 +2140,12 @@ pub async fn uninstall(opts: &GlobalOpts, pkgs: &[String], force: bool) -> Resul
GuardAck::Clear
};
let summary = flow.execute(ack, tx).await?;
drop(pump);
// Drained, not dropped: the last lines of a removal are the ones that say how it ended, and a
// dropped handle let the summary print over them (X38). The other three pumps already wait.
let _ = pump.await;
print_summary(opts, &summary);
Ok(if summary.counts.failed > 0 {
Exit::PartialFailure
} else {
Exit::Success
})
Ok(finished(&summary, snap.as_ref().map(|m| m.id.as_str())))
}
/// Render an execution summary (DATA-FLOW §6).
@@ -1914,16 +2189,49 @@ fn print_summary(opts: &GlobalOpts, summary: &plan::ExecutionSummary) {
/// # Errors
/// Never; reports availability rather than failing.
pub async fn engine_status(opts: &GlobalOpts) -> Result<Exit> {
let env = select_env(opts).await?;
for (id, info) in [
(EngineId::Pip, PipEngine.info(&env).await),
(EngineId::Uv, UvEngine.info(&env).await),
] {
println!(
"{:<4} {}",
id.as_str(),
info.version.unwrap_or_else(|| "not available".into())
);
// No environment is required (X15). uv is a standalone binary; pip is a module of some
// interpreter, so without one it is reported as such rather than failing the command — which
// is what happened in any directory without a .venv.
let env = select_env(opts).await.ok();
let blank = PyEnv {
interpreter: PathBuf::new(),
prefix: PathBuf::new(),
python_version: String::new(),
externally_managed: false,
hidden_user_site: None,
source: EnvSource::Manual,
};
let pip = match &env {
Some(env) => PipEngine.info(env).await,
None => pipdock_core::model::EngineInfo {
id: EngineId::Pip,
version: None,
available: false,
},
};
let uv = UvEngine.info(env.as_ref().unwrap_or(&blank)).await;
if opts.json {
print_json(&[&pip, &uv]);
return Ok(Exit::Success);
}
// The help has always said this command shows the current engine; it listed both and never
// said which one PipDock would use.
let configured = Store::open(&app_data_dir())
.and_then(|store| settings::load(&store))
.map_or(EngineId::Pip, |s| s.engine);
for info in [&pip, &uv] {
let detail = match (&info.version, info.id, &env) {
(Some(v), _, _) => v.clone(),
(None, EngineId::Pip, None) => "no environment selected".to_owned(),
(None, _, _) => "not available".to_owned(),
};
let mark = if info.id == configured {
" (configured)"
} else {
""
};
println!("{:<4} {detail}{mark}", info.id.as_str());
}
Ok(Exit::Success)
}
+9
View File
@@ -46,6 +46,7 @@ const SCHEMA_TYPES: &[&str] = &[
"CacheUsage",
"CacheTarget",
"GuardReport",
"DepsGraph",
"Diff",
"SnapshotMeta",
"EngineInfo",
@@ -63,12 +64,20 @@ const SCHEMA_TYPES: &[&str] = &[
"HealthReport",
"AuditReport",
"FixReport",
"LogTail",
];
fn pipdock() -> Command {
let mut cmd = Command::cargo_bin("pipdock").expect("the `pipdock` binary builds");
// Colour and width leak the terminal into the snapshot; pin both.
cmd.env("NO_COLOR", "1").env("COLUMNS", "100");
// Every invocation writes its log under the app-data root, and a test run's belongs in a
// scratch directory rather than in the developer's own profile. Settings and the store move
// with it, which is the isolation a contract test wants anyway.
cmd.env(
"LOCALAPPDATA",
std::env::temp_dir().join(format!("pd-golden-{}", std::process::id())),
);
cmd
}
@@ -8,7 +8,7 @@ Usage: pipdock audit [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -18,19 +18,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock doctor [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -18,19 +18,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock engine [OPTIONS] [ENGINE]
Arguments:
[ENGINE]
Engine to switch to; omit to print the current one
Engine to switch to; omit to list both, with versions, marking the configured one
Possible values:
- pip: `<python> -m pip`
@@ -16,22 +16,24 @@ Arguments:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock env list [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -18,19 +18,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -12,7 +12,7 @@ Arguments:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -22,19 +22,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -13,7 +13,7 @@ Commands:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -23,19 +23,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock health [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--path <DIR>
Project folder; defaults to the folder remembered for this environment
@@ -32,19 +32,21 @@ Options:
Apply ruff's safe fixes. Prompts before writing
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock index refresh [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -18,19 +18,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -12,7 +12,7 @@ Commands:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -22,19 +22,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -12,7 +12,7 @@ Arguments:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -22,19 +22,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,14 +8,14 @@ Usage: pipdock install [OPTIONS] <SPECS>...
Arguments:
<SPECS>...
`name` or `name==version`
A name with an optional PEP 440 specifier: `six`, `six==[VERSION]`, `"six>=1.16,<2"`
Options:
--dry-run
Print the resolution report and exit without changing anything
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -25,19 +25,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock list [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--outdated
Show only packages with a newer release available
@@ -21,19 +21,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -12,7 +12,7 @@ Arguments:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--reason <REASON>
Why it is pinned
@@ -25,19 +25,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock pin list [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -18,19 +18,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -12,7 +12,7 @@ Arguments:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -22,19 +22,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -14,7 +14,7 @@ Commands:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -24,19 +24,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock pip-upgrade [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -18,19 +18,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -12,7 +12,7 @@ Arguments:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -22,19 +22,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -12,7 +12,7 @@ Arguments:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--limit <LIMIT>
Maximum results
@@ -27,19 +27,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock self report-bug [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -18,19 +18,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -12,7 +12,7 @@ Commands:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -22,19 +22,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock snapshot create [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -18,19 +18,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -12,7 +12,7 @@ Arguments:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -22,19 +22,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock snapshot list [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -18,19 +18,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -12,7 +12,7 @@ Arguments:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -22,19 +22,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -15,7 +15,7 @@ Commands:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -25,19 +25,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock tools status [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -18,19 +18,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -8,7 +8,7 @@ Usage: pipdock tools sync [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--force
Re-install even when the pin set already matches
@@ -24,19 +24,21 @@ Options:
Build on this interpreter instead of the newest discovered one
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -13,7 +13,7 @@ Commands:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -23,19 +23,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -12,7 +12,7 @@ Arguments:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--force
Proceed even when the guard reports dependents that would break
@@ -25,19 +25,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -15,7 +15,7 @@ Options:
Update every outdated package (pins still apply)
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -37,22 +37,24 @@ Options:
Ad-hoc exclusions on top of the pin list
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
--dry-run
Print the resolution report and exit without changing anything
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -30,7 +30,7 @@ Commands:
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
Interpreter or environment directory. Defaults to the one `env use` set, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
@@ -40,19 +40,21 @@ Options:
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
Machine-readable output: exactly one JSON document on stdout (CLI-SPEC §6).
Prompts, warnings and engine output go to stderr. This said "NDJSON for streaming commands" until [VERSION], when several commands printed several documents.
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
Assume the default at every prompt: a held-back package keeps its compatible version and an impossible one is skipped. Only `--strategy latest` forces
--quiet
Reduce log output
Do not stream engine output to stderr. (The log file is written regardless.)
--verbose
Increase log output
Also write the log to stderr, at debug level
--log-file <PATH>
Tee logs to a file
Also write the log to this file. The daily log in `data\logs\` is always kept
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
@@ -88,6 +88,11 @@ expression: out
"description": "uv emitted a shape the adapter does not recognize (uv newer than PipDock).",
"type": "string"
},
{
"const": "PD-ENG-004",
"description": "An engine command ran past its watchdog and was stopped.\n\n**Raised by PipDock, never classified from stderr.** Its own code because the alternative\nwas `PD-INT-001`, which is what the shared watchdog reported until 1.4.0: an sdist build\nstill compiling after ten minutes is not \"a PipDock bug\", and in the batch phase that error\naborted the whole run — no summary, no per-package retry.",
"type": "string"
},
{
"const": "PD-ENG-999",
"description": "Fallback for engine failures no classifier matched. Always last.",
@@ -22,6 +22,186 @@ expression: out
],
"type": "object"
},
"Code": {
"description": "Every code PipDock can surface at v1 launch.\n\n`docs/TESTING.md` §2 requires at least one captured stderr fixture per variant before ship;\nthe test that enforces \"no code without fixture\" lives beside the classifiers.",
"oneOf": [
{
"const": "PD-ENV-001",
"description": "Interpreter path missing or not executable — the env was deleted or moved.",
"type": "string"
},
{
"const": "PD-ENV-002",
"description": "PEP 668 `EXTERNALLY-MANAGED` marker present; mutation blocked by default.",
"type": "string"
},
{
"const": "PD-ENV-003",
"description": "`probe.py` exited non-zero or produced unparseable output.",
"type": "string"
},
{
"const": "PD-ENG-001",
"description": "pip or uv binary not found.",
"type": "string"
},
{
"const": "PD-ENG-002",
"description": "pip older than 22.2, which predates `--dry-run --report`.",
"type": "string"
},
{
"const": "PD-ENG-003",
"description": "uv emitted a shape the adapter does not recognize (uv newer than PipDock).",
"type": "string"
},
{
"const": "PD-ENG-004",
"description": "An engine command ran past its watchdog and was stopped.\n\n**Raised by PipDock, never classified from stderr.** Its own code because the alternative\nwas `PD-INT-001`, which is what the shared watchdog reported until 1.4.0: an sdist build\nstill compiling after ten minutes is not \"a PipDock bug\", and in the batch phase that error\naborted the whole run — no summary, no per-package retry.",
"type": "string"
},
{
"const": "PD-ENG-999",
"description": "Fallback for engine failures no classifier matched. Always last.",
"type": "string"
},
{
"const": "PD-RES-001",
"description": "`ResolutionImpossible` or the uv equivalent: constraints cannot be satisfied.",
"type": "string"
},
{
"const": "PD-RES-002",
"description": "Plan older than 10 minutes, or the env's probe hash changed since the preview.",
"type": "string"
},
{
"const": "PD-RES-003",
"description": "A plan is already resolving or executing in this session.\n\nThe GUI drives one resumable flow across several IPC calls, so \"start a plan\" and \"run the\nplan\" are different messages arriving at different times — nothing structurally stops a\nsecond one arriving in between. Refusing is the only safe answer: two concurrent plans\nwould interleave engine commands against one environment, and DATA-FLOW §9.3's staleness\ncheck would be comparing against a set the other plan is busy changing.",
"type": "string"
},
{
"const": "PD-RES-004",
"description": "A removal was asked for that the reverse-dependency guard refused (DATA-FLOW §5).\n\nIts own code rather than a reused one. The CLI printed `PD-PKG-002` here, which means \"no\nmatching distribution\" — the opposite of the truth: every package involved exists, and\nthat is precisely why the removal is being refused. A user grepping their logs for a typo\nwould have found this instead.\n\nNot raised when the guard merely *finds* dependents. That is a report the caller shows and\nthe user answers; the code appears only when execution is attempted anyway without the\nuser having accepted the breakage.",
"type": "string"
},
{
"const": "PD-BLD-001",
"description": "MSVC build tools required but absent.",
"type": "string"
},
{
"const": "PD-BLD-002",
"description": "Build backend failed (`pyproject.toml` error, `metadata-generation-failed`).",
"type": "string"
},
{
"const": "PD-BLD-003",
"description": "Generic sdist wheel-build failure.",
"type": "string"
},
{
"const": "PD-PKG-001",
"description": "No matching distribution, and metadata shows a requires-python mismatch.",
"type": "string"
},
{
"const": "PD-PKG-002",
"description": "No matching distribution: name or version typo, or the release is gone.",
"type": "string"
},
{
"const": "PD-PKG-003",
"description": "The requested release was yanked.",
"type": "string"
},
{
"const": "PD-PKG-004",
"description": "Downloaded artifact failed hash verification.",
"type": "string"
},
{
"const": "PD-NET-001",
"description": "Timeout, connection aborted, or DNS failure.",
"type": "string"
},
{
"const": "PD-NET-002",
"description": "TLS/SSL verification failed — typically proxy or AV interception.",
"type": "string"
},
{
"const": "PD-NET-010",
"description": "PEP 691 index refresh failed; the stale index stays searchable.",
"type": "string"
},
{
"const": "PD-NET-011",
"description": "Code Health tools-venv bootstrap could not reach PyPI.",
"type": "string"
},
{
"const": "PD-PRM-001",
"description": "`PermissionError` writing site-packages (admin-owned Python).",
"type": "string"
},
{
"const": "PD-PRM-002",
"description": "File locked by a running process (`WinError 32`).",
"type": "string"
},
{
"const": "PD-PRM-003",
"description": "A source file in the user's project cannot be written.\n\n**Not `PD-PRM-001`.** That one is scoped to site-packages and its catalogued action is\n\"use a venv\", which is nonsense advice for a read-only `util.py` — the same class of wrong\nanswer P3 removed when a corrupted `ruff.exe` reported `PD-ENG-001`, \"install the engine\".\n\nRaised by PipDock **before anything is written**, never classified from stderr: ruff can\nfail to write a file and still exit 1, which `is_findings_exit` accepts as a clean run, so\na stderr-matched code would arrive after a fix had already reported success.",
"type": "string"
},
{
"const": "PD-SNP-001",
"description": "Snapshot write failed before execution. **The plan is aborted; nothing runs.**",
"type": "string"
},
{
"const": "PD-SNP-002",
"description": "A release needed to restore a snapshot is no longer available on PyPI.",
"type": "string"
},
{
"const": "PD-SYS-001",
"description": "`MAX_PATH` exceeded without the long-path opt-in.",
"type": "string"
},
{
"const": "PD-SYS-002",
"description": "Disk full.",
"type": "string"
},
{
"const": "PD-HLT-001",
"description": "A Code Health tool is missing from the tools venv.",
"type": "string"
},
{
"const": "PD-HLT-002",
"description": "A Code Health tool exited non-zero.",
"type": "string"
},
{
"const": "PD-HLT-003",
"description": "A Code Health tool exceeded its watchdog timeout; partial report shown.",
"type": "string"
},
{
"const": "PD-HLT-004",
"description": "`python -m venv` failed while building the tools environment.\n\n**Raised by PipDock, not classified from engine stderr.** Its own code rather than a reused\none: `PD-NET-011` is `Area::Net`, so `run::exit_for` would map a broken interpreter to exit\n6 and a script retrying on network failure would loop forever; `PD-HLT-001` tells the user\nto re-sync, which is the operation that just failed; and a Python built without `venv` is\nnot `PD-INT-001`'s \"a PipDock bug\".",
"type": "string"
},
{
"const": "PD-INT-001",
"description": "A PipDock bug: panic or unexpected state.",
"type": "string"
}
]
},
"PkgName": {
"description": "A PEP 503-normalized distribution name.\n\nConstructing one is the *only* way a package name reaches an argv array, which is what makes\nSECURITY §2's \"validated before it reaches argv\" claim structural rather than aspirational.",
"type": "string"
@@ -30,6 +210,17 @@ expression: out
"$schema": "https://json-schema.org/draft/2020-12/schema",
"description": "Post-execution environment verification.",
"properties": {
"error": {
"anyOf": [
{
"$ref": "#/$defs/Code"
},
{
"type": "null"
}
],
"description": "Set when the check could not run at all, with the reason's code; `ok` is false then.\n\nA check that could not run used to be reported as `ok: true` — \"verified\" in exactly the\ncase where nothing was verified, such as a pip broken by the run it was meant to check."
},
"findings": {
"default": [],
"description": "Details when `ok` is false.",
@@ -39,7 +230,7 @@ expression: out
"type": "array"
},
"ok": {
"description": "True when the engine reported no broken requirements.",
"description": "True when the check **ran** and the engine reported no broken requirements.",
"type": "boolean"
}
},
@@ -36,6 +36,11 @@ expression: out
"description": "uv emitted a shape the adapter does not recognize (uv newer than PipDock).",
"type": "string"
},
{
"const": "PD-ENG-004",
"description": "An engine command ran past its watchdog and was stopped.\n\n**Raised by PipDock, never classified from stderr.** Its own code because the alternative\nwas `PD-INT-001`, which is what the shared watchdog reported until 1.4.0: an sdist build\nstill compiling after ten minutes is not \"a PipDock bug\", and in the batch phase that error\naborted the whole run — no summary, no per-package retry.",
"type": "string"
},
{
"const": "PD-ENG-999",
"description": "Fallback for engine failures no classifier matched. Always last.",
@@ -0,0 +1,105 @@
---
source: crates/pipdock-cli/tests/golden.rs
expression: out
---
{
"$defs": {
"DepEdge": {
"description": "One edge of the dependency graph, seen from a focused package.\n\n`pkg` is always the **other end** of the edge and `constraint` always the specifier written on\nit, so one type serves both directions: in a dependents column `pkg` is who requires the focus,\nin a dependencies column it is what the focus requires. `version` is that package's installed\nversion.\n\nThree fields identical to [`BrokenDependent`], and deliberately a separate type. That one is\nabout *breakage* — its doc is written for the uninstall dialog and its `Ord` exists for the\ndedup in [`ReverseDeps::breaking_dependents`] — so reusing it here would have a dependencies\ncolumn claim every dependency is a broken dependent. The `From` impl below is the bridge, and\n[`ReverseDeps::edges_to`] goes through it precisely so the two cannot drift.\n\n`constraint` is the **bare specifier tail** — `\"<2,>=1.26.0\"`, never `\"numpy<2,>=1.26.0\"` — for\n[`BrokenDependent`]'s reason. The other half of the sentence is the focused package, which the\ncaller already has; Rust emits data and each head writes its own sentence (I18N §1). An empty\nstring means unconstrained, which is a different statement from \"no edge\" and the view says so.",
"properties": {
"constraint": {
"description": "The version specifier written on the edge. Empty when unconstrained.",
"type": "string"
},
"pkg": {
"$ref": "#/$defs/PkgName",
"description": "The package at the other end of the edge."
},
"version": {
"description": "Its installed version, when the graph knows it.",
"type": [
"string",
"null"
]
}
},
"required": [
"pkg",
"constraint"
],
"type": "object"
},
"DepsNode": {
"description": "Everything a focus view needs about one installed package.\n\n`impact` and `reach` are the pair the view exists for. Every other question PipDock answers\nabout the graph is single-hop — the uninstall guard, blocker attribution and pin auto-suggest\nall look one edge out — so the only thing a dependency view adds over shipped behaviour is\n**transitive** reach, and it is a number rather than a picture because the picture does not\nsurvive the scale: measured on the 352-package fixture, a depth-2 neighbourhood is a median of\n172 nodes and exceeds 60 for 212 of 352 packages.",
"properties": {
"dependencies": {
"description": "Installed packages this one requires, in force.",
"items": {
"$ref": "#/$defs/DepEdge"
},
"type": "array"
},
"dependents": {
"description": "Installed packages that require this one, with the constraint each declared.",
"items": {
"$ref": "#/$defs/DepEdge"
},
"type": "array"
},
"impact": {
"description": "How many packages would be left broken if this one went, transitively. The size of\n[`ReverseDeps::removal_closure`] without the package itself.",
"format": "uint",
"minimum": 0,
"type": "integer"
},
"reach": {
"description": "How many installed packages this one pulls in, transitively.",
"format": "uint",
"minimum": 0,
"type": "integer"
},
"unsatisfied": {
"description": "In-force requirements with nothing installed to satisfy them.",
"items": {
"$ref": "#/$defs/PkgName"
},
"type": "array"
},
"version": {
"description": "The package's own installed version.",
"type": [
"string",
"null"
]
}
},
"required": [
"dependents",
"dependencies",
"impact",
"reach"
],
"type": "object"
},
"PkgName": {
"description": "A PEP 503-normalized distribution name.\n\nConstructing one is the *only* way a package name reaches an argv array, which is what makes\nSECURITY §2's \"validated before it reaches argv\" claim structural rather than aspirational.",
"type": "string"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"description": "The in-force dependency graph of one environment (PRD P1-6).\n\nKeyed by package name, one entry per installed distribution. Produced by\n[`ReverseDeps::view`]; see its doc for why this crosses the bridge whole rather than a package\nat a time, and why nothing here is capped.",
"properties": {
"nodes": {
"additionalProperties": {
"$ref": "#/$defs/DepsNode"
},
"description": "Every installed package, including those with no edges in either direction.",
"type": "object"
}
},
"required": [
"nodes"
],
"title": "DepsGraph",
"type": "object"
}
@@ -25,6 +25,17 @@ expression: out
"CheckReport": {
"description": "Post-execution environment verification.",
"properties": {
"error": {
"anyOf": [
{
"$ref": "#/$defs/Code"
},
{
"type": "null"
}
],
"description": "Set when the check could not run at all, with the reason's code; `ok` is false then.\n\nA check that could not run used to be reported as `ok: true` — \"verified\" in exactly the\ncase where nothing was verified, such as a pip broken by the run it was meant to check."
},
"findings": {
"default": [],
"description": "Details when `ok` is false.",
@@ -34,7 +45,7 @@ expression: out
"type": "array"
},
"ok": {
"description": "True when the engine reported no broken requirements.",
"description": "True when the check **ran** and the engine reported no broken requirements.",
"type": "boolean"
}
},
@@ -76,6 +87,11 @@ expression: out
"description": "uv emitted a shape the adapter does not recognize (uv newer than PipDock).",
"type": "string"
},
{
"const": "PD-ENG-004",
"description": "An engine command ran past its watchdog and was stopped.\n\n**Raised by PipDock, never classified from stderr.** Its own code because the alternative\nwas `PD-INT-001`, which is what the shared watchdog reported until 1.4.0: an sdist build\nstill compiling after ten minutes is not \"a PipDock bug\", and in the batch phase that error\naborted the whole run — no summary, no per-package retry.",
"type": "string"
},
{
"const": "PD-ENG-999",
"description": "Fallback for engine failures no classifier matched. Always last.",
@@ -354,7 +370,7 @@ expression: out
"properties": {
"cancelled": {
"default": false,
"description": "True when the user stopped this run part-way.\n\nARCHITECTURE §7 words this as `Skipped(UserCancelled)`, but [`StepStatus`] is a\npayload-free enum and giving it one changes the wire shape for every consumer. A flag on\nthe summary also matches what the summary sheet actually needs: \"cancelled\" is said once\nat the top, not repeated on forty rows.\n\nSteps that never ran are `Skipped`, which is already the honest status for them.",
"description": "True when the user stopped this run part-way.\n\nDATA-FLOW §3 used to word this as `Skipped(UserCancelled)`, but [`StepStatus`] is a\npayload-free enum and giving it one changes the wire shape for every consumer. A flag on\nthe summary also matches what the summary sheet actually needs: \"cancelled\" is said once\nat the top, not repeated on forty rows.\n\nSteps that never ran are `Skipped`, which is already the honest status for them.",
"type": "boolean"
},
"check": {
@@ -158,6 +158,11 @@ expression: out
"const": "everything-skipped",
"description": "Every candidate was skipped while resolving conflicts, so no plan remains.",
"type": "string"
},
{
"const": "cancelled",
"description": "The user stopped the resolve before it finished. Nothing was planned, nothing ran.",
"type": "string"
}
]
},
@@ -165,6 +170,34 @@ expression: out
"description": "A PEP 503-normalized distribution name.\n\nConstructing one is the *only* way a package name reaches an argv array, which is what makes\nSECURITY §2's \"validated before it reaches argv\" claim structural rather than aspirational.",
"type": "string"
},
"PythonMismatch": {
"description": "A pin the user asked for that cannot install on this environment's Python (`PD-PKG-001`).\n\nHard invariant 10 says PipDock enforces `Requires-Python` itself, because the engines disagree:\npip refuses such a pin with the same \"No matching distribution\" it uses for a typo, and uv\nignores an upper bound and plans it. Structured, not a sentence (invariant 4): the preview shows\nthe required range against the environment's version, and a catalog cannot un-join a string.",
"properties": {
"pkg": {
"$ref": "#/$defs/PkgName",
"description": "The package."
},
"python": {
"description": "The environment's Python, e.g. `\"3.12.4\"`.",
"type": "string"
},
"requiresPython": {
"description": "That release's `Requires-Python`, verbatim.",
"type": "string"
},
"version": {
"$ref": "#/$defs/Version",
"description": "The version that was asked for or planned."
}
},
"required": [
"pkg",
"version",
"requiresPython",
"python"
],
"type": "object"
},
"ResolutionReport": {
"description": "The normalized dry-run result.\n\n**Both adapters must emit this same shape** — that is the whole point of the `Engine` trait\n(ARCHITECTURE §3). The pip adapter fills it from `--dry-run --report` JSON; the uv adapter from\nuv's text plan output.\n\nThe exact field set is **provisional until spike SP-1** confirms uv's output is rich enough to\npopulate `held_back.blockers`. If it is not, SP-1's go/no-go says v1.0 ships pip-primary with uv\nbehind a beta flag.",
"properties": {
@@ -176,6 +209,13 @@ expression: out
},
"type": "array"
},
"forced": {
"description": "Packages the user chose to **force** past what installed dependents allow, each with what\nit will break — the \"Will break\" section of the preview (DISCLAIMER §2).",
"items": {
"$ref": "#/$defs/HeldBack"
},
"type": "array"
},
"heldBack": {
"default": [],
"description": "Packages that could not reach `latest`, with attribution.",
@@ -195,19 +235,51 @@ expression: out
],
"description": "Present when the whole resolution failed."
},
"raw": {
"description": "The engine's untouched output, kept for the log and for bug reports.",
"type": "string"
"incompatible": {
"description": "Pins left out because their `Requires-Python` excludes this environment (`PD-PKG-001`).",
"items": {
"$ref": "#/$defs/PythonMismatch"
},
"type": "array"
},
"yanked": {
"description": "Yanked releases the plan would install. A warning, not a failure (`PD-PKG-003`, SP-2):\nboth engines exit 0 and install them. Both adapters parsed these and then dropped them, so\nthe preview never showed one.",
"items": {
"$ref": "#/$defs/YankWarning"
},
"type": "array"
}
},
"required": [
"raw"
],
"type": "object"
},
"Version": {
"description": "A version string as the engine reported it. Never reshaped or localized (I18N §2).",
"type": "string"
},
"YankWarning": {
"description": "A yanked release appearing in a plan.\n\nSP-2: a yank is **not** a failure. Both engines exit 0 and install it, so this is a preview\nwarning row, not an error path (`docs/ERROR-CATALOG.md` PD-PKG-003).",
"properties": {
"pkg": {
"$ref": "#/$defs/PkgName",
"description": "The yanked distribution."
},
"reason": {
"description": "Upstream's stated reason, when given.",
"type": [
"string",
"null"
]
},
"version": {
"$ref": "#/$defs/Version",
"description": "The version that was yanked."
}
},
"required": [
"pkg",
"version"
],
"type": "object"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
@@ -37,6 +37,11 @@ expression: out
"description": "uv emitted a shape the adapter does not recognize (uv newer than PipDock).",
"type": "string"
},
{
"const": "PD-ENG-004",
"description": "An engine command ran past its watchdog and was stopped.\n\n**Raised by PipDock, never classified from stderr.** Its own code because the alternative\nwas `PD-INT-001`, which is what the shared watchdog reported until 1.4.0: an sdist build\nstill compiling after ten minutes is not \"a PipDock bug\", and in the batch phase that error\naborted the whole run — no summary, no per-package retry.",
"type": "string"
},
{
"const": "PD-ENG-999",
"description": "Fallback for engine failures no classifier matched. Always last.",
@@ -0,0 +1,27 @@
---
source: crates/pipdock-cli/tests/golden.rs
expression: out
---
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"description": "The end of PipDock's own log, for Settings' Logs row (ARCHITECTURE §7).",
"properties": {
"dir": {
"description": "The folder the log files are in. A path — data, never localized (I18N §2).",
"type": "string"
},
"lines": {
"description": "The most recent lines, oldest first. Empty when nothing has been logged yet.",
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"dir",
"lines"
],
"title": "LogTail",
"type": "object"
}
@@ -9,12 +9,12 @@ expression: out
"oneOf": [
{
"const": "exclude",
"description": "Excluded from bulk updates. The user can still update it deliberately, one package at a\ntime — a pin is \"do not sweep this up\", not \"never touch this\".",
"description": "Left out of every update until it is unpinned (DATA-FLOW §9.5), whether the update names\nit or sweeps it up with *Select all*.",
"type": "string"
},
{
"additionalProperties": false,
"description": "Held at an exact version: excluded from bulk updates *and* restated at this version in\nevery plan, so the resolver treats it as fixed.",
"description": "Held at an exact version: left out of every update *and* restated at this version in\nevery plan, so the resolver treats it as fixed — including as another package's dependency.",
"properties": {
"hold": {
"properties": {
@@ -16,7 +16,7 @@ expression: out
"description": "Normalized distribution name."
},
"versionReq": {
"description": "PEP 440 specifier such as `\">=2,<3\"`, or `None` for \"latest\".",
"description": "PEP 440 specifier such as `\">=2,<3\"` (or a bare version, read as `==`), or `None` for\n\"latest\". Validated on every way in — [`Spec::parse`] and deserialization — so it is\nnever prose, a marker or an option by the time it reaches argv.",
"type": [
"string",
"null"
@@ -150,9 +150,62 @@ expression: out
"description": "A PEP 503-normalized distribution name.\n\nConstructing one is the *only* way a package name reaches an argv array, which is what makes\nSECURITY §2's \"validated before it reaches argv\" claim structural rather than aspirational.",
"type": "string"
},
"PythonMismatch": {
"description": "A pin the user asked for that cannot install on this environment's Python (`PD-PKG-001`).\n\nHard invariant 10 says PipDock enforces `Requires-Python` itself, because the engines disagree:\npip refuses such a pin with the same \"No matching distribution\" it uses for a typo, and uv\nignores an upper bound and plans it. Structured, not a sentence (invariant 4): the preview shows\nthe required range against the environment's version, and a catalog cannot un-join a string.",
"properties": {
"pkg": {
"$ref": "#/$defs/PkgName",
"description": "The package."
},
"python": {
"description": "The environment's Python, e.g. `\"3.12.4\"`.",
"type": "string"
},
"requiresPython": {
"description": "That release's `Requires-Python`, verbatim.",
"type": "string"
},
"version": {
"$ref": "#/$defs/Version",
"description": "The version that was asked for or planned."
}
},
"required": [
"pkg",
"version",
"requiresPython",
"python"
],
"type": "object"
},
"Version": {
"description": "A version string as the engine reported it. Never reshaped or localized (I18N §2).",
"type": "string"
},
"YankWarning": {
"description": "A yanked release appearing in a plan.\n\nSP-2: a yank is **not** a failure. Both engines exit 0 and install it, so this is a preview\nwarning row, not an error path (`docs/ERROR-CATALOG.md` PD-PKG-003).",
"properties": {
"pkg": {
"$ref": "#/$defs/PkgName",
"description": "The yanked distribution."
},
"reason": {
"description": "Upstream's stated reason, when given.",
"type": [
"string",
"null"
]
},
"version": {
"$ref": "#/$defs/Version",
"description": "The version that was yanked."
}
},
"required": [
"pkg",
"version"
],
"type": "object"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
@@ -166,6 +219,13 @@ expression: out
},
"type": "array"
},
"forced": {
"description": "Packages the user chose to **force** past what installed dependents allow, each with what\nit will break — the \"Will break\" section of the preview (DISCLAIMER §2).",
"items": {
"$ref": "#/$defs/HeldBack"
},
"type": "array"
},
"heldBack": {
"default": [],
"description": "Packages that could not reach `latest`, with attribution.",
@@ -185,14 +245,21 @@ expression: out
],
"description": "Present when the whole resolution failed."
},
"raw": {
"description": "The engine's untouched output, kept for the log and for bug reports.",
"type": "string"
"incompatible": {
"description": "Pins left out because their `Requires-Python` excludes this environment (`PD-PKG-001`).",
"items": {
"$ref": "#/$defs/PythonMismatch"
},
"type": "array"
},
"yanked": {
"description": "Yanked releases the plan would install. A warning, not a failure (`PD-PKG-003`, SP-2):\nboth engines exit 0 and install them. Both adapters parsed these and then dropped them, so\nthe preview never showed one.",
"items": {
"$ref": "#/$defs/YankWarning"
},
"type": "array"
}
},
"required": [
"raw"
],
"title": "ResolutionReport",
"type": "object"
}
@@ -37,6 +37,11 @@ expression: out
"description": "uv emitted a shape the adapter does not recognize (uv newer than PipDock).",
"type": "string"
},
{
"const": "PD-ENG-004",
"description": "An engine command ran past its watchdog and was stopped.\n\n**Raised by PipDock, never classified from stderr.** Its own code because the alternative\nwas `PD-INT-001`, which is what the shared watchdog reported until 1.4.0: an sdist build\nstill compiling after ten minutes is not \"a PipDock bug\", and in the batch phase that error\naborted the whole run — no summary, no per-package retry.",
"type": "string"
},
{
"const": "PD-ENG-999",
"description": "Fallback for engine failures no classifier matched. Always last.",
@@ -2,4 +2,4 @@
source: crates/pipdock-cli/tests/golden.rs
expression: "stderr_of(&[\"schema\", \"NoSuchType\"])"
---
error[PD-PKG-002]: unknown type "NoSuchType"; known types: Dist, OutdatedDist, PyEnv, CheckReport, StepResult, PlanRequest, ResolutionReport, ExecutionSummary, Pin, PinSuggestion, ParsedRequirements, CacheUsage, CacheTarget, GuardReport, Diff, SnapshotMeta, EngineInfo, RollbackPlan, RollbackPreview, Hit, PackageMeta, Freshness, RefreshReport, ProgressEvent, FlowStep, Decision, Intent, Code, HealthReport, AuditReport, FixReport
error[PD-PKG-002]: unknown type "NoSuchType"; known types: Dist, OutdatedDist, PyEnv, CheckReport, StepResult, PlanRequest, ResolutionReport, ExecutionSummary, Pin, PinSuggestion, ParsedRequirements, CacheUsage, CacheTarget, GuardReport, DepsGraph, Diff, SnapshotMeta, EngineInfo, RollbackPlan, RollbackPreview, Hit, PackageMeta, Freshness, RefreshReport, ProgressEvent, FlowStep, Decision, Intent, Code, HealthReport, AuditReport, FixReport, LogTail
+17 -13
View File
@@ -5,33 +5,37 @@ version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
repository.workspace = true
authors.workspace = true
[lints]
workspace = true
[features]
# `fixtures.rs`: the L3 payloads xtask writes for the frontend's tests.
fixtures = []
[dependencies]
async-trait = "0.1.91"
jiff = { version = "0.2.35", features = ["serde"] }
async-trait = "0.1.92"
jiff = { version = "0.2.38", features = ["serde"] }
nucleo = "0.5.0"
reqwest = { version = "0.13.4", default-features = false, features = ["rustls", "http2", "json", "gzip", "charset"] }
rusqlite = { version = "0.37", features = ["bundled"] }
schemars = "1.2.1"
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "http2", "json", "gzip", "charset"] }
rusqlite = { version = "0.40.2", features = ["bundled"] }
schemars = "1.2.3"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
sha2 = "0.11.0"
thiserror = "2.0.19"
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "process", "io-util", "time", "sync"] }
serde_json = "1.0.154"
sha2 = "0.11.1"
thiserror = "2.0.21"
tokio = { version = "1.53.3", features = ["rt-multi-thread", "macros", "process", "io-util", "time", "sync"] }
# First-party tokio, for CancellationToken. The alternative was an AtomicBool plus a Notify,
# which is what CancellationToken already is, written worse.
tokio-util = "0.7"
tokio-util = "0.7.20"
tracing = "0.1.44"
[dev-dependencies]
insta = { version = "1.48.0", features = ["json"] }
jiff = "0.2.35"
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros"] }
jiff = "0.2.38"
tokio = { version = "1.53.3", features = ["rt-multi-thread", "macros"] }
[target."cfg(windows)".dependencies]
winreg = "0.56.0"
+8 -191
View File
@@ -10,6 +10,9 @@
use std::path::{Path, PathBuf};
#[path = "src/legal_hash.rs"]
mod legal_hash;
/// The five documents the gate lists. UI-SPEC §4 says five; `legal/` holds four, and the fifth is
/// the GPL-3.0 `LICENSE` at the repository root.
const DOCUMENTS: &[&str] = &[
@@ -22,27 +25,22 @@ const DOCUMENTS: &[&str] = &[
fn main() {
let root = repo_root();
let mut hasher = Sha256::new();
let mut documents = Vec::with_capacity(DOCUMENTS.len());
for name in DOCUMENTS {
let path = root.join(name);
println!("cargo:rerun-if-changed={}", path.display());
// A missing document must not silently drop out of the hash, or removing a file would
// leave existing consent looking current. Hash the name and the bytes.
// leave existing consent looking current. Its name is still hashed, with no bytes.
let bytes = std::fs::read(&path).unwrap_or_else(|e| {
println!("cargo:warning=legal document {name} unreadable ({e}); hashing its absence");
Vec::new()
});
hasher.update(name.as_bytes());
hasher.update(&(bytes.len() as u64).to_le_bytes());
// Normalise line endings: a CRLF checkout must not produce a different hash from an LF
// one, or every Windows contributor would re-trigger the gate for everybody.
hasher.update(&normalise(&bytes));
documents.push((*name, bytes));
}
let pairs: Vec<(&str, &[u8])> = documents.iter().map(|(n, b)| (*n, b.as_slice())).collect();
println!(
"cargo:rustc-env=PIPDOCK_LEGAL_DOCS_HASH={}",
hex(&hasher.finish())
legal_hash::docs_hash(&pairs)
);
}
@@ -53,184 +51,3 @@ fn repo_root() -> PathBuf {
.and_then(Path::parent)
.map_or_else(|| PathBuf::from("."), Path::to_path_buf)
}
fn normalise(bytes: &[u8]) -> Vec<u8> {
bytes.iter().copied().filter(|b| *b != b'\r').collect()
}
fn hex(digest: &[u8; 32]) -> String {
digest.iter().fold(String::with_capacity(64), |mut acc, b| {
use std::fmt::Write as _;
let _ = write!(acc, "{b:02x}");
acc
})
}
/// A small SHA-256, so the build script needs no dependencies.
///
/// A build-dependency here would be one more crate in the supply chain of the thing that decides
/// whether users see the legal gate (SECURITY §7). FIPS 180-4.
struct Sha256 {
state: [u32; 8],
buffer: Vec<u8>,
length: u64,
}
const K: [u32; 64] = [
0x428a_2f98,
0x7137_4491,
0xb5c0_fbcf,
0xe9b5_dba5,
0x3956_c25b,
0x59f1_11f1,
0x923f_82a4,
0xab1c_5ed5,
0xd807_aa98,
0x1283_5b01,
0x2431_85be,
0x550c_7dc3,
0x72be_5d74,
0x80de_b1fe,
0x9bdc_06a7,
0xc19b_f174,
0xe49b_69c1,
0xefbe_4786,
0x0fc1_9dc6,
0x240c_a1cc,
0x2de9_2c6f,
0x4a74_84aa,
0x5cb0_a9dc,
0x76f9_88da,
0x983e_5152,
0xa831_c66d,
0xb003_27c8,
0xbf59_7fc7,
0xc6e0_0bf3,
0xd5a7_9147,
0x06ca_6351,
0x1429_2967,
0x27b7_0a85,
0x2e1b_2138,
0x4d2c_6dfc,
0x5338_0d13,
0x650a_7354,
0x766a_0abb,
0x81c2_c92e,
0x9272_2c85,
0xa2bf_e8a1,
0xa81a_664b,
0xc24b_8b70,
0xc76c_51a3,
0xd192_e819,
0xd699_0624,
0xf40e_3585,
0x106a_a070,
0x19a4_c116,
0x1e37_6c08,
0x2748_774c,
0x34b0_bcb5,
0x391c_0cb3,
0x4ed8_aa4a,
0x5b9c_ca4f,
0x682e_6ff3,
0x748f_82ee,
0x78a5_636f,
0x84c8_7814,
0x8cc7_0208,
0x90be_fffa,
0xa450_6ceb,
0xbef9_a3f7,
0xc671_78f2,
];
impl Sha256 {
fn new() -> Self {
Self {
state: [
0x6a09_e667,
0xbb67_ae85,
0x3c6e_f372,
0xa54f_f53a,
0x510e_527f,
0x9b05_688c,
0x1f83_d9ab,
0x5be0_cd19,
],
buffer: Vec::new(),
length: 0,
}
}
fn update(&mut self, data: &[u8]) {
self.length = self.length.wrapping_add(data.len() as u64);
self.buffer.extend_from_slice(data);
while self.buffer.len() >= 64 {
let block: [u8; 64] = self.buffer[..64].try_into().unwrap_or([0; 64]);
self.compress(&block);
self.buffer.drain(..64);
}
}
fn finish(mut self) -> [u8; 32] {
let bits = self.length.wrapping_mul(8);
self.buffer.push(0x80);
while self.buffer.len() % 64 != 56 {
self.buffer.push(0);
}
let tail = bits.to_be_bytes();
self.buffer.extend_from_slice(&tail);
while self.buffer.len() >= 64 {
let block: [u8; 64] = self.buffer[..64].try_into().unwrap_or([0; 64]);
self.compress(&block);
self.buffer.drain(..64);
}
let mut out = [0u8; 32];
for (chunk, word) in out.chunks_exact_mut(4).zip(self.state) {
chunk.copy_from_slice(&word.to_be_bytes());
}
out
}
fn compress(&mut self, block: &[u8; 64]) {
let mut w = [0u32; 64];
for (slot, chunk) in w.iter_mut().zip(block.chunks_exact(4)) {
*slot = u32::from_be_bytes(chunk.try_into().unwrap_or([0; 4]));
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = self.state;
for i in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ ((!e) & g);
let t1 = h
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(K[i])
.wrapping_add(w[i]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let t2 = s0.wrapping_add(maj);
h = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
for (slot, value) in self.state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
*slot = slot.wrapping_add(value);
}
}
}
+1 -1
View File
@@ -13,7 +13,7 @@
//!
//! ```text
//! pipdock index refresh
//! cargo run --release --example sp3_search -- "%LOCALAPPDATA%\PipDock\index.db"
//! cargo run --release --example sp3_search -- "%LOCALAPPDATA%\PipDock\data\index.db"
//! ```
// A measurement harness reports to a human on stdout; the library-level ban does not apply.
+20 -12
View File
@@ -353,11 +353,20 @@ async fn audit_once(audit_dir: &Path, freeze: &str, sink: &ProgressSink) -> Resu
// The environment reaches pip-audit as a *document*, never as a directory: SP-4 found that
// `--path <site-packages>` is rejected outright alongside `--no-deps`. Written to the system
// temp directory rather than into the user's project or the environment being audited, and
// removed on both paths.
let freeze_path = crate::exec::write_temp("pipdock-audit", "txt", freeze)?;
// removed when it drops, on every path.
//
// **Pins only.** An editable install (`-e …`) or a direct reference (`name @ file:///…`) is a
// line pip-audit cannot look up on an index, and it failed the whole run over one: an
// environment with a single `pip install -e .` could not be audited at all (H21). They are not
// on PyPI, so they have no PyPI advisories; the package count says how many were audited.
let pins: String = crate::snapshot::parse_freeze(freeze)
.iter()
.map(|(name, version)| format!("{name}=={version}\n"))
.collect();
let freeze_file = crate::exec::TempFile::create("pipdock-audit", "txt", &pins)?;
let out = Command::new(&exe)
.args(argv(&freeze_path))
let out = Command::python_tool(&exe)
.args(argv(freeze_file.path()))
.timeout(AUDIT_TIMEOUT)
.cancel(sink.cancel.clone())
.run()
@@ -372,8 +381,7 @@ async fn audit_once(audit_dir: &Path, freeze: &str, sink: &ProgressSink) -> Resu
Ok(out) => parse(&out.stdout).map_err(|e| e.with_stderr(&out.stderr)),
Err(e) => Err(e),
};
let _ = std::fs::remove_file(&freeze_path);
drop(freeze_file);
parsed
}
@@ -394,12 +402,12 @@ fn argv(freeze: &Path) -> Vec<String> {
/// Did the user stop it, or did it break?
///
/// `exec` reports both through `Code::IntUnexpected`, distinguished only by the message it built
/// (`exec::Command::stopped`). Reading the message is unlovely, and it is what P4 warned about
/// when it recorded that wiring the token alone would render *"PipDock hit an internal error"* for
/// a cancel — the mapping has to be done, not merely enabled.
/// Asked of the typed [`PdError::stop`], not of the message. P4 recorded that wiring the token
/// alone would render *"PipDock hit an internal error"* for a cancel — the mapping has to be done,
/// not merely enabled — and until 1.4.0 it was done by matching the `"cancelled:"` prefix
/// `exec::Command::stopped` happened to write.
fn is_cancellation(e: &PdError) -> bool {
e.code == Code::IntUnexpected && e.message.starts_with("cancelled:")
e.is_cancelled()
}
/// Translate `exec`'s vocabulary into this path's.
@@ -408,7 +416,7 @@ fn is_cancellation(e: &PdError) -> bool {
/// an internal error, and a tool that will not start is not a missing engine the user should be
/// told to go and install. Health's `run_one` needed the same translation for the same reason.
fn watchdog(e: PdError) -> PdError {
if e.code == Code::IntUnexpected && e.message.contains("timed out") {
if e.is_timeout() {
return PdError::new(
Code::HltTimeout,
format!("{TOOL} exceeded its {AUDIT_TIMEOUT:?} watchdog; its results are missing"),
+10 -6
View File
@@ -19,12 +19,11 @@
//! reported so the number is honest about where the space went; refreshing the index is
//! `index refresh`, which replaces rows rather than deleting a file.
//!
//! # There are no log files
//! # Log files are not a target
//!
//! [`crate::LOG_RETENTION_DAYS`] has never had a reader. The only log is the in-memory ring buffer
//! behind *Report bug*, and `logs_tail` is still owed. When the logging subsystem lands it becomes
//! a fourth entry here; until then, reporting a "logs" line of zero bytes would be inventing a
//! thing that does not exist.
//! Since 1.4.0 there are log files (`crate::logging`), and they look after themselves: the sweep
//! keeps [`crate::LOG_RETENTION_DAYS`] and nothing more, so a "clear logs" button would only take
//! away the one record a bug report needs. Settings shows where they are instead.
use std::path::{Path, PathBuf};
@@ -262,8 +261,13 @@ mod tests {
use super::*;
fn temp() -> PathBuf {
// A counter, not the clock alone: two tests running in parallel inside one tick of the
// system clock got the same directory, and the fresh-install test read the other's files.
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
"pipdock-cache-{}",
"pipdock-cache-{}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
jiff::Timestamp::now().as_nanosecond()
));
std::fs::create_dir_all(&dir).expect("temp dir");
+503 -6
View File
@@ -13,7 +13,7 @@ pub mod uv;
use async_trait::async_trait;
use crate::errors::Result;
use crate::errors::{Code, PdError, Result};
use crate::model::{
CheckReport, Dist, EngineId, EngineInfo, ExecMode, OutdatedDist, PinnedSpec, PkgName, PyEnv,
StepResult, StepStatus,
@@ -209,17 +209,25 @@ pub trait Engine: Send + Sync {
/// Dry-run resolve `req` against `env`, normalized into a [`ResolutionReport`].
///
/// This is the only way a plan may be produced; DATA-FLOW §9.1 forbids any mutating call
/// without a report accepted in the same session.
async fn resolve(&self, env: &PyEnv, req: &PlanRequest) -> Result<ResolutionReport>;
/// without a report accepted in the same session. `ctx` carries the cancellation token —
/// a resolve used to be the one engine call nothing could stop, so *Stop* while pip
/// backtracked left it running for up to ten minutes — and what the flow changes about the
/// guard set (forced pins, holds, exclusions).
async fn resolve(
&self,
env: &PyEnv,
req: &PlanRequest,
ctx: &ResolveCtx,
) -> Result<ResolutionReport>;
/// Install an exact pinned set.
/// Install an exact pinned set, holding everything in `set.constraints` where it is.
///
/// `Batch` mode passes the whole set in one invocation (Phase A); `Isolated` mode is the
/// per-package retry loop (Phase B), where a failure must **not** stop the caller's loop.
async fn install(
&self,
env: &PyEnv,
specs: &[PinnedSpec],
set: &InstallSet,
mode: ExecMode,
sink: ProgressSink,
) -> Result<StepResult>;
@@ -230,6 +238,7 @@ pub trait Engine: Send + Sync {
&self,
env: &PyEnv,
names: &[PkgName],
system: SystemPackages,
sink: ProgressSink,
) -> Result<StepResult>;
@@ -247,6 +256,266 @@ pub trait Engine: Send + Sync {
/// Upgrade pip inside `env`. The uv adapter returns an `Unsupported` error — DATA-FLOW §7
/// says pip upkeep is surfaced only when pip is the active engine or present in the env.
async fn upgrade_pip(&self, env: &PyEnv) -> Result<StepResult>;
/// Probe `env`: the interpreter, its marker environment, and every distribution with its
/// requirements.
///
/// Provided, and no adapter overrides it: this is `probe.py`, not an engine command. It is on
/// the trait so a flow can be driven end to end against a scripted engine — every flow probed
/// through a free function, so none of `start`'s decisions (the PEP 668 gate, the graph, the
/// drift basis) could be tested without a real interpreter, and the bugs in them were not.
async fn probe(&self, env: &PyEnv) -> Result<crate::envs::ProbeResult> {
crate::envs::probe(&env.interpreter, env.source).await
}
}
/// Whether an engine call may override PEP 668 with `--break-system-packages` (SECURITY §3).
///
/// A named value rather than a `bool`, for the reason [`crate::snapshot::SnapshotProof`] is a
/// named waiver. The only way to [`Self::OverrideAllowed`] is a flow that probed the environment,
/// found it externally managed, and was told by its caller that the Settings override is on —
/// hard invariant 5 says the flag is never passed implicitly, and this is what makes "implicitly"
/// greppable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SystemPackages {
/// The flag is not passed. Everything defaults to this.
#[default]
Protected,
/// The environment is externally managed and the user turned the override on.
OverrideAllowed,
}
impl SystemPackages {
/// `--break-system-packages`, or nothing.
#[must_use]
pub const fn args(self) -> &'static [&'static str] {
match self {
Self::Protected => &[],
Self::OverrideAllowed => &["--break-system-packages"],
}
}
}
/// What the override can do with this engine, for an environment that is externally managed.
///
/// uv has taken `--break-system-packages` throughout its supported range. pip implemented PEP 668
/// in 23.0 and added the flag in 23.0.1: below 23.0 there is nothing to override and the flag is
/// an unknown option, and 23.0 itself enforces the marker with no way past it. An unreadable pip
/// version is assumed modern — a pip that cannot report its version fails on its own first.
///
/// # Errors
/// `PD-ENV-002` for pip 23.0, which no flag gets past.
pub fn system_packages_for(info: &EngineInfo) -> Result<SystemPackages> {
if info.id == EngineId::Uv {
return Ok(SystemPackages::OverrideAllowed);
}
let release = info.version.as_deref().map(|v| {
let mut parts = v.split('.').map(|p| {
p.chars()
.take_while(char::is_ascii_digit)
.collect::<String>()
.parse::<u32>()
.unwrap_or(0)
});
(
parts.next().unwrap_or(0),
parts.next().unwrap_or(0),
parts.next().unwrap_or(0),
)
});
match release {
Some(r) if r < (23, 0, 0) => Ok(SystemPackages::Protected),
Some(r) if r < (23, 0, 1) => Err(PdError::new(
Code::EnvExternallyManaged,
"pip 23.0 enforces PEP 668 and has no override; --break-system-packages arrived in \
pip 23.0.1",
)),
_ => Ok(SystemPackages::OverrideAllowed),
}
}
/// What one resolve is given besides the request itself.
#[derive(Debug, Clone, Default)]
pub struct ResolveCtx {
/// Stops the dry run; a stopped resolve returns an error with `Stop::Cancelled`.
pub cancel: tokio_util::sync::CancellationToken,
/// What the flow changes about the requirement lines the engine is given.
pub adjust: GuardAdjust,
/// uv refuses even a dry run in an externally managed environment without the flag; pip's
/// `--dry-run --report` is exempt and is never given it.
pub system: SystemPackages,
}
/// Changes to the requirement lines of a resolve, made by the flow — never by an adapter.
///
/// SP-1 makes the guard set (every installed package the user is not moving, pinned) the default,
/// and three decisions need to depart from it on purpose: **Force latest** pins a package to its
/// latest and *releases* the packages whose constraints were holding it (DISCLAIMER §2); a **Hold**
/// pin restates its own version; a release whose `Requires-Python` excludes this environment is
/// **excluded** so the engine picks another.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GuardAdjust {
/// Exact requirements added to the resolve; these names leave the upgrade list and the guard.
pub pins: Vec<PinnedSpec>,
/// Installed packages released from the guard set — what a forced package will break.
pub release: Vec<PkgName>,
/// `name!=version` lines, for releases that cannot install here.
pub exclude: Vec<PinnedSpec>,
}
/// One install invocation: what to install, and what must not move while it happens.
///
/// SP-1's rule — restate the installed set or the resolver breaks it — was applied to the
/// *resolve* only. Phase B then installed each package as a bare `pip install name==v`, with no
/// guard: free to pull a dependency past an installed package's upper bound, which pip reports as
/// a warning and exits 0 on. `constraints` carries the target state of everything else, passed as
/// `-c`, which constrains without installing.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct InstallSet {
/// The exact pins to install.
pub specs: Vec<PinnedSpec>,
/// Everything that must stay at these versions if the engine touches it at all.
pub constraints: Vec<PinnedSpec>,
/// Whether the PEP 668 override applies to this install.
pub system: SystemPackages,
}
impl InstallSet {
/// Install `specs`, constraining nothing else.
#[must_use]
pub const fn only(specs: Vec<PinnedSpec>) -> Self {
Self {
specs,
constraints: Vec::new(),
system: SystemPackages::Protected,
}
}
}
/// The requirements (and constraints) files one engine invocation reads, deleted when dropped.
///
/// **Files, not argv.** Every plan restates the whole installed set (SP-1), one argv entry per
/// package — and at around 1,300 packages that passes Windows' 32,767-character command line, so
/// the spawn failed and the user was told to install an engine (PD-ENG-001). `-r`/`-c` keep the
/// command line a constant length. The files hold only rendered [`PinnedSpec`]s and validated
/// [`crate::model::Spec`]s — the same tokens argv held — written under fresh random names.
#[derive(Debug)]
pub struct RequirementFiles {
requirements: crate::exec::TempFile,
constraints: Option<crate::exec::TempFile>,
/// What each file says, line by line, so [`Self::humanize`] can put it back.
requirement_lines: Vec<String>,
constraint_lines: Vec<String>,
}
impl RequirementFiles {
/// Write `requirements` (one per line) and, when there are any, `constraints`.
///
/// # Errors
/// As [`crate::exec::TempFile::create`].
pub fn write(requirements: &[String], constraints: &[PinnedSpec]) -> Result<Self> {
let text = |lines: &[String]| {
let mut text = lines.join("\n");
text.push('\n');
text
};
let requirement_lines = requirements.to_vec();
let constraint_lines: Vec<String> =
constraints.iter().map(PinnedSpec::to_requirement).collect();
let requirements =
crate::exec::TempFile::create("pipdock-req", "txt", &text(&requirement_lines))?;
let constraints = if constraint_lines.is_empty() {
None
} else {
Some(crate::exec::TempFile::create(
"pipdock-con",
"txt",
&text(&constraint_lines),
)?)
};
Ok(Self {
requirements,
constraints,
requirement_lines,
constraint_lines,
})
}
/// Engine text with every reference to these files replaced by the line it points at.
///
/// pip names a requirement that came from a file as `-r <path> (line N)`. Once the plan went
/// through a file, its impossibility read `Cannot install -r C:\…\pipdock-req-….txt (line 1)
/// and h11==0.12.0`: the preview lost the name of the package the user asked for, and every
/// error row showed a path that had already been deleted. Found by running pip, not by
/// reading it — uv names requirements by their text and needs none of this.
#[must_use]
pub fn humanize(&self, text: &str) -> String {
let mut out = replace_file_refs(
text,
&format!("-r {}", self.requirements.path().display()),
&self.requirement_lines,
);
if let Some(c) = &self.constraints {
out = replace_file_refs(
&out,
&format!("-c {}", c.path().display()),
&self.constraint_lines,
);
}
out
}
/// `-r <requirements> [-c <constraints>]`, one argv entry each.
#[must_use]
pub fn args(&self) -> Vec<String> {
let mut out = vec![
"-r".to_owned(),
self.requirements.path().display().to_string(),
];
if let Some(c) = &self.constraints {
out.push("-c".to_owned());
out.push(c.path().display().to_string());
}
out
}
}
/// `<reference> (line N)` becomes line N; `(from <reference> (line N))` goes entirely, since the
/// requirement it annotates is already named just before it.
fn replace_file_refs(text: &str, reference: &str, lines: &[String]) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(at) = rest.find(reference) {
let (head, after) = rest.split_at(at);
let after = &after[reference.len()..];
let parsed = after.strip_prefix(" (line ").and_then(|tail| {
let digits = tail.bytes().take_while(u8::is_ascii_digit).count();
let n: usize = tail[..digits].parse().ok()?;
let close = tail[digits..].strip_prefix(')')?;
Some((n, close))
});
let Some((n, close)) = parsed else {
// Not a line reference; keep it as it was.
out.push_str(head);
out.push_str(reference);
rest = after;
continue;
};
if let (Some(before), Some(close)) = (head.strip_suffix("(from "), close.strip_prefix(')'))
{
out.push_str(before.strip_suffix(' ').unwrap_or(before));
rest = close;
continue;
}
out.push_str(head);
match n.checked_sub(1).and_then(|i| lines.get(i)) {
Some(line) => out.push_str(line),
None => out.push_str(&rest[at..rest.len() - close.len()]),
}
rest = close;
}
out.push_str(rest);
out
}
/// The adapter for `id`.
@@ -297,6 +566,11 @@ pub fn plan_requirements(req: &PlanRequest, installed: &[crate::model::Dist]) ->
installed
.iter()
.filter(|d| !moving.contains(&d.name))
// A version that could be read as more than a version — whitespace, a marker, a URL —
// never reaches argv. pip itself cannot install such a distribution, so restating it
// would only fail the resolve; leaving it out leaves it untouched, which is what a guard
// is for.
.filter(|d| crate::pep440::is_argv_safe(&d.version.0))
.map(|d| PinnedSpec {
name: d.name.clone(),
version: d.version.clone(),
@@ -317,7 +591,27 @@ pub fn plan_requirements(req: &PlanRequest, installed: &[crate::model::Dist]) ->
/// Omitting group 3 is the SP-1 failure — the resolver breaks installed dependents at exit 0.
#[must_use]
pub fn plan_argv_specs(req: &PlanRequest, installed: &[crate::model::Dist]) -> Vec<String> {
let mut out: Vec<String> = req.upgrades.iter().map(ToString::to_string).collect();
plan_lines(req, installed, &GuardAdjust::default())
}
/// [`plan_argv_specs`] with the flow's [`GuardAdjust`] applied.
#[must_use]
pub fn plan_lines(
req: &PlanRequest,
installed: &[crate::model::Dist],
adjust: &GuardAdjust,
) -> Vec<String> {
use std::collections::BTreeSet;
let pinned: BTreeSet<&PkgName> = adjust.pins.iter().map(|p| &p.name).collect();
let released: BTreeSet<&PkgName> = adjust.release.iter().collect();
let mut out: Vec<String> = req
.upgrades
.iter()
.filter(|n| !pinned.contains(n))
.map(ToString::to_string)
.collect();
out.extend(req.installs.iter().map(|s| match &s.version_req {
Some(v) if v.starts_with(['=', '<', '>', '!', '~']) => format!("{}{v}", s.name),
@@ -325,11 +619,19 @@ pub fn plan_argv_specs(req: &PlanRequest, installed: &[crate::model::Dist]) -> V
None => s.name.to_string(),
}));
out.extend(adjust.pins.iter().map(PinnedSpec::to_requirement));
out.extend(
plan_requirements(req, installed)
.iter()
.filter(|g| !pinned.contains(&g.name) && !released.contains(&g.name))
.map(PinnedSpec::to_requirement),
);
out.extend(
adjust
.exclude
.iter()
.map(|e| format!("{}!={}", e.name, e.version)),
);
out
}
@@ -517,6 +819,62 @@ mod tests {
);
}
#[test]
fn a_forced_package_is_pinned_and_what_held_it_is_released() {
// Force latest (DISCLAIMER §2): httpcore goes to its latest *exactly*, and httpx — whose
// constraint was holding it — leaves the guard set, or the engine would hold it right back.
let installed = [
dist("httpx", "0.23.0"),
dist("httpcore", "0.15.0"),
dist("h11", "0.12.0"),
];
let req = PlanRequest {
upgrades: vec![PkgName::parse("httpcore").unwrap()],
installs: Vec::new(),
strategy: Strategy::Compatible,
};
let adjust = GuardAdjust {
pins: vec![PinnedSpec {
name: PkgName::parse("httpcore").unwrap(),
version: Version("1.0.9".into()),
}],
release: vec![PkgName::parse("httpx").unwrap()],
exclude: Vec::new(),
};
assert_eq!(
plan_lines(&req, &installed, &adjust),
["httpcore==1.0.9", "h11==0.12.0"]
);
}
#[test]
fn an_excluded_release_rides_alongside_the_request() {
// A release whose Requires-Python excludes this environment is ruled out by name, and the
// engine is left to pick the next one — PipDock still does not resolve (invariant 3).
let installed = [dist("httpx", "0.23.0"), dist("httpcore", "0.15.0")];
let req = PlanRequest {
upgrades: vec![PkgName::parse("httpcore").unwrap()],
installs: Vec::new(),
strategy: Strategy::Compatible,
};
let adjust = GuardAdjust {
exclude: vec![PinnedSpec {
name: PkgName::parse("httpcore").unwrap(),
version: Version("1.0.9".into()),
}],
..GuardAdjust::default()
};
assert_eq!(
plan_lines(&req, &installed, &adjust),
["httpcore", "httpx==0.23.0", "httpcore!=1.0.9"]
);
assert_eq!(
plan_lines(&req, &installed, &GuardAdjust::default()),
plan_argv_specs(&req, &installed),
"no adjustment is exactly the SP-1 default"
);
}
#[test]
fn updating_everything_still_asks_for_something() {
// With --all every package is moving, so the guard set is empty. If only guards were
@@ -576,4 +934,143 @@ mod tests {
};
assert!(plan_requirements(&req, &[]).is_empty());
}
#[test]
fn the_guard_set_leaves_out_a_version_that_is_not_argv_safe() {
let installed = [
crate::model::Dist {
name: PkgName::parse("good").expect("name"),
version: crate::model::Version("1.0".into()),
requires_dist: Vec::new(),
requires_python: None,
size_bytes: None,
},
crate::model::Dist {
name: PkgName::parse("odd").expect("name"),
version: crate::model::Version("1.0 ; python_version < '0'".into()),
requires_dist: Vec::new(),
requires_python: None,
size_bytes: None,
},
];
let req = PlanRequest {
upgrades: Vec::new(),
installs: Vec::new(),
strategy: crate::plan::Strategy::Compatible,
};
let guards = plan_requirements(&req, &installed);
assert_eq!(guards.len(), 1);
assert_eq!(guards[0].to_requirement(), "good==1.0");
}
#[test]
fn a_huge_environment_still_fits_on_a_command_line() {
// Every plan restates the installed set (SP-1). As argv, ~1,300 packages passed Windows'
// 32,767-character limit, the spawn failed with os error 206, and the user was told to
// install an engine. As a file, the command line no longer grows with the environment.
let installed: Vec<crate::model::Dist> = (0..2000)
.map(|i| crate::model::Dist {
name: PkgName::parse(&format!("package-with-a-long-name-{i:04}")).expect("name"),
version: crate::model::Version("12.34.5678".into()),
requires_dist: Vec::new(),
requires_python: None,
size_bytes: None,
})
.collect();
let req = PlanRequest {
upgrades: Vec::new(),
installs: Vec::new(),
strategy: crate::plan::Strategy::Compatible,
};
let lines = plan_argv_specs(&req, &installed);
assert!(
lines.iter().map(|l| l.len() + 1).sum::<usize>() > 32_767,
"the fixture must be big enough to have broken argv"
);
let files = RequirementFiles::write(&lines, &[]).expect("written");
let argv = pip::PipEngine::argv_dry_run(&files.args());
let command_line: usize = argv.iter().map(|a| a.len() + 1).sum();
assert!(
command_line < 1_000,
"command line is {command_line} characters"
);
}
#[test]
fn pip_names_a_file_requirement_by_its_line_and_the_line_comes_back() {
// The sentence pip 26.2.1 printed when the plan went through a file, verbatim but for
// the path, which is this run's own.
let files = RequirementFiles::write(
&["httpcore>=1.0".to_owned(), "httpx==0.23.0".to_owned()],
&[PinnedSpec {
name: PkgName::parse("h11").unwrap(),
version: Version("0.12.0".into()),
}],
)
.expect("written");
let args = files.args();
let (req, con) = (&args[1], &args[3]);
let stderr = format!(
"ERROR: Cannot install -r {req} (line 1) and -r {req} (line 2) because these package \
versions have conflicting dependencies.\n\
ERROR: Could not find a version that satisfies the requirement httpcore>=1.0 \
(from -r {req} (line 1)) (from versions: none)\n\
The user requested (constraint) -c {con} (line 1)\n\
-r {req} (line 9) is not a line this run wrote\n"
);
let out = files.humanize(&stderr);
assert!(
out.contains("Cannot install httpcore>=1.0 and httpx==0.23.0 because"),
"{out}"
);
assert!(
out.contains("requirement httpcore>=1.0 (from versions: none)"),
"{out}"
);
assert!(out.contains("(constraint) h11==0.12.0"), "{out}");
assert!(
out.contains(&format!("-r {req} (line 9)")),
"an unknown line is left alone rather than invented: {out}"
);
// And the impossibility now names the package the user asked for.
let detail = parse::pip_impossible(&out).expect("impossible");
let names: Vec<&str> = detail.packages.iter().map(PkgName::as_str).collect();
assert_eq!(names, ["httpcore", "httpx"]);
}
#[test]
fn the_override_reaches_pip_only_where_pip_has_the_flag() {
let pip = |v: &str| EngineInfo {
id: EngineId::Pip,
version: Some(v.into()),
available: true,
};
// Below 23.0 nothing enforces the marker, and the flag is an unknown option.
assert_eq!(
system_packages_for(&pip("22.3.1")).expect("ok"),
SystemPackages::Protected
);
// 23.0 enforces it and offers no way past.
assert_eq!(
system_packages_for(&pip("23.0")).expect_err("no flag").code,
Code::EnvExternallyManaged
);
for v in ["23.0.1", "24.1b1", "26.2.1"] {
assert_eq!(
system_packages_for(&pip(v)).expect("ok"),
SystemPackages::OverrideAllowed,
"{v}"
);
}
let uv = EngineInfo {
id: EngineId::Uv,
version: Some("0.13.1".into()),
available: true,
};
assert_eq!(
system_packages_for(&uv).expect("ok"),
SystemPackages::OverrideAllowed
);
assert!(SystemPackages::Protected.args().is_empty());
}
}
+382 -79
View File
@@ -15,14 +15,16 @@
//! by the caller from the reverse-dependency graph, not here.
use crate::errors::{Code, PdError, Result};
use crate::model::{Dist, PkgName, Version};
use crate::model::{Dist, EngineId, PkgName, Version};
use crate::plan::{Change, ChangeKind, ImpossibleDetail, ResolutionReport};
/// A yanked release appearing in a plan.
///
/// SP-2: a yank is **not** a failure. Both engines exit 0 and install it, so this is a preview
/// warning row, not an error path (`docs/ERROR-CATALOG.md` PD-PKG-003).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[derive(
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
pub struct YankWarning {
/// The yanked distribution.
pub pkg: PkgName,
@@ -41,14 +43,28 @@ pub struct ParsedPlan {
pub yanked: Vec<YankWarning>,
}
impl ParsedPlan {
/// The report with its yank warnings inside it, where the preview can see them.
///
/// Both adapters used to take `.report` and drop `.yanked`, so the PD-PKG-003 warning both
/// parsers worked to extract never reached a user.
#[must_use]
pub fn into_report(self) -> crate::plan::ResolutionReport {
crate::plan::ResolutionReport {
yanked: self.yanked,
..self.report
}
}
}
// -- pip ---------------------------------------------------------------------
/// Parse pip's `install --dry-run --report -` JSON from stdout.
///
/// # Errors
/// `PD-ENG-002` when stdout is empty, which is what pip leaves behind when it is too old for
/// `--report` **or** when the SP-2 encoding crash struck; `PD-ENG-003` when the JSON is present
/// but not the shape we know.
/// `--report` **or** when the SP-2 encoding crash struck; `PD-ENG-999` when the JSON is present
/// but not the shape we know — not `PD-ENG-003`, whose advice is to switch to pip.
pub fn pip_report(stdout: &str, stderr: &str, installed: &[Dist]) -> Result<ParsedPlan> {
// Checked before anything is parsed, because the SP-2 crash does not leave stdout empty — it
// leaves a *truncated* report, written up to the byte that could not be encoded. That is more
@@ -68,12 +84,8 @@ pub fn pip_report(stdout: &str, stderr: &str, installed: &[Dist]) -> Result<Pars
return Err(PdError::new(Code::EngPipTooOld, "pip produced no report").with_stderr(stderr));
}
let doc: serde_json::Value = serde_json::from_str(trimmed).map_err(|e| {
PdError::new(
Code::EngUvShapeUnknown,
format!("pip report is not JSON: {e}"),
)
})?;
let doc: serde_json::Value = serde_json::from_str(trimmed)
.map_err(|e| shape_error(EngineId::Pip, &format!("pip report is not JSON: {e}")))?;
let version = doc
.get("version")
@@ -81,9 +93,9 @@ pub fn pip_report(stdout: &str, stderr: &str, installed: &[Dist]) -> Result<Pars
.unwrap_or_default();
if version != "1" {
// Fail loudly rather than mis-parsing a future format into a plausible-looking plan.
return Err(PdError::new(
Code::EngUvShapeUnknown,
format!("unsupported pip report version {version:?}; expected \"1\""),
return Err(shape_error(
EngineId::Pip,
&format!("unsupported pip report version {version:?}; expected \"1\""),
));
}
@@ -92,6 +104,7 @@ pub fn pip_report(stdout: &str, stderr: &str, installed: &[Dist]) -> Result<Pars
let mut changes = Vec::new();
let mut yanked = Vec::new();
let mut declared_python = std::collections::BTreeMap::new();
for entry in doc
.get("install")
@@ -106,12 +119,23 @@ pub fn pip_report(stdout: &str, stderr: &str, installed: &[Dist]) -> Result<Pars
let Ok(name) = PkgName::parse(raw_name) else {
continue;
};
let to = Version(
meta.get("version")
.and_then(serde_json::Value::as_str)
.unwrap_or_default()
.to_owned(),
);
let raw_version = meta
.get("version")
.and_then(serde_json::Value::as_str)
.unwrap_or_default();
// pip normalizes report versions to PEP 440; anything else is not something PipDock will
// turn into an argv token, and the change is left out rather than mis-rendered.
if !crate::pep440::is_argv_safe(raw_version) {
continue;
}
let to = Version(raw_version.to_owned());
if let Some(requires) = meta
.get("requires_python")
.and_then(serde_json::Value::as_str)
.filter(|s| !s.trim().is_empty())
{
declared_python.insert(name.clone(), requires.to_owned());
}
if entry.get("is_yanked").and_then(serde_json::Value::as_bool) == Some(true) {
yanked.push(YankWarning {
@@ -144,30 +168,169 @@ pub fn pip_report(stdout: &str, stderr: &str, installed: &[Dist]) -> Result<Pars
changes,
held_back: Vec::new(),
impossible: None,
raw: stdout.to_owned(),
incompatible: Vec::new(),
forced: Vec::new(),
yanked: Vec::new(),
// pip's stderr — its warnings — not the `--report` document on stdout, which carries
// every package's README and is already parsed above.
raw: stderr.to_owned(),
declared_python,
},
yanked,
})
}
/// pip prints the yank reason on stderr, not in the report JSON.
fn yank_reason_from_stderr(stderr: &str, pkg: &PkgName) -> Option<String> {
let flat = flatten(stderr);
let idx = flat.find("Reason for being yanked:")?;
// Only attribute the reason when this package is the one being discussed.
if !flat[..idx].to_ascii_lowercase().contains(pkg.as_str()) {
/// pip's dry run, read **by its exit status first**.
///
/// A zero exit is a plan. A non-zero one is a failure classified from stderr like any other —
/// except an impossibility, which becomes `report.impossible`: **the same shape uv gives**
/// (ARCHITECTURE §3). It used to be a hard error, so under pip one unsatisfiable package in a
/// fifteen-package request failed the whole preview and the per-package *Skip* the preview offers
/// under uv never appeared.
///
/// # Errors
/// The classified engine failure; `PD-INT-001` for the SP-2 encoding crash whatever the exit.
pub fn pip_resolution(
exit_code: Option<i32>,
stdout: &str,
stderr: &str,
installed: &[Dist],
) -> Result<ParsedPlan> {
// The SP-2 crash exits 2, and is PipDock's bug rather than pip's; `pip_report` says so.
if exit_code == Some(0) || stderr.contains("UnicodeEncodeError") {
return pip_report(stdout, stderr, installed);
}
if let Some(detail) = pip_impossible(stderr) {
return Ok(impossible_plan(detail, stderr));
}
Err(PdError::from_engine_stderr(stderr))
}
/// A plan that is nothing but its impossibility.
fn impossible_plan(detail: ImpossibleDetail, text: &str) -> ParsedPlan {
ParsedPlan {
report: ResolutionReport {
impossible: Some(detail),
raw: text.to_owned(),
..ResolutionReport::default()
},
yanked: Vec::new(),
}
}
/// pip's ResolutionImpossible, read into the shape uv's impossibility already has.
///
/// pip runs with `--quiet`, so its whole explanation is one line — `ERROR: Cannot install A and B
/// because these package versions have conflicting dependencies.` — followed by the
/// ResolutionImpossible pointer. The packages are the requirements that line names. `None` when
/// the stderr is not an impossibility at all, so the caller classifies it instead.
#[must_use]
pub fn pip_impossible(stderr: &str) -> Option<crate::plan::ImpossibleDetail> {
if crate::errors::classify_stderr(stderr) != crate::errors::Code::ResImpossible {
return None;
}
let tail = flat[idx + "Reason for being yanked:".len()..].trim();
Some(
tail.trim_end_matches(|c: char| c == '.' || c.is_whitespace())
.to_owned(),
)
let line = stderr
.lines()
.map(str::trim)
.find(|l| l.contains("Cannot install "))
.or_else(|| {
stderr
.lines()
.map(str::trim)
.find(|l| l.starts_with("ERROR:"))
})?;
let explanation = line.trim_start_matches("ERROR:").trim().to_owned();
let mut packages = Vec::new();
if let Some(rest) = explanation.strip_prefix("Cannot install ")
&& let Some((named, _)) = rest.split_once(" because")
{
for token in named.split([',']).flat_map(|t| t.split(" and ")) {
let token = token.trim();
let end = token
.find(['=', '<', '>', '!', '~', '[', ' '])
.unwrap_or(token.len());
if let Ok(name) = PkgName::parse(&token[..end])
&& !packages.contains(&name)
{
packages.push(name);
}
}
}
Some(crate::plan::ImpossibleDetail {
packages,
explanation,
})
}
/// pip prints the yank reason on stderr, not in the report JSON:
///
/// ```text
/// WARNING: The candidate selected for download or install is a yanked version: 'urllib3' candidate (…)
/// Reason for being yanked: Truncated response bodies when streaming a large compressed body.
/// ```
///
/// The reason is **that one line**, and it belongs to the package the warning above it names.
/// Flattening the whole stderr first made it run to the end of the output — over pip's
/// `[notice]` lines, which carry the user's home directory — and gave the first of two yanked
/// packages both reasons and the second none.
fn yank_reason_from_stderr(stderr: &str, pkg: &PkgName) -> Option<String> {
let mut current: Option<PkgName> = None;
for line in stderr.lines().map(str::trim) {
if let Some((_, rest)) = line.split_once("is a yanked version: '") {
current = rest
.split_once('\'')
.and_then(|(name, _)| PkgName::parse(name).ok());
continue;
}
if let Some(reason) = line.strip_prefix("Reason for being yanked:")
&& current.as_ref() == Some(pkg)
{
let reason = reason
.trim()
.trim_end_matches(|c: char| c == '.' || c.is_whitespace());
return (!reason.is_empty()).then(|| reason.to_owned());
}
}
None
}
// -- uv ----------------------------------------------------------------------
/// Parse uv's dry-run plan.
/// uv's dry run, read **by its exit status first** (C3).
///
/// The adapter used to hand every outcome to [`uv_plan`], which looked for the words of a plan:
/// a build that failed still printed `Resolved 1 package`, so it parsed as an empty plan and the
/// preview said *no changes* for a package that could not be built; a refused connection matched
/// nothing and was reported as a uv newer than PipDock; an unknown name came through the resolver
/// as an impossibility. uv exits non-zero on every one of them, so a non-zero exit is classified
/// like any other engine failure, and only an impossibility becomes a report.
///
/// # Errors
/// The classified engine failure, or [`uv_plan`]'s for a zero exit it cannot read.
pub fn uv_resolution(
exit_code: Option<i32>,
stdout: &str,
stderr: &str,
installed: &[Dist],
) -> Result<ParsedPlan> {
if exit_code == Some(0) {
return uv_plan(stdout, stderr, installed);
}
let text = if stderr.trim().is_empty() {
stdout
} else {
stderr
};
if crate::errors::classify_stderr(text) == Code::ResImpossible
&& let Some(detail) = uv_no_solution(text)
{
return Ok(impossible_plan(detail, text));
}
Err(PdError::from_engine_stderr(text))
}
/// Parse uv's dry-run plan — a run that **exited zero**; [`uv_resolution`] decides that.
///
/// **The plan arrives on stderr** (SP-1); stdout is empty for every uv fixture captured. The
/// format is a decorated, hard-wrapped text block:
@@ -192,18 +355,6 @@ pub fn uv_plan(stdout: &str, stderr: &str, installed: &[Dist]) -> Result<ParsedP
stderr
};
if let Some(detail) = uv_no_solution(text) {
return Ok(ParsedPlan {
report: ResolutionReport {
changes: Vec::new(),
held_back: Vec::new(),
impossible: Some(detail),
raw: text.to_owned(),
},
yanked: Vec::new(),
});
}
let recognized = [
"Would make no changes",
"Would install",
@@ -244,7 +395,16 @@ pub fn uv_plan(stdout: &str, stderr: &str, installed: &[Dist]) -> Result<ParsedP
let Ok(name) = PkgName::parse(name.trim()) else {
continue;
};
let version = Version(version.trim().to_owned());
// `+ pkg==0.1.0 (from file:///…)` for a local or direct-URL source: the version is
// the first token, and the rest is uv explaining where it comes from. Kept whole,
// it reached argv as `pkg==0.1.0 (from file:///…)`.
let Some(version) = version.split_whitespace().next() else {
continue;
};
if !crate::pep440::is_argv_safe(version) {
continue;
}
let version = Version(version.to_owned());
if sign == "-" {
removals.insert(name, version);
} else {
@@ -281,17 +441,28 @@ pub fn uv_plan(stdout: &str, stderr: &str, installed: &[Dist]) -> Result<ParsedP
changes,
held_back: Vec::new(),
impossible: None,
incompatible: Vec::new(),
forced: Vec::new(),
yanked: Vec::new(),
raw: text.to_owned(),
declared_python: Default::default(),
},
yanked: uv_yank_warnings(text),
})
}
/// uv's `No solution found` block, with its wrapping undone.
/// uv's `No solution found` block, with its wrapping and its decoration undone.
///
/// uv 0.11 draws it with miette (`×`, `╰─▶`) and uv 0.13 with `error:` / `cause:` labels; the
/// preview shows the sentence, not either rendering, so both read
/// `No solution found when resolving dependencies: Because …`.
fn uv_no_solution(text: &str) -> Option<ImpossibleDetail> {
let flat = flatten(text);
let flat = crate::errors::catalog::collapse_whitespace(&strip_uv_decoration(text));
let idx = flat.find("No solution found when resolving")?;
let explanation = flat[idx..].trim().to_owned();
let explanation = flat[idx..]
.trim()
.replace("dependencies: :", "dependencies:")
.replace(" : ", ": ");
// uv names the packages inside prose ("Because httpx==0.23.0 depends on httpcore>=0.15.0"),
// so pull out the `name==version` and `name>=…` tokens it mentions.
@@ -322,7 +493,10 @@ fn uv_no_solution(text: &str) -> Option<ImpossibleDetail> {
/// `warning: \`urllib3==2.0.0\` is yanked (reason: "…")`
fn uv_yank_warnings(text: &str) -> Vec<YankWarning> {
let mut out = Vec::new();
for line in flatten(text).split("warning:").skip(1) {
for line in crate::errors::catalog::collapse_whitespace(text)
.split("warning:")
.skip(1)
{
if !line.contains("is yanked") {
continue;
}
@@ -363,10 +537,10 @@ fn uv_yank_warnings(text: &str) -> Vec<YankWarning> {
/// the reverse-dependency graph is built from the probe and not from here.
///
/// # Errors
/// `PD-ENG-003` when the output is not the expected JSON array.
pub fn list_json(stdout: &str) -> Result<Vec<Dist>> {
/// [`shape_error`] when the output is not the expected JSON array.
pub fn list_json(stdout: &str, engine: EngineId) -> Result<Vec<Dist>> {
let items: Vec<serde_json::Value> = serde_json::from_str(stdout.trim())
.map_err(|e| PdError::new(Code::EngUvShapeUnknown, format!("list output: {e}")))?;
.map_err(|e| shape_error(engine, &format!("list output: {e}")))?;
Ok(items
.into_iter()
.filter_map(|v| {
@@ -387,10 +561,10 @@ pub fn list_json(stdout: &str) -> Result<Vec<Dist>> {
/// Parse `list --outdated --format=json`.
///
/// # Errors
/// `PD-ENG-003` when the output is not the expected JSON array.
pub fn outdated_json(stdout: &str) -> Result<Vec<crate::model::OutdatedDist>> {
/// [`shape_error`] when the output is not the expected JSON array.
pub fn outdated_json(stdout: &str, engine: EngineId) -> Result<Vec<crate::model::OutdatedDist>> {
let items: Vec<serde_json::Value> = serde_json::from_str(stdout.trim())
.map_err(|e| PdError::new(Code::EngUvShapeUnknown, format!("outdated output: {e}")))?;
.map_err(|e| shape_error(engine, &format!("outdated output: {e}")))?;
Ok(items
.into_iter()
.filter_map(|v| {
@@ -403,6 +577,19 @@ pub fn outdated_json(stdout: &str) -> Result<Vec<crate::model::OutdatedDist>> {
.collect())
}
/// Output in a shape this adapter does not know.
///
/// `PD-ENG-003` means "this uv is newer than PipDock understands — switch to pip for now", which
/// is advice only uv can earn. pip's own unreadable output was reported with it too, telling a pip
/// user to switch to the engine they were already using; it is `PD-ENG-999` instead.
fn shape_error(engine: EngineId, detail: &str) -> PdError {
let code = match engine {
EngineId::Uv => Code::EngUvShapeUnknown,
EngineId::Pip => Code::EngUnclassified,
};
PdError::new(code, detail.to_owned())
}
/// Normalize `pip check` / `uv pip check` output.
///
/// `ok` is the process's own verdict: both engines exit non-zero when they find problems, which
@@ -414,14 +601,20 @@ pub fn check_text(stdout: &str, ok: bool) -> crate::model::CheckReport {
let mut findings = Vec::new();
for line in stdout.lines() {
let line = line.trim();
// "apiclient 1.4 requires requests<2.31, but you have requests 2.32.3 which is incompatible."
let Some((head, _)) = line.split_once(" requires ") else {
continue;
// Three shapes, each taken from a real broken environment:
// pip "anyio 3.7.1 requires sniffio, which is not installed."
// pip "httpx 0.23.0 has requirement httpcore<0.16.0,>=0.15.0, but you have httpcore 1.0.9."
// uv "The package `httpx` requires `httpcore>=0.15.0,<0.16.0`, but `1.0.9` is installed"
// Only the first was read: pip's version conflicts — the case a post-run check exists
// for — were dropped, and every uv finding was filed under a package called "the".
let name = if let Some(rest) = line.strip_prefix("The package `") {
rest.split_once('`').map(|(name, _)| name)
} else if line.contains(" requires ") || line.contains(" has requirement ") {
line.split_whitespace().next()
} else {
None
};
let Some(name) = head.split_whitespace().next() else {
continue;
};
let Ok(pkg) = PkgName::parse(name) else {
let Some(Ok(pkg)) = name.map(PkgName::parse) else {
continue;
};
findings.push(crate::model::CheckFinding {
@@ -432,29 +625,31 @@ pub fn check_text(stdout: &str, ok: bool) -> crate::model::CheckReport {
crate::model::CheckReport {
ok: ok && findings.is_empty(),
findings,
error: None,
}
}
// -- shared ------------------------------------------------------------------
/// Collapse wrapping and CRLF so multi-word phrases can be found.
///
/// uv hard-wraps its diagnostics mid-sentence, so a literal search for a phrase that spans the
/// wrap point finds nothing. The same normalization is applied by the error classifiers, and for
/// the same reason.
fn flatten(text: &str) -> String {
/// uv's diagnostic decoration, removed line by line: miette's box-drawing glyphs (uv ≤ 0.12) and
/// the `cause:` labels that replaced them (0.13). A `cause:` becomes a colon after the line it
/// explains.
fn strip_uv_decoration(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut in_space = false;
for ch in text.chars() {
if ch.is_whitespace() {
in_space = true;
for line in text.lines() {
let trimmed = line
.trim()
.trim_start_matches(['×', '╰', '├', '─', '▶', '│', ' ']);
if let Some(rest) = trimmed.strip_prefix("cause:") {
let ends_with_colon = out.trim_end().ends_with(':');
let kept = out.trim_end().len();
out.truncate(kept);
out.push_str(if ends_with_colon { " " } else { ": " });
out.push_str(rest.trim_start());
} else {
if in_space && !out.is_empty() {
out.push(' ');
}
in_space = false;
out.push(ch);
out.push_str(trimmed);
}
out.push('\n');
}
out
}
@@ -532,7 +727,8 @@ mod tests {
fn an_unknown_pip_report_version_fails_loudly() {
let err = pip_report(r#"{"version":"2","install":[]}"#, "", &[])
.expect_err("future format must not be guessed at");
assert_eq!(err.code, Code::EngUvShapeUnknown);
// Not PD-ENG-003, whose advice is to switch to pip.
assert_eq!(err.code, Code::EngUnclassified);
}
#[test]
@@ -575,7 +771,7 @@ mod tests {
╰─▶ Because httpx==0.23.0 depends on httpcore>=0.15.0,<0.16.0 and you\r\n \
require httpcore>=1.0, we can conclude that your requirements and\r\n \
httpx==0.23.0 are incompatible.\r\n";
let plan = uv_plan("", text, &[]).expect("parse");
let plan = uv_resolution(Some(1), "", text, &[]).expect("parse");
let detail = plan.report.impossible.expect("impossible detail");
// The wrapping must be undone, or the explanation reads as broken fragments in the UI.
@@ -665,4 +861,111 @@ mod tests {
"a yank must not make the plan dirty"
);
}
#[test]
fn both_uv_renderings_explain_an_impossibility_in_the_same_words() {
let v011 = " × No solution found when resolving dependencies:\n \
╰─▶ Because a==1.0 depends on b<2 and you require b>=2, we can conclude\n \
that your requirements are unsatisfiable.\n";
let v013 = "error: No solution found when resolving dependencies\n \
cause: Because a==1.0 depends on b<2 and you require b>=2, we can conclude\n \
that your requirements are unsatisfiable.\n";
let explain = |text: &str| {
uv_resolution(Some(1), "", text, &[])
.expect("an impossibility is a report")
.report
.impossible
.expect("impossible")
.explanation
};
let expected = "No solution found when resolving dependencies: Because a==1.0 depends \
on b<2 and you require b>=2, we can conclude that your requirements are \
unsatisfiable.";
assert_eq!(explain(v011), expected);
assert_eq!(explain(v013), expected);
}
#[test]
fn a_failed_uv_run_that_still_says_resolved_is_not_an_empty_plan() {
// C3: uv prints "Resolved 1 package" before a build fails, which is one of the words
// `uv_plan` looks for — so a package that could not be built previewed as "no changes".
let text = "Resolved 1 package in 1.2s\n Building numpy==1.19.5\n\
error: Failed to build `numpy==1.19.5`\n \
cause: The build backend returned an error\n";
let err = uv_resolution(Some(1), "", text, &[]).expect_err("a failure");
assert_eq!(err.code, Code::BldBackendFailed);
}
#[test]
fn two_yanked_packages_each_get_their_own_reason_and_nothing_else() {
let doc = r#"{"version":"1","install":[
{"requested":true,"is_yanked":true,"metadata":{"name":"urllib3","version":"2.0.0"}},
{"requested":true,"is_yanked":true,"metadata":{"name":"idna","version":"3.5"}}
]}"#;
let stderr = "WARNING: The candidate selected for download or install is a yanked \
version: 'urllib3' candidate (version 2.0.0 at https://x/urllib3.whl)\n\
Reason for being yanked: Truncated response bodies.\n\
WARNING: The candidate selected for download or install is a yanked \
version: 'idna' candidate (version 3.5 at https://x/idna.whl)\n\
Reason for being yanked: Bad wheel\n\
[notice] To update, run: C:\\Users\\someone\\venv\\python.exe -m pip \
install --upgrade pip\n";
let plan = pip_report(doc, stderr, &[]).expect("parse");
let reason = |n: &str| {
plan.yanked
.iter()
.find(|y| y.pkg.as_str() == n)
.and_then(|y| y.reason.clone())
};
assert_eq!(
reason("urllib3").as_deref(),
Some("Truncated response bodies")
);
assert_eq!(reason("idna").as_deref(), Some("Bad wheel"));
}
#[test]
fn pip_and_uv_check_findings_name_the_package_that_is_broken() {
// Captured from one broken environment, pip 26.2.1 and uv 0.13.1.
let pip = "anyio 3.7.1 requires sniffio, which is not installed.\n\
httpx 0.23.0 requires sniffio, which is not installed.\n\
httpcore 1.0.9 has requirement h11>=0.16, but you have h11 0.12.0.\n\
httpx 0.23.0 has requirement httpcore<0.16.0,>=0.15.0, but you have httpcore 1.0.9.\n";
let uv = "Checked 8 packages in 174ms\nFound 4 incompatibilities\n\
The package `httpx` requires `sniffio`, but it's not installed\n\
The package `httpx` requires `httpcore>=0.15.0,<0.16.0`, but `1.0.9` is installed\n\
The package `httpcore` requires `h11>=0.16`, but `0.12.0` is installed\n\
The package `anyio` requires `sniffio>=1.1`, but it's not installed\n";
let names = |text: &str| -> Vec<String> {
let report = check_text(text, false);
assert!(!report.ok);
report.findings.iter().map(|f| f.pkg.to_string()).collect()
};
assert_eq!(names(pip), ["anyio", "httpx", "httpcore", "httpx"]);
assert_eq!(names(uv), ["httpx", "httpx", "httpcore", "anyio"]);
}
#[test]
fn unreadable_pip_output_does_not_blame_uv() {
// PD-ENG-003 tells the user to switch to pip; under pip that is advice to do nothing.
let err = pip_report("not json", "", &[]).expect_err("unreadable");
assert_eq!(err.code, Code::EngUnclassified);
assert_eq!(
list_json("not json", EngineId::Pip).expect_err("pip").code,
Code::EngUnclassified
);
assert_eq!(
list_json("not json", EngineId::Uv).expect_err("uv").code,
Code::EngUvShapeUnknown
);
}
#[test]
fn a_uv_line_with_a_source_suffix_keeps_only_the_version() {
// `+ pkg==0.1.0 (from file:///…)` reached argv whole as the version.
let text = "Resolved 1 package in 5ms\nWould install 1 package\n + localpkg==0.1.0 (from file:///C:/src/localpkg)\n";
let plan = uv_plan("", text, &[]).expect("parses");
assert_eq!(plan.report.changes.len(), 1);
assert_eq!(plan.report.changes[0].to.0, "0.1.0");
}
}
+108 -45
View File
@@ -1,20 +1,20 @@
//! The pip adapter: `<env-python> -m pip …`.
//!
//! Command mapping is fixed by `docs/DATA-FLOW.md` §7. Implementation lands in M1; the argv
//! builders below are already exercised by tests because they are the surface SECURITY §2 cares
//! about — nothing else in this file may construct engine arguments.
//! Command mapping is fixed by `docs/DATA-FLOW.md` §7. The argv builders below are the surface
//! SECURITY §2 cares about, and are tested as such — nothing else in this file may construct
//! engine arguments.
use async_trait::async_trait;
use crate::errors::{Code, PdError, Result};
use crate::exec::Command;
use crate::exec::{Command, watchdog};
use crate::model::{
CheckReport, Dist, EngineId, EngineInfo, ExecMode, OutdatedDist, PinnedSpec, PkgName, PyEnv,
StepResult,
};
use crate::plan::{PlanRequest, ResolutionReport};
use super::{Engine, ProgressSink, single_pkg};
use super::{Engine, InstallSet, ProgressSink, ResolveCtx, SystemPackages, single_pkg};
/// Drives pip as a subprocess.
#[derive(Debug, Clone, Copy, Default)]
@@ -44,12 +44,35 @@ impl PipEngine {
]
}
/// argv for an install from requirement files. The PEP 668 flag only when `system` says so.
#[must_use]
pub fn argv_install(files: &[String], system: SystemPackages) -> Vec<String> {
let mut argv = vec!["-m".to_owned(), "pip".to_owned(), "install".to_owned()];
argv.extend(system.args().iter().map(|a| (*a).to_owned()));
argv.extend(files.iter().cloned());
argv
}
/// argv for `pip uninstall -y`. pip ≥ 23.0.1 refuses this in a managed environment too.
#[must_use]
pub fn argv_uninstall(names: &[PkgName], system: SystemPackages) -> Vec<String> {
let mut argv = vec![
"-m".to_owned(),
"pip".to_owned(),
"uninstall".to_owned(),
"-y".to_owned(),
];
argv.extend(system.args().iter().map(|a| (*a).to_owned()));
argv.extend(names.iter().map(ToString::to_string));
argv
}
/// argv for the dry-run resolve, whose JSON report goes to stdout.
///
/// `requirements` comes from [`super::plan_argv_specs`] and carries all three groups: bare
/// names to move, explicit installs, and the pinned guard set.
/// `files` is [`super::RequirementFiles::args`] over [`super::plan_argv_specs`], which carries
/// all three groups: bare names to move, explicit installs, and the pinned guard set.
#[must_use]
pub fn argv_dry_run(requirements: &[String]) -> Vec<String> {
pub fn argv_dry_run(files: &[String]) -> Vec<String> {
let mut argv = vec![
"-m".into(),
"pip".into(),
@@ -64,7 +87,7 @@ impl PipEngine {
"--report".into(),
"-".into(),
];
argv.extend(requirements.iter().cloned());
argv.extend(files.iter().cloned());
argv
}
@@ -91,6 +114,7 @@ impl Engine for PipEngine {
async fn info(&self, env: &PyEnv) -> EngineInfo {
let out = Command::python(&env.interpreter)
.args(["-m", "pip", "--version"])
.timeout(watchdog::QUERY)
.run()
.await;
match out {
@@ -111,72 +135,78 @@ impl Engine for PipEngine {
async fn list_installed(&self, env: &PyEnv) -> Result<Vec<Dist>> {
let out = Command::python(&env.interpreter)
.args(Self::argv_list())
.timeout(watchdog::QUERY)
.run()
.await?;
if !out.ok() {
return Err(out.into_error());
}
super::parse::list_json(&out.stdout)
super::parse::list_json(&out.stdout, EngineId::Pip)
}
async fn list_outdated(&self, env: &PyEnv) -> Result<Vec<OutdatedDist>> {
let out = Command::python(&env.interpreter)
.args(Self::argv_outdated())
.timeout(watchdog::OUTDATED)
.run()
.await?;
if !out.ok() {
return Err(out.into_error());
}
super::parse::outdated_json(&out.stdout)
super::parse::outdated_json(&out.stdout, EngineId::Pip)
}
async fn resolve(&self, env: &PyEnv, req: &PlanRequest) -> Result<ResolutionReport> {
async fn resolve(
&self,
env: &PyEnv,
req: &PlanRequest,
ctx: &ResolveCtx,
) -> Result<ResolutionReport> {
// SP-1: the installed set must be restated or the resolver ignores it and plans an
// upgrade that breaks installed dependents. The caller assembles that set into `req`.
let installed = self.list_installed(env).await?;
let requirements = super::plan_argv_specs(req, &installed);
let out = Command::python(&env.interpreter)
.args(Self::argv_dry_run(&requirements))
let lines = super::plan_lines(req, &installed, &ctx.adjust);
let files = super::RequirementFiles::write(&lines, &[])?;
let mut out = Command::python(&env.interpreter)
.args(Self::argv_dry_run(&files.args()))
.timeout(watchdog::RESOLVE)
.cancel(ctx.cancel.clone())
.run()
.await?;
if !out.ok() {
return Err(out.into_error());
}
super::parse::pip_report(&out.stdout, &out.stderr, &installed).map(|p| p.report)
out.stderr = files.humanize(&out.stderr);
super::parse::pip_resolution(out.code, &out.stdout, &out.stderr, &installed)
.map(super::parse::ParsedPlan::into_report)
}
async fn install(
&self,
env: &PyEnv,
specs: &[PinnedSpec],
set: &InstallSet,
mode: ExecMode,
sink: ProgressSink,
) -> Result<StepResult> {
let mut argv = vec!["-m".to_owned(), "pip".to_owned(), "install".to_owned()];
argv.extend(specs.iter().map(PinnedSpec::to_requirement));
let out = Command::python(&env.interpreter)
.args(argv)
let requirements: Vec<String> = set.specs.iter().map(PinnedSpec::to_requirement).collect();
let files = super::RequirementFiles::write(&requirements, &set.constraints)?;
let mut out = Command::python(&env.interpreter)
.args(Self::argv_install(&files.args(), set.system))
.timeout(watchdog::INSTALL)
.cancel(sink.cancel.clone())
.run_streaming(&sink, single_pkg(specs), mode)
.run_streaming(&sink, single_pkg(&set.specs), mode)
.await?;
Ok(super::step_result(specs, &out))
out.stderr = files.humanize(&out.stderr);
Ok(super::step_result(&set.specs, &out))
}
async fn uninstall(
&self,
env: &PyEnv,
names: &[PkgName],
system: SystemPackages,
sink: ProgressSink,
) -> Result<StepResult> {
let mut argv = vec![
"-m".to_owned(),
"pip".to_owned(),
"uninstall".to_owned(),
"-y".to_owned(),
];
argv.extend(names.iter().map(ToString::to_string));
let out = Command::python(&env.interpreter)
.args(argv)
.args(Self::argv_uninstall(names, system))
.timeout(watchdog::INSTALL)
.cancel(sink.cancel.clone())
.run_streaming(&sink, names.first().cloned(), ExecMode::Isolated)
.await?;
@@ -186,6 +216,7 @@ impl Engine for PipEngine {
async fn check(&self, env: &PyEnv) -> Result<CheckReport> {
let out = Command::python(&env.interpreter)
.args(Self::argv_check())
.timeout(watchdog::QUERY)
.run()
.await?;
// `pip check` exits non-zero when it finds problems, which is a successful check with
@@ -196,6 +227,7 @@ impl Engine for PipEngine {
async fn freeze(&self, env: &PyEnv) -> Result<String> {
let out = Command::python(&env.interpreter)
.args(Self::argv_freeze())
.timeout(watchdog::QUERY)
.run()
.await?;
if !out.ok() {
@@ -257,6 +289,7 @@ impl PipEngine {
async fn install_latest_pip(interpreter: &std::path::Path) -> Result<crate::exec::Output> {
Command::python(interpreter)
.args(["-m", "pip", "install", "-U", "pip"])
.timeout(watchdog::INSTALL)
.run()
.await
}
@@ -290,6 +323,7 @@ impl PipEngine {
async fn ensurepip(interpreter: &std::path::Path) -> Result<()> {
let out = Command::python(interpreter)
.args(["-m", "ensurepip", "--upgrade"])
.timeout(watchdog::INSTALL)
.run()
.await?;
if out.ok() {
@@ -331,8 +365,9 @@ mod tests {
}
#[test]
fn requirements_are_appended_as_separate_argv_entries() {
// One token per argument is what makes shell quoting irrelevant (SECURITY §2).
fn requirements_reach_pip_as_a_file_not_as_argv() {
// A requirements file keeps the command line a constant length whatever the size of the
// environment, and each path is still exactly one argv entry (SECURITY §2).
let specs = [
PinnedSpec {
name: PkgName::parse("httpx").unwrap(),
@@ -344,15 +379,16 @@ mod tests {
},
];
let requirements: Vec<String> = specs.iter().map(PinnedSpec::to_requirement).collect();
let argv = PipEngine::argv_dry_run(&requirements);
assert_eq!(
&argv[argv.len() - 2..],
["httpx==0.28.1", "requests==2.32.3"]
);
assert!(
argv.iter().all(|a| !a.contains(' ')),
"no argv entry may bundle multiple arguments"
);
let files = super::super::RequirementFiles::write(&requirements, &specs[..1])
.expect("files are written");
let argv = PipEngine::argv_dry_run(&files.args());
assert_eq!(&argv[argv.len() - 4..argv.len() - 3], ["-r"]);
assert_eq!(&argv[argv.len() - 2..argv.len() - 1], ["-c"]);
let written =
std::fs::read_to_string(&argv[argv.len() - 3]).expect("requirements file exists");
assert_eq!(written, "httpx==0.28.1\nrequests==2.32.3\n");
let constrained = std::fs::read_to_string(&argv[argv.len() - 1]).expect("constraints");
assert_eq!(constrained, "httpx==0.28.1\n");
}
#[test]
@@ -386,4 +422,31 @@ mod tests {
// Not PD-ENG-001: reaching the spawn would mean the guard ran too late.
assert!(!err.message.contains("could not run"), "{}", err.message);
}
#[test]
fn the_pep668_flag_appears_only_when_the_override_applies() {
let files = ["-r".to_owned(), "req.txt".to_owned()];
let names = [PkgName::parse("idna").unwrap()];
for (system, expected) in [
(SystemPackages::Protected, 0),
(SystemPackages::OverrideAllowed, 1),
] {
for argv in [
PipEngine::argv_install(&files, system),
PipEngine::argv_uninstall(&names, system),
] {
let count = argv
.iter()
.filter(|a| *a == "--break-system-packages")
.count();
assert_eq!(count, expected, "{system:?}: {argv:?}");
}
}
// pip's dry run is exempt from PEP 668 (`--dry-run --report`) and is never given it.
assert!(
!PipEngine::argv_dry_run(&files)
.iter()
.any(|a| a == "--break-system-packages")
);
}
}
+97 -34
View File
@@ -7,8 +7,10 @@
//!
//! Two consequences shape this adapter:
//!
//! - `resolve` parses the plan whether or not uv exited zero, because its failure message is the
//! most useful thing it produces.
//! - `resolve` is decided by uv's exit status first: zero is a plan; a non-zero exit whose text
//! says no solution exists is a report (`impossible`), and anything else — a build failure, an
//! unreachable index — is classified as the failure it is. Parsing the plan regardless of the
//! exit status is how a failed build used to read as "nothing to change" (C3).
//! - Every plan restates the installed set as explicit requirements. Without that, uv upgrades
//! straight past an installed package's constraint and exits 0 — see [`super::plan_requirements`].
//!
@@ -18,14 +20,14 @@
use async_trait::async_trait;
use crate::errors::Result;
use crate::exec::Command;
use crate::exec::{Command, watchdog};
use crate::model::{
CheckReport, Dist, EngineId, EngineInfo, ExecMode, OutdatedDist, PinnedSpec, PkgName, PyEnv,
StepResult,
};
use crate::plan::{PlanRequest, ResolutionReport};
use super::{Engine, ProgressSink, single_pkg};
use super::{Engine, InstallSet, ProgressSink, ResolveCtx, SystemPackages, single_pkg};
/// Drives uv as a subprocess.
#[derive(Debug, Clone, Copy, Default)]
@@ -49,7 +51,7 @@ impl UvEngine {
/// `requirements` comes from [`super::plan_argv_specs`] and carries all three groups: bare
/// names to move, explicit installs, and the pinned guard set.
#[must_use]
pub fn argv_dry_run(python: &str, requirements: &[String]) -> Vec<String> {
pub fn argv_dry_run(python: &str, files: &[String]) -> Vec<String> {
let mut argv = vec![
"pip".into(),
"install".into(),
@@ -58,7 +60,35 @@ impl UvEngine {
"--python".into(),
python.into(),
];
argv.extend(requirements.iter().cloned());
argv.extend(files.iter().cloned());
argv
}
/// argv for an install from requirement files. The PEP 668 flag only when `system` says so.
#[must_use]
pub fn argv_install(python: &str, files: &[String], system: SystemPackages) -> Vec<String> {
let mut argv = vec![
"pip".to_owned(),
"install".to_owned(),
"--python".to_owned(),
python.to_owned(),
];
argv.extend(system.args().iter().map(|a| (*a).to_owned()));
argv.extend(files.iter().cloned());
argv
}
/// argv for `uv pip uninstall`, which also refuses a managed environment without the flag.
#[must_use]
pub fn argv_uninstall(python: &str, names: &[PkgName], system: SystemPackages) -> Vec<String> {
let mut argv = vec![
"pip".to_owned(),
"uninstall".to_owned(),
"--python".to_owned(),
python.to_owned(),
];
argv.extend(system.args().iter().map(|a| (*a).to_owned()));
argv.extend(names.iter().map(ToString::to_string));
argv
}
@@ -85,7 +115,12 @@ impl Engine for UvEngine {
async fn info(&self, _env: &PyEnv) -> EngineInfo {
// uv is a standalone binary on PATH, not a module inside the environment, so this is the
// one engine query that does not involve the interpreter.
match Command::new("uv").arg("--version").run().await {
match Command::new("uv")
.arg("--version")
.timeout(watchdog::QUERY)
.run()
.await
{
Ok(o) if o.ok() => EngineInfo {
id: EngineId::Uv,
// "uv 0.11.32 (3010295ae 2026-07-23 x86_64-pc-windows-msvc)" -> "0.11.32"
@@ -104,12 +139,13 @@ impl Engine for UvEngine {
let python = env.interpreter.display().to_string();
let out = Command::new("uv")
.args(Self::argv_list(&python))
.timeout(watchdog::QUERY)
.run()
.await?;
if !out.ok() {
return Err(out.into_error());
}
super::parse::list_json(&out.stdout)
super::parse::list_json(&out.stdout, EngineId::Uv)
}
async fn list_outdated(&self, env: &PyEnv) -> Result<Vec<OutdatedDist>> {
@@ -123,68 +159,72 @@ impl Engine for UvEngine {
"--python".to_owned(),
python,
])
.timeout(watchdog::OUTDATED)
.run()
.await?;
if !out.ok() {
return Err(out.into_error());
}
super::parse::outdated_json(&out.stdout)
super::parse::outdated_json(&out.stdout, EngineId::Uv)
}
async fn resolve(&self, env: &PyEnv, req: &PlanRequest) -> Result<ResolutionReport> {
async fn resolve(
&self,
env: &PyEnv,
req: &PlanRequest,
ctx: &ResolveCtx,
) -> Result<ResolutionReport> {
// SP-1: without the installed set restated, uv plans an upgrade that breaks installed
// dependents and exits 0. Identical requirement to pip's adapter.
let installed = self.list_installed(env).await?;
let requirements = super::plan_argv_specs(req, &installed);
let lines = super::plan_lines(req, &installed, &ctx.adjust);
let files = super::RequirementFiles::write(&lines, &[])?;
let python = env.interpreter.display().to_string();
let mut argv = Self::argv_dry_run(&python, &files.args());
// uv refuses even a dry run in a managed environment without it (verified, uv 0.13.1).
argv.extend(ctx.system.args().iter().map(|a| (*a).to_owned()));
let out = Command::new("uv")
.args(Self::argv_dry_run(&python, &requirements))
.args(argv)
.timeout(watchdog::RESOLVE)
.cancel(ctx.cancel.clone())
.run()
.await?;
// uv exits non-zero on an unsatisfiable set, but its message is the most useful thing it
// produces (SP-1), so the plan is parsed either way and the parser decides.
super::parse::uv_plan(&out.stdout, &out.stderr, &installed).map(|p| p.report)
// uv exits non-zero on an unsatisfiable set, and its explanation is the most useful thing
// it produces (SP-1) — so the exit decides between a plan, an impossibility and a failure.
super::parse::uv_resolution(out.code, &out.stdout, &out.stderr, &installed)
.map(super::parse::ParsedPlan::into_report)
}
async fn install(
&self,
env: &PyEnv,
specs: &[PinnedSpec],
set: &InstallSet,
mode: ExecMode,
sink: ProgressSink,
) -> Result<StepResult> {
let python = env.interpreter.display().to_string();
let mut argv = vec![
"pip".to_owned(),
"install".to_owned(),
"--python".to_owned(),
python,
];
argv.extend(specs.iter().map(PinnedSpec::to_requirement));
let requirements: Vec<String> = set.specs.iter().map(PinnedSpec::to_requirement).collect();
let files = super::RequirementFiles::write(&requirements, &set.constraints)?;
let out = Command::new("uv")
.args(argv)
.args(Self::argv_install(&python, &files.args(), set.system))
.timeout(watchdog::INSTALL)
.cancel(sink.cancel.clone())
.run_streaming(&sink, single_pkg(specs), mode)
.run_streaming(&sink, single_pkg(&set.specs), mode)
.await?;
Ok(super::step_result(specs, &out))
Ok(super::step_result(&set.specs, &out))
}
async fn uninstall(
&self,
env: &PyEnv,
names: &[PkgName],
system: SystemPackages,
sink: ProgressSink,
) -> Result<StepResult> {
let python = env.interpreter.display().to_string();
let mut argv = vec![
"pip".to_owned(),
"uninstall".to_owned(),
"--python".to_owned(),
python,
];
argv.extend(names.iter().map(ToString::to_string));
let out = Command::new("uv")
.args(argv)
.args(Self::argv_uninstall(&python, names, system))
.timeout(watchdog::INSTALL)
.cancel(sink.cancel.clone())
.run_streaming(&sink, names.first().cloned(), ExecMode::Isolated)
.await?;
@@ -200,6 +240,7 @@ impl Engine for UvEngine {
"--python".to_owned(),
python,
])
.timeout(watchdog::QUERY)
.run()
.await?;
// uv reports findings on stderr where pip uses stdout, so both are given to the parser.
@@ -211,6 +252,7 @@ impl Engine for UvEngine {
let python = env.interpreter.display().to_string();
let out = Command::new("uv")
.args(Self::argv_freeze(&python))
.timeout(watchdog::QUERY)
.run()
.await?;
if !out.ok() {
@@ -269,4 +311,25 @@ mod tests {
.expect_err("uv cannot upgrade pip");
assert_eq!(err.code, crate::errors::Code::EngNotFound);
}
#[test]
fn the_pep668_flag_appears_only_when_the_override_applies() {
let files = ["-r".to_owned(), "req.txt".to_owned()];
let names = [PkgName::parse("idna").unwrap()];
for (system, expected) in [
(SystemPackages::Protected, 0),
(SystemPackages::OverrideAllowed, 1),
] {
for argv in [
UvEngine::argv_install(PY, &files, system),
UvEngine::argv_uninstall(PY, &names, system),
] {
let count = argv
.iter()
.filter(|a| *a == "--break-system-packages")
.count();
assert_eq!(count, expected, "{system:?}: {argv:?}");
}
}
}
}
+149 -35
View File
@@ -19,10 +19,10 @@ use std::path::{Path, PathBuf};
use crate::compat::PyVersion;
use crate::errors::{Code, PdError, Result};
use crate::exec::{Command, canonical_interpreter, write_temp};
use crate::exec::{Command, TempFile, canonical_interpreter, watchdog};
use crate::model::{Dist, EnvSource, PkgName, PyEnv, Version};
/// The embedded introspection helper, executed as `<env-python> -I probe.py --json`.
/// The embedded introspection helper, executed as `<env-python> -X utf8 -I probe.py --json`.
///
/// SECURITY §2: `-I` (isolated mode) makes the probe ignore `PYTHONPATH` and user site, so a
/// poisoned environment cannot inject code into it. It is written to a temp file with a random
@@ -39,6 +39,10 @@ pub struct ProbeResult {
pub env: PyEnv,
/// Installed distributions, sorted by normalized name.
pub dists: Vec<Dist>,
/// The PEP 508 marker environment (`sys_platform`, `platform_machine`, …), from probe schema
/// 3. Empty for an older probe, which leaves those markers unevaluated — the conservative
/// direction (`graph::markers`).
pub markers: BTreeMap<String, String>,
}
/// Identity of an environment: SHA-256 of the canonicalized interpreter path (ARCHITECTURE §6).
@@ -47,19 +51,8 @@ pub struct ProbeResult {
/// directory and the recents list, so a change here orphans a user's data.
#[must_use]
pub fn env_hash(interpreter: &Path) -> String {
use std::fmt::Write as _;
use sha2::{Digest as _, Sha256};
let canonical = canonical_interpreter(interpreter);
let digest = Sha256::digest(canonical.as_bytes());
digest
.iter()
.fold(String::with_capacity(64), |mut acc, byte| {
// Infallible: writing to a String cannot fail, and `?` here would need a Result return
// for a function that has no other failure mode.
let _ = write!(acc, "{byte:02x}");
acc
})
crate::model::sha256_hex(canonical.as_bytes())
}
/// Run `probe.py` against an interpreter.
@@ -75,17 +68,21 @@ pub async fn probe(interpreter: &Path, source: EnvSource) -> Result<ProbeResult>
));
}
let script = write_temp("pipdock-probe", "py", PROBE_PY)?;
// The probe is removed whatever happens; a leaked temp file is harmless but untidy, and
// Removed when it drops, whatever happens; a leaked temp file is harmless but untidy, and
// leaving one behind after every scan is not.
let result = Command::python(interpreter)
.arg("-I")
.arg(script.display().to_string())
let script = TempFile::create("pipdock-probe", "py", PROBE_PY)?;
// **`-X utf8` is not redundant with `Command::python`'s environment.** `-I` implies `-E`, so
// PYTHONUTF8 and PYTHONIOENCODING are ignored and stdout falls back to the ANSI code page. The
// probe prints paths with `ensure_ascii=False`, so a venv under `C:\Dự án\` crashed it with a
// UnicodeEncodeError (PD-ENV-003) and a `Jürgen` came back as mojibake. `-X` is a command-line
// option, which isolated mode honours. Reproduced before fixing.
let out = Command::python(interpreter)
.args(["-X", "utf8", "-I"])
.arg(script.path().display().to_string())
.arg("--json")
.timeout(watchdog::PROBE)
.run()
.await;
let _ = std::fs::remove_file(&script);
let out = result?;
.await?;
if !out.ok() {
return Err(
@@ -183,7 +180,21 @@ pub fn parse_probe(stdout: &str, interpreter: &Path, source: EnvSource) -> Resul
source,
};
Ok(ProbeResult { env, dists })
let markers = doc
.get("markers")
.and_then(serde_json::Value::as_object)
.map(|m| {
m.iter()
.filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned())))
.collect()
})
.unwrap_or_default();
Ok(ProbeResult {
env,
dists,
markers,
})
}
/// A discovered interpreter, before it has been probed.
@@ -292,30 +303,39 @@ pub async fn scan_reporting(report: &(dyn Fn(ScanProgress) + Sync)) -> Vec<Candi
found.into_values().collect()
}
/// PEP 514 registry entries, from both `HKCU` and `HKLM`.
/// PEP 514 registry entries: `HKCU`, and both views of `HKLM`.
///
/// SP-6 found `PythonCore` present under **both** hives on the reference machine, which is one of
/// the two ways the same interpreter reaches discovery twice.
///
/// PEP 514 puts a 32-bit all-users install under `HKLM\Software\Wow6432Node\Python`, which a
/// 64-bit process does not see through the default view — so every such Python was missing from
/// the registry source. `HKCU` is shared between the views and needs no second read.
#[must_use]
pub fn registry_interpreters() -> Vec<PathBuf> {
#[cfg(windows)]
{
use winreg::RegKey;
use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ};
use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY};
let mut out = Vec::new();
for hive in [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE] {
for (hive, view) in [
(HKEY_CURRENT_USER, 0),
(HKEY_LOCAL_MACHINE, 0),
(HKEY_LOCAL_MACHINE, KEY_WOW64_32KEY),
] {
let flags = KEY_READ | view;
let root = RegKey::predef(hive);
let Ok(software) = root.open_subkey_with_flags(r"SOFTWARE\Python", KEY_READ) else {
let Ok(software) = root.open_subkey_with_flags(r"SOFTWARE\Python", flags) else {
continue;
};
for company in software.enum_keys().flatten() {
let Ok(company_key) = software.open_subkey_with_flags(&company, KEY_READ) else {
let Ok(company_key) = software.open_subkey_with_flags(&company, flags) else {
continue;
};
for tag in company_key.enum_keys().flatten() {
let Ok(install) =
company_key.open_subkey_with_flags(format!(r"{tag}\InstallPath"), KEY_READ)
company_key.open_subkey_with_flags(format!(r"{tag}\InstallPath"), flags)
else {
continue;
};
@@ -339,7 +359,12 @@ pub fn registry_interpreters() -> Vec<PathBuf> {
/// Interpreters reported by the `py` launcher (`py -0p`).
pub async fn py_launcher_interpreters() -> Vec<PathBuf> {
let Ok(out) = Command::new("py").arg("-0p").run().await else {
let Ok(out) = Command::new("py")
.arg("-0p")
.timeout(watchdog::DISCOVERY)
.run()
.await
else {
return Vec::new();
};
if !out.ok() {
@@ -354,7 +379,12 @@ pub async fn py_launcher_interpreters() -> Vec<PathBuf> {
/// `<download available>` where a path would be, and must be dropped — offering to manage a
/// Python that is not on the machine would be nonsense.
pub async fn uv_interpreters() -> Vec<PathBuf> {
let Ok(out) = Command::new("uv").args(["python", "list"]).run().await else {
let Ok(out) = Command::new("uv")
.args(["python", "list"])
.timeout(watchdog::DISCOVERY)
.run()
.await
else {
return Vec::new();
};
if !out.ok() {
@@ -363,13 +393,25 @@ pub async fn uv_interpreters() -> Vec<PathBuf> {
out.stdout.lines().filter_map(parse_listed_path).collect()
}
/// Take the trailing path from a listing line, rejecting `<download available>` placeholders.
/// The interpreter path of one `py -0p` or `uv python list` row.
///
/// Both print a key that never contains whitespace — `-V:3.14`, `cpython-3.14.7-windows-x86_64-none`
/// — then, for `py`, an optional `*` marking the default, then the path. **The path may contain
/// spaces.** Taking the last whitespace-separated token turned `C:\Program Files\Python312\python.exe`
/// — where every all-users python.org installer puts it — into the relative
/// `Files\Python312\python.exe`, which the existence check then quietly dropped. A row uv offers to
/// download carries `<download available>` where the path would be, and is rejected.
fn parse_listed_path(line: &str) -> Option<PathBuf> {
let last = line.split_whitespace().next_back()?;
if last.starts_with('<') || !last.contains(std::path::MAIN_SEPARATOR) {
let (_key, rest) = line.trim().split_once(char::is_whitespace)?;
let rest = rest.trim_start();
let rest = rest.strip_prefix('*').map_or(rest, str::trim_start);
// uv prints a symlink as `path -> target`; the listed path is the interpreter itself.
let path = rest.split(" -> ").next()?.trim_end();
if path.is_empty() || path.starts_with('<') {
return None;
}
Some(PathBuf::from(last))
let path = PathBuf::from(path);
path.is_absolute().then_some(path)
}
/// Virtual environments in `dir`, one level deep.
@@ -562,6 +604,78 @@ mod tests {
assert!(parse_listed_path("").is_none());
}
#[test]
fn a_listed_path_with_spaces_survives() {
// Where every all-users python.org installer puts Python. The last token alone was the
// relative `Files\Python312\python.exe`, and the interpreter vanished from discovery.
let program_files = r"C:\Program Files\Python312\python.exe";
for line in [
format!(" -V:3.12 {program_files}"),
format!(" -V:3.12 * {program_files}\r"),
format!(" -3.12-64 {program_files}"),
format!("cpython-3.12.10-windows-x86_64-none {program_files}"),
] {
assert_eq!(
parse_listed_path(&line),
Some(PathBuf::from(program_files)),
"{line:?}"
);
}
// uv's warnings, should one reach stdout, are not paths.
assert!(
parse_listed_path("warning: Failed to inspect Python interpreter from search path")
.is_none()
);
assert!(
parse_listed_path("cpython-3.16.0a1-windows-x86_64-none <download available>")
.is_none()
);
}
#[test]
fn the_marker_environment_is_carried_and_an_older_probe_has_none() {
let doc = r#"{"schema":3,"python":"3.14.7","prefix":"C:\\Python314",
"externally_managed":false,"hidden_user_site":null,
"markers":{"sys_platform":"win32","platform_machine":"AMD64","bogus":7},
"dists":[]}"#;
let got = parse_probe(doc, Path::new("python.exe"), EnvSource::Registry).expect("parse");
assert_eq!(
got.markers.get("sys_platform").map(String::as_str),
Some("win32")
);
assert_eq!(
got.markers.get("platform_machine").map(String::as_str),
Some("AMD64")
);
assert!(
!got.markers.contains_key("bogus"),
"only strings are markers"
);
let old = r#"{"schema":2,"python":"3.12.4","prefix":"x","externally_managed":false,
"hidden_user_site":null,"dists":[]}"#;
let got = parse_probe(old, Path::new("python.exe"), EnvSource::Registry).expect("parse");
assert!(got.markers.is_empty());
}
#[test]
fn the_probe_reads_metadata_once_per_distribution() {
// `dist.version` and `dist.requires` each re-parse METADATA; on the path every environment
// open pays, asking all three tripled the work. Measured on CPython 3.14 with 64
// distributions: 154 ms before, 118 ms after, the same document either way.
// On the code, not the words: the probe's own comment names both on purpose.
assert!(
PROBE_PY.contains(r#""version": meta.get("Version")"#),
"the version comes from the one parse"
);
assert!(
PROBE_PY.contains(r#"meta.get_all("Requires-Dist")"#),
"the requirements come from the one parse"
);
// And it does not reach for `platform`, whose uname() is a WMI query on Windows.
assert!(!PROBE_PY.contains("import platform"));
}
#[test]
fn the_probe_python_floor_matches_the_document() {
assert_eq!(MIN_PROBE_PYTHON, (3, 10));
+68 -7
View File
@@ -88,6 +88,14 @@ pub enum Code {
/// uv emitted a shape the adapter does not recognize (uv newer than PipDock).
#[serde(rename = "PD-ENG-003")]
EngUvShapeUnknown,
/// An engine command ran past its watchdog and was stopped.
///
/// **Raised by PipDock, never classified from stderr.** Its own code because the alternative
/// was `PD-INT-001`, which is what the shared watchdog reported until 1.4.0: an sdist build
/// still compiling after ten minutes is not "a PipDock bug", and in the batch phase that error
/// aborted the whole run — no summary, no per-package retry.
#[serde(rename = "PD-ENG-004")]
EngTimedOut,
/// Fallback for engine failures no classifier matched. Always last.
#[serde(rename = "PD-ENG-999")]
EngUnclassified,
@@ -233,6 +241,7 @@ impl Code {
Self::EngNotFound => "PD-ENG-001",
Self::EngPipTooOld => "PD-ENG-002",
Self::EngUvShapeUnknown => "PD-ENG-003",
Self::EngTimedOut => "PD-ENG-004",
Self::EngUnclassified => "PD-ENG-999",
Self::ResImpossible => "PD-RES-001",
Self::ResPlanStale => "PD-RES-002",
@@ -274,6 +283,7 @@ impl Code {
Self::EngNotFound
| Self::EngPipTooOld
| Self::EngUvShapeUnknown
| Self::EngTimedOut
| Self::EngUnclassified => Area::Eng,
Self::ResImpossible
| Self::ResPlanStale
@@ -310,6 +320,7 @@ impl Code {
Self::EngNotFound,
Self::EngPipTooOld,
Self::EngUvShapeUnknown,
Self::EngTimedOut,
Self::ResImpossible,
Self::ResPlanStale,
Self::ResPlanInFlight,
@@ -426,11 +437,26 @@ static CLASSIFIERS: &[Classifier] = &[
code: Code::BldWheelFailed,
all_of: &["failed building wheel"],
},
// -- network errors Windows raises as PermissionError -----------------------
// Ahead of the permission rules on purpose. A firewall or AV refusing a socket is
// `PermissionError: [WinError 10013]`, and "network path not found" is `[WinError 53]` — both
// were PD-PRM-001, "use a venv", which is advice about site-packages for a network problem.
Classifier {
code: Code::NetUnreachable,
all_of: &["[winerror 10013]"],
},
Classifier {
code: Code::NetUnreachable,
all_of: &["[winerror 53]"],
},
// -- permissions ---------------------------------------------------------
// Checked before the generic OSError shapes below, which share their prefix.
//
// **The closing bracket is part of every WinError needle.** Python prints `[WinError N]`, and
// without the bracket "winerror 5" also matched 50, 53 and 59 and "winerror 32" matched 321.
Classifier {
code: Code::PrmFileLocked,
all_of: &["winerror 32"],
all_of: &["[winerror 32]"],
},
Classifier {
code: Code::PrmSitePackagesReadOnly,
@@ -438,7 +464,7 @@ static CLASSIFIERS: &[Classifier] = &[
},
Classifier {
code: Code::PrmSitePackagesReadOnly,
all_of: &["winerror 5"],
all_of: &["[winerror 5]"],
},
// -- system --------------------------------------------------------------
Classifier {
@@ -447,7 +473,7 @@ static CLASSIFIERS: &[Classifier] = &[
},
Classifier {
code: Code::SysDiskFull,
all_of: &["winerror 112"],
all_of: &["[winerror 112]"],
},
Classifier {
code: Code::SysPathTooLong,
@@ -530,6 +556,12 @@ static CLASSIFIERS: &[Classifier] = &[
code: Code::EngPipTooOld,
all_of: &["no such option: --report"],
},
// The planner's argv puts `--dry-run` first, and optparse stops at the first option it does
// not know — so a pip below 22.2 says this, not the `--report` line above.
Classifier {
code: Code::EngPipTooOld,
all_of: &["no such option: --dry-run"],
},
Classifier {
code: Code::EngNotFound,
all_of: &["no module named pip"],
@@ -567,6 +599,15 @@ pub fn classify_stderr(stderr: &str) -> Code {
/// Lowercase and collapse every run of whitespace to a single space, so patterns survive the
/// engines' line wrapping and CRLF.
fn normalize(text: &str) -> String {
collapse_whitespace(text).to_lowercase()
}
/// Collapse every run of whitespace — wrapping, CRLF, indentation — to one space, and trim.
///
/// uv hard-wraps its diagnostics mid-sentence, so a literal search for a phrase that spans the
/// wrap point finds nothing. The classifiers above and the plan parser both need this, and had two
/// copies of it.
pub(crate) fn collapse_whitespace(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut in_space = false;
for ch in text.chars() {
@@ -577,7 +618,7 @@ fn normalize(text: &str) -> String {
out.push(' ');
}
in_space = false;
out.extend(ch.to_lowercase());
out.push(ch);
}
}
out
@@ -592,7 +633,7 @@ mod tests {
fn every_variant_is_listed_in_all() {
// `ALL` drives the fixture-coverage gate, so a variant missing from it would silently
// escape that gate. There is no derive for "enumerate variants", hence this count check.
assert_eq!(Code::ALL.len(), 34, "add the new variant to Code::ALL");
assert_eq!(Code::ALL.len(), 35, "add the new variant to Code::ALL");
}
#[test]
@@ -685,6 +726,26 @@ mod tests {
assert_eq!(classify_stderr(locked), Code::PrmFileLocked);
}
#[test]
fn a_winerror_number_matches_exactly_and_never_as_a_prefix() {
// "winerror 5" used to match `[WinError 53]` — a network path — and report it as a
// read-only site-packages.
let network_path = r"OSError: [WinError 53] The network path was not found: '\\srv\share'";
assert_eq!(classify_stderr(network_path), Code::NetUnreachable);
let denied = r"ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\Program Files\Python312\Lib\site-packages\x'";
assert_eq!(classify_stderr(denied), Code::PrmSitePackagesReadOnly);
// A firewall refusing the socket is a PermissionError by type and a network problem by
// meaning; the user-facing answer is the network one.
let socket = "PermissionError: [WinError 10013] An attempt was made to access a socket in \
a way forbidden by its access permissions";
assert_eq!(classify_stderr(socket), Code::NetUnreachable);
let not_locked = "OSError: [WinError 321] something else entirely";
assert_ne!(classify_stderr(not_locked), Code::PrmFileLocked);
}
#[test]
fn incidental_mentions_of_yanking_do_not_hijack_a_different_failure() {
// pip prefixes an unrelated resolution failure with "Ignored the following yanked
@@ -739,9 +800,9 @@ mod tests {
#[test]
fn every_documented_code_has_exactly_one_variant() {
// Rust has 33; docs/ERROR-CATALOG.md tabulates 30, because it folds PD-HLT-001..004 into
// Rust has 35; docs/ERROR-CATALOG.md tabulates 32, because it folds PD-HLT-001..004 into
// one row. Pin the number so the next person adding a code has to notice the docs exist.
assert_eq!(Code::ALL.len(), 34);
assert_eq!(Code::ALL.len(), 35);
let wire: HashSet<&str> = Code::ALL.iter().map(|c| c.as_str()).collect();
assert_eq!(
wire.len(),
+25
View File
@@ -20,6 +20,11 @@ pub struct PdError {
/// Tail of the engine's stderr, capped at the 40 lines `docs/ERROR-CATALOG.md` §3 shows.
#[serde(skip_serializing_if = "Option::is_none")]
pub stderr_tail: Option<String>,
/// Set when this error is a run that was **stopped** rather than one that failed: cancelled by
/// its token or killed by its watchdog. Never on the wire -- callers turn it into a skipped
/// step or their own timeout code before anything is shown.
#[serde(skip)]
pub stop: Option<crate::exec::Stop>,
}
impl PdError {
@@ -30,9 +35,29 @@ impl PdError {
code,
message: message.into(),
stderr_tail: None,
stop: None,
}
}
/// Record that the run behind this error was stopped, and why.
#[must_use]
pub const fn with_stop(mut self, stop: crate::exec::Stop) -> Self {
self.stop = Some(stop);
self
}
/// True when the run was stopped by its cancellation token.
#[must_use]
pub fn is_cancelled(&self) -> bool {
self.stop == Some(crate::exec::Stop::Cancelled)
}
/// True when the run was stopped by its watchdog.
#[must_use]
pub const fn is_timeout(&self) -> bool {
matches!(self.stop, Some(crate::exec::Stop::TimedOut(_)))
}
/// Attach an engine stderr tail, truncated to the last `MAX_STDERR_TAIL_LINES` lines.
#[must_use]
pub fn with_stderr(mut self, stderr: impl AsRef<str>) -> Self {
+408 -105
View File
@@ -17,16 +17,52 @@ use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::io::{AsyncBufReadExt, AsyncRead, BufReader};
use tokio::process::Command as TokioCommand;
use tokio_util::sync::CancellationToken;
use crate::engine::{ProgressEvent, ProgressSink, Stream};
use crate::engine::{EventSink, ProgressEvent, ProgressSink, Stream};
use crate::errors::{Code, PdError, Result};
use crate::model::{ExecMode, PkgName};
/// Default watchdog. Long resolves on a big environment are normal; hangs are not.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(600);
/// Default watchdog, for anything that does not name its own in [`watchdog`].
pub const DEFAULT_TIMEOUT: Duration = watchdog::RESOLVE;
/// Watchdogs by kind of work.
///
/// One 600 s budget used to cover everything, which was wrong in both directions: a hung `py -0p`
/// held the Environments screen for ten minutes, and a source build of scipy -- legitimately slow
/// -- was killed at the same ten. A watchdog is a unit, not a number (CLAUDE.md, from P1-1): each
/// constant here is sized for one kind of operation.
pub mod watchdog {
use std::time::Duration;
/// `pip install` / `uv pip install` / uninstall. Building an sdist can take many minutes.
pub const INSTALL: Duration = Duration::from_secs(30 * 60);
/// A dry-run resolve, including pip's backtracking on a large environment.
pub const RESOLVE: Duration = Duration::from_secs(10 * 60);
/// `list --outdated`, which makes one index request per installed package.
pub const OUTDATED: Duration = Duration::from_secs(10 * 60);
/// Local queries: `list`, `freeze`, `check`, `--version`.
pub const QUERY: Duration = Duration::from_secs(3 * 60);
/// `probe.py` against one interpreter. It reads metadata files and nothing else.
pub const PROBE: Duration = Duration::from_secs(60);
/// Discovery listings: `py -0p`, `uv python list`.
pub const DISCOVERY: Duration = Duration::from_secs(30);
}
/// Why a run ended before its program did.
///
/// Carried on the [`PdError`] such a run returns ([`PdError::stop`]), so a caller asks a typed
/// question. Three modules used to read the *message* back instead -- `"cancelled:"`, `"timed
/// out"` -- each with its own copy of the prefixes `Command::stopped` happened to write.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stop {
/// The command's [`CancellationToken`] was tripped.
Cancelled,
/// The watchdog fired after this long.
TimedOut(Duration),
}
/// Wait for cancellation, or never, when no token was supplied.
///
@@ -78,6 +114,9 @@ pub struct Command {
env: HashMap<String, String>,
timeout: Duration,
cancel: Option<CancellationToken>,
/// The program is a Python interpreter, so "not found" means the environment is gone
/// (`PD-ENV-001`) rather than that an engine needs installing (`PD-ENG-001`).
interpreter: bool,
}
impl Command {
@@ -91,6 +130,7 @@ impl Command {
env: HashMap::new(),
timeout: DEFAULT_TIMEOUT,
cancel: None,
interpreter: false,
}
}
@@ -99,9 +139,27 @@ impl Command {
/// Use this for **every** `python -m pip …` and `probe.py` call. `PYTHONUTF8=1` covers the
/// interpreter's own text handling and `PYTHONIOENCODING=utf-8` covers the stdio streams pip's
/// vendored `rich` writes through.
///
/// **Not enough on its own for a `-I` run.** Isolated mode implies `-E`, which ignores every
/// `PYTHON*` variable, so `probe.py` must also pass `-X utf8` (see `envs::probe`).
#[must_use]
pub fn python(interpreter: impl Into<PathBuf>) -> Self {
Self::new(interpreter)
let mut cmd = Self::new(interpreter)
.env("PYTHONIOENCODING", "utf-8")
.env("PYTHONUTF8", "1");
cmd.interpreter = true;
cmd
}
/// Invoke a Python **console script** -- vulture, deptry, pip-audit -- with the same mitigation.
///
/// Their `.exe` is a launcher for the tools venv's interpreter, so the variables reach Python
/// exactly as they do for [`Command::python`]. Spawned with [`Command::new`] they were missing:
/// a non-ASCII file name in the user's project could crash vulture's report on cp1252 and read
/// as PD-HLT-002, "the tool stopped with an error".
#[must_use]
pub fn python_tool(exe: impl Into<PathBuf>) -> Self {
Self::new(exe)
.env("PYTHONIOENCODING", "utf-8")
.env("PYTHONUTF8", "1")
}
@@ -156,11 +214,41 @@ impl Command {
}
/// Why a run ended early. Both arms kill the child on the way out.
fn stopped(&self, reason: &str) -> PdError {
PdError::new(
Code::IntUnexpected,
format!("{reason}: {}", self.program.display()),
)
///
/// The message keeps its old wording for the log, but nothing may read it: the typed answer is
/// [`PdError::stop`]. A cancellation keeps `PD-INT-001` because it is never meant to reach a
/// user -- every caller turns a cancelled step into a *skipped* one -- while a timeout is
/// `PD-ENG-004`, which callers on other paths (Code Health, the audit) remap to their own code.
fn stopped(&self, stop: Stop) -> PdError {
tracing::warn!(target: "pipdock::exec", program = %self.program.display(), ?stop, "stopped");
let program = self.program.display();
match stop {
Stop::Cancelled => PdError::new(Code::IntUnexpected, format!("cancelled: {program}")),
Stop::TimedOut(after) => PdError::new(
Code::EngTimedOut,
format!("timed out after {after:?}: {program}"),
),
}
.with_stop(stop)
}
/// Map a failure to *start* the program onto the code whose advice fits.
///
/// Everything used to be `PD-ENG-001`, "install the engine": for a deleted venv's
/// `python.exe` that should be `PD-ENV-001`, and for a command line past Windows' 32,767
/// characters (`ERROR_FILENAME_EXCED_RANGE`, 206) it is a path-length problem.
fn spawn_error(&self, e: &std::io::Error) -> PdError {
const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
let program = self.program.display();
let code = if e.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE) {
Code::SysPathTooLong
} else if e.kind() == std::io::ErrorKind::NotFound && self.interpreter {
Code::EnvInterpreterMissing
} else {
Code::EngNotFound
};
tracing::warn!(target: "pipdock::exec", %program, error = %e, "could not start");
PdError::new(code, format!("could not run {program}: {e}"))
}
/// The argv this command would run, for logging and for the bug-report ring buffer.
@@ -201,34 +289,31 @@ impl Command {
/// Run to completion, capturing output. See [`TreeGuard`] for what "stop" means here.
///
/// # Errors
/// `PD-ENG-001` when the program cannot be spawned, `PD-INT-001` when the watchdog fires.
/// `PD-ENG-001` when the program cannot be spawned, `PD-ENG-004` when the watchdog fires.
pub async fn run(&self) -> Result<Output> {
let started = self.logged_start();
// Spawned rather than `.output()`ed, so the child can be put in a job before it is waited
// on. `.output()` owns the child and never lends out a handle.
let child = self.build().spawn().map_err(|e| {
PdError::new(
Code::EngNotFound,
format!("could not run {}: {e}", self.program.display()),
)
})?;
let child = self.build().spawn().map_err(|e| self.spawn_error(&e))?;
let tree = TreeGuard::attach(&child);
let out = tokio::select! {
out = child.wait_with_output() => out,
() = tokio::time::sleep(self.timeout) => {
return Err(self.stopped(&format!("timed out after {:?}", self.timeout)));
return Err(self.stopped(Stop::TimedOut(self.timeout)));
}
() = cancelled(self.cancel.as_ref()) => {
return Err(self.stopped("cancelled"));
return Err(self.stopped(Stop::Cancelled));
}
};
drop(tree);
let out = out.map_err(|e| {
PdError::new(
Code::EngNotFound,
format!("could not run {}: {e}", self.program.display()),
Code::IntUnexpected,
format!("waiting on {} failed: {e}", self.program.display()),
)
})?;
self.logged_exit(started, out.status.code());
Ok(Output {
code: out.status.code(),
stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
@@ -236,6 +321,22 @@ impl Command {
})
}
/// The argv, at INFO: what PipDock ran is the first thing a bug report needs.
fn logged_start(&self) -> std::time::Instant {
tracing::info!(target: "pipdock::exec", argv = ?self.argv(), "spawn");
std::time::Instant::now()
}
fn logged_exit(&self, started: std::time::Instant, code: Option<i32>) {
tracing::info!(
target: "pipdock::exec",
program = %self.program.display(),
?code,
ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
"exited"
);
}
/// Run while streaming each output line to `sink`, for the live console drawer.
///
/// Output is still captured and returned, because the parsers need the whole document and the
@@ -252,84 +353,45 @@ impl Command {
// The step index comes from the caller's sink rather than a parameter: an adapter cannot
// know its own position in the plan, which is why every call site used to pass 0.
let step = sink.step;
let mut child = self.build().spawn().map_err(|e| {
PdError::new(
Code::EngNotFound,
format!("could not run {}: {e}", self.program.display()),
)
})?;
let started = self.logged_start();
let mut child = self.build().spawn().map_err(|e| self.spawn_error(&e))?;
// Held until this function returns. Dropping it — which the timeout and cancel arms below
// do by returning — terminates the whole tree, not just `child`.
let _tree = TreeGuard::attach(&child);
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let pump = |reader: Option<tokio::process::ChildStdout>| {
let sink = sink.tx.clone();
let pkg = pkg.clone();
async move {
let mut buf = String::new();
if let Some(r) = reader {
let mut lines = BufReader::new(r).lines();
while let Ok(Some(line)) = lines.next_line().await {
// Send failure means the UI stopped listening; keep capturing regardless
// so the summary and the log are still complete.
let _ = sink.send(ProgressEvent::Line {
step,
pkg: pkg.clone(),
phase,
stream: Stream::Stdout,
line: line.clone(),
});
buf.push_str(&line);
buf.push('\n');
}
}
buf
}
};
let pump_err = |reader: Option<tokio::process::ChildStderr>| {
let sink = sink.tx.clone();
let pkg = pkg.clone();
async move {
let mut buf = String::new();
if let Some(r) = reader {
let mut lines = BufReader::new(r).lines();
while let Ok(Some(line)) = lines.next_line().await {
let _ = sink.send(ProgressEvent::Line {
step,
pkg: pkg.clone(),
phase,
stream: Stream::Stderr,
line: line.clone(),
});
buf.push_str(&line);
buf.push('\n');
}
}
buf
}
let tag = |stream| LineTag {
tx: sink.tx.clone(),
step,
pkg: pkg.clone(),
phase,
stream,
};
let run = async {
let (out, err, status) = tokio::join!(pump(stdout), pump_err(stderr), child.wait());
let (out, err, status) = tokio::join!(
pump(stdout, tag(Stream::Stdout)),
pump(stderr, tag(Stream::Stderr)),
child.wait()
);
(out, err, status)
};
let (stdout, stderr, status) = tokio::select! {
triple = run => triple,
() = tokio::time::sleep(self.timeout) => {
return Err(self.stopped(&format!("timed out after {:?}", self.timeout)));
return Err(self.stopped(Stop::TimedOut(self.timeout)));
}
() = cancelled(self.cancel.as_ref()) => {
return Err(self.stopped("cancelled"));
return Err(self.stopped(Stop::Cancelled));
}
};
let status = status.map_err(|e| {
PdError::new(Code::IntUnexpected, format!("waiting on child failed: {e}"))
})?;
self.logged_exit(started, status.code());
Ok(Output {
code: status.code(),
@@ -339,6 +401,55 @@ impl Command {
}
}
/// Where one stream's lines are sent, and what each is tagged with.
struct LineTag {
tx: EventSink,
step: usize,
pkg: Option<PkgName>,
phase: ExecMode,
stream: Stream,
}
/// Read one stream to its end, forwarding each line to the drawer, and return it whole.
///
/// **Bytes, decoded lossily -- never `lines()`.** tokio's `Lines` returns an error at the first
/// byte that is not UTF-8, and the loop this replaced treated that as end of stream: it stopped
/// reading and dropped the pipe, so the child died on a broken pipe mid-install and the stderr the
/// classifier needed was cut off at that point. MSVC writes its diagnostics in the OEM code page,
/// so a non-English Windows was one failed source build away from it.
async fn pump<R: AsyncRead + Unpin>(reader: Option<R>, tag: LineTag) -> String {
let mut buf = String::new();
let Some(reader) = reader else {
return buf;
};
let mut reader = BufReader::new(reader);
let mut raw = Vec::new();
loop {
raw.clear();
match reader.read_until(b'\n', &mut raw).await {
Ok(0) | Err(_) => break,
Ok(_) => {}
}
let text = String::from_utf8_lossy(&raw);
let line = text.trim_end_matches(['\n', '\r']);
// The engine's own words, at DEBUG: everything a run printed is in the log when asked for
// (`PIPDOCK_LOG=debug`, `--verbose`), and a default log stays readable.
tracing::debug!(target: "pipdock::engine", stream = ?tag.stream, "{line}");
// Send failure means the UI stopped listening; keep capturing regardless so the summary
// and the log are still complete.
let _ = tag.tx.send(ProgressEvent::Line {
step: tag.step,
pkg: tag.pkg.clone(),
phase: tag.phase,
stream: tag.stream,
line: line.to_owned(),
});
buf.push_str(line);
buf.push('\n');
}
buf
}
/// Kills a spawned command **and everything it spawned** when dropped.
///
/// `kill_on_drop` reaches the direct child only, and for an engine that is not enough:
@@ -387,29 +498,125 @@ impl TreeGuard {
}
}
/// Write `contents` to a uniquely named temp file and return its path.
/// A file in the temp directory that is deleted when this is dropped.
///
/// SECURITY §2: `probe.py` is written with a random name per invocation and never installed into
/// the environment. The caller removes it; a leaked file in the temp directory is harmless, an
/// overwritten one would not be.
///
/// # Errors
/// `PD-SYS-002` when the file cannot be written.
pub fn write_temp(prefix: &str, extension: &str, contents: &str) -> Result<PathBuf> {
use std::hash::{BuildHasher as _, RandomState};
/// SECURITY §2: what PipDock hands an interpreter or an engine -- `probe.py`, a requirements file,
/// a freeze for pip-audit -- is written under a fresh random name and never installed anywhere.
/// The name is created with `create_new`, so an existing file is never written through: a leaked
/// temp file is harmless, an overwritten one would not be. (The function this replaced documented
/// that rule and then called `fs::write`, which overwrites.)
#[derive(Debug)]
pub struct TempFile {
path: PathBuf,
}
let dir = std::env::temp_dir();
// RandomState is seeded by the OS per process; hashing a fresh allocation's address plus a
// counter gives a unique-enough name without pulling in a rand dependency.
let nonce = RandomState::new().hash_one(std::time::Instant::now().elapsed().as_nanos());
let path = dir.join(format!("{prefix}-{nonce:016x}.{extension}"));
std::fs::write(&path, contents).map_err(|e| {
PdError::new(
Code::SysDiskFull,
format!("could not write {}: {e}", path.display()),
)
})?;
Ok(path)
impl TempFile {
/// Write `contents` to a new, uniquely named file.
///
/// # Errors
/// `PD-SYS-002` when the temp directory is full, `PD-SYS-001` for a path Windows refuses as too
/// long, `PD-PRM-001` when it is not writable, `PD-INT-001` otherwise.
pub fn create(prefix: &str, extension: &str, contents: &str) -> Result<Self> {
use std::io::Write as _;
let dir = std::env::temp_dir();
let mut last = None;
// A collision needs the same 64-bit nonce twice; the retry is for that theoretical case
// and for a planted file, which `create_new` refuses rather than writes through.
for _ in 0..8 {
let path = dir.join(format!("{prefix}-{:016x}.{extension}", nonce()));
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(mut file) => {
return match file.write_all(contents.as_bytes()) {
Ok(()) => Ok(Self { path }),
Err(e) => {
drop(file);
let _ = std::fs::remove_file(&path);
Err(io_error(&path, &e))
}
};
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => last = Some(e),
Err(e) => return Err(io_error(&path, &e)),
}
}
Err(PdError::new(
Code::IntUnexpected,
format!(
"could not create a unique temp file in {}: {}",
dir.display(),
last.map(|e| e.to_string()).unwrap_or_default()
),
))
}
/// Where the file is.
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempFile {
fn drop(&mut self) {
// Best effort: a file the OS still holds open (an antivirus scan, say) stays behind,
// which is untidy and harmless.
let _ = std::fs::remove_file(&self.path);
}
}
/// A per-call nonce: the process id, a process-wide counter and the clock, hashed with a
/// `RandomState` (randomly keyed per process). Unique without a `rand` dependency.
fn nonce() -> u64 {
use std::hash::{BuildHasher as _, RandomState};
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let count = COUNTER.fetch_add(1, Ordering::Relaxed);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
RandomState::new().hash_one((std::process::id(), count, now))
}
/// Map a filesystem failure onto the catalog code whose advice fits it.
///
/// Shared so the shell stops answering every read or write failure with "not enough free disk
/// space" (`PD-SYS-002`), which it did for permission errors and missing files alike.
#[must_use]
pub fn io_error(path: &Path, e: &std::io::Error) -> PdError {
const ERROR_DISK_FULL: i32 = 112;
const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
let code = match (e.raw_os_error(), e.kind()) {
(Some(ERROR_DISK_FULL), _) | (_, std::io::ErrorKind::StorageFull) => Code::SysDiskFull,
(Some(ERROR_FILENAME_EXCED_RANGE), _) => Code::SysPathTooLong,
(_, std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::ReadOnlyFilesystem) => {
Code::PrmSitePackagesReadOnly
}
_ => Code::IntUnexpected,
};
PdError::new(code, format!("{}: {e}", path.display()))
}
/// [`io_error`] for a file **the user chose** — an export, a saved report, a requirements file —
/// where "PipDock is not allowed to write to this environment" (`PD-PRM-001`) would be the wrong
/// advice. The shell answered every such failure with `PD-SYS-002`, "not enough free disk space",
/// for a read-only folder and a missing file alike (U25).
#[must_use]
pub fn user_file_error(path: &Path, e: &std::io::Error) -> PdError {
const ERROR_SHARING_VIOLATION: i32 = 32;
let code = match (e.raw_os_error(), e.kind()) {
(Some(ERROR_SHARING_VIOLATION), _) => Code::PrmFileLocked,
(_, std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::ReadOnlyFilesystem) => {
Code::PrmSourceReadOnly
}
_ => return io_error(path, e),
};
PdError::new(code, format!("{}: {e}", path.display()))
}
/// Canonicalize an interpreter path for identity purposes.
@@ -699,8 +906,63 @@ mod tests {
// does not become the only one.
let cmd = a_slow_command().timeout(Duration::from_millis(300));
let err = cmd.run().await.expect_err("must time out");
assert_eq!(err.code, Code::IntUnexpected);
assert!(err.message.contains("timed out"), "{}", err.message);
// An engine timeout, not "PipDock hit an internal error" — and said in the type, so no
// caller has to read the message to know.
assert_eq!(err.code, Code::EngTimedOut);
assert!(err.is_timeout(), "{err:?}");
assert!(!err.is_cancelled());
}
#[tokio::test]
async fn a_cancelled_run_says_so_in_its_type() {
let token = CancellationToken::new();
let cmd = a_slow_command().cancel(token.clone());
let handle = tokio::spawn(async move { cmd.run().await });
tokio::time::sleep(Duration::from_millis(200)).await;
token.cancel();
let err = handle
.await
.expect("task joins")
.expect_err("a cancelled run must not report success");
assert!(err.is_cancelled(), "{err:?}");
assert!(!err.is_timeout());
}
#[cfg(windows)]
#[tokio::test]
async fn the_pump_reads_past_bytes_that_are_not_utf8() {
// The bug: tokio's `lines()` errors at the first non-UTF-8 byte, the old loop took that as
// end of stream and dropped the pipe — so everything after it was lost, and a real child
// would die writing to a closed pipe. MSVC prints in the OEM code page, so this is a
// source build on a non-English Windows. `type` writes the bytes back verbatim.
let file = TempFile::create("pd-test-bytes", "txt", "").expect("temp file");
std::fs::write(
file.path(),
b"before\r\nL\xf6sung \xe0 \x81\x8d broken\r\nafter the bad line\r\n",
)
.expect("write raw bytes");
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let sink = ProgressSink::new(tx, 1, CancellationToken::new());
let out = Command::new("cmd")
.args(["/C", "type", &file.path().display().to_string()])
.run_streaming(&sink, None, ExecMode::Batch)
.await
.expect("the command runs");
drop(sink);
assert!(
out.stdout.contains("after the bad line"),
"output after the invalid bytes was lost: {:?}",
out.stdout
);
let mut lines = 0;
while let Some(event) = rx.recv().await {
if matches!(event, ProgressEvent::Line { .. }) {
lines += 1;
}
}
assert_eq!(lines, 3, "every line reaches the drawer, lossily decoded");
}
#[tokio::test]
@@ -726,13 +988,54 @@ mod tests {
assert_eq!(err.code, Code::EngNotFound);
}
#[tokio::test]
async fn a_missing_interpreter_is_an_environment_error() {
// A deleted venv's python.exe used to be PD-ENG-001, "install the engine". The engine is
// fine; the environment is gone.
let err = Command::python(r"C:\pipdock\no\such\venv\Scripts\python.exe")
.arg("--version")
.run()
.await
.expect_err("missing interpreter must fail");
assert_eq!(err.code, Code::EnvInterpreterMissing);
}
#[test]
fn temp_files_get_unique_names() {
let a = write_temp("pd-test", "txt", "a").expect("write");
let b = write_temp("pd-test", "txt", "b").expect("write");
assert_ne!(a, b, "two probe writes must not collide");
let _ = std::fs::remove_file(a);
let _ = std::fs::remove_file(b);
fn temp_files_get_unique_names_and_go_away_on_drop() {
let a = TempFile::create("pd-test", "txt", "a").expect("write");
let b = TempFile::create("pd-test", "txt", "b").expect("write");
assert_ne!(a.path(), b.path(), "two probe writes must not collide");
assert_eq!(std::fs::read_to_string(a.path()).expect("read"), "a");
let (pa, pb) = (a.path().to_path_buf(), b.path().to_path_buf());
drop(a);
drop(b);
assert!(
!pa.exists() && !pb.exists(),
"dropping a TempFile removes it"
);
}
#[test]
fn filesystem_failures_carry_the_code_whose_advice_fits() {
use std::io::{Error, ErrorKind};
let p = Path::new(r"C:\x");
assert_eq!(
io_error(p, &Error::from_raw_os_error(112)).code,
Code::SysDiskFull
);
assert_eq!(
io_error(p, &Error::from_raw_os_error(206)).code,
Code::SysPathTooLong
);
assert_eq!(
io_error(p, &Error::from(ErrorKind::PermissionDenied)).code,
Code::PrmSitePackagesReadOnly
);
// A missing file is not "the disk is full", which every shell command used to say.
assert_eq!(
io_error(p, &Error::from(ErrorKind::NotFound)).code,
Code::IntUnexpected
);
}
#[test]
+79 -1
View File
@@ -150,13 +150,74 @@ fn flow_step() -> crate::flow::FlowStep {
explanation: "no version of oldlib is compatible with python 3.12".to_owned(),
packages: vec![pkg("oldlib")],
}),
incompatible: Vec::new(),
forced: Vec::new(),
yanked: Vec::new(),
raw: String::new(),
declared_python: Default::default(),
},
round: 0,
rounds_remaining: 3,
}
}
/// What `plan_resolve` returns once the first fixture's question is answered with *Force latest*
/// for `numpy`: a plan ready to confirm that breaks the two packages which held it back.
///
/// **Computed, not written**, by the functions the flow itself calls. `forced` is
/// [`crate::plan::derive_forced`] over this scenario's rows, so the preview's "Will break" section
/// is tested against the blockers the application would actually show; `incompatible` is
/// [`crate::release::mismatch`], the screen hard invariant 10 is enforced by. Only `yanked` is
/// written out — it is a parse of engine output, with no rule of its own to drift from.
///
/// A fixture of its own rather than more rows in [`flow_step`]: a package cannot be both held back
/// pending a decision and already forced, and a scenario that says both proves nothing.
fn flow_step_forced() -> crate::flow::FlowStep {
use crate::engine::parse::YankWarning;
use crate::plan::{Change, ChangeKind, ResolutionReport};
let pkg = |n: &str| PkgName::parse(n).unwrap_or_else(|e| panic!("fixture name {n:?}: {e:?}"));
let numpy = pkg("numpy");
let mut report = ResolutionReport {
changes: vec![
Change {
name: numpy.clone(),
from: Some(Version("1.26.4".to_owned())),
to: Version("2.5.1".to_owned()),
kind: ChangeKind::Upgrade,
},
Change {
name: pkg("oldlib"),
from: None,
to: Version("2.0.0".to_owned()),
kind: ChangeKind::NewInstall,
},
],
held_back: Vec::new(),
impossible: None,
// numba 0.58's real range: it was the release that did not yet support 3.12.
incompatible: crate::release::mismatch(
&pkg("numba"),
&Version("0.58.1".to_owned()),
Some(">=3.8,<3.12"),
"3.12.4",
)
.into_iter()
.collect(),
forced: Vec::new(),
yanked: vec![YankWarning {
pkg: pkg("oldlib"),
version: Version("2.0.0".to_owned()),
reason: Some("declares the wrong Requires-Python".to_owned()),
}],
raw: String::new(),
declared_python: Default::default(),
};
let graph = crate::graph::ReverseDeps::build_for(&pkg_list(), "3.12.4");
crate::plan::derive_forced(&mut report, &[numpy], &pkg_outdated(), &graph);
crate::flow::FlowStep::NeedsConfirm { report }
}
/// What `plan_execute` returns after a run that was stopped part-way.
///
/// The cancelled case on purpose: it is the one DATA-FLOW §6 does not work through, the one whose
@@ -190,6 +251,7 @@ fn execution_summary() -> crate::plan::ExecutionSummary {
results,
check: CheckReport {
ok: true,
error: None,
findings: Vec::new(),
},
counts,
@@ -229,6 +291,20 @@ fn guard_report() -> crate::graph::GuardReport {
])
}
/// What `deps_graph` returns for the same scenario — PRD P1-6.
///
/// **Computed, not written**, for [`guard_report`]'s reason and with [`numpy_blockers`]'s lesson
/// behind it. Hand-writing this map would let the graph's rules — marker evaluation, the
/// extra-only exclusion, the dedup, the split between a dependency and an unsatisfied requirement
/// — drift away from what `PdDepsFocus` is tested against, and the drift would be invisible
/// because the test would still assert something plausible.
///
/// The SP-5 tangle is the right set for it: `numpy` has two dependents declaring two different
/// specifiers, which is the case both columns exist to show.
fn deps_graph() -> crate::graph::DepsGraph {
crate::graph::ReverseDeps::build_for(&pkg_list(), "3.12.4").view()
}
/// What `snapshot_list` returns: one of each trigger, newest first.
///
/// All three on purpose. A `Rollback` entry *restoring* the `Plan` entry above it is the shape
@@ -369,7 +445,7 @@ fn health_report() -> crate::health::HealthReport {
ran_at: "2026-08-13T09:00:00Z".to_owned(),
tool_versions: [
("deptry".to_owned(), "0.25.1".to_owned()),
("ruff".to_owned(), "0.16.3".to_owned()),
("ruff".to_owned(), "0.17.1".to_owned()),
("vulture".to_owned(), "2.16".to_owned()),
]
.into_iter()
@@ -573,8 +649,10 @@ pub fn ipc_fixtures() -> serde_json::Result<Vec<(&'static str, String)>> {
("pkg_outdated.json", render(&pkg_outdated())?),
("pin_list.json", render(&pin_list())?),
("flow_step.json", render(&flow_step())?),
("flow_step_forced.json", render(&flow_step_forced())?),
("execution_summary.json", render(&execution_summary())?),
("guard_report.json", render(&guard_report())?),
("deps_graph.json", render(&deps_graph())?),
("snapshot_list.json", render(&snapshot_list())?),
("rollback_preview.json", render(&rollback_preview())?),
("health_report.json", render(&health_report())?),
+559 -81
View File
@@ -35,13 +35,15 @@
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::sync::Arc;
use crate::engine::{Engine, EventSink, ProgressSink};
use crate::engine::{Engine, EventSink, ProgressSink, SystemPackages};
use crate::errors::{Code, PdError, Result};
use crate::graph::ReverseDeps;
use crate::model::{Dist, OutdatedDist, PkgName, PyEnv, Spec};
use crate::model::{Dist, EngineId, OutdatedDist, PinnedSpec, PkgName, PyEnv, Spec, Version};
use crate::pins::{self, Pin};
use crate::plan::{self, Decision, PlanRequest, ResolutionReport, Strategy};
use crate::plan::{self, Decision, PlanRequest, PythonMismatch, ResolutionReport, Strategy};
use crate::release::{ReleaseMeta, mismatch, requires_python_of};
use crate::snapshot::{self, Snapshot, SnapshotProof};
use tokio_util::sync::CancellationToken;
@@ -88,6 +90,8 @@ pub enum NothingReason {
NothingToDo,
/// Every candidate was skipped while resolving conflicts, so no plan remains.
EverythingSkipped,
/// The user stopped the resolve before it finished. Nothing was planned, nothing ran.
Cancelled,
}
/// What the flow needs next.
@@ -134,6 +138,73 @@ pub enum FlowStep {
},
}
/// What the caller decides about a flow before it starts.
#[derive(Debug, Clone)]
pub struct FlowOptions {
/// Stops the flow: its resolve rounds and its execution.
///
/// **The caller's, not one the flow makes for itself.** The first resolve runs inside
/// `start`, and a token made there could only be handed out once `start` returned — after the
/// resolve it was needed to stop. The GUI registered a token of its own for that window that
/// nothing listened to, so *Stop* during a first resolve did nothing at all (H13).
pub cancel: CancellationToken,
/// What time it is. A function so a test can age a preview without waiting ten minutes.
pub clock: fn() -> jiff::Timestamp,
/// The Settings PEP 668 override, as the caller read it (SECURITY §3).
///
/// Read by nothing until 1.4.0: the checkbox saved, and every flow refused a managed
/// environment regardless (H11). On its own it still changes nothing — the flag is passed only
/// when this is on **and** the probe finds the marker.
pub allow_externally_managed: bool,
/// Where `Requires-Python` of a release comes from when the engine does not say — uv's plan,
/// and any exact pin before it reaches an engine (hard invariant 10). `None` checks only what
/// the engine itself reported.
pub releases: Option<Arc<dyn ReleaseMeta>>,
}
impl Default for FlowOptions {
fn default() -> Self {
Self {
cancel: CancellationToken::new(),
clock: jiff::Timestamp::now,
allow_externally_managed: false,
releases: None,
}
}
}
/// DATA-FLOW §2's step zero, shared by every mutating flow: probe, then decide on what the probe
/// says (SECURITY §3).
///
/// The gate read `env.externally_managed` — whatever the caller last cached about the environment —
/// before anything had been probed, and the rollback flow had no gate at all (H12). Now each flow
/// probes first and the fresh answer decides; the Settings override is the only way past, and with
/// it the flow carries [`SystemPackages::OverrideAllowed`] to every mutating engine call.
///
/// # Errors
/// `PD-ENV-002` for a managed environment without the override, or with a pip that cannot be
/// overridden; otherwise the probe's own failures.
async fn preamble(
engine: &dyn Engine,
env: &mut PyEnv,
opts: &FlowOptions,
) -> Result<(crate::envs::ProbeResult, SystemPackages)> {
let probed = engine.probe(env).await?;
env.externally_managed = probed.env.externally_managed;
if !env.externally_managed {
return Ok((probed, SystemPackages::Protected));
}
if !opts.allow_externally_managed {
return Err(PdError::new(
Code::EnvExternallyManaged,
"this Python is externally managed (PEP 668). Use a virtual environment; \
the override lives in Settings and is discouraged",
));
}
let system = crate::engine::system_packages_for(&engine.info(env).await)?;
Ok((probed, system))
}
/// Whether to take the pre-execution snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SnapshotPolicy {
@@ -156,8 +227,12 @@ pub struct UpdateFlow {
env: PyEnv,
engine: Box<dyn Engine>,
env_hash: String,
/// The installed set at resolve time; also what `AcceptedPlan` fingerprints against.
/// The installed set the preview was resolved over — the drift basis (DATA-FLOW §9.3).
installed: Vec<Dist>,
/// When the current preview was resolved — the age basis.
resolved_at: jiff::Timestamp,
/// The environment as re-probed at confirm time, which is what execution acts on.
confirmed: Vec<Dist>,
graph: ReverseDeps,
outdated: Vec<OutdatedDist>,
req: PlanRequest,
@@ -167,7 +242,17 @@ pub struct UpdateFlow {
snapshot: SnapshotState,
/// Pinned packages kept out of this plan, so the caller can say which and why.
excluded_pins: Vec<Pin>,
/// Whether the PEP 668 override applies to this flow's engine calls.
system: SystemPackages,
/// See [`FlowOptions::releases`].
releases: Option<Arc<dyn ReleaseMeta>>,
/// Pins left out because this environment's Python cannot install them — every report this
/// flow produces says so (`PD-PKG-001`).
left_out: Vec<PythonMismatch>,
/// `Hold` pins, restated at their version in every resolve (PRD P0-7, H17).
holds: Vec<PinnedSpec>,
cancel: CancellationToken,
clock: fn() -> jiff::Timestamp,
}
impl UpdateFlow {
@@ -180,38 +265,41 @@ impl UpdateFlow {
/// into a database at all — it can be driven in a test without one.
///
/// # Errors
/// `PD-ENV-002` when the environment is externally managed (PEP 668), which is checked before
/// any engine command runs. Otherwise propagates probe and engine failures.
/// `PD-ENV-002` when the environment is externally managed (PEP 668) and the override is off,
/// decided on a fresh probe before any engine command runs. Otherwise propagates probe and
/// engine failures.
pub async fn start(
env: PyEnv,
mut env: PyEnv,
engine: Box<dyn Engine>,
intent: &Intent,
pins: &[Pin],
opts: FlowOptions,
) -> Result<(Self, FlowStep)> {
let env_hash = crate::envs::env_hash(&env.interpreter);
// DATA-FLOW §2: PEP 668 environments are blocked at step zero, before any engine command.
if env.externally_managed {
return Err(PdError::new(
Code::EnvExternallyManaged,
"this Python is externally managed (PEP 668). Use a virtual environment; \
the override lives in Settings and is discouraged",
));
}
let probed = crate::envs::probe(&env.interpreter, env.source).await?;
let (probed, system) = preamble(engine.as_ref(), &mut env, &opts).await?;
// Built against this interpreter so marker-gated requirements are read correctly: without
// it a `python_version < "3.11"` branch is reported as a blocker on 3.12 (SP-5 dogfood).
let graph = ReverseDeps::build_for(&probed.dists, &probed.env.python_version);
let outdated = engine.list_outdated(&env).await?;
let graph = ReverseDeps::for_probe(&probed);
// `list --outdated` asks the index about every installed package — tens of seconds on a
// large environment — and an install uses none of it (M28).
let outdated = match intent {
Intent::Update { .. } => engine.list_outdated(&env).await?,
Intent::Install { .. } => Vec::new(),
};
let (req, excluded_pins) = build_request(intent, &outdated, pins)?;
let plan_id = format!("update-{env_hash:.8}");
// Unique per plan: the snapshot's trigger and the summary carry it, and "update-<env>"
// alone named every plan ever made for one environment the same.
let plan_id = format!("update-{env_hash:.8}-{}", (opts.clock)().as_millisecond());
let mut flow = Self {
env,
engine,
env_hash,
installed: probed.dists,
resolved_at: (opts.clock)(),
confirmed: Vec::new(),
graph,
outdated,
req,
@@ -220,10 +308,20 @@ impl UpdateFlow {
plan_id,
snapshot: SnapshotState::NotTaken,
excluded_pins,
cancel: CancellationToken::new(),
system,
releases: opts.releases,
left_out: Vec::new(),
holds: pins::hold_requirements(pins),
cancel: opts.cancel,
clock: opts.clock,
};
flow.screen_exact_pins().await;
if flow.req.upgrades.is_empty() && flow.req.installs.is_empty() {
// Everything asked for needs a different Python: say that, not "nothing to do".
if let Some(m) = flow.left_out.first() {
return Err(python_refusal(m));
}
return Ok((
flow,
FlowStep::Nothing {
@@ -250,6 +348,7 @@ impl UpdateFlow {
});
}
let before = (self.req.clone(), self.round);
self.req = plan::apply_decisions(&self.req, decisions);
self.round = self.round.saturating_add(1);
@@ -259,14 +358,122 @@ impl UpdateFlow {
});
}
self.resolve().await
// A failed re-resolve leaves the flow exactly as it was: the preview on screen still
// describes it, and can be decided again or confirmed (U24). It used to keep the new
// request beside the old report, which no longer described each other.
let step = self.resolve().await;
if step.is_err() {
(self.req, self.round) = before;
}
step
}
/// Resolve the current request and classify what the caller must do next.
async fn resolve(&mut self) -> Result<FlowStep> {
let mut report = self.engine.resolve(&self.env, &self.req).await?;
// **Force latest** (DISCLAIMER §2). The decision was recorded in the request and nothing
// read it, so forcing re-resolved exactly the preview the user had just been shown (C6).
// The forced package is pinned to its latest and the packages holding it back leave the
// guard set — which is what makes them the "Will break" rows.
let mut forced: Vec<PkgName> = match &self.req.strategy {
Strategy::ForceLatest { overrides } => overrides.clone(),
Strategy::Compatible => Vec::new(),
};
self.screen_forced(&mut forced).await;
let mut adjust = if forced.is_empty() {
crate::engine::GuardAdjust::default()
} else {
let plan = plan::forced_requirements(&forced, &self.outdated, &self.graph);
crate::engine::GuardAdjust {
pins: plan.pins,
release: plan.release_from_guards,
exclude: Vec::new(),
}
};
// A `Hold` pin is "fixed at this version", so every plan says so. `hold_requirements`
// existed for this and nothing called it: a held package was only left out of the
// upgrade list, and free to move as anyone's dependency (H17).
for hold in &self.holds {
if !adjust.pins.iter().any(|p| p.name == hold.name) {
adjust.pins.push(hold.clone());
}
}
let mut rounds = 0;
let mut python_rounds = 0;
// Releases ruled out for their Python, and any still planned once the rounds ran out.
let mut ruled_out: Vec<PythonMismatch> = Vec::new();
let mut report = loop {
let ctx = crate::engine::ResolveCtx {
cancel: self.cancel.clone(),
adjust: adjust.clone(),
system: self.system,
};
let report = match self.engine.resolve(&self.env, &self.req, &ctx).await {
Ok(report) => report,
// A stopped resolve planned nothing and ran nothing; it is not a failure to report.
Err(e) if e.is_cancelled() => {
return Ok(FlowStep::Nothing {
reason: NothingReason::Cancelled,
});
}
Err(e) => return Err(e),
};
let collisions =
plan::forced_collisions(&report, &adjust, &forced, &self.req, &self.installed);
if !collisions.is_empty() && rounds < plan::FORCE_RELEASE_ROUNDS {
adjust.release.extend(collisions);
rounds += 1;
continue;
}
// Hard invariant 10 for what the engine chose: uv ignores an upper bound on
// `Requires-Python` and plans a release this interpreter cannot run. Each one is ruled
// out by name and the engine asked again — it, not PipDock, picks what comes next.
let violations = if report.impossible.is_none() {
self.screen_plan(&report).await
} else {
Vec::new()
};
if !violations.is_empty() && python_rounds < plan::PYTHON_EXCLUDE_ROUNDS {
adjust.exclude.extend(violations.iter().map(|m| PinnedSpec {
name: m.pkg.clone(),
version: m.version.clone(),
}));
ruled_out.extend(violations);
python_rounds += 1;
continue;
}
ruled_out.extend(violations);
break report;
};
plan::derive_held_back(&mut report, &self.req.upgrades, &self.outdated, &self.graph);
// A release ruled out for its Python is not held back by anything installed. The
// incompatible row says why; a held-back row would blame nobody.
report.held_back.retain(|h| {
!ruled_out
.iter()
.any(|m| m.pkg == h.pkg && m.version == h.latest)
});
plan::derive_forced(&mut report, &forced, &self.outdated, &self.graph);
tracing::info!(
target: "pipdock::flow",
plan = %self.plan_id,
round = self.round,
changes = report.changes.len(),
held_back = report.held_back.len(),
impossible = report.impossible.is_some(),
forced = forced.len(),
ruled_out = ruled_out.len(),
"resolved"
);
let mut incompatible = self.left_out.clone();
for m in ruled_out {
if !incompatible.contains(&m) {
incompatible.push(m);
}
}
report.incompatible = incompatible;
self.report = report;
self.resolved_at = (self.clock)();
let report = self.report.clone();
Ok(if self.report.is_clean() {
@@ -288,14 +495,29 @@ impl UpdateFlow {
/// distinct states the UI renders separately, and because a snapshot failure has to abort
/// before anything is touched.
///
/// **This is where DATA-FLOW §9.3 is enforced**: the environment is probed again here, after
/// the user confirmed and before anything is written, and a preview that is too old or no
/// longer describes the environment is refused. Checked any later and the refusal would come
/// after a snapshot nobody needs; checked any earlier and it would miss the minutes the
/// preview sat on screen.
///
/// # Errors
/// `PD-SNP-001` when the snapshot cannot be written. **Nothing has been executed** at that
/// point, and nothing will be: [`Self::execute`] refuses without this step.
/// `PD-RES-002` when the preview is stale or the environment changed; `PD-SNP-001` when the
/// snapshot cannot be written. **Nothing has been executed** in either case, and nothing will
/// be: [`Self::execute`] refuses without this step.
pub async fn take_snapshot(
&mut self,
policy: SnapshotPolicy,
app_data: &Path,
) -> Result<Option<snapshot::Meta>> {
let probed = self.engine.probe(&self.env).await?;
self.accepted().verify(
&crate::envs::env_hash(&probed.env.interpreter),
&probed.dists,
(self.clock)(),
)?;
self.confirmed = probed.dists;
if policy == SnapshotPolicy::Waive {
self.snapshot = SnapshotState::Waived;
return Ok(None);
@@ -308,9 +530,10 @@ impl UpdateFlow {
plan_id: self.plan_id.clone(),
},
self.engine.id(),
jiff::Timestamp::now(),
(self.clock)(),
)?;
let meta = snap.meta.clone();
tracing::info!(target: "pipdock::flow", plan = %self.plan_id, snapshot = %meta.id, "snapshot");
self.snapshot = SnapshotState::Taken(Box::new(snap));
Ok(Some(meta))
}
@@ -328,23 +551,36 @@ impl UpdateFlow {
// pinned-set length.
let sink = ProgressSink::new(tx, 0, self.cancel.clone());
let accepted = plan::AcceptedPlan::accept(
let summary = plan::execute(
self.engine.as_ref(),
&self.env,
&self.accepted(),
proof,
&self.confirmed,
(self.clock)(),
sink,
)
.await;
log_summary("update", &summary);
summary
}
/// The current preview as a plan, against the basis it was resolved over.
fn accepted(&self) -> plan::AcceptedPlan {
plan::AcceptedPlan::accept(
self.plan_id.clone(),
self.report.clone(),
self.env_hash.clone(),
&self.installed,
jiff::Timestamp::now(),
);
plan::execute(
self.engine.as_ref(),
&self.env,
&accepted,
proof,
&self.installed,
jiff::Timestamp::now(),
sink,
self.resolved_at,
)
.await
.with_system_packages(self.system)
}
/// Whether this flow passes `--break-system-packages` — so a head can say so, every time.
#[must_use]
pub const fn overrides_pep668(&self) -> bool {
matches!(self.system, SystemPackages::OverrideAllowed)
}
/// Pinned packages kept out of this plan (DATA-FLOW §9.5).
@@ -384,6 +620,150 @@ impl UpdateFlow {
pub fn cancel(&self) {
self.cancel.cancel();
}
/// Hard invariant 10 for the pins the user typed: an exact `name==v` this environment's
/// Python cannot install is left out before an engine sees it, and the preview says so.
///
/// Neither engine said it. pip refused such a pin with the "No matching distribution" it
/// gives a typo (PD-PKG-002), and uv planned it and failed at install time, building from
/// source. PD-PKG-001 existed in the catalog and nothing raised it (C2).
async fn screen_exact_pins(&mut self) {
let Some(meta) = &self.releases else {
return;
};
let exact: Vec<(PkgName, Version)> =
self.req.installs.iter().filter_map(exact_pin).collect();
if exact.is_empty() {
return;
}
let known = requires_python_of(meta, exact.clone()).await;
let bad: Vec<PythonMismatch> = exact
.iter()
.filter_map(|(name, version)| {
let declared = known.get(&(name.clone(), version.0.clone()));
mismatch(
name,
version,
declared.map(String::as_str),
&self.env.python_version,
)
})
.collect();
self.req
.installs
.retain(|s| !bad.iter().any(|m| m.pkg == s.name));
self.left_out.extend(bad);
}
/// The same for a forced package: forcing a release this Python cannot run is not a choice
/// worth acting on, so it stays where it was and the preview says why.
async fn screen_forced(&mut self, forced: &mut Vec<PkgName>) {
let Some(meta) = &self.releases else {
return;
};
let latest: Vec<(PkgName, Version)> = forced
.iter()
.filter_map(|f| {
self.outdated
.iter()
.find(|o| &o.name == f)
.map(|o| (o.name.clone(), o.latest.clone()))
})
.collect();
if latest.is_empty() {
return;
}
let known = requires_python_of(meta, latest.clone()).await;
for (name, version) in latest {
let declared = known.get(&(name.clone(), version.0.clone()));
if let Some(m) = mismatch(
&name,
&version,
declared.map(String::as_str),
&self.env.python_version,
) {
forced.retain(|f| f != &name);
if !self.left_out.contains(&m) {
self.left_out.push(m);
}
}
}
}
/// Every planned release whose `Requires-Python` excludes this environment.
///
/// pip's report says what each release requires, so nothing is asked; uv's plan says nothing,
/// so PyPI is (`crate::release`), and what it cannot answer does not block.
async fn screen_plan(&self, report: &ResolutionReport) -> Vec<PythonMismatch> {
let asked = match (&self.releases, self.engine.id()) {
(Some(meta), EngineId::Uv) => {
let unknown: Vec<(PkgName, Version)> = report
.changes
.iter()
.filter(|c| !report.declared_python.contains_key(&c.name))
.map(|c| (c.name.clone(), c.to.clone()))
.collect();
requires_python_of(meta, unknown).await
}
_ => BTreeMap::new(),
};
report
.changes
.iter()
.filter_map(|c| {
let declared = report
.declared_python
.get(&c.name)
.or_else(|| asked.get(&(c.name.clone(), c.to.0.clone())));
mismatch(
&c.name,
&c.to,
declared.map(String::as_str),
&self.env.python_version,
)
})
.collect()
}
}
/// One line for every run that ended, or the error that ended it.
fn log_summary(flow: &str, summary: &Result<crate::plan::ExecutionSummary>) {
match summary {
Ok(s) => tracing::info!(
target: "pipdock::flow",
flow,
plan = %s.plan_id,
ok = s.counts.ok,
failed = s.counts.failed,
skipped = s.counts.skipped,
cancelled = s.cancelled,
check_ok = s.check.ok,
"executed"
),
Err(e) => {
tracing::warn!(target: "pipdock::flow", flow, code = %e.code, message = %e.message, "refused")
}
}
}
/// `name==v` or `name===v` with a single exact version — the pins worth checking before the
/// engine sees them. A range or a wildcard is the engine's to choose within.
fn exact_pin(spec: &Spec) -> Option<(PkgName, Version)> {
let req = spec.version_req.as_deref()?;
let version = req.strip_prefix("===").or_else(|| req.strip_prefix("=="))?;
(crate::pep440::is_version(version) && !version.contains('*'))
.then(|| (spec.name.clone(), Version(version.to_owned())))
}
/// `PD-PKG-001` for a request that is nothing but pins this Python cannot install.
fn python_refusal(m: &PythonMismatch) -> PdError {
PdError::new(
Code::PkgRequiresPython,
format!(
"{} {} requires Python {}; this environment has {}",
m.pkg, m.version, m.requires_python, m.python
),
)
}
/// The uninstall flow (DATA-FLOW §5).
@@ -405,7 +785,11 @@ pub struct UninstallFlow {
/// What the guard found, kept so [`Self::execute`] can refuse a removal the user never
/// accepted. Returned to the caller as well, because the caller is what renders it.
guard: crate::graph::GuardReport,
/// What the guard was computed against, and when (DATA-FLOW §9.3).
basis: (jiff::Timestamp, String),
system: SystemPackages,
cancel: CancellationToken,
clock: fn() -> jiff::Timestamp,
}
/// Whether the user has accepted the breakage the guard found (DATA-FLOW §5).
@@ -431,31 +815,21 @@ impl UninstallFlow {
/// # Errors
/// `PD-PKG-002` when a name does not parse; otherwise propagates probe failures.
pub async fn start(
env: PyEnv,
mut env: PyEnv,
engine: Box<dyn Engine>,
pkgs: &[String],
opts: FlowOptions,
) -> Result<(Self, crate::graph::GuardReport)> {
// DATA-FLOW §2's preamble is "all mutating flows", and a removal is one. `UpdateFlow` has
// refused these since S1 and this did not, so PipDock would happily strip packages out of
// a system Python it declines to *upgrade* — the worse of the two operations, since there
// is no resolver between the user and the damage.
if env.externally_managed {
return Err(PdError::new(
Code::EnvExternallyManaged,
"this Python is externally managed (PEP 668). Use a virtual environment; \
the override lives in Settings and is discouraged",
));
}
let names: Vec<PkgName> = pkgs
.iter()
.map(|p| PkgName::parse(p))
.collect::<Result<_>>()?;
// The graph is built from probe.py, which is the only source carrying requires_dist.
let probed = crate::envs::probe(&env.interpreter, env.source).await?;
let report =
ReverseDeps::build_for(&probed.dists, &probed.env.python_version).guard(&names);
// DATA-FLOW §2's preamble is "all mutating flows", and a removal is one — the worse of the
// two, since there is no resolver between the user and the damage. The graph is built
// from the same probe, the only source carrying requires_dist.
let (probed, system) = preamble(engine.as_ref(), &mut env, &opts).await?;
let report = ReverseDeps::for_probe(&probed).guard(&names);
let env_hash = crate::envs::env_hash(&env.interpreter);
let plan_id = format!("uninstall-{env_hash:.8}");
@@ -468,7 +842,10 @@ impl UninstallFlow {
plan_id,
snapshot: SnapshotState::NotTaken,
guard: report.clone(),
cancel: CancellationToken::new(),
basis: ((opts.clock)(), plan::fingerprint(&probed.dists)),
system,
cancel: opts.cancel,
clock: opts.clock,
},
report,
))
@@ -500,13 +877,21 @@ impl UninstallFlow {
/// given to. `Waive` returns `None` — there is no meta to print, and no id for the summary to
/// correlate against.
///
/// Re-probes first: the guard said what this removal breaks *in the environment it looked
/// at*, and a package installed since may depend on what is about to go (M44).
///
/// # Errors
/// `PD-SNP-001` when it cannot be written, in which case nothing is removed.
/// `PD-RES-002` when the environment changed since the guard ran, or the guard is older than
/// ten minutes; `PD-SNP-001` when the snapshot cannot be written. Nothing is removed in either
/// case.
pub async fn take_snapshot(
&mut self,
policy: SnapshotPolicy,
app_data: &Path,
) -> Result<Option<snapshot::Meta>> {
let probed = self.engine.probe(&self.env).await?;
plan::verify_basis(self.basis.0, &self.basis.1, &probed.dists, (self.clock)())?;
if matches!(policy, SnapshotPolicy::Waive) {
self.snapshot = SnapshotState::Waived;
return Ok(None);
@@ -519,7 +904,7 @@ impl UninstallFlow {
plan_id: self.plan_id.clone(),
},
self.engine.id(),
jiff::Timestamp::now(),
(self.clock)(),
)?;
let meta = snap.meta.clone();
self.snapshot = SnapshotState::Taken(Box::new(snap));
@@ -547,18 +932,18 @@ impl UninstallFlow {
SnapshotState::Taken(snap) => snap.meta.id.clone(),
_ => self.plan_id.clone(),
};
plan::execute_uninstall(
let summary = plan::execute_uninstall(
self.engine.as_ref(),
&self.env,
correlation,
&self.names,
proof,
sink,
// The removals are the whole plan here, so they start at step zero. Only a rollback
// has anything in front of them.
0,
self.system,
)
.await
.await;
log_summary("uninstall", &summary);
summary
}
/// The packages this flow will remove.
@@ -567,6 +952,12 @@ impl UninstallFlow {
&self.names
}
/// Whether this flow passes `--break-system-packages` — so a head can say so, every time.
#[must_use]
pub const fn overrides_pep668(&self) -> bool {
matches!(self.system, SystemPackages::OverrideAllowed)
}
/// A handle that stops this flow's execution.
///
/// Cloneable and safe to hold elsewhere, which is the point: `plan_cancel` arrives on a
@@ -610,24 +1001,34 @@ pub struct RollbackFlow {
restore: snapshot::RollbackPlan,
/// The state being *replaced*, captured before it is — a rollback is itself reversible.
pre: SnapshotState,
/// The freeze the restore plan was computed from, and when (DATA-FLOW §9.3).
basis: (jiff::Timestamp, String),
system: SystemPackages,
cancel: CancellationToken,
clock: fn() -> jiff::Timestamp,
}
impl RollbackFlow {
/// Load the target snapshot and work out the minimal restore plan.
///
/// # Errors
/// `PD-SNP-002` when no such snapshot exists; otherwise propagates engine failures.
/// `PD-SNP-002` when no such snapshot exists; `PD-ENV-002` for a managed environment without
/// the override — a restore is a mutating flow, and this one had no gate at all (H12);
/// otherwise propagates engine failures.
pub async fn start(
env: PyEnv,
mut env: PyEnv,
engine: Box<dyn Engine>,
app_data: &Path,
id: &str,
opts: FlowOptions,
) -> Result<(Self, RollbackPreview)> {
let env_hash = crate::envs::env_hash(&env.interpreter);
let target = snapshot::load(app_data, &env_hash, id)?;
let current = snapshot::parse_freeze(&engine.freeze(&env).await?);
let diff = snapshot::diff(&current, &target.entries());
let (_, system) = preamble(engine.as_ref(), &mut env, &opts).await?;
let current_freeze = engine.freeze(&env).await?;
let current = snapshot::parse_freeze(&current_freeze);
let diff =
snapshot::restorable_diff(&current, &target.entries(), target.meta.engine, engine.id());
let restore = snapshot::rollback_plan(&diff);
let preview = RollbackPreview {
@@ -643,7 +1044,10 @@ impl RollbackFlow {
target_id: target.meta.id,
restore,
pre: SnapshotState::NotTaken,
cancel: CancellationToken::new(),
basis: ((opts.clock)(), current_freeze),
system,
cancel: opts.cancel,
clock: opts.clock,
},
preview,
))
@@ -651,18 +1055,33 @@ impl RollbackFlow {
/// Capture the state being replaced, so the rollback is itself reversible (DATA-FLOW §8).
///
/// The freeze this captures is also the drift check: the restore plan is a diff against the
/// freeze `start` took, and applied to anything else it removes and reinstalls the wrong
/// things (M44).
///
/// # Errors
/// `PD-SNP-001` when it cannot be written, in which case nothing is restored.
/// `PD-RES-002` when the environment changed since the preview, or the preview is older than
/// ten minutes; `PD-SNP-001` when the snapshot cannot be written. Nothing is restored in
/// either case.
pub async fn take_snapshot(&mut self, app_data: &Path) -> Result<snapshot::Meta> {
let freeze = self.engine.freeze(&self.env).await?;
let (made_at, then) = &self.basis;
plan::verify_age(*made_at, (self.clock)())?;
if snapshot::parse_freeze(&freeze) != snapshot::parse_freeze(then) {
return Err(PdError::new(
Code::ResPlanStale,
"the environment changed since the rollback was previewed — re-run it",
));
}
let snap = snapshot::create(
app_data,
&self.env_hash,
self.engine.freeze(&self.env).await?,
freeze,
snapshot::Trigger::Rollback {
restoring: self.target_id.clone(),
},
self.engine.id(),
jiff::Timestamp::now(),
(self.clock)(),
)?;
let meta = snap.meta.clone();
self.pre = SnapshotState::Taken(Box::new(snap));
@@ -681,15 +1100,24 @@ impl RollbackFlow {
SnapshotState::Taken(snap) => snap.meta.id.clone(),
_ => self.target_id.clone(),
};
plan::execute_rollback(
let summary = plan::execute_rollback(
self.engine.as_ref(),
&self.env,
correlation,
&self.restore,
proof,
sink,
self.system,
)
.await
.await;
log_summary("rollback", &summary);
summary
}
/// Whether this flow passes `--break-system-packages` — so a head can say so, every time.
#[must_use]
pub const fn overrides_pep668(&self) -> bool {
matches!(self.system, SystemPackages::OverrideAllowed)
}
/// A handle that stops this flow's execution.
@@ -803,13 +1231,7 @@ fn build_request(
upgrades: Vec::new(),
installs: specs
.iter()
.map(|raw| {
let (name, version_req) = match raw.split_once("==") {
Some((n, v)) => (n, Some(v.to_owned())),
None => (raw.as_str(), None),
};
PkgName::parse(name).map(|name| Spec { name, version_req })
})
.map(|raw| Spec::parse(raw))
.collect::<Result<_>>()?,
strategy: Strategy::Compatible,
},
@@ -918,10 +1340,66 @@ mod tests {
)
.expect("builds");
assert_eq!(req.installs.len(), 2);
assert_eq!(req.installs[0].version_req.as_deref(), Some("0.28.1"));
assert_eq!(req.installs[0].version_req.as_deref(), Some("==0.28.1"));
assert_eq!(req.installs[1].version_req, None);
}
#[test]
fn every_spec_a_requirements_file_produces_builds_a_request() {
// The seam P1-B left open: `requirements::parse` emitted `django>=5.0,<6` and the flow
// split on `==` only, so every range failed with PD-PKG-002 and `pkg===1.0` became
// version `=1.0`. Fed through for real, not with hand-written specs.
let parsed = crate::requirements::parse(
"django>=5.0,<6\nrequests==2.32.3\nnumpy ~= 2.1\nlegacy===1.0-final\nidna\n",
);
assert!(parsed.skipped.is_empty(), "{:?}", parsed.skipped);
let (req, _) = build_request(
&Intent::Install {
specs: parsed.specs,
},
&[],
&[],
)
.expect("every parsed spec builds");
let got: Vec<(String, Option<String>)> = req
.installs
.iter()
.map(|s| (s.name.to_string(), s.version_req.clone()))
.collect();
assert_eq!(
got,
[
("django".to_owned(), Some(">=5.0,<6".to_owned())),
("requests".to_owned(), Some("==2.32.3".to_owned())),
("numpy".to_owned(), Some("~=2.1".to_owned())),
("legacy".to_owned(), Some("===1.0-final".to_owned())),
("idna".to_owned(), None),
]
);
}
#[test]
fn a_version_that_is_not_one_never_reaches_argv() {
// SECURITY §2 says versions are validated before argv; they were not. This one is a
// single token pip reads as a requirement whose marker is false — a silent no-op install.
for bad in [
"pkg==2.0 ; python_version<'0'",
"pkg==1.0 --break-system-packages",
"pkg @ https://example.com/pkg.whl",
"pkg is not a requirement",
] {
let err = build_request(
&Intent::Install {
specs: vec![bad.into()],
},
&[],
&[],
)
.expect_err(bad);
assert_eq!(err.code, Code::PkgNotFound, "{bad}");
}
}
#[test]
fn a_malformed_name_is_refused_before_any_engine_runs() {
// SECURITY §2: names are validated before they can reach argv, and both heads inherit
+164 -24
View File
@@ -16,16 +16,20 @@
//! noisy: telling someone on 3.12 that "pandas requires numpy >=1.22.4" is false, and
//! ERROR-CATALOG's whole premise is that what PipDock says about a failure can be trusted.
//!
//! Scope is deliberately narrow. Only `python_version` and `python_full_version` are evaluated,
//! because those are the markers that actually gate version constraints in the wild, and the
//! environment already knows its interpreter version. The platform markers are constants for a
//! Windows-only v1 (PRD non-goals) and reading them would mean plumbing more out of `probe.py`
//! for no present gain.
//! `python_version` and `python_full_version` compare as versions. Since probe schema 3 the
//! platform markers — `sys_platform`, `os_name`, `platform_system`, `platform_machine`, … — are
//! known too, and compare as strings with `==`, `!=`, `in` and `not in`. They were left out at
//! first as "constants for a Windows-only v1", and that was the bug: a constant still has to be
//! *read*, and unread, ipython's `pexpect; sys_platform != "win32"` was in force on Windows, so
//! the dependency view reported pexpect missing from every Windows environment with ipython in
//! it (H25).
//!
//! **An unrecognised marker keeps the requirement.** Over-reporting a constraint is noise;
//! dropping one hides the reason a package is stuck, and ARCHITECTURE §3 would rather show
//! constraints without a culprit than quietly omit them.
use std::collections::BTreeMap;
use crate::compat::PyVersion;
/// The interpreter facts a marker can be evaluated against.
@@ -35,25 +39,41 @@ pub struct MarkerEnv {
python_version: PyVersion,
/// The full interpreter version — PEP 508's `python_full_version`.
python_full_version: PyVersion,
/// Every variable known as a string: the probe's marker environment and the two Python
/// versions. A variable missing from here is unknown, and a requirement gated on it stays in
/// force.
vars: BTreeMap<String, String>,
}
impl MarkerEnv {
/// Build from `PyEnv::python_version`, e.g. `"3.12.10"`.
/// Build from `PyEnv::python_version`, e.g. `"3.12.10"`, knowing nothing about the platform.
///
/// Returns `None` for anything unparseable, which leaves marker evaluation switched off
/// rather than guessing — the conservative direction.
#[must_use]
pub fn from_python_version(raw: &str) -> Option<Self> {
Self::from_probe(raw, &BTreeMap::new())
}
/// Build from the interpreter version and the probe's marker environment (probe schema 3).
#[must_use]
pub fn from_probe(raw: &str, markers: &BTreeMap<String, String>) -> Option<Self> {
let full = PyVersion::parse(raw).ok()?;
// `python_version` is major.minor only. Keeping the patch would make the common
// `python_version == "3.12"` false on 3.12.10, which is backwards.
let mut parts = raw.split('.');
let major = parts.next()?;
let minor = parts.next().unwrap_or("0");
let short = PyVersion::parse(&format!("{major}.{minor}")).ok()?;
let short_raw = format!("{major}.{minor}");
let short = PyVersion::parse(&short_raw).ok()?;
let mut vars = markers.clone();
vars.entry("python_version".to_owned()).or_insert(short_raw);
vars.entry("python_full_version".to_owned())
.or_insert_with(|| raw.to_owned());
Some(Self {
python_version: short,
python_full_version: full,
vars,
})
}
}
@@ -138,15 +158,36 @@ fn compare(lhs: &Operand, op: &str, rhs: &Operand, env: Option<&MarkerEnv>) -> V
_ => return None,
};
let version = match var {
"python_version" => &env.python_version,
"python_full_version" => &env.python_full_version,
_ => return None,
};
// PEP 508's containment, for any variable: `lhs in rhs` asks whether lhs occurs in rhs.
if op == "in" || op == "not in" {
let value = env.vars.get(var)?;
let found = if flipped {
value.contains(literal)
} else {
literal.contains(value.as_str())
};
return Some(found == (op == "in"));
}
// `"3.11" > python_version` means the same as `python_version < "3.11"`.
let op = if flipped { mirror(op) } else { op };
crate::compat::satisfies_clause(&format!("{op}{literal}"), version)
let version = match var {
"python_version" => Some(&env.python_version),
"python_full_version" => Some(&env.python_full_version),
_ => None,
};
if let Some(version) = version {
// `"3.11" > python_version` means the same as `python_version < "3.11"`.
let op = if flipped { mirror(op) } else { op };
return crate::compat::satisfies_clause(&format!("{op}{literal}"), version);
}
// Everything else compares as a string. Ordering a platform name is not something a
// requirement can mean, so `<` and friends stay unevaluated.
let value = env.vars.get(var)?;
match op {
"==" | "===" => Some(value == literal),
"!=" => Some(value != literal),
_ => None,
}
}
fn mirror(op: &str) -> &str {
@@ -183,10 +224,12 @@ impl<'a> Lexer<'a> {
Self { src, at: 0 }
}
/// Whitespace is skipped by **character**, not by byte. `at += 1` stepped into the middle of
/// a no-break space (two bytes) or an ideographic space (three), and the next slice panicked —
/// on a marker read out of some installed package's metadata (H19).
fn skip_ws(&mut self) {
while self.src[self.at..].starts_with(char::is_whitespace) {
self.at += 1;
}
let rest = &self.src[self.at..];
self.at += rest.len() - rest.trim_start().len();
}
fn eat_char(&mut self, c: char) -> bool {
@@ -200,13 +243,17 @@ impl<'a> Lexer<'a> {
fn eat_word(&mut self, word: &str) -> bool {
self.skip_ws();
let rest = &self.src[self.at..];
// Prefix first, then look past it: slicing `word.len()` bytes in before knowing the text
// starts with `word` cut a multi-byte character in half and panicked.
let Some(after) = self.src[self.at..].strip_prefix(word) else {
return false;
};
// Must be a whole word: `android_api` must not be read as the operator `and`.
let ends_cleanly = rest[word.len().min(rest.len())..]
if after
.chars()
.next()
.is_none_or(|c| !c.is_alphanumeric() && c != '_');
if rest.starts_with(word) && ends_cleanly {
.is_none_or(|c| !c.is_alphanumeric() && c != '_')
{
self.at += word.len();
return true;
}
@@ -241,8 +288,15 @@ impl<'a> Lexer<'a> {
return Some(op);
}
}
// `in` / `not in` are string-containment operators PipDock does not evaluate; letting
// them fall through to "unrecognised" keeps the requirement.
// The word operators, PEP 508's string containment.
if self.eat_word("in") {
return Some("in");
}
let before = self.at;
if self.eat_word("not") && self.eat_word("in") {
return Some("not in");
}
self.at = before;
None
}
}
@@ -356,6 +410,92 @@ mod tests {
assert!(applies(Some("android_api == \"21\""), Some(&e)));
}
fn windows(v: &str) -> MarkerEnv {
// What probe schema 3 reported for CPython 3.14.7 on Windows 11, x64.
let markers = [
("implementation_name", "cpython"),
("os_name", "nt"),
("platform_machine", "AMD64"),
("platform_python_implementation", "CPython"),
("platform_system", "Windows"),
("sys_platform", "win32"),
]
.into_iter()
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect();
MarkerEnv::from_probe(v, &markers).expect("parses")
}
#[test]
fn a_requirement_gated_to_another_platform_is_not_in_force() {
// ipython's pexpect, read on Windows: reported missing from every Windows environment
// that had ipython, until the platform markers were read.
let e = windows("3.14.7");
assert!(!applies(
Some(r#"sys_platform != "win32" and sys_platform != "emscripten""#),
Some(&e)
));
assert!(applies(Some(r#"sys_platform == "win32""#), Some(&e)));
assert!(applies(Some(r#"platform_system == "Windows""#), Some(&e)));
assert!(!applies(Some(r#"os_name == "posix""#), Some(&e)));
assert!(applies(
Some(r#"platform_machine == "x86_64" or platform_machine == "AMD64""#),
Some(&e)
));
assert!(!applies(
Some(r#"platform_python_implementation == "PyPy""#),
Some(&e)
));
}
#[test]
fn containment_reads_in_both_directions() {
let e = windows("3.14.7");
assert!(!applies(Some(r#""linux" in sys_platform"#), Some(&e)));
assert!(applies(Some(r#""win" in sys_platform"#), Some(&e)));
assert!(applies(Some(r#"sys_platform in "win32 cygwin""#), Some(&e)));
assert!(applies(
Some(r#"sys_platform not in "linux darwin""#),
Some(&e)
));
assert!(!applies(
Some(r#"python_version not in "3.13 3.14""#),
Some(&e)
));
}
#[test]
fn what_the_probe_did_not_report_still_keeps_the_requirement() {
// Windows probes leave out platform_release (a WMI query); ordering a platform name means
// nothing. Both stay "applies".
let e = windows("3.14.7");
assert!(applies(Some(r#"platform_release >= "10""#), Some(&e)));
assert!(applies(Some(r#"sys_platform > "a""#), Some(&e)));
}
#[test]
fn unicode_whitespace_never_panics_the_lexer() {
// Markers come from any installed package's metadata. Each of these sliced a multi-byte
// character in half.
let e = windows("3.14.7");
for marker in [
"python_version\u{a0}>= \"3.8\"",
"\u{3000}python_version >= \"3.8\"",
"python_version >= \"3.8\"\u{2003}and\u{2003}os_name == \"nt\"",
"é",
"andé",
"python_version >= \"3.8\" ändé",
"\u{a0}",
] {
let _ = applies(Some(marker), Some(&e));
let _ = applies(Some(marker), None);
}
assert!(applies(
Some("python_version\u{a0}>=\u{a0}\"3.8\""),
Some(&e)
));
}
#[test]
fn an_unparseable_interpreter_version_disables_evaluation() {
assert_eq!(MarkerEnv::from_python_version("not-a-version"), None);
+536 -15
View File
@@ -111,6 +111,13 @@ fn is_specifier_start(c: char) -> bool {
pub struct ReverseDeps {
/// `dependency -> [(dependent, the requirement it declared)]`.
edges: BTreeMap<PkgName, Vec<(PkgName, Requirement)>>,
/// `dependent -> [the requirements it declared]` — the same edges the other way up.
///
/// Held rather than derived because deriving it means scanning every value of `edges` for
/// one package, which is O(edges) per lookup where this is O(1); the whole-graph view asks
/// once per installed package. Built in the same pass, from the same parse, filtered by the
/// same rule — a second traversal is how the two directions would come to disagree.
forward: BTreeMap<PkgName, Vec<Requirement>>,
/// Installed versions, so attribution can name `apiclient 1.4` rather than bare `apiclient`.
versions: BTreeMap<PkgName, String>,
/// The interpreter these requirements are read against, when known. `None` disables marker
@@ -135,6 +142,7 @@ impl ReverseDeps {
#[must_use]
pub fn build(dists: &[Dist]) -> Self {
let mut edges: BTreeMap<PkgName, Vec<(PkgName, Requirement)>> = BTreeMap::new();
let mut forward: BTreeMap<PkgName, Vec<Requirement>> = BTreeMap::new();
let mut versions = BTreeMap::new();
for dist in dists {
@@ -148,6 +156,10 @@ impl ReverseDeps {
if req.name == dist.name {
continue;
}
forward
.entry(dist.name.clone())
.or_default()
.push(req.clone());
edges
.entry(req.name.clone())
.or_default()
@@ -157,11 +169,23 @@ impl ReverseDeps {
Self {
edges,
forward,
versions,
env: None,
}
}
/// Build the graph from a probe, evaluating markers against everything it reported: the
/// interpreter version and, from probe schema 3, the platform. **Prefer this** wherever a
/// probe is in hand — it is the only constructor that knows `sys_platform`.
#[must_use]
pub fn for_probe(probe: &crate::envs::ProbeResult) -> Self {
Self {
env: MarkerEnv::from_probe(&probe.env.python_version, &probe.markers),
..Self::build(&probe.dists)
}
}
/// Build the graph and evaluate markers against `python_version`, e.g. `"3.12.10"`.
///
/// An unparseable version silently leaves evaluation off rather than guessing — the same
@@ -282,15 +306,6 @@ impl ReverseDeps {
out
}
/// Every package in `all` that nothing else depends on.
#[must_use]
pub fn leaves(&self, all: &[PkgName]) -> Vec<PkgName> {
all.iter()
.filter(|p| self.dependents_of(p).is_empty())
.cloned()
.collect()
}
/// Everything that must also go if `removing` is removed and nothing may be left broken.
///
/// This is the *transitive* closure, which DATA-FLOW §5's "[Remove dependents too] (adds Y,Z
@@ -312,6 +327,132 @@ impl ReverseDeps {
seen.into_iter().collect()
}
/// What `pkg` requires: in force, and installed.
///
/// The forward mirror of [`Self::dependents_of`]. The two must filter by one rule or a focus
/// view's two columns describe the same edge differently, so both go through
/// [`Requirement::applies_in`] — which is also why neither can be recomputed in the frontend.
/// That restriction is not about phrasing (I18N §1); it is that PEP 508 marker evaluation and
/// the extra-gating rule live in [`markers`], and a second implementation would drift from the
/// guard the user is warned by.
///
/// Requirements that are in force but **not installed** are excluded here and reported by
/// [`Self::unsatisfied`] instead. Two disjoint sets whose union is the in-force requirement
/// list, so no row has to carry an "is it actually there?" flag the reader must then interpret.
#[must_use]
pub fn requires_of(&self, pkg: &PkgName) -> Vec<DepEdge> {
let mut out: BTreeSet<DepEdge> = BTreeSet::new();
for req in self.forward.get(pkg).into_iter().flatten() {
if !req.applies_in(self.env.as_ref()) {
continue;
}
if let Some(version) = self.versions.get(&req.name) {
out.insert(DepEdge {
pkg: req.name.clone(),
version: Some(version.clone()),
constraint: req.constraint.clone(),
});
}
}
out.into_iter().collect()
}
/// Who requires `pkg`, each with the constraint it declared.
///
/// Deliberately a projection of [`Self::breaking_dependents`] rather than a second walk of
/// `edges`: the dependents column and the uninstall guard are then the same set by
/// construction, and cannot come to disagree about which edges count. That is the failure
/// this module exists to prevent — `ReverseDeps::build`'s doc records the last time two
/// features nearly applied two edge rules.
#[must_use]
pub fn edges_to(&self, pkg: &PkgName) -> Vec<DepEdge> {
self.breaking_dependents(pkg)
.into_iter()
.map(DepEdge::from)
.collect()
}
/// In-force requirements of `pkg` that no installed distribution satisfies.
///
/// Nothing else in PipDock reports this. It is the one thing a dependency view can say that
/// the package list cannot, and it is only trustworthy because the markers are evaluated:
/// counting raw `Requires-Dist` names would report every `python_version < "3.11"` backport
/// as missing on 3.12 and make a healthy environment look broken.
#[must_use]
pub fn unsatisfied(&self, pkg: &PkgName) -> Vec<PkgName> {
let mut out: BTreeSet<PkgName> = BTreeSet::new();
for req in self.forward.get(pkg).into_iter().flatten() {
if req.applies_in(self.env.as_ref()) && !self.versions.contains_key(&req.name) {
out.insert(req.name.clone());
}
}
out.into_iter().collect()
}
/// How many installed packages `pkg` pulls in, transitively, excluding itself.
///
/// The forward mirror of [`Self::removal_closure`], and cycle-safe for its reason: a package
/// enters the frontier at most once. `pkg` itself is never counted, so a dependency cycle
/// through it reports the same number an acyclic graph would.
///
/// Goes through [`Self::requires_of`] rather than walking `forward` itself, and that was
/// measured rather than assumed. Walking `forward` directly takes the whole-graph
/// [`Self::view`] from **42.4 ms to 31.4 ms** on the 352-package fixture in `--release` — 11 ms
/// against a probe that costs 605 ms, so **1.8% of an operation the user waits for**, bought
/// with a second copy of the in-force-and-installed rule. This module exists because two
/// features applying two edge rules is the failure worth designing against; a 1.8% saving does
/// not buy that risk back.
#[must_use]
pub fn reach(&self, pkg: &PkgName) -> usize {
let mut seen: BTreeSet<PkgName> = BTreeSet::new();
let mut frontier = vec![pkg.clone()];
while let Some(current) = frontier.pop() {
for edge in self.requires_of(&current) {
if edge.pkg != *pkg && seen.insert(edge.pkg.clone()) {
frontier.push(edge.pkg);
}
}
}
seen.len()
}
/// The whole graph, precomputed once per environment (PRD P1-6).
///
/// **One value rather than one call per package**, because the alternative pays a 605 ms
/// probe on every re-centring click. Everything a focus view needs is decided here, in Rust,
/// with markers evaluated; the frontend indexes this map by name and computes nothing about
/// which edges are in force.
///
/// Uncapped on purpose. `setuptools` has 150 dependents in the 352-package fixture, and the
/// view shows a bounded window — but the "+ N more" count has to come from the full set or a
/// capped view misreports a total, which is the rule `SUGGESTIONS_SHOWN` and `RUFF_ROWS_SHOWN`
/// already follow. Capping here would put that count out of reach.
///
/// Every installed package gets a node, including the leaves: a package with no edges in
/// either direction is a fact worth rendering, not an absence to fall through on.
#[must_use]
pub fn view(&self) -> DepsGraph {
let nodes = self
.versions
.iter()
.map(|(pkg, version)| {
let node = DepsNode {
version: Some(version.clone()),
dependents: self.edges_to(pkg),
dependencies: self.requires_of(pkg),
impact: self
.removal_closure(std::slice::from_ref(pkg))
.len()
.saturating_sub(1),
reach: self.reach(pkg),
unsatisfied: self.unsatisfied(pkg),
};
(pkg.clone(), node)
})
.collect();
DepsGraph { nodes }
}
/// Evaluate the uninstall guard against a removal set (DATA-FLOW §5).
#[must_use]
pub fn guard(&self, removing: &[PkgName]) -> GuardReport {
@@ -403,6 +544,99 @@ impl GuardReport {
}
}
/// One edge of the dependency graph, seen from a focused package.
///
/// `pkg` is always the **other end** of the edge and `constraint` always the specifier written on
/// it, so one type serves both directions: in a dependents column `pkg` is who requires the focus,
/// in a dependencies column it is what the focus requires. `version` is that package's installed
/// version.
///
/// Three fields identical to [`BrokenDependent`], and deliberately a separate type. That one is
/// about *breakage* — its doc is written for the uninstall dialog and its `Ord` exists for the
/// dedup in [`ReverseDeps::breaking_dependents`] — so reusing it here would have a dependencies
/// column claim every dependency is a broken dependent. The `From` impl below is the bridge, and
/// [`ReverseDeps::edges_to`] goes through it precisely so the two cannot drift.
///
/// `constraint` is the **bare specifier tail** — `"<2,>=1.26.0"`, never `"numpy<2,>=1.26.0"` — for
/// [`BrokenDependent`]'s reason. The other half of the sentence is the focused package, which the
/// caller already has; Rust emits data and each head writes its own sentence (I18N §1). An empty
/// string means unconstrained, which is a different statement from "no edge" and the view says so.
#[derive(
Debug,
Clone,
PartialEq,
Eq,
PartialOrd,
Ord,
serde::Serialize,
serde::Deserialize,
schemars::JsonSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct DepEdge {
/// The package at the other end of the edge.
pub pkg: PkgName,
/// Its installed version, when the graph knows it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// The version specifier written on the edge. Empty when unconstrained.
pub constraint: String,
}
impl From<BrokenDependent> for DepEdge {
fn from(d: BrokenDependent) -> Self {
Self {
pkg: d.pkg,
version: d.version,
constraint: d.constraint,
}
}
}
/// Everything a focus view needs about one installed package.
///
/// `impact` and `reach` are the pair the view exists for. Every other question PipDock answers
/// about the graph is single-hop — the uninstall guard, blocker attribution and pin auto-suggest
/// all look one edge out — so the only thing a dependency view adds over shipped behaviour is
/// **transitive** reach, and it is a number rather than a picture because the picture does not
/// survive the scale: measured on the 352-package fixture, a depth-2 neighbourhood is a median of
/// 172 nodes and exceeds 60 for 212 of 352 packages.
#[derive(
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct DepsNode {
/// The package's own installed version.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// Installed packages that require this one, with the constraint each declared.
pub dependents: Vec<DepEdge>,
/// Installed packages this one requires, in force.
pub dependencies: Vec<DepEdge>,
/// How many packages would be left broken if this one went, transitively. The size of
/// [`ReverseDeps::removal_closure`] without the package itself.
pub impact: usize,
/// How many installed packages this one pulls in, transitively.
pub reach: usize,
/// In-force requirements with nothing installed to satisfy them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub unsatisfied: Vec<PkgName>,
}
/// The in-force dependency graph of one environment (PRD P1-6).
///
/// Keyed by package name, one entry per installed distribution. Produced by
/// [`ReverseDeps::view`]; see its doc for why this crosses the bridge whole rather than a package
/// at a time, and why nothing here is capped.
#[derive(
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct DepsGraph {
/// Every installed package, including those with no edges in either direction.
pub nodes: BTreeMap<PkgName, DepsNode>,
}
/// Does `version` satisfy the PEP 440 specifier set `constraint`?
///
/// Reuses [`crate::compat`]'s evaluator: a `Requires-Dist` specifier and a `Requires-Python`
@@ -747,12 +981,6 @@ mod tests {
assert!(g.dependent_count(&pkg("urllib3")) >= PIN_SUGGEST_THRESHOLD);
}
#[test]
fn leaves_are_packages_nothing_depends_on() {
let g = ReverseDeps::build(&[dist("x", "1.0", &[]), dist("y", "2.0", &["x>=1"])]);
assert_eq!(g.leaves(&[pkg("x"), pkg("y")]), [pkg("y")]);
}
#[test]
fn the_guard_reports_the_documented_example() {
// DATA-FLOW §5: "Removing X breaks Y (requires X>=1), Z".
@@ -807,4 +1035,297 @@ mod tests {
let g = ReverseDeps::build(&[dist("x", "1.0", &[]), dist("y", "2.0", &["x>=1"])]);
assert!(g.guard(&[pkg("x"), pkg("y")]).is_clear());
}
// --- P1-6: the dependency view -------------------------------------------------------
/// The environment the view tests share: a diamond, an extra-gated edge, a marker for
/// another Python, a requirement nothing satisfies, and a leaf.
fn env() -> Vec<Dist> {
vec![
dist(
"app",
"1.0",
&["lib>=2", "plot; extra == \"charts\"", "gone>=9"],
),
dist("also", "1.0", &["lib<3"]),
dist("lib", "2.5", &["core", "old; python_version < \"3.0\""]),
dist("core", "0.9", &[]),
dist("plot", "4.0", &[]),
dist("leaf", "1.0", &[]),
]
}
#[test]
fn the_two_directions_agree_edge_for_edge() {
// One rule, two directions. If these ever disagree, a focus view describes the same edge
// twice and differently, and its dependents column stops matching the guard the user is
// actually warned by.
let g = ReverseDeps::build_for(&env(), "3.12.10");
let all: Vec<PkgName> = env().iter().map(|d| d.name.clone()).collect();
for from in &all {
for edge in g.requires_of(from) {
let back = g.edges_to(&edge.pkg);
assert!(
back.iter()
.any(|e| e.pkg == *from && e.constraint == edge.constraint),
"{from} -> {} is missing from edges_to({})",
edge.pkg,
edge.pkg
);
}
for edge in g.edges_to(from) {
let fwd = g.requires_of(&edge.pkg);
assert!(
fwd.iter()
.any(|e| e.pkg == *from && e.constraint == edge.constraint),
"{} -> {from} is missing from requires_of({})",
edge.pkg,
edge.pkg
);
}
}
}
#[test]
fn an_extra_gated_edge_appears_in_neither_direction() {
// `plot` is installed, but `app` wants it only under `extra == "charts"`. Counting it
// would have the view claim a dependency the environment does not rely on — the rule
// `dependents_of` already applies, which is why both directions go through `applies_in`.
let g = ReverseDeps::build_for(&env(), "3.12.10");
assert!(
!g.requires_of(&pkg("app"))
.iter()
.any(|e| e.pkg == pkg("plot"))
);
assert!(g.edges_to(&pkg("plot")).is_empty());
}
#[test]
fn a_marker_for_another_python_is_not_a_missing_dependency() {
// `lib` wants `old` only below Python 3.0, and `old` is not installed. Reporting it as
// unsatisfied on 3.12 would make a healthy environment look broken, which is exactly why
// this cannot be recomputed in the frontend from the raw strings.
let g = ReverseDeps::build_for(&env(), "3.12.10");
assert!(g.unsatisfied(&pkg("lib")).is_empty());
// ...while a genuinely absent requirement still is one.
assert_eq!(g.unsatisfied(&pkg("app")), [pkg("gone")]);
}
#[test]
fn an_unsatisfied_requirement_is_never_also_a_dependency_row() {
// The two sets are disjoint by construction, so no row carries an "is it installed?"
// flag for the reader to interpret.
let g = ReverseDeps::build_for(&env(), "3.12.10");
let deps: Vec<PkgName> = g
.requires_of(&pkg("app"))
.into_iter()
.map(|e| e.pkg)
.collect();
for missing in g.unsatisfied(&pkg("app")) {
assert!(!deps.contains(&missing), "{missing} is in both sets");
}
}
#[test]
fn reach_and_impact_count_transitively_and_exclude_the_package() {
let g = ReverseDeps::build_for(&env(), "3.12.10");
// app -> lib -> core: two, not one, and `plot` is extra-gated so not three.
assert_eq!(g.reach(&pkg("app")), 2);
// core <- lib <- {app, also}: three.
assert_eq!(g.removal_closure(&[pkg("core")]).len() - 1, 3);
// A leaf is zero in both directions, which is a fact to render, not an absence.
assert_eq!(g.reach(&pkg("leaf")), 0);
assert_eq!(g.removal_closure(&[pkg("leaf")]).len() - 1, 0);
}
#[test]
fn reach_terminates_on_a_cycle_and_does_not_count_the_package_itself() {
// `removal_closure` has had this test since S3. `reach` is the same walk the other way
// and needs its own: a cycle through the focus would otherwise count it as its own
// transitive dependency.
let g = ReverseDeps::build(&[
dist("a", "1.0", &["b"]),
dist("b", "1.0", &["c"]),
dist("c", "1.0", &["a"]),
]);
assert_eq!(g.reach(&pkg("a")), 2);
assert_eq!(g.removal_closure(&[pkg("a")]).len() - 1, 2);
}
#[test]
fn the_view_has_a_node_for_every_installed_package() {
// Including `leaf`, which has no edge in either direction. A view that fell through on
// those would leave 32 of the 352-package fixture with nothing to render.
let g = ReverseDeps::build_for(&env(), "3.12.10");
let view = g.view();
assert_eq!(view.nodes.len(), env().len());
for d in env() {
assert!(view.nodes.contains_key(&d.name), "{} has no node", d.name);
}
let leaf = &view.nodes[&pkg("leaf")];
assert!(leaf.dependents.is_empty() && leaf.dependencies.is_empty());
assert_eq!(leaf.version.as_deref(), Some("1.0"));
}
#[test]
fn the_view_agrees_with_the_methods_it_is_built_from() {
// The view is what crosses the bridge; the methods are what every test above pins. If
// the two can differ, all of that is proved about something the user never sees — which
// is the shape of the fixture bug Slice 0 found.
let g = ReverseDeps::build_for(&env(), "3.12.10");
for (name, node) in &g.view().nodes {
assert_eq!(node.dependents, g.edges_to(name), "{name} dependents");
assert_eq!(
node.dependencies,
g.requires_of(name),
"{name} dependencies"
);
assert_eq!(node.reach, g.reach(name), "{name} reach");
assert_eq!(node.unsatisfied, g.unsatisfied(name), "{name} unsatisfied");
assert_eq!(
node.impact,
g.removal_closure(std::slice::from_ref(name)).len() - 1,
"{name} impact"
);
}
}
#[test]
fn the_dependents_column_is_the_set_the_guard_warns_about() {
// `edges_to` projects `breaking_dependents` rather than walking `edges` again, so this
// holds by construction. Asserted anyway: it is the property that makes the projection
// worth having, and an "optimisation" that inlined the walk would break it silently.
let g = ReverseDeps::build_for(&env(), "3.12.10");
// Compared whole, not by name. Comparing names alone passed a mutation that dropped the
// version and the constraint from every row — the two halves of the sentence the column
// exists to show.
for d in env() {
let guarded: Vec<DepEdge> = g
.breaking_dependents(&d.name)
.into_iter()
.map(DepEdge::from)
.collect();
assert_eq!(g.edges_to(&d.name), guarded, "{} disagrees", d.name);
}
}
/// The shape of a real environment, which no synthetic fixture can supply.
///
/// Everything above is built from six hand-written dists. This one runs the probe against a
/// live interpreter and reports what the graph actually looks like — the numbers that decided
/// the view is drawn at depth 1 and navigated beyond it. Opt-in, like `audit`'s live tests:
///
/// ```text
/// PIPDOCK_GRAPH_PYTHON=C:\Python314\python.exe \
/// cargo test -p pipdock-core --release --lib graph::tests::the_real_environment -- --ignored --nocapture
/// ```
///
/// `--release` is not optional. A debug build measures bounds checks; the same slice measured
/// an index load at 572 ms in debug and 140 ms in release, and a design was justified on the
/// larger number before anyone noticed.
#[tokio::test]
#[ignore = "needs a real interpreter; run with --ignored and PIPDOCK_GRAPH_PYTHON"]
async fn the_real_environment() {
let Ok(exe) = std::env::var("PIPDOCK_GRAPH_PYTHON") else {
panic!("set PIPDOCK_GRAPH_PYTHON to an interpreter path");
};
let probed =
crate::envs::probe(std::path::Path::new(&exe), crate::model::EnvSource::Manual)
.await
.expect("probe succeeds");
let built = std::time::Instant::now();
let g = ReverseDeps::build_for(&probed.dists, &probed.env.python_version);
let build_ms = built.elapsed();
let viewed = std::time::Instant::now();
let view = g.view();
let view_ms = viewed.elapsed();
let json = serde_json::to_string(&view).expect("serializes");
let edges: usize = view.nodes.values().map(|n| n.dependencies.len()).sum();
let mut fan_in: Vec<usize> = view.nodes.values().map(|n| n.dependents.len()).collect();
let mut impacts: Vec<usize> = view.nodes.values().map(|n| n.impact).collect();
fan_in.sort_unstable();
impacts.sort_unstable();
let p = |v: &[usize], q: f64| v[((v.len() as f64 * q) as usize).min(v.len() - 1)];
let leaves = view
.nodes
.values()
.filter(|n| n.dependents.is_empty())
.count();
let missing: usize = view.nodes.values().map(|n| n.unsatisfied.len()).sum();
eprintln!("packages {}", view.nodes.len());
eprintln!("in-force edges {edges}");
eprintln!("build {build_ms:?}");
eprintln!("view {view_ms:?}");
eprintln!("payload {} KB", json.len() / 1024);
eprintln!(
"fan-in median {} p90 {} max {}",
p(&fan_in, 0.5),
p(&fan_in, 0.9),
fan_in.last().copied().unwrap_or(0)
);
eprintln!(
"impact median {} p90 {} max {}",
p(&impacts, 0.5),
p(&impacts, 0.9),
impacts.last().copied().unwrap_or(0)
);
eprintln!("leaves {leaves}");
eprintln!("unsatisfied {missing}");
// Not a benchmark assertion — those belong in `tests/`, and this number is a report. What
// is asserted is the invariant a benchmark cannot state: every installed package has a
// node, and no edge points anywhere but at another node.
assert_eq!(view.nodes.len(), probed.dists.len());
for (name, node) in &view.nodes {
for edge in node.dependencies.iter().chain(&node.dependents) {
assert!(
view.nodes.contains_key(&edge.pkg),
"{name} has an edge to {}, which has no node",
edge.pkg
);
}
}
}
#[test]
fn a_dependency_gated_to_another_platform_is_not_reported_missing() {
// ipython on Windows, as probe schema 3 describes it. pexpect is POSIX-only and was
// reported missing from every Windows environment with ipython in it; colorama is the
// Windows-only one, and *is* missing here.
let probe = crate::envs::ProbeResult {
env: crate::model::PyEnv {
interpreter: "python.exe".into(),
prefix: r"C:\venv".into(),
python_version: "3.14.7".into(),
externally_managed: false,
hidden_user_site: None,
source: crate::model::EnvSource::Manual,
},
dists: vec![dist(
"ipython",
"9.4.0",
&[
r#"pexpect>4.3; sys_platform != "win32" and sys_platform != "emscripten""#,
r#"colorama; sys_platform == "win32""#,
],
)],
markers: [("sys_platform", "win32"), ("os_name", "nt")]
.into_iter()
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect(),
};
let g = ReverseDeps::for_probe(&probe);
assert_eq!(g.unsatisfied(&pkg("ipython")), [pkg("colorama")]);
// Without the platform, both stay in force — the conservative reading, kept for an older
// probe.
let blind = ReverseDeps::build_for(&probe.dists, "3.14.7");
assert_eq!(
blind.unsatisfied(&pkg("ipython")),
[pkg("colorama"), pkg("pexpect")]
);
}
}
+56 -5
View File
@@ -60,6 +60,11 @@ pub struct DirtyTree {
/// Checked rather than reasoned about, and re-check it if the process layer ever changes.
pub async fn dirty(project: &Path) -> Option<DirtyTree> {
let out = Command::new("git")
// **A repository can name a program for `git status` to run**: `core.fsmonitor` in its
// `.git/config`. A project folder the user downloaded rather than cloned carries its own
// `.git/config`, so asking "is it safe to write here" would have run whatever it named
// (M40). Overridden on the command line, which wins over every config file.
.args(["-c", "core.fsmonitor=false"])
.arg("--no-optional-locks")
.arg("status")
.arg("--porcelain")
@@ -234,7 +239,8 @@ pub async fn recheck(
.cwd(project)
.timeout(super::TOOL_TIMEOUT)
.run()
.await?;
.await
.map_err(|e| super::run::watchdog(e, "ruff"))?;
if !super::is_findings_exit("ruff", out.code) {
return Err(PdError::new(
Code::HltToolFailed,
@@ -254,8 +260,8 @@ pub async fn recheck(
/// and `RuffFindings.fixable` counts only `Safe` for the same reason — the number in the dialog
/// has to be the number the fix delivers.
///
/// **`ruff format` is deliberately not wired.** §4's `--check` toggle is read-only and stays
/// default-off. Formatting a whole project is a far larger blast radius than fixing seventeen lint
/// **`ruff format` is deliberately not wired**, not even as a check (CODE-HEALTH-SPEC §1).
/// Formatting a whole project is a far larger blast radius than fixing seventeen lint
/// findings, and §7's non-goals are contractual per ROADMAP's standing risks.
///
/// # Errors
@@ -267,6 +273,7 @@ pub async fn apply(
project: &Path,
before: &super::report::RuffFindings,
consent: FixConsent,
opts: &super::RunOptions,
) -> Result<FixReport> {
use super::report::FixApplicability;
@@ -289,11 +296,24 @@ pub async fn apply(
}
let out = Command::new(&exe)
.args(["check", ".", "--fix", "--output-format", "json"])
.args(fix_argv(opts))
.cwd(project)
.timeout(super::TOOL_TIMEOUT)
.run()
.await?;
.await
.map_err(|e| {
// Stopped part-way through is the one outcome a fix cannot report as nothing: ruff
// writes as it goes, so some files may already be rewritten.
let e = super::run::watchdog(e, "ruff");
if e.code == Code::HltTimeout {
PdError::new(
Code::HltTimeout,
format!("{} — some files may already have been rewritten", e.message),
)
} else {
e
}
})?;
if !super::is_findings_exit("ruff", out.code) {
return Err(PdError::new(
Code::HltToolFailed,
@@ -315,10 +335,41 @@ pub async fn apply(
})
}
/// The read-only run's argv plus `--fix` — **the same exclusions, by construction**.
///
/// The fix ran `check . --fix` with none of them (C4). The preview never looked inside `.venv`,
/// `node_modules` or a notebook, so the fix rewrote files nobody had been shown: site-packages,
/// and every `.ipynb` in the tree. `recheck` and the run share `ruff_argv`; now so does this.
fn fix_argv(opts: &super::RunOptions) -> Vec<String> {
let mut argv = super::run::ruff_argv(opts);
argv.push("--fix".to_owned());
argv
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_fix_excludes_everything_the_preview_excluded() {
let opts = super::super::RunOptions {
excludes: vec!["generated".to_owned()],
..super::super::RunOptions::default()
};
let read = super::super::run::ruff_argv(&opts);
let fix = fix_argv(&opts);
assert_eq!(
&fix[..read.len()],
read.as_slice(),
"the read-only argv, untouched"
);
assert_eq!(fix.last().map(String::as_str), Some("--fix"));
for excluded in ["*.ipynb", ".venv", "node_modules", "generated"] {
assert!(fix.iter().any(|a| a == excluded), "{excluded} is excluded");
}
assert!(!fix.iter().any(|a| a == "--unsafe-fixes"));
}
#[test]
fn a_frontend_claiming_a_clean_tree_against_a_dirty_one_is_refused() {
let found = Some(DirtyTree { entries: 3 });
+146 -59
View File
@@ -37,7 +37,8 @@ pub const TOOL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120
/// CODE-HEALTH-SPEC §4: vulture's default confidence floor.
pub const DEFAULT_MIN_CONFIDENCE: u8 = 80;
/// CODE-HEALTH-SPEC §4: directories excluded from every tool, plus user globs from Settings.
/// CODE-HEALTH-SPEC §4: directories excluded from every tool. (Settings has no globs of its
/// own; a project's `exclude` in its own config is respected by ruff as usual.)
pub const DEFAULT_EXCLUDES: &[&str] = &[".venv", "venv", "node_modules", "build", "dist", ".git"];
/// The release-time pin ledger, baked into the binary (CODE-HEALTH-SPEC §2).
@@ -54,6 +55,36 @@ pub const TOOLS_REQUIREMENTS: &str = include_str!(concat!(
"/../../tools/tools-requirements.txt"
));
/// Every package either venv can install, pinned `==`: the tools' **whole** dependency tree.
///
/// The ledger pins four tools and nothing beneath them, so each sync resolved their thirty-odd
/// dependencies against whatever PyPI held that day — a report was reproducible for a build only
/// as far as the top of the tree, and a compromised or broken release of `requests` or `rich`
/// reached every user on their next Health click (H27). This file constrains without installing,
/// so one file serves both venvs. Generated, never hand-edited — the command is in its header —
/// and a test refuses a ledger pin it does not match. Hashes are the next step and are not here.
///
/// `pip` itself is left out on purpose: it is the installer, pip-audit depends on it, and a
/// constraint would make pip replace itself half-way through installing pip-audit.
pub const TOOLS_CONSTRAINTS: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tools/tools-constraints.txt"
));
/// [`TOOLS_CONSTRAINTS`] as written beside the venv: its pin lines alone, LF-terminated.
#[must_use]
pub fn constraints_body() -> String {
TOOLS_CONSTRAINTS
.lines()
.map(|l| l.split('#').next().unwrap_or("").trim())
.filter(|l| !l.is_empty())
.fold(String::new(), |mut acc, line| {
acc.push_str(line);
acc.push('\n');
acc
})
}
/// The tools actually installed into the venv, out of the shipped ledger.
///
/// The ledger is the **release-time pin set** and also carries `pip-audit` for the post-1.0
@@ -106,8 +137,9 @@ pub const MIN_TOOLS_PYTHON: (u32, u32) = crate::envs::MIN_PROBE_PYTHON;
///
/// * **deptry 0.25.1** — `0` clean, `1` findings
/// * **vulture 2.16** — `0` none, `1` invalid input, `2` bad arguments, `3` dead code
/// * **ruff 0.16.3** — `0` clean, `1` violations, `2` error (re-checked at 0.16.3 on 2026-08-13;
/// 0.16.0 and 0.16.3 produced identical finding sets over two real packages)
/// * **ruff 0.17.1** — `0` clean, `1` violations, `2` error (re-checked at 0.17.1 on 2026-10-16:
/// `health/sample/capture.py` reproduced all four committed `ruff/*.json` byte for byte, and the
/// three exit codes held; 0.16.0 → 0.16.3 had already produced identical finding sets)
///
/// A pin bump has to re-check this, and its real gate is the fixture corpus plus the integration
/// job — not this comment.
@@ -178,19 +210,7 @@ pub fn pins_for(tools: &[&str]) -> Result<Vec<PinnedSpec>> {
/// Same construction as `envs::env_hash`, so there is one hashing idiom in the codebase.
#[must_use]
pub fn pins_hash(pins: &[PinnedSpec]) -> String {
use std::fmt::Write as _;
use sha2::{Digest as _, Sha256};
let digest = Sha256::digest(requirements_body(pins).as_bytes());
digest
.iter()
.fold(String::with_capacity(64), |mut acc, byte| {
// Infallible: writing to a String cannot fail, and `?` here would need a Result return
// for a function that has no other failure mode.
let _ = write!(acc, "{byte:02x}");
acc
})
crate::model::sha256_hex(requirements_body(pins).as_bytes())
}
/// The requirements file written into the tools directory, and the bytes the hash covers.
@@ -214,6 +234,9 @@ const MANIFEST_FILE: &str = "manifest.json";
/// The resolved requirements written beside the venv, for the user to read.
const REQUIREMENTS_FILE: &str = "tools-requirements.txt";
/// [`TOOLS_CONSTRAINTS`], written beside the venv for the install to read.
const CONSTRAINTS_FILE: &str = "tools-constraints.txt";
/// `ERROR_FILENAME_EXCED_RANGE` — Windows' "the path is too long".
const OS_PATH_TOO_LONG: i32 = 206;
@@ -414,10 +437,9 @@ fn parse_ledger(text: &str) -> Result<BTreeMap<PkgName, Version>> {
/// Refuse a ledger version that is not shaped like one.
///
/// The same character-class check `pins::validated_hold` applies, and for the same reason: these
/// strings reach argv as `name==version`, so SECURITY §2's "validated before argv" claim has to
/// hold here too. Deliberately not a full PEP 440 parse — the job is to refuse whitespace, quotes,
/// path separators and control characters, not to second-guess an epoch or a local-version segment.
/// The same `pep440::is_version` check `pins::validated_hold` applies, and for the same reason:
/// these strings reach argv as `name==version`, so SECURITY §2's "validated before argv" claim has
/// to hold here too.
fn validated_version(raw: &str) -> Result<Version> {
let invalid = || {
PdError::new(
@@ -425,14 +447,7 @@ fn validated_version(raw: &str) -> Result<Version> {
format!("invalid version in tools-requirements.txt: {raw:?}"),
)
};
let bytes = raw.as_bytes();
if bytes.is_empty() || !bytes[0].is_ascii_alphanumeric() {
return Err(invalid());
}
if !bytes
.iter()
.all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b'+' | b'!'))
{
if !crate::pep440::is_version(raw) {
return Err(invalid());
}
Ok(Version(raw.to_owned()))
@@ -486,6 +501,9 @@ pub async fn sync_tools_venv(
// and whatever line endings the build machine checked out stop.
std::fs::write(&requirements, requirements_body(&pins))
.map_err(|e| fs_failure("write the tools requirements", &e))?;
let constraints = tools_dir.join(CONSTRAINTS_FILE);
std::fs::write(&constraints, constraints_body())
.map_err(|e| fs_failure("write the tools constraints", &e))?;
// The venv is rebuilt, not repaired. `pip install -r` over an existing venv is a no-op when
// the pins are already satisfied — so a sync run to replace a deleted `ruff.exe` installed
@@ -500,7 +518,7 @@ pub async fn sync_tools_venv(
// needed anyway — `needs_sync` short-circuits the common case in ~30 ms.
remove_venv(&venv)?;
create_venv(base_python, &venv, &sink.at(0)).await?;
install_pins(&venv, &requirements, &sink.at(1)).await?;
install_pins(&venv, &requirements, &constraints, &sink.at(1)).await?;
let tools = verify_tools(tools_dir, tool_set, sink).await?;
let python = venv_python(tools_dir);
@@ -530,6 +548,22 @@ pub async fn sync_tools_venv(
Ok(manifest)
}
/// `pip install --only-binary=:all: -r <pins> -c <the whole tree>`.
fn install_argv(requirements: &Path, constraints: &Path) -> Vec<String> {
vec![
"-m".to_owned(),
"pip".to_owned(),
"install".to_owned(),
"--only-binary=:all:".to_owned(),
"--disable-pip-version-check".to_owned(),
"--no-input".to_owned(),
"-r".to_owned(),
requirements.display().to_string(),
"-c".to_owned(),
constraints.display().to_string(),
]
}
/// Clear the way for a fresh venv.
///
/// A locked file here is the common Windows failure — something is running out of the venv — and
@@ -600,21 +634,17 @@ async fn create_venv(base_python: &Path, venv: &Path, sink: &ProgressSink) -> Re
/// falls back to an sdist build, which ends at `PD-BLD-001` — telling someone who clicked *Health*
/// to install Visual Studio Build Tools. With it, the same situation is a clean resolution failure
/// this maps to `PD-NET-011`. As of 2026-08-12 it never fires, which is exactly when to add it.
async fn install_pins(venv: &Path, requirements: &Path, sink: &ProgressSink) -> Result<()> {
async fn install_pins(
venv: &Path,
requirements: &Path,
constraints: &Path,
sink: &ProgressSink,
) -> Result<()> {
let python = venv.join("Scripts").join("python.exe");
sink.started(None, ExecMode::Batch);
let out = crate::exec::Command::python(&python)
.args([
"-m",
"pip",
"install",
"--only-binary=:all:",
"--disable-pip-version-check",
"--no-input",
"-r",
])
.arg(requirements.display().to_string())
.args(install_argv(requirements, constraints))
.cancel(sink.cancel.clone())
.run_streaming(sink, None, ExecMode::Batch)
.await
@@ -803,17 +833,13 @@ async fn reported_version(path: &Path) -> Option<String> {
/// Re-read a failure out of `exec` before it reaches the user.
///
/// `exec::Command::stopped` raises `PD-INT-001` for **both** its watchdog and cancellation, so
/// every timeout anywhere in PipDock currently says "PipDock hit an internal error". That is a
/// pre-existing defect and bigger than this module, but it must not be inherited here: a bootstrap
/// that stalled for ten minutes is a reachability failure, not a bug report.
fn is_timeout(e: &PdError) -> bool {
e.code == Code::IntUnexpected && e.message.contains("timed out")
}
/// `exec` reports its watchdog as `PD-ENG-004`, an *engine* timeout, and this path is not an
/// engine: a bootstrap that stalled is a reachability failure, a venv that would not build is the
/// interpreter's, and a tool's `--version` hanging is Code Health's. The question is asked of the
/// typed [`PdError::is_timeout`] — it used to be a substring of the message.
/// Remap an `exec` failure from the install step.
fn bootstrap_failure(e: PdError) -> PdError {
if is_timeout(&e) {
if e.is_timeout() {
return PdError::new(
Code::NetToolsBootstrapFailed,
format!("tools venv bootstrap timed out ({})", e.message),
@@ -824,7 +850,7 @@ fn bootstrap_failure(e: PdError) -> PdError {
/// Remap an `exec` failure from the venv step.
fn venv_failure(e: PdError, base_python: &Path) -> PdError {
if is_timeout(&e) {
if e.is_timeout() {
return PdError::new(
Code::HltVenvCreateFailed,
format!("`{} -m venv` timed out", base_python.display()),
@@ -835,7 +861,7 @@ fn venv_failure(e: PdError, base_python: &Path) -> PdError {
/// Remap an `exec` failure from a tool's `--version`.
fn tool_failure(e: PdError, tool: &str) -> PdError {
if is_timeout(&e) {
if e.is_timeout() {
return PdError::new(
Code::HltTimeout,
format!("{tool} --version exceeded its {TOOL_TIMEOUT:?} watchdog"),
@@ -1233,11 +1259,15 @@ mod tests {
);
}
/// `exec::Command::stopped` raises PD-INT-001 for both its watchdog and cancellation, so the
/// remaps below are the only thing standing between a stalled download and a bug report.
/// `exec`'s watchdog is an engine timeout (`PD-ENG-004`); none of these paths is an engine, so
/// the remaps below decide what a stalled download or venv build actually says.
#[test]
fn a_watchdog_never_reaches_the_user_as_an_internal_error() {
let timed_out = || PdError::new(Code::IntUnexpected, "timed out after 600s: pip.exe");
let timed_out = || {
PdError::new(Code::EngTimedOut, "timed out after 600s: pip.exe").with_stop(
crate::exec::Stop::TimedOut(std::time::Duration::from_secs(600)),
)
};
assert_eq!(
bootstrap_failure(timed_out()).code,
@@ -1252,13 +1282,21 @@ mod tests {
#[test]
fn a_cancellation_is_not_mistaken_for_a_watchdog() {
// `stopped` builds both from the same constructor; only the message tells them apart, and
// a cancel must not be reported as a bootstrap failure.
let cancelled = PdError::new(Code::IntUnexpected, "cancelled: pip.exe");
// A cancel must not be reported as a bootstrap failure.
let cancelled = PdError::new(Code::IntUnexpected, "cancelled: pip.exe")
.with_stop(crate::exec::Stop::Cancelled);
assert_eq!(bootstrap_failure(cancelled).code, Code::IntUnexpected);
}
#[test]
fn the_message_alone_no_longer_decides() {
// The remap used to be `message.contains("timed out")`, so any error whose text happened
// to say so — pip's own "Read timed out" is a network failure — was relabelled a watchdog.
let pips_own = PdError::new(Code::NetUnreachable, "pip: Read timed out.");
assert_eq!(bootstrap_failure(pips_own).code, Code::NetUnreachable);
}
#[test]
fn the_filesystem_codes_are_the_ones_whose_user_action_differs() {
use std::io::Error;
@@ -1303,8 +1341,9 @@ mod tests {
/// The whole bootstrap, against real PyPI, into a scratch directory.
///
/// `#[ignore]`d because `cargo test --workspace` must not need a network. CI runs it explicitly
/// (`ci-integration.yml`), and so should anyone touching this module:
/// `#[ignore]`d because `cargo test --workspace` must not need a network. No CI job runs this
/// test — `ci-integration.yml` drives the same bootstrap end to end through `pipdock tools
/// sync` instead — so anyone touching this module should:
/// `cargo test -p pipdock-core -- --ignored the_bootstrap`.
#[tokio::test]
#[ignore = "hits real PyPI; run with --ignored"]
@@ -1433,4 +1472,52 @@ mod tests {
);
pins_hash(&pins)
}
#[test]
fn every_tool_is_constrained_at_the_version_the_ledger_pins() {
// A Dependabot bump of a tool that is not followed by regenerating the constraints would
// install the tool at one version and constrain it at another: pip refuses that, and every
// user's next Health click fails with PD-NET-011.
let ledger = parse_ledger(TOOLS_REQUIREMENTS).expect("ledger parses");
let body = constraints_body();
for (name, version) in &ledger {
let line = format!("{name}=={version}");
assert!(
body.lines()
.any(|l| l == line || l.starts_with(&format!("{line} ;"))),
"tools-constraints.txt does not pin {line}. Regenerate it with the command in its \
header"
);
}
}
#[test]
fn the_constraints_are_exact_pins_and_never_pip() {
for line in constraints_body().lines() {
let (pin, marker) = line.split_once(" ; ").unwrap_or((line, ""));
let (name, version) = pin.split_once("==").unwrap_or_else(|| panic!("{line}"));
let name = PkgName::parse(name).unwrap_or_else(|_| panic!("{line}"));
assert!(crate::pep440::is_version(version), "{line}");
assert_ne!(
name.as_str(),
"pip",
"pip is the installer, not a dependency to pin"
);
assert!(
marker
.chars()
.all(|c| c.is_ascii_alphanumeric() || " ._'<>=!~()".contains(c)),
"{line}"
);
}
assert!(constraints_body().lines().count() > HEALTH_TOOLS.len() + AUDIT_TOOLS.len());
}
#[test]
fn the_install_is_constrained_by_the_whole_tree() {
let argv = install_argv(Path::new("req.txt"), Path::new("con.txt"));
let at = argv.iter().position(|a| a == "-c").expect("-c");
assert_eq!(argv[at + 1], "con.txt");
assert!(argv.iter().any(|a| a == "--only-binary=:all:"));
}
}
+49 -11
View File
@@ -36,15 +36,6 @@ impl DeclaredSource {
}
}
/// What `project` declares its dependencies in (CODE-HEALTH-SPEC §3's detection order).
///
/// `pyproject.toml` wins outright when present, rather than being merged with any
/// `requirements*.txt` beside it. That is deptry's own precedence, and reporting both would invite
/// the UI to explain a distinction deptry did not make.
///
/// # Errors
/// `PD-ENV-003` when the folder cannot be read at all — a path that is not a directory, or one the
/// user cannot list. Health has nothing to run against in either case.
/// Refuse a project folder Code Health must not run in.
///
/// SECURITY §2 validates package names, versions and interpreter paths; the project folder is the
@@ -57,7 +48,7 @@ impl DeclaredSource {
/// # Errors
/// `PD-ENV-003` when the path is not a readable directory, or is inside `tools_dir`.
pub fn validate_project(project: &Path, tools_dir: &Path) -> Result<PathBuf> {
let canonical = project.canonicalize().map_err(|e| {
let canonical = project.canonicalize().map(plain).map_err(|e| {
PdError::new(
Code::EnvProbeFailed,
format!("cannot read {}: {e}", project.display()),
@@ -70,7 +61,7 @@ pub fn validate_project(project: &Path, tools_dir: &Path) -> Result<PathBuf> {
));
}
// Compared against the canonical tools path, or `..` walks straight past this.
if let Ok(tools) = tools_dir.canonicalize()
if let Ok(tools) = tools_dir.canonicalize().map(plain)
&& canonical.starts_with(&tools)
{
return Err(PdError::new(
@@ -84,6 +75,37 @@ pub fn validate_project(project: &Path, tools_dir: &Path) -> Result<PathBuf> {
Ok(canonical)
}
/// A canonical path without Windows' verbatim prefix.
///
/// `canonicalize` returns `\\?\C:\…`. Used as a tool's working directory, every filename ruff
/// and vulture reported came back under that prefix — on screen, in the saved report — and the
/// report's own project path read the same (M47). The drive and UNC forms are the only two a
/// project folder can take; anything else is returned untouched.
#[must_use]
pub fn plain(path: PathBuf) -> PathBuf {
let Some(text) = path.to_str() else {
return path;
};
if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
return PathBuf::from(format!(r"\\{rest}"));
}
if let Some(rest) = text.strip_prefix(r"\\?\")
&& rest.as_bytes().get(1) == Some(&b':')
{
return PathBuf::from(rest);
}
path
}
/// What `project` declares its dependencies in (CODE-HEALTH-SPEC §3's detection order).
///
/// `pyproject.toml` wins outright when present, rather than being merged with any
/// `requirements*.txt` beside it. That is deptry's own precedence, and reporting both would invite
/// the UI to explain a distinction deptry did not make.
///
/// # Errors
/// `PD-ENV-003` when the folder cannot be read at all — a path that is not a directory, or one the
/// user cannot list. Health has nothing to run against in either case.
pub fn declared_source(project: &Path) -> Result<DeclaredSource> {
let unreadable = |e: &dyn std::fmt::Display| {
PdError::new(
@@ -228,4 +250,20 @@ mod tests {
fn write(dir: &Path, name: &str) {
std::fs::write(dir.join(name), "").expect("write");
}
#[test]
fn a_verbatim_path_comes_back_plain() {
assert_eq!(
plain(PathBuf::from(r"\\?\C:\Dự án\proj")),
PathBuf::from(r"C:\Dự án\proj")
);
assert_eq!(
plain(PathBuf::from(r"\\?\UNC\server\share\proj")),
PathBuf::from(r"\\server\share\proj")
);
assert_eq!(plain(PathBuf::from(r"C:\proj")), PathBuf::from(r"C:\proj"));
// A volume GUID path has no drive letter to fall back to, so it stays as it is.
let guid = r"\\?\Volume{0b1c2d3e-0000-0000-0000-000000000000}\proj";
assert_eq!(plain(PathBuf::from(guid)), PathBuf::from(guid));
}
}
+16 -17
View File
@@ -165,9 +165,15 @@ pub async fn run(
continue;
}
match run_one(tools_dir, project, opts, tool).await {
Ok(out) => {
collect(&mut report, tool, &out)?;
// A tool whose output cannot be read is that tool's problem, like one that cannot run. The
// `?` this replaced returned from the whole run, so one deptry format change took ruff's
// and vulture's findings with it — the skip-and-continue rule, broken at the last step
// (H24).
match run_one(tools_dir, project, opts, tool)
.await
.and_then(|out| collect(&mut report, tool, &out))
{
Ok(()) => {
step.finished(Some(name), ExecMode::Isolated, StepStatus::Ok);
}
Err(e) => {
@@ -224,7 +230,7 @@ async fn run_one(
})?;
}
let out = Command::new(&exe)
let out = Command::python_tool(&exe)
.args(argv(tool, opts, &report_path))
.cwd(project)
.timeout(TOOL_TIMEOUT)
@@ -378,8 +384,8 @@ fn collect(report: &mut HealthReport, tool: &str, stdout: &str) -> Result<()> {
///
/// Found by replacing a tool with a non-executable file of the same name — present, so the sync
/// check said Fresh, and unrunnable, so the run reached this path.
fn watchdog(e: PdError, tool: &str) -> PdError {
if e.code == Code::IntUnexpected && e.message.contains("timed out") {
pub(super) fn watchdog(e: PdError, tool: &str) -> PdError {
if e.is_timeout() {
return PdError::new(
Code::HltTimeout,
format!("{tool} exceeded its {TOOL_TIMEOUT:?} watchdog; its results are missing"),
@@ -405,15 +411,6 @@ pub fn has_findings(report: &HealthReport) -> bool {
!report.deptry.is_empty() || !report.vulture.is_empty() || !report.ruff.findings.is_empty()
}
/// Ensure `total` is not smaller than what will actually be emitted.
///
/// A sink whose total is wrong is a progress bar that stops short or overshoots, and the caller
/// cannot always know whether a tools-venv sync will be needed until it asks.
#[must_use]
pub fn sink_for(sink: &ProgressSink, first_step: usize) -> ProgressSink {
sink.at(first_step)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -535,7 +532,8 @@ mod tests {
}
#[test]
fn a_watchdog_reads_as_the_health_code_not_an_internal_error() {
let timed_out = PdError::new(Code::IntUnexpected, "timed out after 120s: ruff.exe");
let timed_out = PdError::new(Code::EngTimedOut, "timed out after 120s: ruff.exe")
.with_stop(crate::exec::Stop::TimedOut(TOOL_TIMEOUT));
assert_eq!(watchdog(timed_out, "ruff").code, Code::HltTimeout);
}
@@ -582,7 +580,8 @@ mod tests {
#[test]
fn a_cancellation_is_not_a_watchdog() {
let cancelled = PdError::new(Code::IntUnexpected, "cancelled: ruff.exe");
let cancelled = PdError::new(Code::IntUnexpected, "cancelled: ruff.exe")
.with_stop(crate::exec::Stop::Cancelled);
assert_eq!(watchdog(cancelled, "ruff").code, Code::IntUnexpected);
}
+136 -32
View File
@@ -272,15 +272,19 @@ pub struct RefreshReport {
/// offers to disable verification.
///
/// # Errors
/// `PD-NET-010` when the fetch or ingest fails. The previous index is left in place and stays
/// searchable, because a failed refresh must not cost the user the index they already had.
/// `PD-NET-001`/`PD-NET-002` when PyPI cannot be reached or TLS fails (read from the error's
/// source chain), `PD-NET-010` when it answers with something that is not an index. Either way
/// the previous index is left in place and stays searchable, because a failed refresh must not
/// cost the user the index they already had.
pub async fn refresh(app_data: &std::path::Path, now: jiff::Timestamp) -> Result<RefreshReport> {
let started = std::time::Instant::now();
let client = http_client()?;
let response = client
let response = shared_client()?
.get(SIMPLE_INDEX_URL)
.header("Accept", PEP691_ACCEPT)
// Tens of megabytes. The client's connect and read timeouts catch a dead connection; a
// slow one that is still delivering gets this long (M36).
.timeout(REFRESH_TIMEOUT)
.send()
.await
.map_err(|e| net_err("could not fetch the package index", &e))?;
@@ -298,34 +302,52 @@ pub async fn refresh(app_data: &std::path::Path, now: jiff::Timestamp) -> Result
.map_err(|e| net_err("could not read the package index", &e))?;
let wire_bytes = body.len();
let doc: serde_json::Value = serde_json::from_slice(&body).map_err(|e| {
// Typed, borrowing the names out of the body: a `serde_json::Value` of 700,000 objects is the
// whole document again in allocations, for a parse that only wants one field of each (M36).
#[derive(serde::Deserialize)]
struct Simple<'a> {
#[serde(borrow)]
projects: Vec<Project<'a>>,
}
#[derive(serde::Deserialize)]
struct Project<'a> {
#[serde(borrow)]
name: std::borrow::Cow<'a, str>,
}
let doc: Simple<'_> = serde_json::from_slice(&body).map_err(|e| {
PdError::new(
Code::NetIndexRefreshFailed,
format!("index is not JSON: {e}"),
format!("the package index is not the PEP 691 document: {e}"),
)
})?;
let projects = doc
.get("projects")
.and_then(serde_json::Value::as_array)
.ok_or_else(|| {
PdError::new(
Code::NetIndexRefreshFailed,
"index JSON has no `projects` array",
)
})?;
let rows: Vec<(String, String)> = projects
// An empty list is not an index, whatever said it was: a captive portal or a broken mirror.
// Ingesting it replaced every name with none, and search found nothing until the next week's
// refresh (L55).
if doc.projects.is_empty() {
return Err(PdError::new(
Code::NetIndexRefreshFailed,
"the package index listed no projects; the previous index is kept",
));
}
let rows: Vec<(String, String)> = doc
.projects
.iter()
.filter_map(|p| p.get("name")?.as_str())
.map(|name| (crate::model::normalize_name(name), name.to_owned()))
.map(|p| (crate::model::normalize_name(&p.name), p.name.to_string()))
.collect();
// Opened only now, after the download: the ingest is synchronous, so the handle never spans an
// await. Holding one open across a multi-second PyPI transfer would block every other command
// that wanted the store, for no benefit.
let store = Store::open(app_data)?;
ingest(&store, &rows)?;
store.set(KEY_LAST_REFRESH, &now.to_string())?;
// Opened only now, after the download, and on a blocking thread: hundreds of thousands of
// inserts are a second of synchronous work, which on an async worker stalls every other task
// scheduled there (M36). The handle never spans an await.
let app_data = app_data.to_path_buf();
let stamp = now.to_string();
let rows = tokio::task::spawn_blocking(move || -> Result<Vec<(String, String)>> {
let store = Store::open(&app_data)?;
ingest(&store, &rows)?;
store.set(KEY_LAST_REFRESH, &stamp)?;
Ok(rows)
})
.await
.map_err(|e| PdError::new(Code::IntUnexpected, format!("index ingest stopped: {e}")))??;
Ok(RefreshReport {
projects: rows.len(),
@@ -497,7 +519,9 @@ fn cached_metadata(
async fn fetch_metadata(name: &PkgName) -> Result<PackageMeta> {
let url = format!("https://pypi.org/pypi/{}/json", name.as_str());
let response = http_client()?
// The shared client: a new one per call meant a new connection pool and TLS handshake for
// every package opened in Search (M37).
let response = shared_client()?
.get(&url)
.send()
.await
@@ -532,6 +556,23 @@ async fn fetch_metadata(name: &PkgName) -> Result<PackageMeta> {
})
}
/// One PyPI client for the process, for the many small requests a plan's lookups make — each
/// [`http_client`] call builds a connection pool and a TLS configuration from scratch.
///
/// # Errors
/// `PD-INT-001` when the client cannot be built.
pub(crate) fn shared_client() -> Result<&'static reqwest::Client> {
static CLIENT: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
if let Some(client) = CLIENT.get() {
return Ok(client);
}
let client = http_client()?;
Ok(CLIENT.get_or_init(|| client))
}
/// The whole-request ceiling for the index download, which is tens of megabytes.
const REFRESH_TIMEOUT: Duration = Duration::from_secs(600);
/// An HTTPS client restricted to PyPI's hosts.
///
/// SECURITY §4: certificate verification is always on and redirects may not leave `pypi.org` or
@@ -541,6 +582,11 @@ fn http_client() -> Result<reqwest::Client> {
reqwest::Client::builder()
.user_agent(concat!("pipdock/", env!("CARGO_PKG_VERSION")))
// A dead connection is caught by these; a request's own `.timeout` bounds the whole
// thing. One 120 s total used to cover both, which a slow link downloading the index
// could exceed while making progress the whole time (M36).
.connect_timeout(Duration::from_secs(15))
.read_timeout(Duration::from_secs(60))
.timeout(Duration::from_secs(120))
.redirect(reqwest::redirect::Policy::custom(|attempt| {
let host_ok = attempt.url().host_str().is_some_and(|h| {
@@ -559,15 +605,36 @@ fn http_client() -> Result<reqwest::Client> {
}
fn net_err(what: &str, e: &reqwest::Error) -> PdError {
// A TLS failure gets its own code because its guidance is different: corporate proxy or AV
// interception, and never "turn verification off" (SECURITY §4).
let text = e.to_string().to_ascii_lowercase();
let code = if text.contains("certificate") || text.contains("tls") || text.contains("ssl") {
let chain = error_chain(e);
PdError::new(net_code(&chain), format!("{what}: {chain}"))
}
/// An error and every `source()` beneath it, as one line.
///
/// reqwest's own message is "error sending request for url (…)"; the reason — refused, reset,
/// "invalid peer certificate: UnknownIssuer" — is in the chain beneath it, and reading only the
/// top made every TLS failure PD-NET-001, so PD-NET-002's corporate-proxy guidance never showed
/// (M32).
fn error_chain(e: &dyn std::error::Error) -> String {
let mut out = e.to_string();
let mut source = e.source();
while let Some(s) = source {
out.push_str(": ");
out.push_str(&s.to_string());
source = s.source();
}
out
}
/// A TLS failure gets its own code because its guidance is different: corporate proxy or AV
/// interception, and never "turn verification off" (SECURITY §4).
fn net_code(chain: &str) -> Code {
let text = chain.to_ascii_lowercase();
if text.contains("certificate") || text.contains("tls") || text.contains("ssl") {
Code::NetTlsFailure
} else {
Code::NetUnreachable
};
PdError::new(code, format!("{what}: {e}"))
}
}
#[cfg(test)]
@@ -795,4 +862,41 @@ mod tests {
.expect("write");
assert_eq!(last_refresh(&store).expect("read"), Some(now));
}
#[test]
fn a_tls_failure_below_a_generic_message_is_still_a_tls_failure() {
// reqwest says "error sending request"; the certificate is two sources down.
#[derive(Debug)]
struct Layer(&'static str, Option<Box<Layer>>);
impl std::fmt::Display for Layer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for Layer {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.1.as_deref().map(|l| l as _)
}
}
let e = Layer(
"error sending request for url (https://pypi.org/simple/)",
Some(Box::new(Layer(
"client error (Connect)",
Some(Box::new(Layer(
"invalid peer certificate: UnknownIssuer",
None,
))),
))),
);
let chain = error_chain(&e);
assert!(
chain.ends_with("invalid peer certificate: UnknownIssuer"),
"{chain}"
);
assert_eq!(net_code(&chain), Code::NetTlsFailure);
assert_eq!(
net_code("error sending request: connection refused"),
Code::NetUnreachable
);
}
}
+255
View File
@@ -0,0 +1,255 @@
//! The legal-documents hash: the re-consent trigger `build.rs` bakes into the binary.
//!
//! A file of its own so that `build.rs` can `#[path]`-include it — a build script cannot use the
//! crate it builds — and so the tests below exercise the very function that runs there, rather
//! than a copy of it.
/// Hash `(name, contents)` pairs into the value consent is stored against (UI-SPEC §4).
///
/// Line endings are normalised **before anything is hashed, the length included**. The length
/// used to be taken of the raw bytes, two lines above a normalisation that existed precisely so a
/// CRLF checkout — Windows' default — would hash like an LF one. It did not: every build from a
/// CRLF checkout carried a different hash from one built on an LF checkout of the same commit,
/// which is a legal gate shown again for nothing (X25).
#[must_use]
pub fn docs_hash(documents: &[(&str, &[u8])]) -> String {
let mut hasher = Sha256::new();
for (name, bytes) in documents {
let text = normalise(bytes);
hasher.update(name.as_bytes());
hasher.update(&(text.len() as u64).to_le_bytes());
hasher.update(&text);
}
hex(&hasher.finish())
}
fn normalise(bytes: &[u8]) -> Vec<u8> {
bytes.iter().copied().filter(|b| *b != b'\r').collect()
}
fn hex(digest: &[u8; 32]) -> String {
digest.iter().fold(String::with_capacity(64), |mut acc, b| {
use std::fmt::Write as _;
let _ = write!(acc, "{b:02x}");
acc
})
}
/// A small SHA-256, so the build script needs no dependencies.
///
/// A build-dependency here would be one more crate in the supply chain of the thing that decides
/// whether users see the legal gate (SECURITY §7). FIPS 180-4.
struct Sha256 {
state: [u32; 8],
buffer: Vec<u8>,
length: u64,
}
const K: [u32; 64] = [
0x428a_2f98,
0x7137_4491,
0xb5c0_fbcf,
0xe9b5_dba5,
0x3956_c25b,
0x59f1_11f1,
0x923f_82a4,
0xab1c_5ed5,
0xd807_aa98,
0x1283_5b01,
0x2431_85be,
0x550c_7dc3,
0x72be_5d74,
0x80de_b1fe,
0x9bdc_06a7,
0xc19b_f174,
0xe49b_69c1,
0xefbe_4786,
0x0fc1_9dc6,
0x240c_a1cc,
0x2de9_2c6f,
0x4a74_84aa,
0x5cb0_a9dc,
0x76f9_88da,
0x983e_5152,
0xa831_c66d,
0xb003_27c8,
0xbf59_7fc7,
0xc6e0_0bf3,
0xd5a7_9147,
0x06ca_6351,
0x1429_2967,
0x27b7_0a85,
0x2e1b_2138,
0x4d2c_6dfc,
0x5338_0d13,
0x650a_7354,
0x766a_0abb,
0x81c2_c92e,
0x9272_2c85,
0xa2bf_e8a1,
0xa81a_664b,
0xc24b_8b70,
0xc76c_51a3,
0xd192_e819,
0xd699_0624,
0xf40e_3585,
0x106a_a070,
0x19a4_c116,
0x1e37_6c08,
0x2748_774c,
0x34b0_bcb5,
0x391c_0cb3,
0x4ed8_aa4a,
0x5b9c_ca4f,
0x682e_6ff3,
0x748f_82ee,
0x78a5_636f,
0x84c8_7814,
0x8cc7_0208,
0x90be_fffa,
0xa450_6ceb,
0xbef9_a3f7,
0xc671_78f2,
];
impl Sha256 {
fn new() -> Self {
Self {
state: [
0x6a09_e667,
0xbb67_ae85,
0x3c6e_f372,
0xa54f_f53a,
0x510e_527f,
0x9b05_688c,
0x1f83_d9ab,
0x5be0_cd19,
],
buffer: Vec::new(),
length: 0,
}
}
fn update(&mut self, data: &[u8]) {
self.length = self.length.wrapping_add(data.len() as u64);
self.buffer.extend_from_slice(data);
while self.buffer.len() >= 64 {
let block: [u8; 64] = self.buffer[..64].try_into().unwrap_or([0; 64]);
self.compress(&block);
self.buffer.drain(..64);
}
}
fn finish(mut self) -> [u8; 32] {
let bits = self.length.wrapping_mul(8);
self.buffer.push(0x80);
while self.buffer.len() % 64 != 56 {
self.buffer.push(0);
}
let tail = bits.to_be_bytes();
self.buffer.extend_from_slice(&tail);
while self.buffer.len() >= 64 {
let block: [u8; 64] = self.buffer[..64].try_into().unwrap_or([0; 64]);
self.compress(&block);
self.buffer.drain(..64);
}
let mut out = [0u8; 32];
let (words, _) = out.as_chunks_mut::<4>();
for (chunk, word) in words.iter_mut().zip(self.state) {
*chunk = word.to_be_bytes();
}
out
}
fn compress(&mut self, block: &[u8; 64]) {
let mut w = [0u32; 64];
let (words, _) = block.as_chunks::<4>();
for (slot, chunk) in w.iter_mut().zip(words) {
*slot = u32::from_be_bytes(*chunk);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = self.state;
for i in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ ((!e) & g);
let t1 = h
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(K[i])
.wrapping_add(w[i]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let t2 = s0.wrapping_add(maj);
h = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
for (slot, value) in self.state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
*slot = slot.wrapping_add(value);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_crlf_checkout_hashes_like_an_lf_one() {
let lf = docs_hash(&[
("LICENSE", b"GPL\nv3\n"),
("legal/EULA.md", b"# EULA\n\nterms\n"),
]);
let crlf = docs_hash(&[
("LICENSE", b"GPL\r\nv3\r\n"),
("legal/EULA.md", b"# EULA\r\n\r\nterms\r\n"),
]);
assert_eq!(lf, crlf);
}
#[test]
fn a_changed_document_changes_the_hash() {
let before = docs_hash(&[("legal/EULA.md", b"terms\n")]);
let after = docs_hash(&[("legal/EULA.md", b"terms, amended\n")]);
assert_ne!(before, after);
}
#[test]
fn a_document_moving_between_files_changes_the_hash() {
// The length is what separates one document from the next: without it, text moved from
// the end of one file to the start of the next would hash the same.
let a = docs_hash(&[("a", b"xy"), ("b", b"z")]);
let b = docs_hash(&[("a", b"x"), ("b", b"yz")]);
assert_ne!(a, b);
}
#[test]
fn the_sha256_is_sha256() {
// The build script carries its own SHA-256 so it needs no dependency (SECURITY §7). The
// library has sha2 anyway, which makes it the oracle — across block boundaries.
use sha2::Digest as _;
for len in [0_usize, 1, 55, 56, 63, 64, 65, 119, 1000] {
let data: Vec<u8> = (0..len).map(|i| (i * 31 % 251) as u8).collect();
let mut ours = Sha256::new();
ours.update(&data);
let theirs: [u8; 32] = sha2::Sha256::digest(&data).into();
assert_eq!(ours.finish(), theirs, "length {len}");
}
}
}
+11 -3
View File
@@ -17,9 +17,8 @@
//!
//! # Status
//!
//! Phase 0. Types and command surfaces are defined; behaviour lands in M1, gated on the spikes in
//! `docs/ROADMAP.md`. In particular [`engine::uv`] is gated on SP-1, which decides whether v1.0
//! ships both engines.
//! Shipped, with both engines, since 1.0. What is built and what is owed is `docs/ROADMAP.md`; the
//! spikes whose findings bind every adapter are `spikes/README.md`.
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
@@ -31,14 +30,23 @@ pub mod engine;
pub mod envs;
pub mod errors;
pub mod exec;
// The L3 fixtures are generated by xtask and checked by a test here; nothing in a release build
// reads them, so they are not compiled into one.
#[cfg(any(test, feature = "fixtures"))]
pub mod fixtures;
pub mod flow;
pub mod graph;
pub mod health;
pub mod index;
// build.rs's legal-documents hash, compiled here only so its tests run with the others.
#[cfg(test)]
mod legal_hash;
pub mod logging;
pub mod model;
pub mod pep440;
pub mod pins;
pub mod plan;
pub mod release;
pub mod report;
pub mod requirements;
pub mod settings;
+275
View File
@@ -0,0 +1,275 @@
//! Where PipDock's own log goes: one file per day under `data\logs\`, kept for
//! [`crate::LOG_RETENTION_DAYS`].
//!
//! Until 1.4.0 there was none. `tracing` was a dependency of three crates and called zero times,
//! the CLI's `--verbose` and `--log-file` were parsed and ignored, `LOG_RETENTION_DAYS` had no
//! reader — and the privacy policy described "log files (14-day rotation)" that did not exist. A
//! bug report could attach the last run's engine output and nothing about what PipDock did.
//!
//! This module owns the parts both heads share: the daily file, the sweep, reading the tail back.
//! The subscriber — which levels go where — is each head's, because only the head knows whether a
//! terminal is listening. **Nothing here ever writes to stdout**: stdout is the CLI's contract.
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
/// The log directory under the app-data root.
#[must_use]
pub fn log_dir(app_data: &Path) -> PathBuf {
app_data.join("logs")
}
/// One file per (UTC) day: `<prefix>.<YYYY-MM-DD>.log`, opened on first write and reopened when
/// the day changes. Cloning shares the open file.
///
/// UTC rather than local time, so a file's name and the timestamps inside it agree without
/// consulting a time-zone database.
#[derive(Debug, Clone)]
pub struct DailyFile {
inner: Arc<Mutex<Inner>>,
}
#[derive(Debug)]
struct Inner {
dir: PathBuf,
prefix: &'static str,
open: Option<(jiff::civil::Date, std::fs::File)>,
}
impl DailyFile {
/// Log under `dir` as `<prefix>.<date>.log` — `pipdock` for the GUI, `pipdock-cli` for the CLI,
/// so two heads running at once never interleave lines in one file.
#[must_use]
pub fn new(dir: impl Into<PathBuf>, prefix: &'static str) -> Self {
Self {
inner: Arc::new(Mutex::new(Inner {
dir: dir.into(),
prefix,
open: None,
})),
}
}
/// Today's file — what a user is pointed at when something went wrong.
#[must_use]
pub fn current_path(&self) -> PathBuf {
let inner = self.lock();
file_for(&inner.dir, inner.prefix, today())
}
fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
self.inner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
impl std::io::Write for DailyFile {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let mut inner = self.lock();
let day = today();
if inner.open.as_ref().is_none_or(|(d, _)| *d != day) {
std::fs::create_dir_all(&inner.dir)?;
let file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(file_for(&inner.dir, inner.prefix, day))?;
inner.open = Some((day, file));
}
match &mut inner.open {
Some((_, file)) => {
file.write_all(buf)?;
Ok(buf.len())
}
None => Ok(buf.len()),
}
}
fn flush(&mut self) -> std::io::Result<()> {
match &mut self.lock().open {
Some((_, file)) => file.flush(),
None => Ok(()),
}
}
}
fn today() -> jiff::civil::Date {
jiff::Timestamp::now()
.to_zoned(jiff::tz::TimeZone::UTC)
.date()
}
fn file_for(dir: &Path, prefix: &str, day: jiff::civil::Date) -> PathBuf {
dir.join(format!("{prefix}.{day}.log"))
}
/// The date in a file name this module wrote, if it is one.
fn date_of(name: &str) -> Option<jiff::civil::Date> {
let stem = name.strip_suffix(".log")?;
let (_, date) = stem.rsplit_once('.')?;
date.parse().ok()
}
/// Delete log files older than `keep_days`. Returns how many went.
///
/// Only files whose name carries a date this module could have written are considered, so a
/// file a user dropped into the folder is never touched. A file that cannot be removed — open in
/// an editor — is left for the next sweep.
pub fn sweep(dir: &Path, keep_days: u32, now: jiff::Timestamp) -> usize {
let Ok(entries) = std::fs::read_dir(dir) else {
return 0;
};
let today = now.to_zoned(jiff::tz::TimeZone::UTC).date();
let Ok(oldest) = today.checked_sub(jiff::Span::new().days(i64::from(keep_days))) else {
return 0;
};
entries
.flatten()
.filter(|e| {
e.file_name()
.to_str()
.and_then(date_of)
.is_some_and(|d| d < oldest)
})
.filter(|e| std::fs::remove_file(e.path()).is_ok())
.count()
}
/// The end of PipDock's own log, for Settings' Logs row (ARCHITECTURE §7).
#[derive(
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct LogTail {
/// The folder the log files are in. A path — data, never localized (I18N §2).
pub dir: String,
/// The most recent lines, oldest first. Empty when nothing has been logged yet.
pub lines: Vec<String>,
}
/// The last `max_lines` lines across the newest log files in `dir`, oldest first.
///
/// Reads backwards through the files by date, so a tail that straddles midnight still has the
/// lines from before it. Bounded: at most a few files are read.
#[must_use]
pub fn tail(dir: &Path, max_lines: usize) -> Vec<String> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut files: Vec<(jiff::civil::Date, String, PathBuf)> = entries
.flatten()
.filter_map(|e| {
let name = e.file_name().to_str()?.to_owned();
Some((date_of(&name)?, name, e.path()))
})
.collect();
// Newest first; within a day, by name, so the two heads' files stay in a fixed order.
files.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.cmp(&a.1)));
let mut lines: Vec<String> = Vec::new();
for (_, _, path) in files.iter().take(4) {
let Ok(text) = std::fs::read_to_string(path) else {
continue;
};
let mut chunk: Vec<String> = text.lines().map(str::to_owned).collect();
chunk.append(&mut lines);
lines = chunk;
if lines.len() >= max_lines {
break;
}
}
let start = lines.len().saturating_sub(max_lines);
lines.split_off(start)
}
/// Record a panic in the log before the default hook prints it.
///
/// A GUI panic otherwise vanishes with the window: there is no terminal to print to, and the next
/// launch has no trace of why the last one ended.
pub fn install_panic_hook() {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
tracing::error!(target: "pipdock::panic", "{info}");
previous(info);
}));
}
#[cfg(test)]
mod tests {
use std::io::Write as _;
use super::*;
fn scratch(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("pd-logs-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
dir
}
#[test]
fn lines_land_in_todays_file_and_never_anywhere_else() {
let dir = scratch("write");
let mut log = DailyFile::new(&dir, "pipdock-cli");
writeln!(log, "first").expect("write");
writeln!(log.clone(), "second").expect("write through a clone");
let path = log.current_path();
assert!(
path.file_name()
.unwrap()
.to_str()
.unwrap()
.starts_with("pipdock-cli.")
);
assert_eq!(
std::fs::read_to_string(&path).expect("read"),
"first\nsecond\n"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_sweep_keeps_fourteen_days_and_nothing_it_did_not_write() {
let dir = scratch("sweep");
std::fs::create_dir_all(&dir).expect("dir");
for name in [
"pipdock.2026-09-30.log",
"pipdock-cli.2026-10-01.log",
"pipdock.2026-10-02.log",
"pipdock.2026-10-16.log",
"notes.txt",
"pipdock.not-a-date.log",
] {
std::fs::write(dir.join(name), "x").expect("seed");
}
let now: jiff::Timestamp = "2026-10-16T12:00:00Z".parse().expect("now");
assert_eq!(sweep(&dir, 14, now), 2);
let mut left: Vec<String> = std::fs::read_dir(&dir)
.expect("read")
.flatten()
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
left.sort();
assert_eq!(
left,
[
"notes.txt",
"pipdock.2026-10-02.log",
"pipdock.2026-10-16.log",
"pipdock.not-a-date.log"
]
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_tail_spans_files_and_keeps_order() {
let dir = scratch("tail");
std::fs::create_dir_all(&dir).expect("dir");
std::fs::write(dir.join("pipdock.2026-10-15.log"), "a\nb\nc\n").expect("seed");
std::fs::write(dir.join("pipdock.2026-10-16.log"), "d\ne\n").expect("seed");
assert_eq!(tail(&dir, 3), ["c", "d", "e"]);
assert_eq!(tail(&dir, 50), ["a", "b", "c", "d", "e"]);
assert!(tail(&scratch("absent"), 5).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
}
+173 -12
View File
@@ -1,10 +1,25 @@
//! Core domain types shared by every module, the CLI and the GUI.
//!
//! These are the types `specta`/`tauri-specta` will export to TypeScript (ARCHITECTURE §9), so
//! their serde representation is part of the public contract — see `docs/CLI-SPEC.md` §6.
//! These are the types `cargo run -p xtask -- bindings` exports to TypeScript through `schemars`
//! (ARCHITECTURE §9, as `bindings.rs` corrects it), so their serde representation is part of the
//! public contract — see `docs/CLI-SPEC.md` §6.
use std::path::PathBuf;
/// SHA-256 of `data`, as lowercase hex. Three hashes folded their own digests by hand.
#[must_use]
pub(crate) fn sha256_hex(data: &[u8]) -> String {
use sha2::{Digest as _, Sha256};
use std::fmt::Write as _;
Sha256::digest(data)
.iter()
.fold(String::with_capacity(64), |mut acc, byte| {
// Infallible: writing to a String cannot fail.
let _ = write!(acc, "{byte:02x}");
acc
})
}
use crate::errors::{Code, PdError, Result};
/// Which resolver PipDock is driving.
@@ -170,7 +185,9 @@ impl PkgName {
impl std::fmt::Display for PkgName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
// `pad`, not `write_str`: the CLI lays tables out with `{:<32}`, and `write_str` ignores
// width — every name column printed unaligned (X27).
f.pad(&self.0)
}
}
@@ -206,24 +223,92 @@ pub struct Version(pub String);
impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
f.pad(&self.0)
}
}
/// What the user asked for: a name, optionally constrained.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[derive(Debug, Clone, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Spec {
/// Normalized distribution name.
pub name: PkgName,
/// PEP 440 specifier such as `">=2,<3"`, or `None` for "latest".
/// PEP 440 specifier such as `">=2,<3"` (or a bare version, read as `==`), or `None` for
/// "latest". Validated on every way in — [`Spec::parse`] and deserialization — so it is
/// never prose, a marker or an option by the time it reaches argv.
pub version_req: Option<String>,
}
impl Spec {
/// Parse what a user typed, or what a requirements file said: `name`, `name==1.0`,
/// `name>=5.0,<6`, `name ~= 1.4`, `name===legacy`.
///
/// The flow used to split on `==` alone, so every imported range failed — `django>=5.0,<6`
/// became the "package name" `django>=5.0,<6` and PD-PKG-002 — and `pkg===1.0` became
/// `pkg` at version `=1.0`.
///
/// # Errors
/// `PD-PKG-002` when the name is not a distribution name or the rest is not a PEP 440
/// specifier set.
pub fn parse(raw: &str) -> Result<Self> {
let raw = raw.trim();
let end = raw
.find(|c: char| matches!(c, '=' | '<' | '>' | '!' | '~') || c.is_whitespace())
.unwrap_or(raw.len());
let name = PkgName::parse(raw[..end].trim())?;
let rest = raw[end..].trim();
if rest.is_empty() {
return Ok(Self {
name,
version_req: None,
});
}
if !crate::pep440::is_specifier_set(rest) {
return Err(PdError::new(
Code::PkgNotFound,
format!("not a version specifier: {rest:?}"),
));
}
Ok(Self {
name,
version_req: Some(crate::pep440::normalize_specifier_set(rest)),
})
}
}
/// Deserialize through the same checks as [`Spec::parse`] — the IPC door, as for [`PkgName`].
impl<'de> serde::Deserialize<'de> for Spec {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Raw {
name: PkgName,
version_req: Option<String>,
}
let raw = Raw::deserialize(deserializer)?;
let version_req = match raw.version_req {
None => None,
Some(v) if crate::pep440::is_version(&v) => Some(v),
Some(v) if crate::pep440::is_specifier_set(&v) => {
Some(crate::pep440::normalize_specifier_set(&v))
}
Some(v) => {
return Err(serde::de::Error::custom(format!(
"not a version specifier: {v:?}"
)));
}
};
Ok(Self {
name: raw.name,
version_req,
})
}
}
/// A resolved, exact `name==version` pair. Only these reach a mutating engine command.
#[derive(
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, schemars::JsonSchema)]
pub struct PinnedSpec {
/// Normalized distribution name.
pub name: PkgName,
@@ -232,10 +317,43 @@ pub struct PinnedSpec {
}
impl PinnedSpec {
/// Render as the `name==version` argv token.
/// Render as the argv token: `name==version`, or `name===version` for an installed version
/// that is not PEP 440 (packaging dropped `LegacyVersion`, so `==` would be refused).
///
/// Every producer of a `PinnedSpec` admits only a [`crate::pep440::is_argv_safe`] version —
/// the parsers, the guard set, the snapshot reader and deserialization all check — so this
/// cannot render a marker, a URL or whitespace into one token.
#[must_use]
pub fn to_requirement(&self) -> String {
format!("{}=={}", self.name, self.version)
if crate::pep440::is_version(&self.version.0) {
format!("{}=={}", self.name, self.version)
} else {
format!("{}==={}", self.name, self.version)
}
}
}
/// Deserialize with the version checked, the same door [`PkgName`] closes for names.
impl<'de> serde::Deserialize<'de> for PinnedSpec {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
#[derive(serde::Deserialize)]
struct Raw {
name: PkgName,
version: Version,
}
let raw = Raw::deserialize(deserializer)?;
if !crate::pep440::is_argv_safe(&raw.version.0) {
return Err(serde::de::Error::custom(format!(
"not a version: {:?}",
raw.version.0
)));
}
Ok(Self {
name: raw.name,
version: raw.version,
})
}
}
@@ -338,11 +456,17 @@ pub struct CheckFinding {
/// Post-execution environment verification.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct CheckReport {
/// True when the engine reported no broken requirements.
/// True when the check **ran** and the engine reported no broken requirements.
pub ok: bool,
/// Details when `ok` is false.
#[serde(default)]
pub findings: Vec<CheckFinding>,
/// Set when the check could not run at all, with the reason's code; `ok` is false then.
///
/// A check that could not run used to be reported as `ok: true` — "verified" in exactly the
/// case where nothing was verified, such as a pip broken by the run it was meant to check.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<Code>,
}
#[cfg(test)]
@@ -439,4 +563,41 @@ mod tests {
};
assert_eq!(spec.to_requirement(), "typing-extensions==4.12.2");
}
#[test]
fn a_spec_from_the_ipc_door_is_validated_like_one_from_a_parser() {
let ok: Spec = serde_json::from_str(r#"{"name":"Django","versionReq":">=5.0, <6"}"#)
.expect("a range deserializes");
assert_eq!(ok.name.as_str(), "django");
assert_eq!(ok.version_req.as_deref(), Some(">=5.0,<6"));
let bare: Spec = serde_json::from_str(r#"{"name":"idna","versionReq":"3.10"}"#)
.expect("a bare version deserializes");
assert_eq!(bare.version_req.as_deref(), Some("3.10"));
for junk in [
r#"{"name":"x","versionReq":"2.0 ; python_version<'0'"}"#,
r#"{"name":"x","versionReq":"--break-system-packages"}"#,
] {
assert!(serde_json::from_str::<Spec>(junk).is_err(), "{junk}");
}
}
#[test]
fn a_pinned_spec_refuses_a_version_that_could_be_more_than_one() {
assert!(serde_json::from_str::<PinnedSpec>(r#"{"name":"x","version":"1.0 ; x"}"#).is_err());
let ok: PinnedSpec =
serde_json::from_str(r#"{"name":"x","version":"1.0"}"#).expect("a version");
assert_eq!(ok.to_requirement(), "x==1.0");
}
#[test]
fn a_legacy_installed_version_is_restated_with_arbitrary_equality() {
// packaging dropped LegacyVersion, so `==1.0-SNAPSHOT` is refused; `===` compares strings.
let spec = PinnedSpec {
name: PkgName::parse("old").expect("name"),
version: Version("1.0-SNAPSHOT".into()),
};
assert_eq!(spec.to_requirement(), "old===1.0-SNAPSHOT");
}
}
+359
View File
@@ -0,0 +1,359 @@
//! PEP 440 at the boundary where text becomes argv (SECURITY §2).
//!
//! SECURITY §2 has always said names *and versions* are validated before they reach an argv array.
//! Names were — [`crate::model::PkgName`] is the only way one gets there — but versions were plain
//! strings: a dock-bay entry of `2.0 ; python_version<'0'` became one argv token pip accepted as a
//! requirement whose marker is false, so the install silently did nothing, and an imported
//! `django>=5.0,<6` failed outright because the flow split on `==` alone. This module is the one
//! place that decides what a version and a specifier set may look like.
//!
//! It is a **grammar check**, not an ordering: nothing here compares versions (that is
//! [`crate::compat`]'s job, and the engines'). It accepts what `packaging`'s `VERSION_PATTERN`
//! accepts — epochs, pre/post/dev segments in all their spellings, local labels — so a legitimate
//! version is never refused, and it rejects everything else, which is what keeps whitespace,
//! markers (`;`), URLs (`@`) and option-looking tokens out of argv.
/// Is `raw` a PEP 440 version (the permissive `VERSION_PATTERN`, case-insensitive)?
#[must_use]
pub fn is_version(raw: &str) -> bool {
Parser::new(raw).version()
}
/// Is `raw` safe to put after `===` (PEP 440 "arbitrary equality")?
///
/// Installed metadata can carry versions that are not PEP 440 — pip still lists them — and the
/// guard set must restate them. `===` compares strings, so the only requirement is that the token
/// cannot be read as anything *but* a version: ASCII alphanumerics and `. _ + ! -`, starting with
/// an alphanumeric. No whitespace, `;`, `@`, quotes, commas or operators.
#[must_use]
pub fn is_argv_safe(raw: &str) -> bool {
let bytes = raw.as_bytes();
!bytes.is_empty()
&& bytes[0].is_ascii_alphanumeric()
&& bytes
.iter()
.all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'!' | b'-'))
}
/// Is `raw` a PEP 440 specifier set: `op version` clauses separated by commas?
///
/// Whitespace is allowed around commas and between an operator and its version (`~= 1.4`), never
/// inside a version. `==` and `!=` may end in `.*`; `===` takes any [`is_argv_safe`] token. An
/// empty string is **not** a specifier set — callers that allow "any version" check for that
/// themselves, so an empty clause like `>=1,` cannot slip through as one.
#[must_use]
pub fn is_specifier_set(raw: &str) -> bool {
!raw.trim().is_empty() && raw.split(',').all(is_clause)
}
/// The normalized form of a specifier set: whitespace removed around operators and commas.
///
/// Only call on something [`is_specifier_set`] accepted. `~= 1.4, <2` becomes `~=1.4,<2`, a single
/// argv-safe token.
#[must_use]
pub fn normalize_specifier_set(raw: &str) -> String {
raw.split(',')
.map(|clause| {
let clause = clause.trim();
let (op, rest) = split_operator(clause).unwrap_or(("", clause));
format!("{op}{}", rest.trim())
})
.collect::<Vec<_>>()
.join(",")
}
fn is_clause(clause: &str) -> bool {
let clause = clause.trim();
let Some((op, version)) = split_operator(clause) else {
return false;
};
let version = version.trim();
if version.is_empty() || version.contains(char::is_whitespace) {
return false;
}
match op {
"===" => is_argv_safe(version),
"==" | "!=" => {
// `==1.4.*` is a prefix match; the wildcard may only replace the final release part.
version
.strip_suffix(".*")
.map_or_else(|| is_version(version), is_release_prefix)
}
// `~=` needs at least two release segments (PEP 440); the grammar check is enough here
// and the engine will say so if it disagrees.
_ => is_version(version),
}
}
fn split_operator(clause: &str) -> Option<(&'static str, &str)> {
// Longest first, so `===` is not read as `==` followed by `=1.0`.
["===", "==", "!=", "<=", ">=", "~=", "<", ">"]
.into_iter()
.find_map(|op| clause.strip_prefix(op).map(|rest| (op, rest)))
}
/// `1`, `1.4`, `1!2.0` — what may precede `.*` in a prefix match.
fn is_release_prefix(raw: &str) -> bool {
let mut p = Parser::new(raw);
p.epoch();
p.release() && p.done()
}
/// A recursive-descent reader over `packaging`'s `VERSION_PATTERN`, lowercased.
struct Parser {
s: Vec<u8>,
at: usize,
}
impl Parser {
/// Not trimmed: a version is one argv token, and `" 1.0"` is not one. Callers that read a
/// clause with spaces around it (`~= 1.4`) trim the clause, not the version inside it.
fn new(raw: &str) -> Self {
Self {
s: raw.to_ascii_lowercase().into_bytes(),
at: 0,
}
}
fn done(&self) -> bool {
self.at == self.s.len()
}
fn peek(&self) -> Option<u8> {
self.s.get(self.at).copied()
}
fn eat(&mut self, b: u8) -> bool {
if self.peek() == Some(b) {
self.at += 1;
true
} else {
false
}
}
fn eat_word(&mut self, words: &[&str]) -> bool {
// Longest first is the caller's job; `words` is ordered that way below.
for w in words {
if self.s[self.at..].starts_with(w.as_bytes()) {
self.at += w.len();
return true;
}
}
false
}
fn digits(&mut self) -> bool {
let start = self.at;
while self.peek().is_some_and(|b| b.is_ascii_digit()) {
self.at += 1;
}
self.at > start
}
fn sep(&mut self) {
if matches!(self.peek(), Some(b'-' | b'_' | b'.')) {
self.at += 1;
}
}
/// `(N!)?` — only consumed when the digits really are followed by `!`.
fn epoch(&mut self) {
let save = self.at;
if !(self.digits() && self.eat(b'!')) {
self.at = save;
}
}
/// `N(.N)*`
fn release(&mut self) -> bool {
if !self.digits() {
return false;
}
loop {
let save = self.at;
if self.eat(b'.') && self.digits() {
continue;
}
self.at = save;
return true;
}
}
/// An optional segment `[-_.]? label [-_.]? N?`; restores the position when absent.
fn labelled(&mut self, labels: &[&str]) -> bool {
let save = self.at;
self.sep();
if self.eat_word(labels) {
let after = self.at;
self.sep();
if !self.digits() {
// The separator after a label is only part of the segment when digits follow.
self.at = after;
}
true
} else {
self.at = save;
false
}
}
fn post(&mut self) {
let save = self.at;
// `-N` is an implicit post-release.
if self.eat(b'-') && self.digits() {
return;
}
self.at = save;
self.labelled(&["post", "rev", "r"]);
}
fn local(&mut self) -> bool {
if !self.eat(b'+') {
return true;
}
let part = |p: &mut Self| {
let start = p.at;
while p.peek().is_some_and(|b| b.is_ascii_alphanumeric()) {
p.at += 1;
}
p.at > start
};
if !part(self) {
return false;
}
while matches!(self.peek(), Some(b'-' | b'_' | b'.')) {
self.at += 1;
if !part(self) {
return false;
}
}
true
}
fn version(mut self) -> bool {
if self.s.is_empty() {
return false;
}
self.eat(b'v');
self.epoch();
if !self.release() {
return false;
}
self.labelled(&["alpha", "beta", "preview", "pre", "rc", "a", "b", "c"]);
self.post();
self.labelled(&["dev"]);
self.local() && self.done()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn real_versions_are_accepted_in_every_spelling() {
for v in [
"1",
"1.0",
"2.32.3",
"1!2.0",
"1.0a1",
"1.0.alpha.1",
"1.0-beta2",
"1.0rc1",
"1.0c3",
"1.0.post1",
"1.0-1",
"1.0.rev2",
"1.0.dev0",
"1.0a1.dev2",
"1.0+ubuntu.1",
"1.0+abc-def_ghi",
"v1.2",
"2026.10.16",
"1.0.post",
"1.0.dev",
] {
assert!(is_version(v), "{v} is PEP 440");
}
}
#[test]
fn anything_that_is_not_a_version_is_refused() {
for v in [
"",
" ",
"2.0 ; python_version<'0'",
"1.0 --break-system-packages",
"1.0@https://evil",
"latest",
"1..0",
"1.0+",
"1.0+a..b",
">=1.0",
"1.0,2.0",
"1.0 2.0",
"'1.0'",
"1.0;",
"SNAPSHOT",
" 1.0",
"1.0 ",
] {
assert!(!is_version(v), "{v:?} must not pass as a version");
}
}
#[test]
fn specifier_sets_accept_what_requirements_files_contain() {
for s in [
"==2.32.3",
">=5.0,<6",
">=5.0, <6",
"~= 1.4",
"!=1.0.*",
"==1.4.*",
"===1.0-legacy",
">1,!=1.5,<2",
"<=2026.1",
] {
assert!(is_specifier_set(s), "{s:?} is a specifier set");
}
}
#[test]
fn specifier_sets_refuse_prose_markers_urls_and_options() {
for s in [
"",
">=1,",
"is not a requirement",
"==1.0 ; python_version<'3'",
"==1.0 --break-system-packages",
"@ https://example.com/x.whl",
"==",
"1.0",
">=1.0 <2",
"==1.*.0",
"~=1.0.*",
"===has space",
] {
assert!(!is_specifier_set(s), "{s:?} must be refused");
}
}
#[test]
fn normalizing_removes_only_the_whitespace_pep_440_allows() {
assert_eq!(normalize_specifier_set("~= 1.4, < 2"), "~=1.4,<2");
assert_eq!(normalize_specifier_set(">=5.0,<6"), ">=5.0,<6");
}
#[test]
fn arbitrary_equality_takes_a_legacy_version_but_nothing_that_could_be_more() {
assert!(is_argv_safe("1.0-SNAPSHOT"));
assert!(is_argv_safe("2.0.0.final"));
assert!(!is_argv_safe("1.0 ; x"));
assert!(!is_argv_safe("-1.0"));
assert!(!is_argv_safe("1.0@x"));
assert!(!is_argv_safe(""));
}
}
+39 -28
View File
@@ -21,11 +21,14 @@ use crate::store::Store;
)]
#[serde(rename_all = "kebab-case")]
pub enum PinMode {
/// Excluded from bulk updates. The user can still update it deliberately, one package at a
/// time — a pin is "do not sweep this up", not "never touch this".
/// Left out of every update until it is unpinned (DATA-FLOW §9.5), whether the update names
/// it or sweeps it up with *Select all*.
// This said "bulk updates" and that the user "can still update it deliberately, one package
// at a time", which nothing implemented: `filter_upgrades` has always applied to a named
// package as much as to *Select all*. §9.5 is the rule; unpinning is the deliberate step.
Exclude,
/// Held at an exact version: excluded from bulk updates *and* restated at this version in
/// every plan, so the resolver treats it as fixed.
/// Held at an exact version: left out of every update *and* restated at this version in
/// every plan, so the resolver treats it as fixed — including as another package's dependency.
Hold {
/// The version to hold at.
version: Version,
@@ -106,10 +109,10 @@ pub fn list(store: &Store, env_hash: &str) -> Result<Vec<Pin>> {
/// but `Version` is a transparent newtype over whatever the engine reported — so the one place a
/// *user* supplies a version is the one place that claim needs enforcing.
///
/// Deliberately a character-class check and not a full PEP 440 parse. The job is to refuse
/// whitespace, quotes, path separators and control characters, not to second-guess an epoch or a
/// local-version segment that the resolver understands better than PipDock does. Rejecting a
/// legitimate version would be the worse failure: it would make a package unpinnable.
/// The PEP 440 grammar check every argv boundary shares (`pep440::is_version`), not a resolver's
/// parse: it refuses whitespace, quotes, separators and anything else no version contains, and
/// leaves epochs and local segments to the engine. Rejecting a legitimate version would be the
/// worse failure — it would make a package unpinnable.
fn validated_hold(version: &Version) -> Result<&str> {
let raw = version.0.as_str();
let invalid = || {
@@ -118,14 +121,8 @@ fn validated_hold(version: &Version) -> Result<&str> {
format!("invalid version for a pin: {raw:?}"),
)
};
let bytes = raw.as_bytes();
if bytes.is_empty() || !bytes[0].is_ascii_alphanumeric() {
return Err(invalid());
}
if !bytes
.iter()
.all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b'+' | b'!'))
{
// The one PEP 440 check, shared with the tools ledger and every argv boundary.
if !crate::pep440::is_version(raw) {
return Err(invalid());
}
Ok(raw)
@@ -256,8 +253,8 @@ pub struct PinSuggestion {
/// rough edge rather than an oversight, and both are on the same screen so it is visible.
#[must_use]
pub fn suggest(
graph: &ReverseDeps,
dists: &[Dist],
python_version: &str,
existing: &[Pin],
threshold: usize,
) -> Vec<PinSuggestion> {
@@ -268,10 +265,9 @@ pub fn suggest(
}
let pinned: BTreeSet<&PkgName> = existing.iter().map(|p| &p.pkg).collect();
// `build_for`, not `build`: without the interpreter, a requirement gated on some other
// `python_version` counts as if it were in force, and the suggestion inherits the same wrong
// answer the preview used to give (SP-5).
let graph = ReverseDeps::build_for(dists, python_version);
// The caller builds the graph — `ReverseDeps::for_probe` in production, since without the
// interpreter and platform a gated requirement counts as if it were in force and the
// suggestion inherits the wrong answer the preview used to give (SP-5).
let mut out: Vec<PinSuggestion> = dists
.iter()
@@ -352,7 +348,10 @@ mod tests {
#[test]
fn a_package_below_the_threshold_is_not_suggested() {
let dists = depended_on_by("urllib3", 4);
assert_eq!(suggest(&dists, "3.12.4", &[], 5), Vec::new());
assert_eq!(
suggest(&ReverseDeps::build_for(&dists, "3.12.4"), &dists, &[], 5),
Vec::new()
);
}
#[test]
@@ -360,7 +359,7 @@ mod tests {
// PRD P1-2 says "count >= threshold". Off by one here means the default of 5 fires at 6,
// and nobody would notice because both are plausible.
let dists = depended_on_by("urllib3", 5);
let got = suggest(&dists, "3.12.4", &[], 5);
let got = suggest(&ReverseDeps::build_for(&dists, "3.12.4"), &dists, &[], 5);
assert_eq!(got.len(), 1);
assert_eq!(got[0].pkg, pkg("urllib3"));
assert_eq!(got[0].dependents, 5);
@@ -371,7 +370,10 @@ mod tests {
// Suggesting what the user has already done is noise, however high the count.
let dists = depended_on_by("urllib3", 50);
let pins = vec![exclude("urllib3", None)];
assert_eq!(suggest(&dists, "3.12.4", &pins, 5), Vec::new());
assert_eq!(
suggest(&ReverseDeps::build_for(&dists, "3.12.4"), &dists, &pins, 5),
Vec::new()
);
}
#[test]
@@ -386,7 +388,10 @@ mod tests {
dist(&name, &["urllib3; extra == \"socks\""])
}))
.collect();
assert_eq!(suggest(&dists, "3.12.4", &[], 5), Vec::new());
assert_eq!(
suggest(&ReverseDeps::build_for(&dists, "3.12.4"), &dists, &[], 5),
Vec::new()
);
}
#[test]
@@ -399,7 +404,10 @@ mod tests {
dist(&name, &["urllib3; python_version < \"3.11\""])
}))
.collect();
assert_eq!(suggest(&dists, "3.12.4", &[], 5), Vec::new());
assert_eq!(
suggest(&ReverseDeps::build_for(&dists, "3.12.4"), &dists, &[], 5),
Vec::new()
);
}
#[test]
@@ -420,7 +428,7 @@ mod tests {
dists.push(dist(&format!("extra{i}"), &["urllib3"]));
}
let got = suggest(&dists, "3.12.4", &[], 5);
let got = suggest(&ReverseDeps::build_for(&dists, "3.12.4"), &dists, &[], 5);
let names: Vec<&str> = got.iter().map(|s| s.pkg.as_str()).collect();
assert_eq!(names, ["urllib3", "certifi", "idna"]);
assert_eq!(got[0].dependents, 10);
@@ -433,7 +441,10 @@ mod tests {
// The degenerate setting. Every package trivially has >= 0 dependents, so without the
// guard this offers to pin the whole environment, leaves included.
let dists = depended_on_by("urllib3", 6);
assert_eq!(suggest(&dists, "3.12.4", &[], 0), Vec::new());
assert_eq!(
suggest(&ReverseDeps::build_for(&dists, "3.12.4"), &dists, &[], 0),
Vec::new()
);
}
#[test]
+373 -147
View File
@@ -5,10 +5,11 @@
pub mod preview;
pub use preview::{
Decision, ForcedPlan, apply_decisions, default_decision, derive_held_back, forced_requirements,
Decision, ForcedPlan, apply_decisions, default_decision, derive_forced, derive_held_back,
forced_collisions, forced_requirements,
};
use crate::engine::{Engine, ProgressSink};
use crate::engine::{Engine, InstallSet, ProgressSink, SystemPackages};
use crate::errors::{Code, PdError, Result};
use crate::model::{
CheckReport, ExecMode, PinnedSpec, PkgName, PyEnv, Spec, StepResult, StepStatus, Version,
@@ -118,6 +119,27 @@ pub struct HeldBack {
pub blockers: Vec<Blocker>,
}
/// A pin the user asked for that cannot install on this environment's Python (`PD-PKG-001`).
///
/// Hard invariant 10 says PipDock enforces `Requires-Python` itself, because the engines disagree:
/// pip refuses such a pin with the same "No matching distribution" it uses for a typo, and uv
/// ignores an upper bound and plans it. Structured, not a sentence (invariant 4): the preview shows
/// the required range against the environment's version, and a catalog cannot un-join a string.
#[derive(
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct PythonMismatch {
/// The package.
pub pkg: PkgName,
/// The version that was asked for or planned.
pub version: Version,
/// That release's `Requires-Python`, verbatim.
pub requires_python: String,
/// The environment's Python, e.g. `"3.12.4"`.
pub python: String,
}
/// A `ResolutionImpossible` outcome and whatever detail the engine gave (`PD-RES-001`).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct ImpossibleDetail {
@@ -151,8 +173,30 @@ pub struct ResolutionReport {
/// Present when the whole resolution failed.
#[serde(skip_serializing_if = "Option::is_none")]
pub impossible: Option<ImpossibleDetail>,
/// The engine's untouched output, kept for the log and for bug reports.
/// Pins left out because their `Requires-Python` excludes this environment (`PD-PKG-001`).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub incompatible: Vec<PythonMismatch>,
/// Packages the user chose to **force** past what installed dependents allow, each with what
/// it will break — the "Will break" section of the preview (DISCLAIMER §2).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub forced: Vec<HeldBack>,
/// Yanked releases the plan would install. A warning, not a failure (`PD-PKG-003`, SP-2):
/// both engines exit 0 and install them. Both adapters parsed these and then dropped them, so
/// the preview never showed one.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub yanked: Vec<crate::engine::parse::YankWarning>,
/// What the engine wrote while resolving — uv's plan, pip's warnings — for the log ring and
/// the debug log. **Never on the wire.** It used to be, as pip's whole `--report` document
/// with every package's README inside it, cloned into each `FlowStep` and serialized over IPC
/// on every round (33 KB for two packages; megabytes for "update all").
#[serde(skip)]
#[schemars(skip)]
pub raw: String,
/// What the engine itself said each planned release requires of Python — pip's report carries
/// it, uv's plan does not. For the flow's own check (hard invariant 10); never on the wire.
#[serde(skip)]
#[schemars(skip)]
pub declared_python: std::collections::BTreeMap<PkgName, String>,
}
impl ResolutionReport {
@@ -214,7 +258,7 @@ pub struct ExecutionSummary {
pub counts: Counts,
/// True when the user stopped this run part-way.
///
/// ARCHITECTURE §7 words this as `Skipped(UserCancelled)`, but [`StepStatus`] is a
/// DATA-FLOW §3 used to word this as `Skipped(UserCancelled)`, but [`StepStatus`] is a
/// payload-free enum and giving it one changes the wire shape for every consumer. A flag on
/// the summary also matches what the summary sheet actually needs: "cancelled" is said once
/// at the top, not repeated on forty rows.
@@ -286,6 +330,7 @@ pub fn json_schema(type_name: &str) -> Result<serde_json::Value> {
"CacheUsage" => crate::cache::Usage,
"CacheTarget" => crate::cache::Target,
"GuardReport" => crate::graph::GuardReport,
"DepsGraph" => crate::graph::DepsGraph,
"Diff" => crate::snapshot::Diff,
"SnapshotMeta" => crate::snapshot::Meta,
"EngineInfo" => crate::model::EngineInfo,
@@ -306,6 +351,7 @@ pub fn json_schema(type_name: &str) -> Result<serde_json::Value> {
"HealthReport" => crate::health::HealthReport,
"AuditReport" => crate::audit::AuditReport,
"FixReport" => crate::health::fix::FixReport,
"LogTail" => crate::logging::LogTail,
}
}
@@ -325,6 +371,7 @@ pub const SCHEMA_TYPES: &[&str] = &[
"CacheUsage",
"CacheTarget",
"GuardReport",
"DepsGraph",
"Diff",
"SnapshotMeta",
"EngineInfo",
@@ -342,6 +389,7 @@ pub const SCHEMA_TYPES: &[&str] = &[
"HealthReport",
"AuditReport",
"FixReport",
"LogTail",
];
/// DATA-FLOW §9.3: a report older than this is refused by [`execute`] and must be re-resolved.
@@ -351,6 +399,15 @@ pub const PLAN_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(10
/// prevents decision ping-pong.
pub const MAX_CONFLICT_ROUNDS: u8 = 3;
/// How many times one forced resolve may release guard pins the engine names as colliding with a
/// forced package, before the impossibility is shown as it stands. See
/// [`preview::forced_collisions`].
pub const FORCE_RELEASE_ROUNDS: usize = 3;
/// How many times one resolve may rule out releases whose `Requires-Python` excludes this
/// environment and ask again, before what remains is shown as a warning.
pub const PYTHON_EXCLUDE_ROUNDS: usize = 2;
/// A [`ResolutionReport`] the user has confirmed.
///
/// **This type is how DATA-FLOW §9.1 stops being a rule and starts being a fact.** There is no
@@ -371,30 +428,43 @@ pub struct AcceptedPlan {
pub env_hash: String,
/// Fingerprint of the installed set at resolve time, for the drift check.
pub probe_hash: String,
/// Whether the PEP 668 override applies to the installs this plan runs.
pub system: SystemPackages,
}
impl AcceptedPlan {
/// Record the user's confirmation of a report.
///
/// `installed` and `resolved_at` are the **basis the report was made against** — the listing
/// the preview was resolved over, and when — not the moment of confirmation. The flow used to
/// pass the current time and the resolve-time listing back to a check against the same
/// listing, so neither half of §9.3 could ever fire (C1). `id` is the flow's, so the summary
/// and the snapshot taken for it carry one id (M31).
#[must_use]
pub fn accept(
id: String,
report: ResolutionReport,
env_hash: String,
installed: &[crate::model::Dist],
now: jiff::Timestamp,
resolved_at: jiff::Timestamp,
) -> Self {
Self {
id: format!(
"{}-{}",
&env_hash[..8.min(env_hash.len())],
now.as_millisecond()
),
id,
report,
accepted_at: now,
accepted_at: resolved_at,
env_hash,
probe_hash: fingerprint(installed),
system: SystemPackages::Protected,
}
}
/// The same plan, run with the PEP 668 override. Only a flow's preamble decides this.
#[must_use]
pub const fn with_system_packages(mut self, system: SystemPackages) -> Self {
self.system = system;
self
}
/// DATA-FLOW §9.3: refuse a plan that is too old, or one whose environment has drifted.
///
/// Both cases mean the preview the user approved no longer describes what would happen — and
@@ -409,58 +479,76 @@ impl AcceptedPlan {
installed: &[crate::model::Dist],
now: jiff::Timestamp,
) -> Result<()> {
let age = now
.as_millisecond()
.saturating_sub(self.accepted_at.as_millisecond());
if age < 0 || u128::try_from(age).unwrap_or(u128::MAX) > PLAN_MAX_AGE.as_millis() {
return Err(PdError::new(
Code::ResPlanStale,
format!(
"this preview is older than {} minutes — re-run it",
PLAN_MAX_AGE.as_secs() / 60
),
));
}
if env_hash != self.env_hash {
return Err(PdError::new(
Code::ResPlanStale,
"this preview was made for a different environment",
));
}
if fingerprint(installed) != self.probe_hash {
return Err(PdError::new(
Code::ResPlanStale,
"the environment changed since the preview was made — re-run it",
));
}
Ok(())
verify_basis(self.accepted_at, &self.probe_hash, installed, now)
}
}
/// DATA-FLOW §9.3's two refusals, for any decision made against a listing of an environment: it
/// is older than [`PLAN_MAX_AGE`], or the environment no longer matches the listing.
///
/// Shared by the three flows. A removal's guard and a rollback's restore plan are decisions made
/// against a listing just as a preview is, and both were executed against whatever the environment
/// had become (M44).
///
/// # Errors
/// `PD-RES-002` in either case.
pub fn verify_basis(
made_at: jiff::Timestamp,
fingerprint_then: &str,
installed_now: &[crate::model::Dist],
now: jiff::Timestamp,
) -> Result<()> {
verify_age(made_at, now)?;
if fingerprint(installed_now) != fingerprint_then {
return Err(PdError::new(
Code::ResPlanStale,
"the environment changed since the preview was made — re-run it",
));
}
Ok(())
}
/// The age half of [`verify_basis`], for a decision whose drift is checked another way.
///
/// # Errors
/// `PD-RES-002` when `made_at` is more than [`PLAN_MAX_AGE`] before `now`, or after it.
pub fn verify_age(made_at: jiff::Timestamp, now: jiff::Timestamp) -> Result<()> {
let age = now
.as_millisecond()
.saturating_sub(made_at.as_millisecond());
if age < 0 || u128::try_from(age).unwrap_or(u128::MAX) > PLAN_MAX_AGE.as_millis() {
return Err(PdError::new(
Code::ResPlanStale,
format!(
"this preview is older than {} minutes — re-run it",
PLAN_MAX_AGE.as_secs() / 60
),
));
}
Ok(())
}
/// A cheap, order-independent fingerprint of an installed set.
///
/// Order-independent on purpose: engines do not promise a stable listing order, and a reordering
/// is not drift. Only the set of `name==version` pairs matters.
#[must_use]
pub fn fingerprint(installed: &[crate::model::Dist]) -> String {
use std::fmt::Write as _;
use sha2::{Digest as _, Sha256};
let mut pairs: Vec<String> = installed
.iter()
.map(|d| format!("{}=={}", d.name, d.version))
.collect();
pairs.sort_unstable();
let digest = Sha256::digest(pairs.join("\n").as_bytes());
digest
.iter()
.take(16)
.fold(String::with_capacity(32), |mut acc, b| {
let _ = write!(acc, "{b:02x}");
acc
})
let mut hex = crate::model::sha256_hex(pairs.join("\n").as_bytes());
hex.truncate(32);
hex
}
/// Execute a confirmed plan (ARCHITECTURE §8, DATA-FLOW §3).
@@ -495,7 +583,8 @@ pub async fn execute(
now: jiff::Timestamp,
sink: ProgressSink,
) -> Result<ExecutionSummary> {
plan.verify(&plan.env_hash, installed_now, now)?;
// Against the environment actually being changed. This compared the plan's hash with itself.
plan.verify(&crate::envs::env_hash(&env.interpreter), installed_now, now)?;
let pinned = plan.report.pinned_set();
if pinned.is_empty() {
@@ -503,10 +592,7 @@ pub async fn execute(
plan_id: plan.id.clone(),
phase: ExecMode::Batch,
results: Vec::new(),
check: engine.check(env).await.unwrap_or(CheckReport {
ok: true,
findings: Vec::new(),
}),
check: post_check(engine, env).await,
counts: Counts::default(),
cancelled: false,
});
@@ -517,61 +603,93 @@ pub async fn execute(
total: pinned.len(),
..sink
};
// What each package moves *from*. The engine cannot say — pip's report has no "before" and an
// adapter runs one command — so every row used to carry `from: None`, and the summary and
// `--json` called every upgrade a fresh install.
let before: std::collections::BTreeMap<&crate::model::PkgName, &crate::model::Version> = plan
.report
.changes
.iter()
.filter_map(|c| c.from.as_ref().map(|v| (&c.name, v)))
.collect();
let row = |spec: &PinnedSpec, status: StepStatus| StepResult {
pkg: spec.name.clone(),
from: before.get(&spec.name).map(|v| (*v).clone()),
to: Some(spec.version.clone()),
status,
code: None,
stderr_tail: None,
};
// Phase A. The markers are emitted here rather than inside the adapter for the same reason
// `step` is: an adapter runs one command and cannot know its position in the plan.
let batch_sink = sink.at(0);
batch_sink.started(None, ExecMode::Batch);
// **An `Err` here is an outcome, not a reason to abandon the run.** The adapters return one
// when the batch is stopped (cancel, watchdog) or cannot start, and the `?` this replaced sent
// all three out of `execute` as PD-INT-001: no summary, no "cancelled", no rollback offer, and
// the cancelled-Phase-A branch below unreachable outside a test whose fake returned `Ok`.
let batch = engine
.install(env, &pinned, ExecMode::Batch, batch_sink.clone())
.await?;
batch_sink.finished(None, ExecMode::Batch, batch.status);
.install(
env,
&InstallSet {
specs: pinned.clone(),
constraints: hold_still(installed_now, &pinned, None),
system: plan.system,
},
ExecMode::Batch,
batch_sink.clone(),
)
.await;
let stopped_by_user = sink.is_cancelled() || batch.as_ref().is_err_and(PdError::is_cancelled);
batch_sink.finished(
None,
ExecMode::Batch,
match &batch {
Ok(step) => step.status,
Err(_) if stopped_by_user => StepStatus::Skipped,
Err(_) => StepStatus::Failed,
},
);
// A cancelled Phase A must **not** fall through to Phase B. Isolating would re-run every
// package the user just stopped, one at a time — the opposite of what cancelling means.
if sink.is_cancelled() {
if stopped_by_user {
let results: Vec<StepResult> = pinned
.iter()
.map(|spec| StepResult {
pkg: spec.name.clone(),
from: None,
to: Some(spec.version.clone()),
status: StepStatus::Skipped,
code: None,
stderr_tail: None,
})
.map(|spec| row(spec, StepStatus::Skipped))
.collect();
let counts = ExecutionSummary::tally(&results);
return Ok(ExecutionSummary {
plan_id: plan.id.clone(),
phase: ExecMode::Batch,
results,
check: post_check(engine, env).await,
counts,
cancelled: true,
});
return Ok(summary(plan, ExecMode::Batch, results, engine, env, true).await);
}
if batch.status == StepStatus::Ok {
let failure = match batch {
Ok(step) if step.status == StepStatus::Ok => {
let results: Vec<StepResult> = pinned
.iter()
.map(|spec| row(spec, StepStatus::Ok))
.collect();
return Ok(summary(plan, ExecMode::Batch, results, engine, env, false).await);
}
Ok(step) => (step.code, step.stderr_tail),
Err(e) => (Some(e.code), e.stderr_tail),
};
// Phase B only helps when the failure could be one package's. Offline is offline for every
// package, a missing engine is missing for every retry, and a batch the watchdog killed would
// be the same hang N times over — so those fail every row with the batch's code, and the trace
// is attached once rather than N times.
if !isolates(failure.0) {
let results: Vec<StepResult> = pinned
.iter()
.map(|spec| StepResult {
pkg: spec.name.clone(),
from: None,
to: Some(spec.version.clone()),
status: StepStatus::Ok,
code: None,
stderr_tail: None,
.enumerate()
.map(|(i, spec)| StepResult {
status: StepStatus::Failed,
code: failure.0,
stderr_tail: if i == 0 { failure.1.clone() } else { None },
..row(spec, StepStatus::Failed)
})
.collect();
let counts = ExecutionSummary::tally(&results);
return Ok(ExecutionSummary {
plan_id: plan.id.clone(),
phase: ExecMode::Batch,
results,
check: post_check(engine, env).await,
counts,
cancelled: false,
});
return Ok(summary(plan, ExecMode::Batch, results, engine, env, false).await);
}
// Phase B: isolate. One failure must not cost the user the other fourteen packages.
@@ -581,14 +699,11 @@ pub async fn execute(
// which is what `Skipped` already means. The one in flight when the token tripped is
// handled below.
if sink.is_cancelled() {
results.extend(pinned[index..].iter().map(|remaining| StepResult {
pkg: remaining.name.clone(),
from: None,
to: Some(remaining.version.clone()),
status: StepStatus::Skipped,
code: None,
stderr_tail: None,
}));
results.extend(
pinned[index..]
.iter()
.map(|remaining| row(remaining, StepStatus::Skipped)),
);
break;
}
@@ -597,7 +712,11 @@ pub async fn execute(
let step = engine
.install(
env,
std::slice::from_ref(spec),
&InstallSet {
specs: vec![spec.clone()],
constraints: hold_still(installed_now, &pinned, Some(&spec.name)),
system: plan.system,
},
ExecMode::Isolated,
step_sink.clone(),
)
@@ -606,34 +725,29 @@ pub async fn execute(
// A step that failed *because we killed it* is not the package's failure. Reclassifying
// here rather than inventing a "cancelled" catalog code keeps the summary honest without
// widening the error catalog: it was not attempted to completion, so it is Skipped.
if sink.is_cancelled() && step.is_err() {
if sink.is_cancelled() && step.as_ref().is_err_and(PdError::is_cancelled) {
step_sink.finished(
Some(spec.name.clone()),
ExecMode::Isolated,
StepStatus::Skipped,
);
results.push(StepResult {
pkg: spec.name.clone(),
from: None,
to: Some(spec.version.clone()),
status: StepStatus::Skipped,
code: None,
stderr_tail: None,
});
results.push(row(spec, StepStatus::Skipped));
continue;
}
let result = match step {
Ok(r) => r,
// An engine that could not even be spawned is still one package's outcome here;
// aborting would discard the packages that already succeeded.
Ok(r) => StepResult {
from: before.get(&spec.name).map(|v| (*v).clone()),
..r
},
// An engine that could not even be spawned, or a step its watchdog killed, is still
// one package's outcome here; aborting would discard the packages that already
// succeeded.
Err(e) => StepResult {
pkg: spec.name.clone(),
from: None,
to: Some(spec.version.clone()),
status: StepStatus::Failed,
code: Some(e.code),
stderr_tail: e.stderr_tail,
..row(spec, StepStatus::Failed)
},
};
// Every StepStarted gets exactly one StepFinished, whichever way the step ended — the
@@ -642,25 +756,92 @@ pub async fn execute(
results.push(result);
}
let cancelled = sink.is_cancelled();
Ok(summary(plan, ExecMode::Isolated, results, engine, env, cancelled).await)
}
/// What must not move while part of a plan installs: every **other** planned package at the
/// version the preview showed, and everything installed that the plan does not touch at the
/// version it has now.
///
/// Phase A passes `except: None` (the whole plan is the requirement); a Phase B step passes its
/// own package. Without this a Phase B `pip install alpha==2` was free to pull a dependency past
/// an installed package's upper bound — pip warns and exits 0 — leaving a state no preview showed.
fn hold_still(
installed: &[crate::model::Dist],
pinned: &[PinnedSpec],
except: Option<&crate::model::PkgName>,
) -> Vec<PinnedSpec> {
let planned: std::collections::BTreeSet<&crate::model::PkgName> =
pinned.iter().map(|p| &p.name).collect();
let others = pinned
.iter()
.filter(|p| except.is_some_and(|name| *name != p.name))
.cloned();
let untouched = installed
.iter()
.filter(|d| !planned.contains(&d.name))
.filter(|d| crate::pep440::is_argv_safe(&d.version.0))
.map(|d| PinnedSpec {
name: d.name.clone(),
version: d.version.clone(),
});
others.chain(untouched).collect()
}
/// Whether retrying package by package could get further than the batch did.
///
/// False for failures that are the **environment's**, not one package's: the network (PD-NET-*),
/// a read-only site-packages, a full disk, an engine that is missing or too old, the watchdog, an
/// environment that is gone or managed. Every per-package retry would meet the same wall — after
/// pip's own retry backoff, each time. A failure with no code isolates, as it always did.
fn isolates(code: Option<Code>) -> bool {
!matches!(
code,
Some(
Code::NetUnreachable
| Code::NetTlsFailure
| Code::PrmSitePackagesReadOnly
| Code::SysDiskFull
| Code::EngNotFound
| Code::EngPipTooOld
| Code::EngTimedOut
| Code::EnvInterpreterMissing
| Code::EnvExternallyManaged
)
)
}
/// Assemble a summary: the rows, their tally, and the post-execution check.
async fn summary(
plan: &AcceptedPlan,
phase: ExecMode,
results: Vec<StepResult>,
engine: &dyn Engine,
env: &PyEnv,
cancelled: bool,
) -> ExecutionSummary {
let counts = ExecutionSummary::tally(&results);
Ok(ExecutionSummary {
ExecutionSummary {
plan_id: plan.id.clone(),
phase: ExecMode::Isolated,
phase,
results,
check: post_check(engine, env).await,
counts,
cancelled: sink.is_cancelled(),
})
cancelled,
}
}
/// Run the post-execution check, treating an unrunnable check as "no findings".
/// Run the post-execution check, reporting a check that could not run **as not having run**.
///
/// A check that could not run must not turn a successful run into a reported failure; the summary
/// already carries the per-package truth.
/// It must not turn a successful run into a failed one — the summary's rows still carry the
/// per-package truth — but it must not say "verified" either, which `unwrap_or(ok: true)` did:
/// exactly when pip had been broken by the run it was meant to check.
async fn post_check(engine: &dyn Engine, env: &PyEnv) -> CheckReport {
engine.check(env).await.unwrap_or(CheckReport {
ok: true,
engine.check(env).await.unwrap_or_else(|e| CheckReport {
ok: false,
findings: Vec::new(),
error: Some(e.code),
})
}
@@ -682,26 +863,21 @@ pub async fn execute_rollback(
env: &PyEnv,
plan_id: String,
restore: &crate::snapshot::RollbackPlan,
snapshot: SnapshotProof<'_>,
_snapshot: SnapshotProof<'_>,
sink: ProgressSink,
system: SystemPackages,
) -> Result<ExecutionSummary> {
let mut results = Vec::new();
// One index space across both halves: the sink's `total` counts the removals and the restores
// together, so the restores continue where the removals stopped rather than both starting at
// zero and the live region counting to half.
//
// The removals are run as steps, not as a nested `execute_uninstall`: that one ends with its
// own `pip check`, which here ran between the removals and the restores — a check of a state
// that exists for a few seconds, against an environment about to change again.
if !restore.uninstall.is_empty() {
let removed = execute_uninstall(
engine,
env,
plan_id.clone(),
&restore.uninstall,
snapshot,
sink.clone(),
0,
)
.await?;
results.extend(removed.results);
results.extend(removal_steps(engine, env, &restore.uninstall, &sink, 0, system).await);
}
for (index, spec) in restore.install.iter().enumerate() {
@@ -724,10 +900,21 @@ pub async fn execute_rollback(
let step_sink = sink.at(restore.uninstall.len() + index);
step_sink.started(Some(spec.name.clone()), ExecMode::Isolated);
// The rest of the restore is the target state, so it is what this step must not move.
let constraints: Vec<PinnedSpec> = restore
.install
.iter()
.filter(|other| other.name != spec.name)
.cloned()
.collect();
let step = engine
.install(
env,
std::slice::from_ref(spec),
&InstallSet {
specs: vec![spec.clone()],
constraints,
system,
},
ExecMode::Isolated,
step_sink.clone(),
)
@@ -780,11 +967,8 @@ pub async fn execute_rollback(
/// The reverse-dependency guard is the caller's job and runs **once against the full set** before
/// this is called; by the time execution starts the user has already decided.
///
/// `base` is where this run's steps begin in the sink's index space. It exists because
/// [`execute_rollback`] calls this for the removal half of a restore and then installs on top,
/// under **one** `ProgressSink` whose `total` counts both — so the removals are steps
/// `base..base+names.len()` and the restores continue from there. Passing `0` is right for a plain
/// uninstall, where the removals are the whole plan.
/// The removals are the whole plan here, so they are steps `0..names.len()`; only
/// [`execute_rollback`], which installs on top under one sink, starts them anywhere else.
///
/// # Errors
/// Never for a package failure — those land in the summary. Only a stale plan aborts.
@@ -795,8 +979,32 @@ pub async fn execute_uninstall(
names: &[PkgName],
_snapshot: SnapshotProof<'_>,
sink: ProgressSink,
base: usize,
system: SystemPackages,
) -> Result<ExecutionSummary> {
let results = removal_steps(engine, env, names, &sink, 0, system).await;
let counts = ExecutionSummary::tally(&results);
Ok(ExecutionSummary {
plan_id,
phase: ExecMode::Isolated,
results,
check: post_check(engine, env).await,
counts,
cancelled: sink.is_cancelled(),
})
}
/// The removal loop shared by [`execute_uninstall`] and [`execute_rollback`]'s first half.
///
/// `base` is where these steps begin in the sink's index space: a rollback removes and then
/// installs under **one** `ProgressSink` whose `total` counts both.
async fn removal_steps(
engine: &dyn Engine,
env: &PyEnv,
names: &[PkgName],
sink: &ProgressSink,
base: usize,
system: SystemPackages,
) -> Vec<StepResult> {
let mut results = Vec::with_capacity(names.len());
for (index, name) in names.iter().enumerate() {
// Checked before each removal, so a cancelled run reports the rest as never attempted
@@ -823,7 +1031,7 @@ pub async fn execute_uninstall(
step_sink.started(Some(name.clone()), ExecMode::Isolated);
let step = engine
.uninstall(env, std::slice::from_ref(name), step_sink.clone())
.uninstall(env, std::slice::from_ref(name), system, step_sink.clone())
.await;
// Killed by us is not the package's failure — the same reclassification the install path
@@ -856,15 +1064,7 @@ pub async fn execute_uninstall(
results.push(result);
}
let counts = ExecutionSummary::tally(&results);
Ok(ExecutionSummary {
plan_id,
phase: ExecMode::Isolated,
results,
check: post_check(engine, env).await,
counts,
cancelled: sink.is_cancelled(),
})
results
}
#[cfg(test)]
@@ -939,7 +1139,11 @@ mod tests {
changes: vec![],
held_back: vec![held],
impossible: None,
incompatible: Vec::new(),
forced: Vec::new(),
yanked: Vec::new(),
raw: String::new(),
declared_python: Default::default(),
};
assert!(!report.is_clean());
}
@@ -955,7 +1159,11 @@ mod tests {
}],
held_back: vec![],
impossible: None,
incompatible: Vec::new(),
forced: Vec::new(),
yanked: Vec::new(),
raw: String::new(),
declared_python: Default::default(),
};
assert!(report.is_clean());
let pinned = report.pinned_set();
@@ -1013,4 +1221,22 @@ mod tests {
offenders.join("\n ")
);
}
#[test]
fn the_engine_output_never_crosses_the_wire() {
// pip's whole `--report` — every README in the plan — rode in each FlowStep over IPC and
// into `--json`. It stays in Rust, for the log.
let report = ResolutionReport {
raw: "a very large engine document".into(),
..ResolutionReport::default()
};
let wire = serde_json::to_value(&report).expect("serializes");
assert!(wire.get("raw").is_none(), "{wire}");
let schema = serde_json::to_value(schemars::schema_for!(ResolutionReport))
.expect("schema serializes");
assert!(
schema["properties"].get("raw").is_none(),
"the schema must not promise it either"
);
}
}
+74
View File
@@ -195,6 +195,76 @@ pub fn forced_requirements(
}
}
/// Fill in [`ResolutionReport::forced`]: each forced package, and what forcing it will break.
///
/// The "Will break" section of the preview (UI-SPEC §4, DISCLAIMER §2). The blockers are the same
/// ones a held-back row would have named — the packages whose declared constraint the user just
/// chose to override — attributed by the graph, never guessed (ARCHITECTURE §3).
pub fn derive_forced(
report: &mut ResolutionReport,
forced: &[PkgName],
outdated: &[OutdatedDist],
graph: &ReverseDeps,
) {
let latest: BTreeMap<&PkgName, &OutdatedDist> = outdated.iter().map(|o| (&o.name, o)).collect();
report.forced = forced
.iter()
.filter_map(|pkg| {
let target = latest.get(pkg)?;
let blockers = PyVersion::parse(&target.latest.0)
.map(|v| graph.blockers_for(pkg, &v))
.unwrap_or_default();
Some(HeldBack {
pkg: pkg.clone(),
resolved: target.latest.clone(),
latest: target.latest.clone(),
blockers,
})
})
.collect();
}
/// The guard pins an impossibility says collide with a forced pin — which forcing must release.
///
/// The guard set pins **every** installed package the plan does not move, the forced package's
/// own dependencies included. So forcing httpcore to 1.0.9 over `h11==0.12.0` was impossible:
/// 1.0.9 needs `h11>=0.16`. Which pins collide is resolution, and PipDock does not resolve
/// (invariant 3) — but the engine names them in its impossibility, and releasing exactly those
/// lets it move them. Only installed, still-pinned names count: releasing anything else changes
/// no line and would ask the same question again.
#[must_use]
pub fn forced_collisions(
report: &ResolutionReport,
adjust: &crate::engine::GuardAdjust,
forced: &[PkgName],
req: &PlanRequest,
installed: &[crate::model::Dist],
) -> Vec<PkgName> {
// Only a *forced* pin releases anything. A `Hold` pin is the user saying a package stays put;
// releasing the packages it collides with would move them to accommodate it, which nobody
// asked for — its impossibility is shown as it stands.
if forced.is_empty() {
return Vec::new();
}
let Some(detail) = &report.impossible else {
return Vec::new();
};
let moving: BTreeSet<&PkgName> = req
.upgrades
.iter()
.chain(req.installs.iter().map(|s| &s.name))
.chain(adjust.pins.iter().map(|p| &p.name))
.chain(adjust.release.iter())
.collect();
let installed: BTreeSet<&PkgName> = installed.iter().map(|d| &d.name).collect();
detail
.packages
.iter()
.filter(|p| installed.contains(p) && !moving.contains(p))
.cloned()
.collect()
}
/// What forcing a set of packages requires of the plan.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ForcedPlan {
@@ -238,7 +308,11 @@ mod tests {
changes: Vec::new(),
held_back: Vec::new(),
impossible: None,
incompatible: Vec::new(),
forced: Vec::new(),
yanked: Vec::new(),
raw: String::new(),
declared_python: Default::default(),
}
}
+67 -6
View File
@@ -4,7 +4,7 @@ Prints a single JSON document describing the interpreter it runs under and every
distribution installed in it. Rust cannot cheaply read a foreign environment's
metadata, so this helper is executed as:
<env-python> -I <tempfile> --json
<env-python> -X utf8 -I <tempfile> --json
Constraints (docs/ARCHITECTURE.md section 4, docs/SECURITY.md section 2):
@@ -12,12 +12,15 @@ Constraints (docs/ARCHITECTURE.md section 4, docs/SECURITY.md section 2):
runs in are the user's, and may contain anything.
* Python 3.10 floor: `importlib.metadata` only, no `packaging`.
* Run with -I so PYTHONPATH and user site are ignored and a poisoned environment
cannot inject code into the probe.
cannot inject code into the probe. -I also ignores PYTHONUTF8, which is why the
core passes -X utf8: this prints paths unescaped, and a venv under a folder
named in Vietnamese crashed the probe on the ANSI code page.
* Written to a temp file with a random name per invocation; never installed.
Output shape:
{"python": "3.12.4", "prefix": "...", "externally_managed": false,
{"schema": 3, "python": "3.12.4", "prefix": "...", "externally_managed": false,
"markers": {"sys_platform": "win32", "python_version": "3.12", ...},
"dists": [{"name": "requests", "version": "2.32.3",
"requires_dist": ["urllib3<3,>=1.21.1"],
"requires_python": ">=3.8", "size_bytes": 131072}]}
@@ -34,7 +37,7 @@ import os
import sys
import sysconfig
SCHEMA_VERSION = 2
SCHEMA_VERSION = 3
def _normalize(name: str) -> str:
@@ -86,6 +89,55 @@ def _externally_managed() -> bool:
return any(os.path.isfile(p) for p in candidates)
def _full_version(info) -> str:
"""`3.12.4`, or `3.14.0rc1` -- PEP 508's spelling of a version_info."""
version = f"{info.major}.{info.minor}.{info.micro}"
if info.releaselevel != "final":
version += info.releaselevel[0] + str(info.serial)
return version
def _marker_env() -> dict[str, str]:
"""The PEP 508 environment this interpreter evaluates requirement markers against.
The core needs it to tell an in-force requirement from one gated to another platform:
without `sys_platform`, ipython's `pexpect; sys_platform != "win32"` read as a missing
dependency of every Windows environment that had ipython.
Built from `sys` and `os`, not `platform`. On Windows `platform.uname()` runs a WMI query
-- 55 ms on 3.14, a third of a small environment's whole probe -- for two values,
`platform_release` and `platform_version`, that almost no requirement mentions. Those two
are therefore omitted on Windows, and the core keeps any requirement whose marker it cannot
evaluate. `platform_machine` reads the same PROCESSOR_* variables `platform` itself falls
back to there.
"""
env = {
"implementation_name": sys.implementation.name,
"implementation_version": _full_version(sys.implementation.version),
"os_name": os.name,
"python_full_version": _full_version(sys.version_info),
"python_version": f"{sys.version_info[0]}.{sys.version_info[1]}",
"sys_platform": sys.platform,
}
implementation = {"cpython": "CPython", "pypy": "PyPy"}.get(sys.implementation.name)
if implementation:
env["platform_python_implementation"] = implementation
if os.name == "nt":
env["platform_system"] = "Windows"
machine = os.environ.get("PROCESSOR_ARCHITEW6432") or os.environ.get(
"PROCESSOR_ARCHITECTURE"
)
if machine:
env["platform_machine"] = machine
elif hasattr(os, "uname"):
uname = os.uname()
env["platform_system"] = uname.sysname
env["platform_release"] = uname.release
env["platform_version"] = uname.version
env["platform_machine"] = uname.machine
return env
def _hidden_user_site() -> str | None:
"""Return the user site-packages path when it exists but is NOT on this run's sys.path.
@@ -204,6 +256,9 @@ def _dists() -> list[dict[str, object]]:
seen: set[str] = set()
for dist in distributions():
try:
# **One parse of METADATA per distribution.** `dist.version` and `dist.requires` each
# re-read and re-parse it, so asking all three cost three parses per package on the
# path every environment open pays.
meta = dist.metadata
if meta is None:
continue
@@ -218,11 +273,16 @@ def _dists() -> list[dict[str, object]]:
if name in seen:
continue
seen.add(name)
requires = meta.get_all("Requires-Dist")
if requires is None and dist.read_text("requires.txt") is not None:
# An .egg-info keeps its requirements in requires.txt, in sections
# importlib.metadata turns into markers; only then is the second read needed.
requires = dist.requires
out.append(
{
"name": name,
"version": dist.version or "",
"requires_dist": list(dist.requires or []),
"version": meta.get("Version") or "",
"requires_dist": list(requires or []),
"requires_python": meta.get("Requires-Python"),
"size_bytes": _size_bytes(dist),
}
@@ -253,6 +313,7 @@ def main(argv: list[str] | None = None) -> int:
"executable": sys.executable,
"is_venv": sys.prefix != sys.base_prefix,
"externally_managed": _externally_managed(),
"markers": _marker_env(),
# Non-null means -I is hiding packages that pip would list; the UI shows a note.
"hidden_user_site": _hidden_user_site(),
"dists": _dists(),
+235
View File
@@ -0,0 +1,235 @@
//! What a release requires of the interpreter — the half of PipDock's own `Requires-Python`
//! enforcement an engine's plan cannot always supply (hard invariant 10).
//!
//! The engines disagree, which is why PipDock checks at all: pip filters candidates by
//! `Requires-Python` and refuses an incompatible exact pin with the same "No matching
//! distribution" it gives a typo; uv honours the lower bound and **ignores an upper bound**, so it
//! plans `scipy==1.7.3` (`<3.10`) on Python 3.14 and the install fails later, building from
//! source. pip's report carries each planned release's `requires_python`; uv's plan is text and
//! carries nothing, so for uv — and for an exact pin under either engine, checked before the
//! engine runs — the answer comes from PyPI's per-release JSON.
//!
//! **Unknown never blocks.** A release PyPI does not know (a private index), a network that is
//! down, a specifier that will not parse: each is "do not block", because refusing an installable
//! package on PipDock's uncertainty is the worse failure, and the engine still judges.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use crate::model::{PkgName, Version};
use crate::store::Store;
/// How many lookups may be in flight at once. A plan for "update everything" can name fifty
/// releases; PyPI is a CDN, but fifty simultaneous connections from one desktop app is rude.
pub const LOOKUP_CONCURRENCY: usize = 8;
/// Per-request watchdog. A lookup that takes longer is treated as unknown, which never blocks.
pub const LOOKUP_TIMEOUT: Duration = Duration::from_secs(15);
/// Where `Requires-Python` of a release comes from.
#[async_trait]
pub trait ReleaseMeta: Send + Sync + std::fmt::Debug {
/// `Requires-Python` of `name==version`; `None` when it declares none **or nobody knows** —
/// both mean "do not block".
async fn requires_python(&self, name: &PkgName, version: &Version) -> Option<String>;
}
/// PyPI's per-release JSON, remembered in the store's `release_meta` table **forever**: an
/// uploaded release's metadata never changes, so a row is never refreshed. Only an answer is
/// remembered; a failure is asked again next time.
#[derive(Debug, Clone)]
pub struct PyPiReleases {
app_data: PathBuf,
}
impl PyPiReleases {
/// Lookups cached under `app_data`'s store.
#[must_use]
pub fn new(app_data: impl Into<PathBuf>) -> Self {
Self {
app_data: app_data.into(),
}
}
/// `Some(answer)` when this release has been asked about before.
///
/// The store is opened for this one read and dropped: `Store` is not `Sync`, and holding it
/// across the network call would make every caller's future not `Send`.
fn cached(&self, name: &PkgName, version: &Version) -> Option<Option<String>> {
let store = Store::open(&self.app_data).ok()?;
store
.conn()
.query_row(
"SELECT requires_python FROM release_meta WHERE normalized = ?1 AND version = ?2",
rusqlite::params![name.as_str(), version.0],
|r| r.get::<_, Option<String>>(0),
)
.ok()
}
fn remember(&self, name: &PkgName, version: &Version, requires_python: Option<&str>) {
// A cache that cannot be written only costs the next run a request.
if let Ok(store) = Store::open(&self.app_data) {
let _ = store.conn().execute(
"INSERT INTO release_meta (normalized, version, requires_python)
VALUES (?1, ?2, ?3)
ON CONFLICT (normalized, version) DO UPDATE SET
requires_python = excluded.requires_python",
rusqlite::params![name.as_str(), version.0, requires_python],
);
}
}
}
#[async_trait]
impl ReleaseMeta for PyPiReleases {
async fn requires_python(&self, name: &PkgName, version: &Version) -> Option<String> {
if let Some(answer) = self.cached(name, version) {
return answer;
}
let answer = fetch(name, version).await?;
self.remember(name, version, answer.as_deref());
answer
}
}
/// `GET https://pypi.org/pypi/{name}/{version}/json` → `info.requires_python`.
///
/// `Some(None)` is a real answer — the release declares no constraint. `None` is "could not
/// find out": not on PyPI, unreachable, slow, unreadable.
async fn fetch(name: &PkgName, version: &Version) -> Option<Option<String>> {
// The version goes into a URL path; only a PEP 440 version is allowed to.
if !crate::pep440::is_version(&version.0) {
return None;
}
let url = format!("https://pypi.org/pypi/{}/{}/json", name.as_str(), version.0);
let response = crate::index::shared_client()
.ok()?
.get(&url)
.timeout(LOOKUP_TIMEOUT)
.send()
.await
.ok()?;
if !response.status().is_success() {
return None;
}
let doc: serde_json::Value = response.json().await.ok()?;
Some(
doc.get("info")
.and_then(|i| i.get("requires_python"))
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned),
)
}
/// Look up many releases at once, at most [`LOOKUP_CONCURRENCY`] in flight. Releases with no
/// known constraint are absent from the answer.
pub async fn requires_python_of(
meta: &Arc<dyn ReleaseMeta>,
releases: Vec<(PkgName, Version)>,
) -> BTreeMap<(PkgName, String), String> {
let gate = Arc::new(tokio::sync::Semaphore::new(LOOKUP_CONCURRENCY));
let mut set = tokio::task::JoinSet::new();
for (name, version) in releases {
let meta = Arc::clone(meta);
let gate = Arc::clone(&gate);
set.spawn(async move {
let _permit = gate.acquire_owned().await.ok();
let answer = meta.requires_python(&name, &version).await;
(name, version, answer)
});
}
let mut out = BTreeMap::new();
while let Some(joined) = set.join_next().await {
if let Ok((name, version, Some(requires))) = joined {
out.insert((name, version.0), requires);
}
}
out
}
/// `Some` when `requires_python` excludes the interpreter at `python` (e.g. `"3.14.7"`).
///
/// An unparseable interpreter version or specifier is not a mismatch — see the module note.
#[must_use]
pub fn mismatch(
pkg: &PkgName,
version: &Version,
requires_python: Option<&str>,
python: &str,
) -> Option<crate::plan::PythonMismatch> {
let interpreter = crate::compat::PyVersion::parse(python).ok()?;
match crate::compat::check(requires_python, &interpreter) {
crate::compat::Compatibility::RequiresPython { required, .. } => {
Some(crate::plan::PythonMismatch {
pkg: pkg.clone(),
version: version.clone(),
requires_python: required,
python: python.to_owned(),
})
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn pkg(n: &str) -> PkgName {
PkgName::parse(n).unwrap()
}
#[test]
fn a_capped_release_on_a_newer_python_is_a_mismatch() {
let m = mismatch(
&pkg("scipy"),
&Version("1.7.3".into()),
Some(">=3.7,<3.10"),
"3.14.7",
)
.expect("excluded");
assert_eq!(m.requires_python, ">=3.7,<3.10");
assert_eq!(m.python, "3.14.7");
assert!(
mismatch(
&pkg("scipy"),
&Version("1.16.0".into()),
Some(">=3.11"),
"3.14.7"
)
.is_none()
);
}
#[test]
fn what_cannot_be_read_never_blocks() {
let v = Version("1.0".into());
assert!(mismatch(&pkg("a"), &v, None, "3.14.7").is_none());
assert!(mismatch(&pkg("a"), &v, Some(""), "3.14.7").is_none());
assert!(mismatch(&pkg("a"), &v, Some("not a specifier"), "3.14.7").is_none());
assert!(mismatch(&pkg("a"), &v, Some("<3.10"), "not a version").is_none());
}
#[test]
fn an_answer_is_remembered_and_a_failure_is_not() {
let dir = std::env::temp_dir().join(format!("pd-release-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let meta = PyPiReleases::new(&dir);
let (name, v) = (pkg("scipy"), Version("1.7.3".into()));
assert_eq!(meta.cached(&name, &v), None, "never asked");
meta.remember(&name, &v, Some(">=3.7,<3.10"));
assert_eq!(meta.cached(&name, &v), Some(Some(">=3.7,<3.10".to_owned())));
// "Declares nothing" is an answer too, and is not asked again.
let free = Version("1.0".into());
meta.remember(&name, &free, None);
assert_eq!(meta.cached(&name, &free), Some(None));
let _ = std::fs::remove_dir_all(&dir);
}
}
+76 -3
View File
@@ -59,13 +59,40 @@ pub fn bug_report_url(report: &BugReport, os: &str) -> String {
url.push_str(&format!("&error-code={}", urlencode(code.as_str())));
}
let excerpt = excerpt(&report.log);
if !excerpt.is_empty() {
url.push_str(&format!("&log-excerpt={}", urlencode(&excerpt)));
let encoded = encoded_excerpt(&excerpt(&report.log));
if !encoded.is_empty() {
url.push_str(&format!("&log-excerpt={encoded}"));
}
url
}
/// The excerpt as it goes into the URL, cut further until its **encoded** form fits.
///
/// [`crate::BUG_REPORT_EXCERPT_CHARS`] counts characters before encoding, but percent-encoding
/// decides the length GitHub sees: an ASCII letter costs one byte, a path separator three and a
/// Vietnamese letter up to nine (`%E1%BB%87`). A log full of accented paths made a URL several
/// times the budget, and GitHub answers that with an error page instead of the form (M51). Lines
/// are dropped from the front — the tail is where the failure is — until the encoding fits.
fn encoded_excerpt(excerpt: &str) -> String {
let mut text = excerpt;
loop {
let encoded = urlencode(text);
if encoded.len() <= crate::BUG_REPORT_EXCERPT_CHARS || text.is_empty() {
return encoded;
}
text = match text.find('\n') {
Some(i) if i + 1 < text.len() => &text[i + 1..],
// One line left: drop a tenth of it from the front, at a `char` boundary.
_ => {
let keep_from = text.chars().count() / 10 + 1;
text.char_indices()
.nth(keep_from)
.map_or("", |(at, _)| &text[at..])
}
};
}
}
/// The tail of `log`, at most [`crate::BUG_REPORT_EXCERPT_CHARS`] characters.
///
/// Tail-biased on purpose: a failing install's last twenty lines are the traceback, and its first
@@ -162,4 +189,50 @@ mod tests {
let cut = excerpt(&log);
assert!(cut.chars().count() <= crate::BUG_REPORT_EXCERPT_CHARS);
}
/// The `log-excerpt` parameter of `url`, still encoded.
fn encoded_excerpt_of(url: &str) -> &str {
url.split("&log-excerpt=").nth(1).unwrap_or("")
}
#[test]
fn a_log_of_accented_paths_still_fits_in_the_url() {
// M51: 6000 characters of this encode to roughly 20 KB, and GitHub refuses the form.
let line = "C:\\Users\\Nguyễn\\Tài liệu\\dự án\\.venv\\Lib\\site-packages\\gói\n";
let url = bug_report_url(
&BugReport {
log: line.repeat(400),
..BugReport::default()
},
"Windows 11",
);
let encoded = encoded_excerpt_of(&url);
assert!(!encoded.is_empty(), "the excerpt is cut, not dropped");
assert!(
encoded.len() <= crate::BUG_REPORT_EXCERPT_CHARS,
"{} bytes encoded",
encoded.len()
);
// Still the tail, still whole lines.
assert!(
encoded.ends_with("g%C3%B3i%0A"),
"{}",
&encoded[encoded.len() - 20..]
);
assert!(encoded.starts_with("C%3A%5CUsers"), "{}", &encoded[..20]);
}
#[test]
fn one_enormous_line_is_cut_rather_than_dropped() {
let url = bug_report_url(
&BugReport {
log: "đ".repeat(5_000),
..BugReport::default()
},
"Windows 11",
);
let encoded = encoded_excerpt_of(&url);
assert!(!encoded.is_empty());
assert!(encoded.len() <= crate::BUG_REPORT_EXCERPT_CHARS);
}
}
+4 -13
View File
@@ -190,25 +190,16 @@ pub fn parse(text: &str) -> ParsedRequirements {
/// uninstallable, while the job here is only to reject whitespace and anything that is not part
/// of a specifier's alphabet. An empty constraint is valid and means "any version".
fn is_specifier(raw: &str) -> bool {
if raw.is_empty() {
return true;
}
raw.starts_with(['<', '>', '=', '!', '~'])
&& raw.chars().all(|c| {
c.is_ascii_alphanumeric()
|| matches!(
c,
'<' | '>' | '=' | '!' | '~' | '.' | ',' | '*' | '-' | '_' | '+'
)
})
// The shape check this used to be accepted `>=1.0--break-system-packages` (every character is
// in a specifier's alphabet); the grammar does not.
raw.is_empty() || crate::pep440::is_specifier_set(raw)
}
/// Render a parsed requirement back as a spec `Intent::Install` accepts.
///
/// **The marker is dropped, and the extras with it.** A marker is a condition on the *installing*
/// environment that the resolver evaluates itself, and PipDock's job here is to say which packages
/// to ask for. Keeping either would put a token into argv that
/// `plan::build_request`'s `name==version` split does not understand.
/// to ask for. What is rendered is exactly what [`crate::model::Spec::parse`] reads back.
fn render(req: &Requirement) -> String {
if req.constraint.is_empty() {
req.name.as_str().to_owned()
Loaded 100 of 293 files, more files were not shown because too many files have changed in this diff. Show more