fix: the 16 Rust findings and the coverage gap from the first CI analysis of main (#91)

The first CI analysis of main failed its gate: 16 Rust bugs and new-code
coverage 78.3 % against 80 %, over all of 1.4.0 (sending a version did not
move the previous-version baseline).

- rust:S6677 x3: a failure's message is logged as `error`, not as a second
  `message` field (CLI, update flow, app startup); golden.rs reads the
  CLI's log to hold it, and failed first.
- rust:S7493 x13: std::fs inside async fns goes through tokio::fs (tools
  venv sync, deptry's report, export/requirements/report commands).
- Tests for 1.4.0 code nothing drove: rollback end to end, forcing a
  latest this Python cannot run, PEP 691 parsing (L55), user_file_error
  (U25), a plan verified in another environment, PyPiReleases' cache, and
  the plan/env stores' success and late-error paths. InstallSet::only had
  no caller and is removed.
- ROADMAP, TESTING and CLAUDE.md record what the analysis found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 authored and GitHub committed 2026-10-25 07:21:45 +07:00
1 parent 4a617722d6
commit 2f6ad04967
23 files changed
+697 -78

No files matched your search

+6 -3
View File
@@ -92,9 +92,12 @@ case no PR will catch: an advisory against something already merged.
**SonarQube Cloud is CI-based since 2026-10-25** — `sonar.yml` and `sonar-project.properties`;
automatic analysis is off in the project's settings and must stay off, or the CI analysis is
refused. Automatic analysis never analysed a line of Rust and imported no coverage, which is why it
went. The gate's "new code" is *previous version*, and the version comes from `package.json`, so a
release bump starts a new period; new code needs 80 % coverage, so a slice whose new lines no
test reaches turns `main`'s gate red. Dependabot PRs have no `SONAR_TOKEN` and skip the analysis.
went. The gate's "new code" is *previous version*, with the version from `package.json` — but the
first analysis to send one (`1.4.0`) kept the 2026-09-27 baseline, so read `periods` from
`api/qualitygates/project_status` after the next bump instead of assuming it moved. New code needs
80 % coverage and no new issue, so a slice whose new lines no test reaches turns `main`'s gate red,
and so does a `std::fs` call inside an `async fn` (`rust:S7493`) or a tracing field named
`message` (`rust:S6677`). Dependabot PRs have no `SONAR_TOKEN` and skip the analysis.
## Current state
+1 -1
View File
@@ -428,7 +428,7 @@ async fn main() -> ExitCode {
match result {
Ok(exit) => exit.into(),
Err(e) => {
tracing::error!(target: "pipdock::cli", code = %e.code, message = %e.message, "failed");
tracing::error!(target: "pipdock::cli", code = %e.code, error = %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 {
+29
View File
@@ -244,6 +244,35 @@ fn the_human_error_line_carries_its_code() {
);
}
#[test]
fn a_logged_failure_names_its_message() {
// `message = %e.message` beside a format string records two fields called `message`, and the
// text formatter prints that field without its name — so the line read `failed
// code=PD-ENV-001 no interpreter at …`, the error's own words indistinguishable from the
// event's (SonarQube rust:S6677). `error=`, as every other failure in the codebase logs it.
let copy = std::env::temp_dir().join(format!("pd-golden-log-{}.log", std::process::id()));
let _ = std::fs::remove_file(&copy);
let copy_arg = copy.to_string_lossy().into_owned();
code_of(&[
"--log-file",
&copy_arg,
"list",
"--env",
"C:/definitely/not/here",
]);
let log = std::fs::read_to_string(&copy).expect("--log-file wrote its copy");
let _ = std::fs::remove_file(&copy);
let line = log
.lines()
.find(|l| l.contains("PD-ENV-001"))
.unwrap_or_else(|| panic!("the failure was not logged:\n{log}"));
assert!(
line.contains("failed") && line.contains("error=no interpreter at"),
"the error's message must be a field of its own: {line}"
);
}
#[test]
fn an_unknown_schema_type_lists_the_known_ones() {
insta::assert_snapshot!("schema-unknown-type", stderr_of(&["schema", "NoSuchType"]));
+3 -1
View File
@@ -27,7 +27,9 @@ serde = { version = "1.0.229", features = ["derive"] }
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"] }
# `fs`: an async fn that touches a file goes through tokio's pool rather than blocking a runtime
# worker (SonarQube rust:S7493).
tokio = { version = "1.53.3", features = ["rt-multi-thread", "macros", "process", "io-util", "time", "sync", "fs"] }
# 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.20"
-12
View File
@@ -380,18 +380,6 @@ pub struct InstallSet {
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
+29
View File
@@ -1038,6 +1038,35 @@ mod tests {
);
}
#[test]
fn a_file_the_user_chose_is_never_blamed_on_the_environment() {
// U25. An export, a saved report or a requirements file is the user's own path, so a
// refusal there is about that folder — not PD-PRM-001's "PipDock may not write to this
// environment", and not PD-SYS-002's full disk.
use std::io::{Error, ErrorKind};
let p = Path::new(r"C:\Users\me\Desktop\requirements.txt");
assert_eq!(
user_file_error(p, &Error::from_raw_os_error(32)).code,
Code::PrmFileLocked,
"ERROR_SHARING_VIOLATION: another program has it open"
);
for kind in [ErrorKind::PermissionDenied, ErrorKind::ReadOnlyFilesystem] {
assert_eq!(
user_file_error(p, &Error::from(kind)).code,
Code::PrmSourceReadOnly,
"{kind:?}"
);
}
// Everything else is what any file failure is.
assert_eq!(
user_file_error(p, &Error::from_raw_os_error(112)).code,
Code::SysDiskFull
);
let missing = user_file_error(p, &Error::from(ErrorKind::NotFound));
assert_eq!(missing.code, Code::IntUnexpected);
assert!(missing.message.contains("requirements.txt"), "{missing}");
}
#[test]
fn interpreter_identity_is_case_folded_on_windows() {
// SP-6: the Chocolatey shim and the direct install differ only in casing, and env_hash is
+1 -1
View File
@@ -741,7 +741,7 @@ fn log_summary(flow: &str, summary: &Result<crate::plan::ExecutionSummary>) {
"executed"
),
Err(e) => {
tracing::warn!(target: "pipdock::flow", flow, code = %e.code, message = %e.message, "refused")
tracing::warn!(target: "pipdock::flow", flow, code = %e.code, error = %e.message, "refused")
}
}
}
+10 -6
View File
@@ -488,21 +488,25 @@ pub async fn sync_tools_venv(
let requirements = tools_dir.join(REQUIREMENTS_FILE);
let manifest_path = tools_dir.join(MANIFEST_FILE);
std::fs::create_dir_all(tools_dir).map_err(|e| fs_failure("create the tools directory", &e))?;
tokio::fs::create_dir_all(tools_dir)
.await
.map_err(|e| fs_failure("create the tools directory", &e))?;
// Deleted **before** anything is touched, which inverts `snapshot::create`'s data-then-metadata
// ordering — and for the opposite reason. A snapshot writes a sidecar that did not exist; a
// re-sync replaces a manifest that already describes the *old* pin set. If the sync then dies
// half-way, a surviving manifest would claim tools that have just been part-replaced. With it
// gone, a torn sync reads as `NeverSynced` and the next run redoes the whole thing.
let _ = std::fs::remove_file(&manifest_path);
let _ = tokio::fs::remove_file(&manifest_path).await;
// A rendering of the ledger, not a copy: this is where the *other* venv's pins, the comments,
// and whatever line endings the build machine checked out stop.
std::fs::write(&requirements, requirements_body(&pins))
tokio::fs::write(&requirements, requirements_body(&pins))
.await
.map_err(|e| fs_failure("write the tools requirements", &e))?;
let constraints = tools_dir.join(CONSTRAINTS_FILE);
std::fs::write(&constraints, constraints_body())
tokio::fs::write(&constraints, constraints_body())
.await
.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
@@ -541,8 +545,8 @@ pub async fn sync_tools_venv(
)
})?;
// Written last: until it exists, the venv is not claimed to be anything.
if let Err(e) = std::fs::write(&manifest_path, json) {
let _ = std::fs::remove_file(&manifest_path);
if let Err(e) = tokio::fs::write(&manifest_path, json).await {
let _ = tokio::fs::remove_file(&manifest_path).await;
return Err(fs_failure("write the tools manifest", &e));
}
Ok(manifest)
+3 -3
View File
@@ -222,7 +222,7 @@ async fn run_one(
if tool == "deptry"
&& let Some(parent) = report_path.parent()
{
std::fs::create_dir_all(parent).map_err(|e| {
tokio::fs::create_dir_all(parent).await.map_err(|e| {
PdError::new(
Code::HltToolFailed,
format!("could not make room for deptry's report: {e}"),
@@ -241,7 +241,7 @@ async fn run_one(
let stdout = match out {
Ok(out) if super::is_findings_exit(tool, out.code) => {
if tool == "deptry" {
std::fs::read_to_string(&report_path).map_err(|e| {
tokio::fs::read_to_string(&report_path).await.map_err(|e| {
PdError::new(
Code::HltToolFailed,
format!("deptry exited cleanly but wrote no report: {e}"),
@@ -261,7 +261,7 @@ async fn run_one(
// Cleaned on both paths: `%LOCALAPPDATA%\PipDock\data` is what SECURITY §8 promises a delete
// resets, and leaving a report per run turns that into a slow leak.
let _ = std::fs::remove_file(&report_path);
let _ = tokio::fs::remove_file(&report_path).await;
stdout
}
+78 -33
View File
@@ -301,39 +301,7 @@ pub async fn refresh(app_data: &std::path::Path, now: jiff::Timestamp) -> Result
.await
.map_err(|e| net_err("could not read the package index", &e))?;
let wire_bytes = body.len();
// 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!("the package index is not the PEP 691 document: {e}"),
)
})?;
// 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()
.map(|p| (crate::model::normalize_name(&p.name), p.name.to_string()))
.collect();
let rows = parse_simple_index(&body)?;
// 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
@@ -356,6 +324,46 @@ pub async fn refresh(app_data: &std::path::Path, now: jiff::Timestamp) -> Result
})
}
/// PEP 691's project list as `(normalized, display)` rows — everything `refresh` decides about a
/// body it was given, apart from the download, so it can be held without a network.
///
/// # Errors
/// `PD-NET-010` for a body that is not the document, or one that lists no projects.
fn parse_simple_index(body: &[u8]) -> Result<Vec<(String, String)>> {
// 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!("the package index is not the PEP 691 document: {e}"),
)
})?;
// 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",
));
}
Ok(doc
.projects
.iter()
.map(|p| (crate::model::normalize_name(&p.name), p.name.to_string()))
.collect())
}
/// Replace the `names` table's contents in one transaction.
///
/// All-or-nothing on purpose: a refresh interrupted half-way must not leave a partial index that
@@ -641,6 +649,43 @@ fn net_code(chain: &str) -> Code {
mod tests {
use super::*;
#[test]
fn a_pep_691_body_becomes_normalized_rows_with_the_display_name_kept() {
let rows = parse_simple_index(
br#"{"meta": {"api-version": "1.1"},
"projects": [{"name": "Flask"}, {"name": "zope.interface"}, {"name": "ruamel_yaml"}]}"#,
)
.expect("a real index");
assert_eq!(
rows,
[
("flask".to_owned(), "Flask".to_owned()),
("zope-interface".to_owned(), "zope.interface".to_owned()),
("ruamel-yaml".to_owned(), "ruamel_yaml".to_owned()),
]
);
}
#[test]
fn an_empty_project_list_is_refused_rather_than_wiping_the_index() {
// L55: a captive portal or a broken mirror answering 200 with nothing in it.
let err = parse_simple_index(br#"{"meta": {"api-version": "1.1"}, "projects": []}"#)
.expect_err("an index with no projects");
assert_eq!(err.code, Code::NetIndexRefreshFailed);
assert!(err.message.contains("previous index is kept"), "{err}");
}
#[test]
fn a_body_that_is_not_the_document_is_an_index_error() {
for body in [
&b"<html>Sign in to the Wi-Fi</html>"[..],
br#"{"projects": "all"}"#,
] {
let err = parse_simple_index(body).expect_err("not PEP 691");
assert_eq!(err.code, Code::NetIndexRefreshFailed);
}
}
fn index(names: &[&str]) -> NameIndex {
NameIndex {
entries: names
+22
View File
@@ -1239,4 +1239,26 @@ mod tests {
"the schema must not promise it either"
);
}
#[test]
fn a_plan_confirmed_for_one_environment_is_refused_in_another() {
// DATA-FLOW §9.3 has two halves the flow tests drive end to end — age and drift. The
// third refusal sits in front of both: a plan accepted for one interpreter, executed
// against another, would install a preview nobody was shown for that environment.
let now = jiff::Timestamp::now();
let plan = AcceptedPlan::accept(
"plan-1".to_owned(),
ResolutionReport::default(),
"hash-of-a".to_owned(),
&[],
now,
);
let err = plan
.verify("hash-of-b", &[], now)
.expect_err("another environment");
assert_eq!(err.code, Code::ResPlanStale);
assert!(err.message.contains("different environment"), "{err}");
plan.verify("hash-of-a", &[], now)
.expect("the environment it was made for, unchanged, a moment later");
}
}
+56 -8
View File
@@ -118,14 +118,18 @@ async fn fetch(name: &PkgName, version: &Version) -> Option<Option<String>> {
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),
)
Some(declared_in(&doc))
}
/// `info.requires_python` of a release document, `None` when it is absent, null or blank — all
/// three of which PyPI serves for a release that declares nothing.
fn declared_in(doc: &serde_json::Value) -> Option<String> {
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
@@ -232,4 +236,48 @@ mod tests {
assert_eq!(meta.cached(&name, &free), Some(None));
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn a_remembered_release_is_answered_without_asking_pypi() {
// Both answers come from the store: a constraint, and "declares nothing". Neither
// reaches the network, which this test has no way to offer.
let dir = std::env::temp_dir().join(format!("pd-release-cached-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let meta = PyPiReleases::new(&dir);
let name = pkg("scipy");
meta.remember(&name, &Version("1.7.3".into()), Some(">=3.7,<3.10"));
meta.remember(&name, &Version("1.16.0".into()), None);
let capped = meta.requires_python(&name, &Version("1.7.3".into())).await;
let free = meta.requires_python(&name, &Version("1.16.0".into())).await;
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(capped.as_deref(), Some(">=3.7,<3.10"));
assert_eq!(free, None);
}
#[tokio::test]
async fn a_version_that_is_not_pep_440_never_reaches_a_url() {
// `fetch` puts the version into a URL path; anything else is unknown, which never blocks,
// and is not remembered as if it were an answer.
let dir = std::env::temp_dir().join(format!("pd-release-url-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let meta = PyPiReleases::new(&dir);
let (name, odd) = (pkg("scipy"), Version("1.0/../../evil".into()));
assert_eq!(meta.requires_python(&name, &odd).await, None);
assert_eq!(meta.cached(&name, &odd), None, "a failure is not an answer");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_release_document_s_constraint_is_read_trimmed_and_blank_is_none() {
let doc = |v: serde_json::Value| serde_json::json!({ "info": { "requires_python": v } });
assert_eq!(
declared_in(&doc(" >=3.9 ".into())).as_deref(),
Some(">=3.9")
);
assert_eq!(declared_in(&doc("".into())), None);
assert_eq!(declared_in(&doc(serde_json::Value::Null)), None);
assert_eq!(declared_in(&serde_json::json!({ "info": {} })), None);
assert_eq!(declared_in(&serde_json::json!({ "urls": [] })), None);
}
}
+157
View File
@@ -1107,6 +1107,85 @@ async fn a_requires_python_nobody_knows_never_blocks() {
assert!(releases.asked.load(std::sync::atomic::Ordering::SeqCst) >= 1);
}
#[tokio::test]
async fn forcing_a_latest_this_python_cannot_run_forces_nothing_and_says_why() {
// The SP-1 world, except that httpcore's latest needs a newer Python than the environment's
// 3.12.4. Forcing it would pin a release that cannot install and release httpx from the
// guard set for nothing — so the decision is dropped, httpx is not named as breaking, and the
// preview carries the reason as an incompatible row instead.
let releases = Arc::new(Releases::default().with("httpcore", "1.0.9", ">=3.13"));
let engine = Scripted::default()
.with("httpx", "0.23.0", &["httpcore<0.16.0,>=0.15.0"])
.with("httpcore", "0.15.0", &["h11<0.13,>=0.11"])
.with("h11", "0.12.0", &[])
.offering("httpcore", "1.0.9")
.offering("h11", "0.16.0")
.needing("httpcore", "h11", "0.16");
let intent = Intent::Update {
all: false,
pkgs: vec!["httpcore".to_owned()],
except: Vec::new(),
force_latest: false,
};
let (mut flow, step) = UpdateFlow::start(
env(),
Box::new(engine.clone()),
&intent,
&[],
checking(&releases),
)
.await
.expect("start");
assert!(
matches!(step, FlowStep::NeedsDecisions { .. }),
"httpx holds httpcore back: {step:?}"
);
let step = flow
.decide(&BTreeMap::from([(pkg("httpcore"), Decision::ForceLatest)]))
.await
.expect("decide");
let report = match step {
FlowStep::NeedsDecisions { report, .. } | FlowStep::NeedsConfirm { report } => report,
other => panic!("a preview, not {other:?}"),
};
assert!(report.forced.is_empty(), "nothing was forced: {report:?}");
assert!(
!report
.changes
.iter()
.any(|c| c.name == pkg("httpcore") && c.to.0 == "1.0.9"),
"httpcore did not move to a release this Python cannot run"
);
let why: Vec<(String, String, String)> = report
.incompatible
.iter()
.map(|m| {
(
m.pkg.to_string(),
m.version.0.clone(),
m.requires_python.clone(),
)
})
.collect();
assert_eq!(
why,
[(
"httpcore".to_owned(),
"1.0.9".to_owned(),
">=3.13".to_owned()
)]
);
let world = engine.world();
let last = &world.resolves.last().expect("resolved").adjust;
assert!(
!last.release.contains(&pkg("httpx")),
"httpx stayed in the guard set: forcing was dropped before it reached the engine"
);
assert!(!last.pins.iter().any(|p| p.name == pkg("httpcore")));
}
#[tokio::test]
async fn a_rollback_across_engines_never_removes_pip() {
// C7. uv's freeze has no `--all`, so a uv snapshot never lists pip; compared with pip's
@@ -1151,6 +1230,84 @@ async fn a_rollback_across_engines_never_removes_pip() {
assert_eq!(restored, ["idna==3.2"]);
}
#[tokio::test]
async fn a_rollback_runs_end_to_end_one_package_at_a_time() {
// The restore half of `execute_rollback`, which nothing drove until the analysis measured
// it: each package installs alone, constrained by the rest of the target, so a restore that
// is 90% restorable restores 90% — and what was added since the snapshot goes first.
let engine = Scripted::default()
.with("idna", "3.4", &[])
.with("urllib3", "2.2.0", &[])
.with(
"requests",
"2.32.3",
&["idna<4,>=2.5", "urllib3<3,>=1.21.1"],
);
let dir = app_data("rollback-e2e");
let hash = pipdock_core::envs::env_hash(std::path::Path::new("python.exe"));
let target = snapshot::create(
&dir,
&hash,
"idna==3.2\nurllib3==1.26.20\n".to_owned(),
Trigger::Manual,
EngineId::Pip,
jiff::Timestamp::now(),
)
.expect("snapshot");
let (mut flow, preview) = RollbackFlow::start(
env(),
Box::new(engine.clone()),
&dir,
&target.meta.id,
FlowOptions::default(),
)
.await
.expect("start");
assert_eq!(preview.restore.uninstall, [pkg("requests")]);
let pre = flow
.take_snapshot(&dir)
.await
.expect("the pre-rollback snapshot");
assert!(matches!(pre.trigger, Trigger::Rollback { .. }));
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
let summary = flow.execute(tx).await.expect("execute");
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(summary.counts.ok, 3, "{summary:?}");
assert_eq!(
summary.plan_id, pre.id,
"the summary is filed under the snapshot it can undo to"
);
assert_eq!(engine.version_of("requests"), None);
assert_eq!(engine.version_of("idna").as_deref(), Some("3.2"));
assert_eq!(engine.version_of("urllib3").as_deref(), Some("1.26.20"));
let world = engine.world();
let alone: Vec<(String, Vec<String>)> = world
.installs
.iter()
.map(|set| {
(
set.specs
.iter()
.map(|s| s.to_requirement())
.collect::<Vec<_>>()
.join(" "),
set.constraints.iter().map(|c| c.to_requirement()).collect(),
)
})
.collect();
assert_eq!(
alone,
[
("idna==3.2".to_owned(), vec!["urllib3==1.26.20".to_owned()]),
("urllib3==1.26.20".to_owned(), vec!["idna==3.2".to_owned()]),
],
"one package per step, held to the rest of the target"
);
}
#[tokio::test]
async fn a_held_package_is_restated_in_every_plan() {
// H17. `hold_requirements` existed and nothing called it, so a held package was only left
+19 -1
View File
@@ -1439,7 +1439,7 @@ are required, every PR would have been red as well. Dependabot opened a PR for n
|---|---|
| Analysis | `sonar.yml`: one Windows job — vitest and `cargo llvm-cov` LCOV, clippy's JSON, `sonarqube-scan-action` v8.3.0 pinned by commit, `sonar.qualitygate.wait` so a red gate on `main` reaches Discord |
| Scope | `sonar-project.properties`: everything tracked, tests split out, fixtures and binaries excluded, coverage excluded only where no test here can execute the code, with the reason beside each |
| New code | `sonar.projectVersion` from `package.json`, so a release bump starts a period |
| New code | `sonar.projectVersion` from `package.json`, which the previous-version period keys on — though sending the first one did not move it (below) |
| The token | In the scanner step's environment alone; a job with no token (Dependabot, forks) is skipped, not failed |
| Audits | The four bumps above, and nothing ignored |
| Dependabot | A `vitest` group, because `@vitest/coverage-v8` peers vitest exactly; the `rfd` and `typescript` ignores re-checked and both still needed |
@@ -1458,6 +1458,24 @@ are required, every PR would have been red as well. Dependabot opened a PR for n
once `sonar.sources=.` replaced automatic analysis's own scoping.
- **The scanner's signature check works on a Windows runner.** v8 verifies the CLI's OpenPGP
signature by default, and Git for Windows' `gpg.exe` does it; no `skipSignatureVerification`.
- **The first analysis of `main` failed its gate**, on the two things automatic analysis could
never have seen. **Sixteen Rust findings**, every one a bug by Sonar's classification: three
`rust:S6677` — `message = %e.message` beside a format string records two fields called
`message`, and the log line read `failed code=PD-ENV-001 no interpreter at …` with the error's
words indistinguishable from the event's (now `error = …`, as every other failure logs it, and
`golden.rs` reads the CLI's log to hold it) — and thirteen `rust:S7493`, `std::fs` inside an
`async fn`: the tools-venv sync, Code Health's deptry report, and the four commands that write or
read a file the user chose, on what may be a network drive. They go through `tokio::fs` now.
And **new-code coverage 78.3 %** against 80 %.
- **Sending a version did not move the baseline.** The analysis that first sent `1.4.0` still
measured new code from 2026-09-27, so "new" was all of 1.4.0's audit — 4 037 lines, 849 of them
uncovered. The answer was tests rather than a setting: the restore half of `execute_rollback`, a
force the environment's Python cannot run, PEP 691 parsing (split out of `index::refresh`, with
L55's empty list finally under test), `user_file_error` (U25), a plan verified against another
environment, the cached half of `release::PyPiReleases`, and the store paths no test had driven
— a resolve that succeeds, a round of decisions, a rollback preview, and late answers on the
error paths. `InstallSet::only` had no caller and went. Estimated against Sonar's own per-line
data before pushing, by a script that reproduced its 78.28 % exactly: 81.2 %.
- **Cost:** eight to eleven minutes on a Windows runner beside the required checks, three of them restoring
ci-rust.yml's cache read-only. Saving a cache of its own was rejected: the repository is at 8.6 of
its 10 GB, and a fourth Windows cargo cache would evict the ones the required checks restore.
+1 -1
View File
@@ -72,7 +72,7 @@ The plan was one scripted tauri-driver run on a Windows runner — launch → le
## 3. Coverage & gates
**Coverage is measured since 2026-10-25, and gated only on new code.** `sonar.yml` runs `cargo llvm-cov --workspace` and `npm run test:coverage` (vitest's v8 provider) on Windows and hands both LCOV files to SonarQube Cloud, whose quality gate asks **80 % of new lines** covered — new meaning since the version in `package.json` last changed. The first measurement, of `main` at 1.4.0: **Rust 71.6 %** of 15 364 lines, **TypeScript 68.4 %** of 1 569. The two large holes are honest rather than unmeasured: `pipdock-cli/src/run.rs` (4 %) is the CLI driving a real interpreter, which L2 exercises and L1 cannot, and `src-tauri/src/commands.rs` (0 %) is the IPC surface, reached only by a running app. `sonar-project.properties` excludes from coverage only what no test here can execute (tooling, spikes, `probe.py`, generated bindings, the two entry points) and says why for each.
**Coverage is measured since 2026-10-25, and gated only on new code.** `sonar.yml` runs `cargo llvm-cov --workspace` and `npm run test:coverage` (vitest's v8 provider) on Windows and hands both LCOV files to SonarQube Cloud, whose quality gate asks **80 % of new lines** covered — new meaning since the previous version's period began, which at the switch was still the first analysis (2026-09-27), so all of 1.4.0 counted. The first measurement, of `main` at 1.4.0: **Rust 71.6 %** of 15 364 lines, **TypeScript 68.4 %** of 1 569. The two large holes are honest rather than unmeasured: `pipdock-cli/src/run.rs` (4 %) is the CLI driving a real interpreter, which L2 exercises and L1 cannot, and `src-tauri/src/commands.rs` (0 %) is the IPC surface, reached only by a running app. `sonar-project.properties` excludes from coverage only what no test here can execute (tooling, spikes, `probe.py`, generated bindings, the two entry points) and says why for each.
This section once set targets — core ≥ 85 % line coverage, classifiers and plan module ≥ 95 % — that nothing measured until then. They are not the gate; the gate is new code, and §1's rule — a test that failed first — is still the guarantee a percentage cannot give. By file, `errors/catalog.rs` is at 99.5 % and `plan/` at 85–99 %.
+2 -1
View File
@@ -5,7 +5,8 @@
# could import no coverage at all. It also sent no project version, so the "previous version"
# new-code period stayed anchored to the first analysis (2026-09-27) and "new code" only ever grew.
# The workflow passes `sonar.projectVersion` from package.json, which is one of the five places the
# version lives (CLAUDE.md), so a release bump is what starts a new period.
# version lives (CLAUDE.md) and what the previous-version period keys on. The first analysis to
# send one kept the old baseline; whether a bump moves it is to be read from the gate, not assumed.
sonar.organization=poli0981
sonar.projectKey=poli0981_pipdock
+2 -1
View File
@@ -31,7 +31,8 @@ tauri-plugin-clipboard-manager = "2.5.0"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
jiff = "0.2.38"
tokio = { version = "1.53.3", features = ["rt-multi-thread", "sync"] }
# `fs` for the commands that write a file the user chose, which may be on a slow or network drive.
tokio = { version = "1.53.3", features = ["rt-multi-thread", "sync", "fs"] }
# `plan_cancel` trips the same `CancellationToken` the core threads through `exec`.
tokio-util = "0.7.20"
tracing = "0.1.44"
+8 -4
View File
@@ -449,7 +449,8 @@ pub async fn env_export(
};
let freeze = engine.freeze(&env).await?;
let target = std::path::PathBuf::from(&path);
std::fs::write(&target, freeze)
tokio::fs::write(&target, freeze)
.await
.map_err(|e| pipdock_core::exec::user_file_error(&target, &e))?;
Ok(target.display().to_string())
}
@@ -469,7 +470,8 @@ pub async fn env_export(
pub async fn requirements_read(
path: String,
) -> Wire<pipdock_core::requirements::ParsedRequirements> {
let text = std::fs::read_to_string(&path)
let text = tokio::fs::read_to_string(&path)
.await
.map_err(|e| pipdock_core::exec::user_file_error(std::path::Path::new(&path), &e))?;
Ok(pipdock_core::requirements::parse(&text))
}
@@ -1239,7 +1241,8 @@ pub async fn audit_save_report(
})?;
for (target, contents) in [(&md, body), (&json, document)] {
std::fs::write(target, contents)
tokio::fs::write(target, contents)
.await
.map_err(|e| pipdock_core::exec::user_file_error(target, &e))?;
}
Ok(vec![md.display().to_string(), json.display().to_string()])
@@ -1398,7 +1401,8 @@ pub async fn health_save_report(
})?;
for (target, contents) in [(&md, body), (&json, document)] {
std::fs::write(target, contents)
tokio::fs::write(target, contents)
.await
.map_err(|e| pipdock_core::exec::user_file_error(target, &e))?;
}
Ok(vec![md.display().to_string(), json.display().to_string()])
+1 -1
View File
@@ -92,7 +92,7 @@ pub fn run() {
let state = match state::AppState::new() {
Ok(state) => state,
Err(e) => {
tracing::error!(target: "pipdock::app", code = %e.code, message = %e.message, "could not start");
tracing::error!(target: "pipdock::app", code = %e.code, error = %e.message, "could not start");
startup_failed(&e, &log);
return;
}
+35
View File
@@ -176,6 +176,41 @@ describe('what the report says besides the changes', () => {
expect(within(section('new-install')).getByText('oldlib')).toBeInTheDocument()
})
it('shows an unattributed blocker as its bare constraint, and a dependent without a version', () => {
// ARCHITECTURE §3: when attribution is ambiguous the constraint is shown without a culprit
// rather than guessed (`Blocker.by` absent), and the probe does not always know a dependent's
// version. Each still counts once toward what forcing breaks.
const numpy = FORCED.forced?.[0]
if (numpy === undefined) throw new Error('the forced fixture forces numpy')
show({
...FORCED,
forced: [
{
...numpy,
blockers: [{ constraint: 'numpy<2' }, { by: 'pandas', constraint: 'numpy<2,>=1.26.0' }],
},
],
yanked: [{ pkg: 'oldlib', version: '2.0.0' }],
})
const forced = section('forced')
expect(within(forced).getByText('Will break (2)')).toBeInTheDocument()
expect(within(forced).getByText('numpy<2')).toBeInTheDocument()
expect(within(forced).getByText('pandas requires numpy<2,>=1.26.0')).toBeInTheDocument()
// A withdrawal with no reason given is still said, without a dangling colon.
expect(
within(section('yanked')).getByText('oldlib 2.0.0 was withdrawn by its maintainers.'),
).toBeInTheDocument()
})
it('heads a force that breaks nothing by what was forced, not by a count of zero', () => {
const numpy = FORCED.forced?.[0]
if (numpy === undefined) throw new Error('the forced fixture forces numpy')
show({ ...FORCED, forced: [{ pkg: numpy.pkg, latest: numpy.latest, resolved: numpy.resolved }] })
const forced = section('forced')
expect(within(forced).getByText('Forced (1)')).toBeInTheDocument()
expect(within(forced).queryByText(/Will break/)).toBeNull()
})
it('does not call a plan whose only content is a left-out package "nothing to change"', () => {
// The user asked for numba and is owed the reason it is not happening.
show({ changes: [], heldBack: [], incompatible: FORCED.incompatible ?? [] })
+138 -1
View File
@@ -10,8 +10,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import * as ipc from '@/ipc'
import type { GuardReport, PyEnv } from '@/ipc'
import type { FlowStep, GuardReport, Intent, PyEnv, RollbackPreview } from '@/ipc'
import { PANEL_PHASES, usePlanStore } from '@/stores/plan'
import flowStep from '@/test/fixtures/flow_step.json'
import rollbackPreview from '@/test/fixtures/rollback_preview.json'
import { resetStore } from '@/test/stores'
// The factory imports lazily because `vi.mock` is hoisted above every import in this file — a
@@ -37,6 +39,23 @@ const BREAKING: GuardReport = {
}
const CLEAR: GuardReport = { removing: ['numpy', 'pandas'], breaks: {}, withDependents: [] }
/** Computed from the real `FlowStep` by `cargo run -p xtask -- ipc-fixtures`. */
const DECISIONS = flowStep as FlowStep
const SKIPPED: FlowStep = { step: 'nothing', reason: 'everything-skipped' }
const PREVIEW = rollbackPreview as RollbackPreview
const UPDATE_ALL: Intent = { intent: 'update', all: true, pkgs: [], except: [], forceLatest: false }
/** A promise the test settles by hand, so a second action can overtake the first. */
function deferred<T>() {
let resolve!: (value: T) => void
let reject!: (reason: unknown) => void
const promise = new Promise<T>((res, rej) => {
resolve = res
reject = rej
})
return { promise, resolve, reject }
}
describe('usePlanStore', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -150,4 +169,122 @@ describe('usePlanStore', () => {
expect(unlisten).toHaveBeenCalledOnce()
expect(usePlanStore.getState().phase).toBe('summary')
})
it('shows a resolved plan as a preview of the kind that was asked for', async () => {
vi.mocked(ipc.planResolve).mockResolvedValue(DECISIONS)
await usePlanStore.getState().resolve(ENV, { intent: 'install', specs: ['httpx'] })
const { phase, step, kind, env } = usePlanStore.getState()
expect(phase).toBe('preview')
expect(step).toEqual(DECISIONS)
expect(kind).toBe('install')
expect(env).toEqual(ENV)
})
it('sends the round its answers belong to, and clears them with it', async () => {
vi.mocked(ipc.planResolve).mockResolvedValue(DECISIONS)
vi.mocked(ipc.planDecide).mockResolvedValue(SKIPPED)
await usePlanStore.getState().resolve(ENV, UPDATE_ALL)
usePlanStore.getState().choose('numpy', 'skip')
usePlanStore.getState().choose('scipy', 'force-latest')
await usePlanStore.getState().submitDecisions()
expect(ipc.planDecide).toHaveBeenCalledWith({ numpy: 'skip', scipy: 'force-latest' })
const { phase, step, decisions } = usePlanStore.getState()
expect(phase).toBe('preview')
expect(step).toEqual(SKIPPED)
// The next preview may name other packages; an answer about one no longer in conflict
// would be sent back to a flow that has moved on.
expect(decisions).toEqual({})
})
it('keeps the preview usable when a round of decisions fails', async () => {
// U24: a failed re-resolve leaves the flow as it was, so the screen must too — the same
// preview, with the error beside it, decidable again.
vi.mocked(ipc.planResolve).mockResolvedValue(DECISIONS)
vi.mocked(ipc.planDecide).mockRejectedValue({ code: 'PD-NET-001', message: 'index down' })
await usePlanStore.getState().resolve(ENV, UPDATE_ALL)
usePlanStore.getState().choose('numpy', 'force-latest')
await usePlanStore.getState().submitDecisions()
const { phase, step, error, decisions } = usePlanStore.getState()
expect(phase).toBe('preview')
expect(step).toEqual(DECISIONS)
expect(error?.code).toBe('PD-NET-001')
expect(decisions).toEqual({ numpy: 'force-latest' })
})
it('previews a rollback as a rollback, and confirms it with the rollback command', async () => {
vi.mocked(ipc.snapshotRollbackPreview).mockResolvedValue(PREVIEW)
await usePlanStore.getState().rollback(ENV, PREVIEW.target.id)
expect(ipc.snapshotRollbackPreview).toHaveBeenCalledWith(ENV, PREVIEW.target.id)
const { phase, preview, kind } = usePlanStore.getState()
expect(phase).toBe('preview')
expect(preview).toEqual(PREVIEW)
expect(kind).toBe('rollback')
// One Confirm button for both flows: which command it sends is the session's kind.
vi.mocked(ipc.snapshotRollback).mockRejectedValue({ code: 'PD-SNP-001', message: 'no room' })
await usePlanStore.getState().execute()
expect(ipc.snapshotRollback).toHaveBeenCalledOnce()
expect(ipc.planExecute).not.toHaveBeenCalled()
})
it('lands a failed rollback preview where the user can see it', async () => {
vi.mocked(ipc.snapshotRollbackPreview).mockRejectedValue({
code: 'PD-SNP-002',
message: 'that snapshot is gone',
})
await usePlanStore.getState().rollback(ENV, 'missing')
expect(usePlanStore.getState().phase).toBe('failed')
expect(usePlanStore.getState().error?.code).toBe('PD-SNP-002')
})
it('drops the answer to a resolve the user has already moved on from', async () => {
// Every action bumps the generation; a reply from the one before it must not overwrite the
// screen the user is now on — here, a preview arriving over an uninstall guard.
const late = deferred<FlowStep>()
vi.mocked(ipc.planResolve).mockReturnValue(late.promise)
vi.mocked(ipc.uninstallGuard).mockResolvedValue(BREAKING)
const resolving = usePlanStore.getState().resolve(ENV, UPDATE_ALL)
await usePlanStore.getState().startUninstall(ENV, ['numpy'])
late.resolve(DECISIONS)
await resolving
const { phase, step, guard } = usePlanStore.getState()
expect(phase).toBe('guard')
expect(guard).toEqual(BREAKING)
expect(step).toBeNull()
})
it('drops a late failure the same way, for every action that waits', async () => {
const lateResolve = deferred<FlowStep>()
const lateDecide = deferred<FlowStep>()
const latePreview = deferred<RollbackPreview>()
vi.mocked(ipc.planResolve).mockResolvedValueOnce(DECISIONS).mockReturnValueOnce(lateResolve.promise)
vi.mocked(ipc.planDecide).mockReturnValue(lateDecide.promise)
vi.mocked(ipc.snapshotRollbackPreview).mockReturnValue(latePreview.promise)
vi.mocked(ipc.uninstallGuard).mockResolvedValue(CLEAR)
await usePlanStore.getState().resolve(ENV, UPDATE_ALL)
const deciding = usePlanStore.getState().submitDecisions()
const resolving = usePlanStore.getState().resolve(ENV, UPDATE_ALL)
const previewing = usePlanStore.getState().rollback(ENV, 'id')
await usePlanStore.getState().startUninstall(ENV, ['numpy', 'pandas'])
lateDecide.reject({ code: 'PD-NET-001', message: 'late' })
lateResolve.reject({ code: 'PD-NET-001', message: 'late' })
latePreview.reject({ code: 'PD-NET-001', message: 'late' })
await Promise.all([deciding, resolving, previewing])
const { phase, error, guard } = usePlanStore.getState()
expect(phase).toBe('guard')
expect(guard).toEqual(CLEAR)
expect(error).toBeNull()
})
})
+87
View File
@@ -86,6 +86,45 @@ describe('a slow answer for an environment the user has left', () => {
expect(useEnvStore.getState().outdated).toEqual([])
expect(useEnvStore.getState().outdatedStatus).toBe('idle')
})
it('does not put the left environment’s failure on the new one either', async () => {
// The same rule on the error path: an unreachable index for the environment the user left
// must not mark the one they are now looking at as unreadable.
const list = deferredFailure()
const outdated = deferredFailure()
vi.mocked(ipc.pkgList).mockReturnValueOnce(list.promise)
vi.mocked(ipc.pkgOutdated).mockReturnValueOnce(outdated.promise)
const listing = useEnvStore.getState().loadPackages()
const badges = useEnvStore.getState().loadOutdated()
useEnvStore.getState().select(env('b').interpreter)
list.fail({ code: 'PD-ENV-003', message: 'probe failed' })
outdated.fail({ code: 'PD-NET-001', message: 'offline' })
await Promise.all([listing, badges])
const { listError, outdatedError, listing: state } = useEnvStore.getState()
expect(listError).toBeNull()
expect(outdatedError).toBeNull()
expect(state).not.toBe('error')
})
})
/** A promise the test rejects when it chooses, with a `PdError`-shaped plain object. */
function deferredFailure() {
let fail: (error: { code: string; message: string }) => void = () => undefined
const promise = new Promise<never>((_, reject) => {
fail = reject
})
return { promise, fail }
}
const meta = (id: string) => ({
id,
createdAt: '2026-10-25T00:00:00Z',
trigger: 'manual' as const,
engine: 'pip' as const,
packageCount: 3,
appVersion: '1.4.0',
})
describe('the timeline', () => {
@@ -108,6 +147,54 @@ describe('the timeline', () => {
expect(useEnvStore.getState().selectedSnapshot).toBe('two')
expect(useEnvStore.getState().diff).toEqual(second)
})
it('lists the snapshots of the environment that is open, by its hash', async () => {
vi.mocked(ipc.snapshotList).mockResolvedValueOnce([meta('one')])
await useEnvStore.getState().loadSnapshots()
// By `envHash`: a snapshot outlives the Python that made it.
expect(ipc.snapshotList).toHaveBeenCalledWith('hash-a')
const { snapshots, snapshotsFor, snapshotsLoading } = useEnvStore.getState()
expect(snapshots).toEqual([meta('one')])
expect(snapshotsFor).toBe(env('a').interpreter)
expect(snapshotsLoading).toBe('ready')
})
it('drops the timeline of an environment closed before it arrived, and its failure', async () => {
useEnvStore.setState({ rows: [row('a'), row('b')] })
const slow = held<ReturnType<typeof meta>[]>()
const failing = deferredFailure()
vi.mocked(ipc.snapshotList).mockReturnValueOnce(slow.promise).mockReturnValueOnce(failing.promise)
const first = useEnvStore.getState().loadSnapshots()
useEnvStore.getState().openEnv(env('b').interpreter)
slow.release([meta('of-a')])
await first
expect(useEnvStore.getState().snapshots).not.toEqual([meta('of-a')])
const second = useEnvStore.getState().loadSnapshots()
useEnvStore.getState().openEnv(env('a').interpreter)
failing.fail({ code: 'PD-SNP-003', message: 'unreadable' })
await second
expect(ipc.snapshotList).toHaveBeenCalledTimes(2)
expect(useEnvStore.getState().snapshotsError).toBeNull()
})
it('does not show the failure of a diff the user has clicked away from', async () => {
const failing = deferredFailure()
const second = { added: [], removed: [], changed: [] }
vi.mocked(ipc.snapshotDiff).mockReturnValueOnce(failing.promise).mockResolvedValueOnce(second)
const first = useEnvStore.getState().selectSnapshot('one')
await useEnvStore.getState().selectSnapshot('two')
failing.fail({ code: 'PD-SNP-003', message: 'unreadable' })
await first
const { diff, diffLoading, snapshotsError } = useEnvStore.getState()
expect(diff).toEqual(second)
expect(diffLoading).toBe('ready')
expect(snapshotsError).toBeNull()
})
})
describe('leaving a plan the backend is still working on', () => {
+9
View File
@@ -62,7 +62,10 @@ export interface IpcMock {
healthDirty: ReturnType<typeof vi.fn>
reportBugUrl: ReturnType<typeof vi.fn>
logsTail: ReturnType<typeof vi.fn>
snapshotList: ReturnType<typeof vi.fn>
snapshotDiff: ReturnType<typeof vi.fn>
snapshotRollbackPreview: ReturnType<typeof vi.fn>
snapshotRollback: ReturnType<typeof vi.fn>
indexSearch: ReturnType<typeof vi.fn>
appInfo: ReturnType<typeof vi.fn>
settingsGet: ReturnType<typeof vi.fn>
@@ -127,7 +130,13 @@ export function ipcMock(): IpcMock {
healthDirty: vi.fn().mockResolvedValue(null),
// Settings renders the Logs row, so every Settings test needs this to resolve to a real shape.
logsTail: vi.fn().mockResolvedValue({ dir: 'C:/data/logs', lines: [] }),
// An empty timeline. Missing until the timeline's own race tests needed it: every test that
// opened an environment reached `loadSnapshots`, threw on the absent export, and rendered
// the timeline's error without anyone asking for one.
snapshotList: vi.fn().mockResolvedValue([]),
snapshotDiff: vi.fn(),
snapshotRollbackPreview: vi.fn(),
snapshotRollback: vi.fn(),
// Ready and empty by default: a test about warming says so.
indexSearch: vi.fn().mockResolvedValue({ hits: [], ready: true }),
// `PdErrorRow` asks for this on mount, so any test that renders a screen containing an error