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>
This commit is contained in:
poli0981andClaude Opus 5.5 committed 2026-10-17 00:55:27 +07:00
1 parent 040571c7f7
commit a9f476a2ae
5 files changed
+352 -305

No files matched your search

+6 -1
View File
@@ -261,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");
+17
View File
@@ -602,6 +602,23 @@ pub fn io_error(path: &Path, e: &std::io::Error) -> PdError {
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.
///
/// **Spike SP-6.** The same interpreter reports different casing depending on how it was launched
+1 -1
View File
@@ -30,7 +30,7 @@ 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"] }
tokio = { version = "1.53.3", features = ["rt-multi-thread", "sync"] }
# `plan_cancel` trips the same `CancellationToken` the core threads through `exec`.
tokio-util = "0.7.20"
tracing = "0.1.44"
+134 -136
View File
@@ -196,12 +196,31 @@ pub async fn env_scan(
.collect()
};
let mut rows = Vec::with_capacity(candidates.len());
for candidate in candidates {
// Four at a time rather than one after another (U19, part). Each probe is a Python start-up
// and a walk of site-packages; on a machine with eight interpreters the screen waited for all
// eight in series. Each probe still has its own 60 s watchdog, so one hung interpreter costs
// its own row, not the scan. Results keep discovery order.
let gate = std::sync::Arc::new(tokio::sync::Semaphore::new(4));
let mut probes = tokio::task::JoinSet::new();
for (index, candidate) in candidates.into_iter().enumerate() {
let folder = folders.remove(&envs::env_hash(&candidate.path));
rows.push(probe_row(candidate.path, candidate.source, folder).await);
let gate = std::sync::Arc::clone(&gate);
probes.spawn(async move {
let _permit = gate.acquire_owned().await.ok();
(
index,
probe_row(candidate.path, candidate.source, folder).await,
)
});
}
Ok(rows)
let mut rows = Vec::new();
while let Some(joined) = probes.join_next().await {
if let Ok(row) = joined {
rows.push(row);
}
}
rows.sort_by_key(|(index, _)| *index);
Ok(rows.into_iter().map(|(_, row)| row).collect())
}
/// Probe one interpreter, for the manual *Browse…* path — and to refresh a single row.
@@ -430,12 +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).map_err(|e| {
PdError::new(
pipdock_core::errors::Code::SysDiskFull,
format!("write {}: {e}", target.display()),
)
})?;
std::fs::write(&target, freeze)
.map_err(|e| pipdock_core::exec::user_file_error(&target, &e))?;
Ok(target.display().to_string())
}
@@ -454,12 +469,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).map_err(|e| {
PdError::new(
pipdock_core::errors::Code::SysDiskFull,
format!("read {path}: {e}"),
)
})?;
let text = std::fs::read_to_string(&path)
.map_err(|e| pipdock_core::exec::user_file_error(std::path::Path::new(&path), &e))?;
Ok(pipdock_core::requirements::parse(&text))
}
@@ -491,7 +502,40 @@ pub async fn cache_clear(
state: tauri::State<'_, AppState>,
target: pipdock_core::cache::Target,
) -> Wire<u64> {
Ok(pipdock_core::cache::clear(&state.app_data, target)?)
use pipdock_core::cache::Target;
// Each target is held by the slot of the feature using it, so a clear is refused with
// `PD-RES-003` while that feature runs rather than deleting the venv a Health run is executing
// from, the audit venv mid-audit, or the snapshots a plan is writing (U36). A session merely
// parked there is put back afterwards — a preview on screen is not something to lose to a
// clear in another tab.
let app_data = state.app_data.clone();
Ok(match target {
Target::Snapshots => clear_holding(&state.sessions, app_data, target).await?,
Target::Tools => clear_holding(&state.health, app_data, target).await?,
Target::Audit => clear_holding(&state.audit, app_data, target).await?,
})
}
/// Clear `target` while holding `slot`, off the async workers: a venv is thousands of files.
async fn clear_holding<T: Send>(
slot: &crate::state::Sessions<T>,
app_data: std::path::PathBuf,
target: pipdock_core::cache::Target,
) -> pipdock_core::Result<u64> {
let (claim, parked) = slot.claim()?;
let freed = tokio::task::spawn_blocking(move || pipdock_core::cache::clear(&app_data, target))
.await
.map_err(|e| {
PdError::new(
pipdock_core::errors::Code::IntUnexpected,
format!("cache clear stopped: {e}"),
)
})?;
if let Some(session) = parked {
claim.park(session);
}
freed
}
/// What `index_search` returns.
@@ -524,6 +568,7 @@ pub struct SearchResults {
/// "refresh the index" is an action, not a failure.
#[tauri::command]
pub async fn index_search(
app: tauri::AppHandle,
state: tauri::State<'_, AppState>,
query: String,
limit: usize,
@@ -537,20 +582,17 @@ pub async fn index_search(
}
if state.begin_index_load() {
let loaded = {
let store = state.store.lock().await;
NameIndex::load(&store)
};
state.finish_index_load(loaded);
// The load that this keystroke paid for is done, so answer from it rather than making the
// user press another key.
if let Some(hits) = state.search_index(&query, limit) {
return Ok(SearchResults {
hits,
ready: true,
unavailable: None,
});
}
// In the background, on a connection of its own. The load held `state.store` for its
// 140 ms — every other command that wanted the store queued behind a keystroke — and ran
// on an async worker the rest of the app shares (U35). This search answers `ready: false`
// and the screen asks again, which is the contract the doc above always described.
let app_data = state.app_data.clone();
let handle = app.clone();
tauri::async_runtime::spawn_blocking(move || {
let loaded = pipdock_core::store::Store::open(&app_data)
.and_then(|store| NameIndex::load(&store));
handle.state::<AppState>().finish_index_load(loaded);
});
}
Ok(SearchResults {
@@ -638,7 +680,7 @@ pub async fn plan_resolve(
// Claiming before any work means a second resolve is refused rather than racing this one.
// Whatever flow was parked is dropped: starting a new plan abandons the old preview, which is
// what the user just asked for.
let _ = state.claim().await?;
let (claim, _) = state.sessions.claim()?;
// A bug report carries one run, so the ring starts here rather than at execute.
state.log.clear();
@@ -676,15 +718,14 @@ pub async fn plan_resolve(
// without this the commonest thing anyone reports — a plan that would not resolve —
// would attach an empty excerpt.
state.log.push(flow.report().raw.as_str());
state.park(Session::Update(Box::new(flow))).await;
claim.park(Session::Update(Box::new(flow)));
Ok(step)
}
Err(e) => {
if let Some(tail) = e.stderr_tail.as_deref() {
state.log.push(tail);
}
// Every failure path releases the slot, or the session refuses plans forever.
state.release().await;
// The claim drops here and releases the slot — as it does on every `?` above.
Err(e.into())
}
}
@@ -700,7 +741,7 @@ pub async fn plan_decide(
state: tauri::State<'_, AppState>,
decisions: std::collections::BTreeMap<String, Decision>,
) -> Wire<flow::FlowStep> {
let mut flow = state.claim_update().await?;
let (claim, mut flow) = state.sessions.claim_update()?;
let parsed = decisions
.into_iter()
@@ -712,7 +753,7 @@ pub async fn plan_decide(
Err(e) => {
// The flow is still good — only the argument was bad, so park it rather than losing
// the preview the user is looking at.
state.park(Session::Update(flow)).await;
claim.park(Session::Update(flow));
return Err(e.into());
}
};
@@ -721,7 +762,7 @@ pub async fn plan_decide(
// the preview on screen is still a plan that can be decided again or confirmed; releasing it
// here left a preview whose Confirm answered "no plan" (U24).
let step = flow.decide(&parsed).await;
state.park(Session::Update(flow)).await;
claim.park(Session::Update(flow));
Ok(step?)
}
@@ -739,25 +780,18 @@ pub async fn plan_execute(
app: tauri::AppHandle,
state: tauri::State<'_, AppState>,
) -> Wire<ExecutionOutcome> {
let mut flow = state.claim_update().await?;
let (claim, mut flow) = state.sessions.claim_update()?;
state.set_cancel(Some(flow.cancel_handle()));
let snapshot = match flow
let snapshot = flow
.take_snapshot(flow::SnapshotPolicy::Take, &state.app_data)
.await
{
Ok(meta) => meta,
Err(e) => {
state.release().await;
return Err(e.into());
}
};
.await?;
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
forward_progress(&app, "plan-progress", rx);
let result = flow.execute(tx).await;
state.release().await;
drop(claim);
Ok(ExecutionOutcome {
summary: result?,
@@ -781,7 +815,7 @@ pub async fn plan_execute(
/// mean the UI has to race the thing it is trying to stop.
#[tauri::command]
pub async fn plan_cancel(state: tauri::State<'_, AppState>) -> Wire<bool> {
Ok(state.stop().await)
Ok(state.sessions.stop())
}
/// Check what a removal would break, and park the flow that would do it (DATA-FLOW §5).
@@ -800,23 +834,16 @@ pub async fn uninstall_guard(
env: PyEnv,
pkgs: Vec<String>,
) -> Wire<pipdock_core::graph::GuardReport> {
let _ = state.claim().await?;
let (claim, _) = state.sessions.claim()?;
// Read, then drop, before any await: `Store` is not `Sync`, so a future holding the guard is
// not `Send` and this command would not compile — and where it does compile it serializes
// every other command behind a subprocess.
// every other command behind a subprocess. A failure releases the slot with the claim.
let (engine, opts) = flow_inputs(&state).await?;
match flow::UninstallFlow::start(env, engine, &pkgs, opts).await {
Ok((flow, report)) => {
state.park(Session::Uninstall(Box::new(flow))).await;
Ok(report)
}
Err(e) => {
state.release().await;
Err(e.into())
}
}
let (flow, report) = flow::UninstallFlow::start(env, engine, &pkgs, opts).await?;
claim.park(Session::Uninstall(Box::new(flow)));
Ok(report)
}
/// Snapshot, then remove (DATA-FLOW §5's tail).
@@ -834,7 +861,7 @@ pub async fn uninstall_execute(
state: tauri::State<'_, AppState>,
force: bool,
) -> Wire<ExecutionOutcome> {
let mut flow = state.sessions.claim_uninstall().await?;
let (claim, mut flow) = state.sessions.claim_uninstall()?;
state.set_cancel(Some(flow.cancel_handle()));
let ack = if force {
@@ -843,26 +870,21 @@ pub async fn uninstall_execute(
flow::GuardAck::Clear
};
if let Err(e) = flow.check(ack) {
state.release().await;
// The guard dialog is still on screen, and *Force remove* is still a choice the user can
// make: the flow stays parked rather than leaving a dialog whose buttons answer "no plan".
claim.park(Session::Uninstall(flow));
return Err(e.into());
}
let snapshot = match flow
let snapshot = flow
.take_snapshot(flow::SnapshotPolicy::Take, &state.app_data)
.await
{
Ok(meta) => meta,
Err(e) => {
state.release().await;
return Err(e.into());
}
};
.await?;
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
forward_progress(&app, "plan-progress", rx);
let result = flow.execute(ack, tx).await;
state.release().await;
drop(claim);
Ok(ExecutionOutcome {
summary: result?,
@@ -949,20 +971,14 @@ pub async fn snapshot_rollback_preview(
env: PyEnv,
id: String,
) -> Wire<flow::RollbackPreview> {
let _ = state.claim().await?;
let (claim, _) = state.sessions.claim()?;
let (engine, opts) = flow_inputs(&state).await?;
match flow::RollbackFlow::start(env, engine, &state.app_data, &id, opts).await {
Ok((rollback, preview)) => {
state.park(Session::Rollback(Box::new(rollback))).await;
Ok(preview)
}
Err(e) => {
state.release().await;
Err(e.into())
}
}
let (rollback, preview) =
flow::RollbackFlow::start(env, engine, &state.app_data, &id, opts).await?;
claim.park(Session::Rollback(Box::new(rollback)));
Ok(preview)
}
/// Snapshot the current state, then restore the parked target (DATA-FLOW §8).
@@ -978,22 +994,16 @@ pub async fn snapshot_rollback(
app: tauri::AppHandle,
state: tauri::State<'_, AppState>,
) -> Wire<ExecutionOutcome> {
let mut rollback = state.sessions.claim_rollback().await?;
let (claim, mut rollback) = state.sessions.claim_rollback()?;
state.set_cancel(Some(rollback.cancel_handle()));
let snapshot = match rollback.take_snapshot(&state.app_data).await {
Ok(meta) => meta,
Err(e) => {
state.release().await;
return Err(e.into());
}
};
let snapshot = rollback.take_snapshot(&state.app_data).await?;
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
forward_progress(&app, "plan-progress", rx);
let result = rollback.execute(tx).await;
state.release().await;
drop(claim);
Ok(ExecutionOutcome {
summary: result?,
@@ -1053,7 +1063,7 @@ pub async fn health_run(
) -> Wire<pipdock_core::health::HealthReport> {
use pipdock_core::health;
state.health.claim().await?;
let (claim, _) = state.health.claim()?;
let project = std::path::PathBuf::from(&project);
let tools_dir = health::tools_dir(&state.app_data);
@@ -1110,18 +1120,15 @@ pub async fn health_run(
}
// Parked rather than dropped: P5 checks its consent against this exact report, and the
// folder it ran in is what a fix would rewrite.
state
.health
.park(crate::state::HealthSession {
project,
env,
report: report.clone(),
})
.await;
claim.park(crate::state::HealthSession {
project,
env,
report: report.clone(),
});
Ok(report)
}
Err(e) => {
state.health.release().await;
drop(claim);
Err(e.into())
}
}
@@ -1156,7 +1163,12 @@ pub async fn audit_run(
) -> Wire<pipdock_core::audit::AuditReport> {
use pipdock_core::{audit, health};
state.audit.claim().await?;
let (claim, _) = state.audit.claim()?;
// Registered before anything slow. It was registered after the freeze and the settings read,
// so a Stop pressed during either found no token and did nothing — the audit ran to the end
// (U37). A token tripped this early skips the venv sync and makes the run report `cancelled`.
let token = CancellationToken::new();
state.audit.set_cancel(Some(token.clone()));
let dir = health::audit_dir(&state.app_data);
let outcome = async {
@@ -1175,11 +1187,9 @@ pub async fn audit_run(
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
forward_progress(&app, "audit-progress", rx);
let token = CancellationToken::new();
state.audit.set_cancel(Some(token.clone()));
let sink = engine::ProgressSink::new(tx, audit::AUDIT_STEPS + synced, token);
let sink = engine::ProgressSink::new(tx, audit::AUDIT_STEPS + synced, token.clone());
if sync_needed {
if sync_needed && !token.is_cancelled() {
let (python, _) = health::choose_tools_python(&envs::scan().await).await?;
health::sync_tools_venv(&dir, &python, health::AUDIT_TOOLS, &sink).await?;
}
@@ -1187,11 +1197,9 @@ pub async fn audit_run(
}
.await;
// Released on both paths, and the token cleared with it: a token left registered would let the
// *next* `audit_cancel` stop a run that had not started, which is S5's wedge bug wearing a
// different hat.
state.audit.release().await;
state.audit.set_cancel(None);
// Released on both paths, and the token cleared with it — the claim's drop does both. A token
// left registered would let the *next* `audit_cancel` stop a run that had not started.
drop(claim);
Ok(outcome?)
}
@@ -1223,12 +1231,8 @@ pub async fn audit_save_report(
})?;
for (target, contents) in [(&md, body), (&json, document)] {
std::fs::write(target, contents).map_err(|e| {
PdError::new(
pipdock_core::errors::Code::SysDiskFull,
format!("write {}: {e}", target.display()),
)
})?;
std::fs::write(target, contents)
.map_err(|e| pipdock_core::exec::user_file_error(target, &e))?;
}
Ok(vec![md.display().to_string(), json.display().to_string()])
}
@@ -1242,7 +1246,7 @@ pub async fn audit_save_report(
/// Never fails.
#[tauri::command]
pub async fn audit_cancel(state: tauri::State<'_, AppState>) -> Wire<bool> {
Ok(state.audit.stop().await)
Ok(state.audit.stop())
}
/// Whether the parked report's project has uncommitted work, so the confirm can say so.
@@ -1259,9 +1263,9 @@ pub async fn audit_cancel(state: tauri::State<'_, AppState>) -> Wire<bool> {
/// `PD-INT-001` when no run is parked.
#[tauri::command]
pub async fn health_dirty(state: tauri::State<'_, AppState>) -> Wire<Option<usize>> {
let session = state.health.claim_one().await?;
let (claim, session) = state.health.claim_one()?;
let found = pipdock_core::health::fix::dirty(&session.project).await;
state.health.park(session).await;
claim.park(session);
Ok(found.map(|tree| tree.entries))
}
@@ -1289,7 +1293,7 @@ pub async fn health_fix(
// `claim_one`, not `claim`: finding nothing must leave the slot **idle** rather than writing
// `Busy` and wedging every later command with `PD-RES-003` for a session that does not exist.
let session = state.health.claim_one().await?;
let (claim, session) = state.health.claim_one()?;
let outcome = async {
// What the dialog named must be what the server is holding. Only a frontend that is out
@@ -1344,7 +1348,7 @@ pub async fn health_fix(
if let Ok(report) = &outcome {
session.report.ruff = report.remaining.clone();
}
state.health.park(session).await;
claim.park(session);
outcome.map_err(Into::into)
}
@@ -1386,12 +1390,8 @@ pub async fn health_save_report(
})?;
for (target, contents) in [(&md, body), (&json, document)] {
std::fs::write(target, contents).map_err(|e| {
PdError::new(
pipdock_core::errors::Code::SysDiskFull,
format!("write {}: {e}", target.display()),
)
})?;
std::fs::write(target, contents)
.map_err(|e| pipdock_core::exec::user_file_error(target, &e))?;
}
Ok(vec![md.display().to_string(), json.display().to_string()])
}
@@ -1422,13 +1422,11 @@ pub async fn pip_upgrade(state: tauri::State<'_, AppState>, env: PyEnv) -> Wire<
// `claim` rather than `claim_update`: there is nothing parked to expect. It discards a parked
// session, which is reachable only if a preview is open — and the plan panel replaces the whole
// content area while one is, so the Environments row is not clickable.
state.sessions.claim().await?;
let (claim, _) = state.sessions.claim()?;
let result = PipEngine.upgrade_pip(&env).await;
// Released on **both** paths. A claim that is never released leaves every later command
// answering PD-RES-003 for a plan that never existed — S5 bug 1, and the reason this is not an
// early `?`.
state.release().await;
// Released on both paths by the claim's drop — S5 bug 1 cannot be written any more.
drop(claim);
Ok(result?)
}
+194 -167
View File
@@ -133,7 +133,9 @@ impl<T> PlanSlot<T> {
///
/// Generic over the parked value so the protocol below can be tested without an `UpdateFlow`.
pub struct Sessions<T> {
slot: tokio::sync::Mutex<PlanSlot<T>>,
/// A `std` mutex, not tokio's: it is only ever held to read or replace the slot, never across
/// an await, and [`Claim`]'s `Drop` has to be able to take it — a drop cannot await.
slot: std::sync::Mutex<PlanSlot<T>>,
/// The token for whatever engine work is in flight.
///
/// Deliberately **not** inside [`PlanSlot`]: `plan_cancel` must be able to trip it while the
@@ -145,49 +147,105 @@ pub struct Sessions<T> {
impl<T> Default for Sessions<T> {
fn default() -> Self {
Self {
slot: tokio::sync::Mutex::new(PlanSlot::Idle),
slot: std::sync::Mutex::new(PlanSlot::Idle),
cancel: std::sync::Mutex::new(None),
}
}
}
/// A claimed slot. **Dropping it releases the slot** — on every path out of a command, the `?`s
/// included — unless it was [`Self::park`]ed first.
///
/// Release used to be a call each exit path had to remember, and three did not: `plan_resolve`,
/// `uninstall_guard` and the rollback preview all claimed and then had a `?` before their first
/// release, so a settings read that failed left the slot `Busy` and every later plan answered
/// `PD-RES-003` until the app was restarted (U4). A guard makes forgetting unrepresentable.
#[must_use = "dropping a claim releases the slot at once"]
pub struct Claim<'a, T> {
sessions: &'a Sessions<T>,
settled: bool,
}
impl<T> Claim<'_, T> {
/// Put a session back for the next call to pick up. Consumes the claim.
pub fn park(mut self, session: T) {
self.sessions.put(PlanSlot::Ready(session));
self.settled = true;
}
}
impl<T> Drop for Claim<'_, T> {
fn drop(&mut self) {
if !self.settled {
self.sessions.put(PlanSlot::Idle);
self.sessions.set_cancel(None);
}
}
}
impl<T> Sessions<T> {
/// Claim the slot for work that is about to *start*, returning whatever was parked.
fn lock(&self) -> std::sync::MutexGuard<'_, PlanSlot<T>> {
self.slot
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn put(&self, next: PlanSlot<T>) {
*self.lock() = next;
}
/// Claim the slot for work that is about to *start*, with whatever was parked.
///
/// `Ok(None)` means the slot was idle and is now claimed — which is what `plan_resolve` wants,
/// because it is beginning a plan and must exclude a second one for the whole of the resolve.
/// A caller that needs an *existing* session wants [`Self::claim_one`] instead.
/// The empty case is a successful claim — `plan_resolve` is beginning a plan and must exclude
/// a second one for the whole of the resolve. A caller that needs an *existing* session wants
/// [`Self::claim_one`] instead.
///
/// # Errors
/// `PD-RES-003` when a plan is already in flight.
pub async fn claim(&self) -> Result<Option<T>> {
let mut slot = self.slot.lock().await;
pub fn claim(&self) -> Result<(Claim<'_, T>, Option<T>)> {
let mut slot = self.lock();
if slot.is_busy() {
return Err(in_flight());
}
Ok(match std::mem::replace(&mut *slot, PlanSlot::Busy) {
let parked = match std::mem::replace(&mut *slot, PlanSlot::Busy) {
PlanSlot::Ready(session) => Some(session),
PlanSlot::Idle | PlanSlot::Busy => None,
})
};
drop(slot);
Ok((
Claim {
sessions: self,
settled: false,
},
parked,
))
}
/// Claim the session a caller expects to already be parked.
///
/// The difference from [`Self::claim`] is the empty case, and it is the whole reason this
/// method exists. `plan_decide` and `plan_execute` used to call `claim()` and turn its `None`
/// into `PD-INT-001` at the call site — but `claim()` had already written `Busy`, and nothing
/// on that path released it. One out-of-order call from the UI therefore wedged the slot for
/// the rest of the process: every later command answered `PD-RES-003`, for a plan that did not
/// exist. Finding nothing is not claiming anything, so this leaves the slot idle.
/// method exists: finding nothing is not claiming anything, so the slot is left idle. The old
/// code wrote `Busy` before discovering there was nothing to take, and one out-of-order call
/// from the UI wedged the slot for the rest of the process.
///
/// # Errors
/// `PD-RES-003` when a plan is already in flight; `PD-INT-001` when there is nothing parked.
pub async fn claim_one(&self) -> Result<T> {
let mut slot = self.slot.lock().await;
pub fn claim_one(&self) -> Result<(Claim<'_, T>, T)> {
let mut slot = self.lock();
if slot.is_busy() {
return Err(in_flight());
}
match std::mem::replace(&mut *slot, PlanSlot::Busy) {
PlanSlot::Ready(session) => Ok(session),
PlanSlot::Ready(session) => {
drop(slot);
Ok((
Claim {
sessions: self,
settled: false,
},
session,
))
}
PlanSlot::Idle | PlanSlot::Busy => {
*slot = PlanSlot::Idle;
drop(slot);
@@ -197,21 +255,6 @@ impl<T> Sessions<T> {
}
}
/// Put a session back for the next call to pick up.
pub async fn park(&self, session: T) {
*self.slot.lock().await = PlanSlot::Ready(session);
}
/// Release the slot with no session — the plan finished, or failed.
///
/// Called on **every** exit path out of a claimed slot. A claim that is never released leaves
/// the session permanently refusing plans with `PD-RES-003`, which is the failure mode this
/// design has to be careful about.
pub async fn release(&self) {
*self.slot.lock().await = PlanSlot::Idle;
self.set_cancel(None);
}
/// Record the token for the work about to start.
pub fn set_cancel(&self, token: Option<CancellationToken>) {
if let Ok(mut guard) = self.cancel.lock() {
@@ -238,12 +281,12 @@ impl<T> Sessions<T> {
/// Stop whatever the session is doing, whichever half of it that is.
///
/// Two states both count as "there was something to stop", and only one of them is a running
/// process. Engine work in flight is cancelled through the token. A session merely *parked* —
/// a preview on screen, a guard the user is reading — has no process to kill and is discarded
/// instead, because leaving it there means the next plan is refused by a flow nobody is
/// looking at any more.
pub async fn stop(&self) -> bool {
let mut slot = self.slot.lock().await;
/// process. Engine work in flight is cancelled through the token, and the command running it
/// releases the slot when its claim drops. A session merely *parked* — a preview on screen, a
/// guard the user is reading — has no process to kill and is discarded instead, because
/// leaving it there means the next plan is refused by a flow nobody is looking at any more.
pub fn stop(&self) -> bool {
let mut slot = self.lock();
if slot.is_busy() {
drop(slot);
return self.cancel_current();
@@ -254,18 +297,27 @@ impl<T> Sessions<T> {
self.set_cancel(None);
was_parked
}
/// Put a session in the slot without having claimed it. For tests of what comes after.
#[cfg(test)]
pub fn park_for_test(&self, session: T) {
self.put(PlanSlot::Ready(session));
}
}
/// A claimed slot holding the mutation session.
pub type SessionClaim<'a> = Claim<'a, Session>;
impl Sessions<Session> {
/// Claim a parked [`Session::Update`].
///
/// # Errors
/// `PD-RES-003` when a plan is in flight, `PD-INT-001` when nothing is parked or the parked
/// session is a different flow.
pub async fn claim_update(&self) -> Result<Box<UpdateFlow>> {
match self.claim_one().await? {
Session::Update(flow) => Ok(flow),
other => Err(self.wrong_kind(SessionKind::Update, other).await),
pub fn claim_update(&self) -> Result<(SessionClaim<'_>, Box<UpdateFlow>)> {
match self.claim_one()? {
(claim, Session::Update(flow)) => Ok((claim, flow)),
(claim, other) => Err(wrong_kind(claim, SessionKind::Update, other)),
}
}
@@ -273,10 +325,10 @@ impl Sessions<Session> {
///
/// # Errors
/// As [`Self::claim_update`].
pub async fn claim_uninstall(&self) -> Result<Box<UninstallFlow>> {
match self.claim_one().await? {
Session::Uninstall(flow) => Ok(flow),
other => Err(self.wrong_kind(SessionKind::Uninstall, other).await),
pub fn claim_uninstall(&self) -> Result<(SessionClaim<'_>, Box<UninstallFlow>)> {
match self.claim_one()? {
(claim, Session::Uninstall(flow)) => Ok((claim, flow)),
(claim, other) => Err(wrong_kind(claim, SessionKind::Uninstall, other)),
}
}
@@ -284,30 +336,30 @@ impl Sessions<Session> {
///
/// # Errors
/// As [`Self::claim_update`].
pub async fn claim_rollback(&self) -> Result<Box<RollbackFlow>> {
match self.claim_one().await? {
Session::Rollback(flow) => Ok(flow),
other => Err(self.wrong_kind(SessionKind::Rollback, other).await),
pub fn claim_rollback(&self) -> Result<(SessionClaim<'_>, Box<RollbackFlow>)> {
match self.claim_one()? {
(claim, Session::Rollback(flow)) => Ok((claim, flow)),
(claim, other) => Err(wrong_kind(claim, SessionKind::Rollback, other)),
}
}
}
/// Put back a session the caller could not use, and say what was wrong.
///
/// Parking rather than dropping: the session is intact and its owner may still come back for
/// it. A command asking for the wrong kind is a bug in the frontend's sequencing, and losing
/// the user's preview to it would turn a mis-ordered call into lost work.
async fn wrong_kind(&self, want: SessionKind, found: Session) -> PdError {
let found_kind = found.kind();
self.park(found).await;
PdError::new(
Code::IntUnexpected,
format!(
"expected {} session, found {}",
want.as_str(),
found_kind.as_str()
),
)
}
/// Put back a session the caller could not use, and say what was wrong.
///
/// Parking rather than dropping: the session is intact and its owner may still come back for it.
/// A command asking for the wrong kind is a bug in the frontend's sequencing, and losing the
/// user's preview to it would turn a mis-ordered call into lost work.
fn wrong_kind(claim: SessionClaim<'_>, want: SessionKind, found: Session) -> PdError {
let found_kind = found.kind();
claim.park(found);
PdError::new(
Code::IntUnexpected,
format!(
"expected {} session, found {}",
want.as_str(),
found_kind.as_str()
),
)
}
/// A second plan was asked for while one is running.
@@ -518,46 +570,10 @@ impl AppState {
}
}
/// See [`Sessions::claim`].
///
/// # Errors
/// `PD-RES-003` when a plan is already in flight.
pub async fn claim(&self) -> Result<Option<Session>> {
self.sessions.claim().await
}
/// See [`Sessions::claim_update`].
///
/// # Errors
/// `PD-RES-003` when a plan is in flight; `PD-INT-001` when nothing of that kind is parked.
pub async fn claim_update(&self) -> Result<Box<UpdateFlow>> {
self.sessions.claim_update().await
}
/// See [`Sessions::park`].
pub async fn park(&self, session: Session) {
self.sessions.park(session).await;
}
/// See [`Sessions::release`].
pub async fn release(&self) {
self.sessions.release().await;
}
/// See [`Sessions::set_cancel`].
pub fn set_cancel(&self, token: Option<CancellationToken>) {
self.sessions.set_cancel(token);
}
/// See [`Sessions::cancel_current`].
pub fn cancel_current(&self) -> bool {
self.sessions.cancel_current()
}
/// See [`Sessions::stop`].
pub async fn stop(&self) -> bool {
self.sessions.stop().await
}
}
#[cfg(test)]
@@ -570,72 +586,92 @@ mod tests {
Sessions::default()
}
#[tokio::test]
async fn claiming_an_empty_slot_leaves_it_claimed_for_the_caller() {
#[test]
fn claiming_an_empty_slot_leaves_it_claimed_for_the_caller() {
let s = sessions();
assert!(s.claim().await.expect("idle slot is claimable").is_none());
let (claim, parked) = s.claim().expect("idle slot is claimable");
assert!(parked.is_none());
// `plan_resolve` is about to start work, so the slot must exclude a second resolve for the
// whole of it — the empty case is a successful claim, not a miss.
let second = s.claim().await;
assert_eq!(
second.err().map(|e| e.code),
s.claim().err().map(|e| e.code),
Some(Code::ResPlanInFlight),
"a second plan must be refused while the first holds the slot"
);
drop(claim);
assert!(s.claim().is_ok(), "a dropped claim is a released slot");
}
#[tokio::test]
async fn claiming_a_session_that_is_not_there_does_not_wedge_the_slot() {
let s = sessions();
let missed = s.claim_one().await;
assert_eq!(missed.err().map(|e| e.code), Some(Code::IntUnexpected));
// The regression this whole method exists for: the old code wrote `Busy` before
// discovering there was nothing to take, so every later command answered `PD-RES-003`
// for a plan that had never existed.
s.park(7).await;
assert_eq!(s.claim_one().await.ok(), Some(7));
}
#[tokio::test]
async fn a_failed_claim_clears_the_token_it_did_not_set() {
#[test]
fn a_claim_abandoned_by_an_early_return_releases_the_slot() {
// U4. Three commands claimed and then had a `?` before their first release; a failed
// settings read left the slot Busy and every later plan answered PD-RES-003.
fn command(s: &Sessions<u32>) -> Result<()> {
let (_claim, _) = s.claim()?;
Err(PdError::new(Code::IntUnexpected, "store read failed"))?;
Ok(())
}
let s = sessions();
let token = CancellationToken::new();
s.set_cancel(Some(token.clone()));
assert!(command(&s).is_err());
assert!(s.claim().is_ok(), "the next plan is not refused");
assert!(!s.cancel_current(), "and the token went with the claim");
}
let _ = s.claim_one().await;
#[test]
fn claiming_a_session_that_is_not_there_does_not_wedge_the_slot() {
let s = sessions();
assert_eq!(
s.claim_one().err().map(|e| e.code),
Some(Code::IntUnexpected)
);
// The regression this whole method exists for: the old code wrote `Busy` before
// discovering there was nothing to take.
s.park_for_test(7);
assert_eq!(s.claim_one().ok().map(|(_, v)| v), Some(7));
}
#[test]
fn a_failed_claim_clears_the_token_it_did_not_set() {
let s = sessions();
let token = CancellationToken::new();
s.set_cancel(Some(token.clone()));
let _ = s.claim_one();
// Releasing means releasing: a stale token left behind would let the *next* plan's
// `plan_cancel` report that it stopped something.
assert!(!s.cancel_current(), "the stale token must be gone");
assert!(!token.is_cancelled());
}
#[tokio::test]
async fn a_parked_session_survives_until_someone_claims_it() {
#[test]
fn a_parked_session_survives_until_someone_claims_it() {
let s = sessions();
s.park(1).await;
s.park(2).await;
assert_eq!(s.claim_one().await.ok(), Some(2), "parking replaces");
s.park(3).await;
s.release().await;
let (claim, _) = s.claim().expect("claim");
claim.park(2);
let (claim, value) = s.claim_one().expect("parked");
assert_eq!(value, 2);
claim.park(3);
let (claim, value) = s.claim_one().expect("parked again");
assert_eq!(value, 3);
drop(claim);
assert_eq!(
s.claim_one().await.err().map(|e| e.code),
s.claim_one().err().map(|e| e.code),
Some(Code::IntUnexpected),
"release discards whatever was parked"
"a claim dropped without parking discards the session"
);
}
#[tokio::test]
async fn asking_for_the_wrong_kind_gives_it_back() {
#[test]
fn asking_for_the_wrong_kind_gives_it_back() {
let s: Sessions<Session> = Sessions::default();
s.park(Session::Fake(SessionKind::Uninstall)).await;
s.park_for_test(Session::Fake(SessionKind::Uninstall));
let wrong = s.claim_update().await;
let err = wrong.err().expect("an uninstall is not an update");
let err = s
.claim_update()
.err()
.expect("an uninstall is not an update");
assert_eq!(err.code, Code::IntUnexpected);
assert!(
err.message
@@ -643,10 +679,9 @@ mod tests {
"the message must name both kinds, not just say 'no plan': {}",
err.message
);
// Parked, not dropped: a command asking out of order is a frontend sequencing bug, and
// losing the user's guard dialog to it would turn a mis-ordered call into lost work.
let still_there = s.claim().await.expect("slot is free");
// Parked, not dropped: losing the user's guard dialog to a mis-ordered call would turn a
// frontend sequencing bug into lost work.
let (_, still_there) = s.claim().expect("slot is free");
assert_eq!(
still_there.map(|x| x.kind()),
Some(SessionKind::Uninstall),
@@ -654,38 +689,30 @@ mod tests {
);
}
#[tokio::test]
async fn stop_discards_a_parked_session_and_cancels_a_running_one() {
#[test]
fn stop_discards_a_parked_session_and_cancels_a_running_one() {
let s: Sessions<Session> = Sessions::default();
assert!(!s.stop().await, "nothing to stop");
assert!(!s.stop(), "nothing to stop");
// Parked: no process exists, so stopping means letting go. Leaving it would refuse the
// next plan on behalf of a preview nobody is looking at.
s.park(Session::Fake(SessionKind::Update)).await;
assert!(s.stop().await);
assert!(s.claim().await.expect("free").is_none());
// Busy: there is a child process, and the token is the only thing that reaches it.
let token = CancellationToken::new();
s.park(Session::Fake(SessionKind::Update)).await;
let _running = s.claim_one().await.expect("parked");
s.set_cancel(Some(token.clone()));
assert!(s.stop().await);
assert!(token.is_cancelled());
// Parked: no process exists, so stopping means letting go.
s.park_for_test(Session::Fake(SessionKind::Update));
assert!(s.stop());
assert!(s.claim().expect("free").1.is_none());
}
#[tokio::test]
async fn cancel_reaches_a_session_the_slot_no_longer_owns() {
#[test]
fn cancel_reaches_a_session_the_slot_no_longer_owns() {
let s = sessions();
let token = CancellationToken::new();
s.park(1).await;
let _claimed = s.claim_one().await.expect("parked");
s.park_for_test(1);
let (claim, _) = s.claim_one().expect("parked");
s.set_cancel(Some(token.clone()));
// The slot is `Busy` and the session is owned by the caller — which is exactly when
// `plan_cancel` has to work, and why the token is not stored inside the slot.
assert!(s.cancel_current());
assert!(s.stop());
assert!(token.is_cancelled());
drop(claim);
assert!(s.claim().is_ok(), "the owner's drop is what frees it");
}
}