Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions Native/pcai_core/pcai_media/src/ffi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
//! - The Tokio runtime is created lazily via `OnceLock` and reused
//! - Errors are stored in thread-local storage
//!
//! [Worker acquisition controls](../../../../../Tests/Portable/media-worker-lock/README.md)
//! exercise poisoned-lock refusal without a model or device.
//!
//! ## Usage from PowerShell
//!
//! ```powershell
Expand Down Expand Up @@ -791,11 +794,11 @@ pub extern "C" fn pcai_media_generate_image_async(
let state = get_state();
let guard = match state.lock() {
Ok(g) => g,
Err(e) => {
if let Ok(mut g2) = get_state().lock() {
g2.requests
.insert(id, MediaRequestStatus::Failed(format!("Lock failed: {e}")));
}
Err(error) => {
let message = format!("Lock failed: {error}");
// PoisonError owns this guard; locking the same mutex again deadlocks.
let mut guard = error.into_inner();
guard.requests.insert(id, MediaRequestStatus::Failed(message));
return;
}
};
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,9 @@ pwsh -NoProfile -Command "Invoke-Pester -Path .\Tests\Boot\PersistentVHDX.Tests.
The exact test count changes as native and workstation tooling grows. Prefer
current command output and report artifacts over static README counts.

The [media worker acquisition controls](Tests/Portable/media-worker-lock/README.md)
exercise the actual FFI lock/error block with bounded, model-free Rust children.

## Project Structure

```
Expand Down
120 changes: 120 additions & 0 deletions Tests/Portable/media-worker-lock-review.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
{
"schema_version": 1,
"hash_normalization": "UTF-8 bytes with CRLF converted to LF",
"reviews": [
{
"selector": "MediaWorkerLockTests.test_healthy_running_acquisition_preserves_existing_states",
"test_path": "Tests/Portable/test_media_worker_lock.py",
"test_sha256": "559111fd4fd0b17f6b5d6ec9c7c785473bd1bd027a39bb14ad54f70b496e4a29",
"selector_sha256": "37d5c3f996db44dae61edbb753716d49adfdb3fc167e7dfdb156defec47b9f68",
"source_path": "Native/pcai_core/pcai_media/src/ffi/mod.rs",
"source_sha256": "ccd590784e41f1bf2f812f8baf35ed24f59fb8b25a02c49fc5684edc36e6ba88",
"base_commit": "816038d4eeafcdeefb42bca37a8834fec3ce7491",
"disposition": "keep",
"reviewer": "codex-p1-obsbot-fork-prep",
"reviewer_type": "independent-codex",
"reviewed_utc": "2026-11-03T02:31:25.111768+00:00",
"scope": "Source-bound acquisition subpath with minimal state; no complete FFI, public polling recovery, model, GPU, installation or hardware qualification.",
"receipt": "media-worker-lock/README.md",
"fixture_peers": [
{
"path": "Tests/Portable/media-worker-lock/Cargo.toml",
"sha256": "66d8ef65bb7df43328e92b94272b78a514091ce1aceea4f18d3084c845afff74"
},
{
"path": "Tests/Portable/media-worker-lock/Cargo.lock",
"sha256": "8902acc0a67913642d5c962ebe53349ce85c1a0af6db34ed0c7c7fa716666dca"
},
{
"path": "Tests/Portable/media-worker-lock/build.rs",
"sha256": "d08c6ab76a2b6c38ef375c150b3826615afb58c2adbe8c983203bf70e051b476"
},
{
"path": "Tests/Portable/media-worker-lock/src/main.rs",
"sha256": "a3fb728f54da54f8be57bb1fa5bc9006ea7a04ee75994e0715ad23e020f6ff42"
}
],
"review_verdict": "approve",
"review_receipt_sha256": "fd45c2f980dc95257b1f0f6edf2d84372b6271388f1f42ceb0d2a496774e3fa5",
"review_scope": "Actual source acquisition/error block and default discovery; no full model/FFI/public polling recovery, GPU or hardware acceptance",
"review_reason": "The poisoned error owns the mutex guard. Consuming it records the original internal failure and returns without relocking or clearing poison. Healthy/cancelled states and unrelated requests remain intact. The source-extracted owned-child controls detect the original deadlock and bound termination; missing boundary/compile/child failures cannot be reported as success.",
"validation": "Windows x64 native Rust 1.99.1: original source two healthy passes and one owned poisoned-child 3s timeout; repaired explicit and normal-discovery cohorts each 3 passes, no skips; independent normal discovery 3 passes. CPU-only pcai-media ffi check and strict Clippy passed with pinned compiler. Fresh seven-file Git export also built --locked/--offline and passed 3 controls."
},
{
"selector": "MediaWorkerLockTests.test_healthy_cancelled_acquisition_does_not_rewrite_cancellation",
"test_path": "Tests/Portable/test_media_worker_lock.py",
"test_sha256": "559111fd4fd0b17f6b5d6ec9c7c785473bd1bd027a39bb14ad54f70b496e4a29",
"selector_sha256": "10cf94ffa0c671f66f618513822b99f6c23b803973e572fe6ef65ea4777ca19b",
"source_path": "Native/pcai_core/pcai_media/src/ffi/mod.rs",
"source_sha256": "ccd590784e41f1bf2f812f8baf35ed24f59fb8b25a02c49fc5684edc36e6ba88",
"base_commit": "816038d4eeafcdeefb42bca37a8834fec3ce7491",
"disposition": "keep",
"reviewer": "codex-p1-obsbot-fork-prep",
"reviewer_type": "independent-codex",
"reviewed_utc": "2026-11-03T02:31:25.111768+00:00",
"scope": "Source-bound acquisition subpath with minimal state; no complete FFI, public polling recovery, model, GPU, installation or hardware qualification.",
"receipt": "media-worker-lock/README.md",
"fixture_peers": [
{
"path": "Tests/Portable/media-worker-lock/Cargo.toml",
"sha256": "66d8ef65bb7df43328e92b94272b78a514091ce1aceea4f18d3084c845afff74"
},
{
"path": "Tests/Portable/media-worker-lock/Cargo.lock",
"sha256": "8902acc0a67913642d5c962ebe53349ce85c1a0af6db34ed0c7c7fa716666dca"
},
{
"path": "Tests/Portable/media-worker-lock/build.rs",
"sha256": "d08c6ab76a2b6c38ef375c150b3826615afb58c2adbe8c983203bf70e051b476"
},
{
"path": "Tests/Portable/media-worker-lock/src/main.rs",
"sha256": "a3fb728f54da54f8be57bb1fa5bc9006ea7a04ee75994e0715ad23e020f6ff42"
}
],
"review_verdict": "approve",
"review_receipt_sha256": "fd45c2f980dc95257b1f0f6edf2d84372b6271388f1f42ceb0d2a496774e3fa5",
"review_scope": "Actual source acquisition/error block and default discovery; no full model/FFI/public polling recovery, GPU or hardware acceptance",
"review_reason": "The poisoned error owns the mutex guard. Consuming it records the original internal failure and returns without relocking or clearing poison. Healthy/cancelled states and unrelated requests remain intact. The source-extracted owned-child controls detect the original deadlock and bound termination; missing boundary/compile/child failures cannot be reported as success.",
"validation": "Windows x64 native Rust 1.99.1: original source two healthy passes and one owned poisoned-child 3s timeout; repaired explicit and normal-discovery cohorts each 3 passes, no skips; independent normal discovery 3 passes. CPU-only pcai-media ffi check and strict Clippy passed with pinned compiler. Fresh seven-file Git export also built --locked/--offline and passed 3 controls."
},
{
"selector": "MediaWorkerLockTests.test_poisoned_acquisition_records_failure_without_relocking",
"test_path": "Tests/Portable/test_media_worker_lock.py",
"test_sha256": "559111fd4fd0b17f6b5d6ec9c7c785473bd1bd027a39bb14ad54f70b496e4a29",
"selector_sha256": "364f524ca52df3b29325442555f465c7084239c793ab098fc6b7f2c43f988820",
"source_path": "Native/pcai_core/pcai_media/src/ffi/mod.rs",
"source_sha256": "ccd590784e41f1bf2f812f8baf35ed24f59fb8b25a02c49fc5684edc36e6ba88",
"base_commit": "816038d4eeafcdeefb42bca37a8834fec3ce7491",
"disposition": "keep",
"reviewer": "codex-p1-obsbot-fork-prep",
"reviewer_type": "independent-codex",
"reviewed_utc": "2026-11-03T02:31:25.111768+00:00",
"scope": "Source-bound acquisition subpath with minimal state; no complete FFI, public polling recovery, model, GPU, installation or hardware qualification.",
"receipt": "media-worker-lock/README.md",
"fixture_peers": [
{
"path": "Tests/Portable/media-worker-lock/Cargo.toml",
"sha256": "66d8ef65bb7df43328e92b94272b78a514091ce1aceea4f18d3084c845afff74"
},
{
"path": "Tests/Portable/media-worker-lock/Cargo.lock",
"sha256": "8902acc0a67913642d5c962ebe53349ce85c1a0af6db34ed0c7c7fa716666dca"
},
{
"path": "Tests/Portable/media-worker-lock/build.rs",
"sha256": "d08c6ab76a2b6c38ef375c150b3826615afb58c2adbe8c983203bf70e051b476"
},
{
"path": "Tests/Portable/media-worker-lock/src/main.rs",
"sha256": "a3fb728f54da54f8be57bb1fa5bc9006ea7a04ee75994e0715ad23e020f6ff42"
}
],
"review_verdict": "approve",
"review_receipt_sha256": "fd45c2f980dc95257b1f0f6edf2d84372b6271388f1f42ceb0d2a496774e3fa5",
"review_scope": "Actual source acquisition/error block and default discovery; no full model/FFI/public polling recovery, GPU or hardware acceptance",
"review_reason": "The poisoned error owns the mutex guard. Consuming it records the original internal failure and returns without relocking or clearing poison. Healthy/cancelled states and unrelated requests remain intact. The source-extracted owned-child controls detect the original deadlock and bound termination; missing boundary/compile/child failures cannot be reported as success.",
"validation": "Windows x64 native Rust 1.99.1: original source two healthy passes and one owned poisoned-child 3s timeout; repaired explicit and normal-discovery cohorts each 3 passes, no skips; independent normal discovery 3 passes. CPU-only pcai-media ffi check and strict Clippy passed with pinned compiler. Fresh seven-file Git export also built --locked/--offline and passed 3 controls."
}
]
}
2 changes: 2 additions & 0 deletions Tests/Portable/media-worker-lock/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Retain the dependency-free probe lock for the --locked controls.
!Cargo.lock
7 changes: 7 additions & 0 deletions Tests/Portable/media-worker-lock/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions Tests/Portable/media-worker-lock/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "pcai-media-worker-lock-probe"
version = "0.1.0"
edition = "2021"
rust-version = "1.95"
build = "build.rs"
publish = false

[workspace]

[[bin]]
name = "pcai-media-worker-lock-probe"
path = "src/main.rs"

[lints.clippy]
pedantic = "warn"
perf = "warn"
suspicious = "warn"
52 changes: 52 additions & 0 deletions Tests/Portable/media-worker-lock/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Media worker acquisition controls

From the [repository root](../../../README.md), using PowerShell:

```powershell
# Install Rust tooling prerequisites.
rustup component add rustfmt clippy
# Build the source-bound, std-only probe with two jobs.
$env:PCAI_MEDIA_FFI_SOURCE=(Resolve-Path Native/pcai_core/pcai_media/src/ffi/mod.rs); cargo build --manifest-path Tests/Portable/media-worker-lock/Cargo.toml --locked --offline --jobs 2 --target-dir .temp/media-worker-lock/build
# Test through the same discovery entrypoint as Linux CI's Python admission job.
uv run --no-project python -m unittest discover -s Tests/Portable -p test_media_worker_lock.py -v
# Run an explicit source and retain its executable/source receipt.
uv run --no-project python Tests/Portable/test_media_worker_lock.py --source Native/pcai_core/pcai_media/src/ffi/mod.rs --target-dir .temp/media-worker-lock/run --receipt .temp/media-worker-lock/receipt.json -v
```

Windows checks start with CargoTools `Test-BuildEnvironment -Detailed`; see
[machine tooling](../../../CLAUDE.md#git-hooks-lefthook). Select native Cargo
explicitly with `--cargo <absolute-cargo.exe>` when wrappers are present.
The fixture needs Rust 1.95 or newer and a native linker. It loads no model,
media DLL, GPU, camera or network service. It reports missing prerequisites as
failures. The existing [Python admission job](../../../.github/workflows/linux-ci.yml)
discovers these tests without another workflow or test framework.

## Contract

The asynchronous producer in
[the FFI module](../../../Native/pcai_core/pcai_media/src/ffi/mod.rs)
must return when model-state acquisition yields a poisoned mutex. `PoisonError`
already holds its guard; trying to lock that mutex again deadlocks. The repair
consumes the held guard, records the original internal failure and returns.
It preserves poison and changes no C ABI.

[The build script](build.rs) extracts the actual acquisition block between
maintained producer boundaries and compiles it unchanged with minimal state
types in [the probe](src/main.rs). Boundary drift fails the build. This exercises
the acquisition/error subpath, rather than the full media crate or pipeline.
The [Python supervisor](../test_media_worker_lock.py) starts one owned child per
scenario, bounds it to three seconds, and kills/reaps that exact child on timeout.
No process-name or external-PID termination is used. Each build receipt records
source, fixture and executable hashes. Distinct source inputs require separate
target directories; automatic discovery creates a private temporary target.

The healthy running/cancelled controls preserve both request states and their
count. The poisoned control checks the entry/return markers, original failure
text, unrelated cancellation and retained poison. The pre-repair source passes
the two healthy controls and times out in the poisoned control. The repaired
source passes all three. See the [hash-bound review register](../media-worker-lock-review.json)
for the exact source and selector disposition.

The mutex remains poisoned. Existing public polling can still return `-1`.
These controls do not establish public failure delivery, state recovery, full
FFI/model execution, installed binaries or hardware acceptance.
27 changes: 27 additions & 0 deletions Tests/Portable/media-worker-lock/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use std::env;
use std::fs;
use std::path::PathBuf;

fn main() {
println!("cargo:rerun-if-env-changed=PCAI_MEDIA_FFI_SOURCE");
let source = PathBuf::from(env::var_os("PCAI_MEDIA_FFI_SOURCE").expect("set an explicit media FFI source path"));
println!("cargo:rerun-if-changed={}", source.display());
let text = fs::read_to_string(&source).expect("read selected media FFI source");
let entry = "pub extern \"C\" fn pcai_media_generate_image_async(";
assert_eq!(text.matches(entry).count(), 1, "one actual async producer");
let body = text.split_once(entry).expect("async producer").1;
let begin = "// Run the synchronous generation under the lock.";
assert_eq!(body.matches(begin).count(), 1, "one model acquisition boundary");
let acquisition = body.split_once(begin).expect("acquisition boundary").1;
let acquisition = acquisition.split_once("let result = {").expect("actual result block").1;
let end = "// Check for cancellation before expensive work.";
assert_eq!(acquisition.matches(end).count(), 1, "one cancellation boundary");
let acquisition = acquisition.split_once(end).expect("cancellation boundary").0;
assert!(acquisition.contains("let state = get_state();"));
assert!(acquisition.contains("let guard = match state.lock()"));
// The body is copied verbatim between maintained producer boundaries. Only
// its enclosing unit-returning fixture function and final guard drop are new.
let generated = format!("fn run_actual_worker_acquisition(id: i64) {{\n{acquisition}\n drop(guard);\n}}\n");
let target = PathBuf::from(env::var_os("OUT_DIR").expect("Cargo output directory"));
fs::write(target.join("worker_acquisition.rs"), generated).expect("write source-bound probe");
}
76 changes: 76 additions & 0 deletions Tests/Portable/media-worker-lock/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};

#[derive(Debug, PartialEq, Eq)]
enum MediaRequestStatus {
Running,
Failed(String),
Cancelled,
}

#[derive(Debug)]
struct MediaState {
requests: HashMap<i64, MediaRequestStatus>,
}

static STATE: OnceLock<Mutex<MediaState>> = OnceLock::new();

fn get_state() -> &'static Mutex<MediaState> {
STATE.get_or_init(|| {
Mutex::new(MediaState {
requests: HashMap::from([(7, MediaRequestStatus::Running), (8, MediaRequestStatus::Cancelled)]),
})
})
}

include!(concat!(env!("OUT_DIR"), "/worker_acquisition.rs"));

fn healthy(id: i64) {
let state = get_state();
run_actual_worker_acquisition(id);
assert!(!state.is_poisoned(), "healthy acquisition must not poison state");
let guard = state.lock().expect("healthy fixture state"); // ast-grep-ignore: mandate-rust-panic // SAFETY: Owned std-only child assertion; healthy setup must be unpoisoned.
assert_eq!(guard.requests.get(&7), Some(&MediaRequestStatus::Running));
assert_eq!(guard.requests.get(&8), Some(&MediaRequestStatus::Cancelled));
assert_eq!(guard.requests.len(), 2);
println!("PCAI_HEALTHY_ACQUISITION_COMPLETE id={id}");
}

fn poisoned() {
let state = get_state();
let result = std::panic::catch_unwind(|| {
let _guard = state.lock().expect("fixture begins unpoisoned"); // ast-grep-ignore: mandate-rust-panic // SAFETY: Owned std-only child setup; the guard is dropped by the deliberate caught panic.
panic!("owned model-state poisoning control"); // ast-grep-ignore: mandate-rust-panic // SAFETY: Test-only panic is caught to poison this child's mutex; parent bounds execution to 3s and reaps it.
});
assert!(result.is_err(), "fixture must actually poison its own mutex");
let expected = {
let error = state.lock().expect_err("fixture state must retain poison");
let message = format!("Lock failed: {error}");
drop(error);
message
};
eprintln!("PCAI_OWNED_POISON_ACQUISITION_ENTER");
run_actual_worker_acquisition(7);
eprintln!("PCAI_OWNED_POISON_ACQUISITION_RETURNED");
assert!(state.is_poisoned(), "failure must not silently resume poisoned state");
let guard = state
.lock()
.expect_err("repair must preserve poisoned-state refusal")
.into_inner();
assert_eq!(guard.requests.get(&7), Some(&MediaRequestStatus::Failed(expected)));
assert_eq!(guard.requests.get(&8), Some(&MediaRequestStatus::Cancelled));
assert_eq!(guard.requests.len(), 2);
println!("PCAI_OWNED_POISON_FAILURE_RECORDED");
}

fn main() {
match std::env::args().nth(1).as_deref() {
Some("healthy-running") => healthy(7),
Some("healthy-cancelled") => healthy(8),
Some("poisoned-running") => poisoned(),
_ => {
eprintln!("expected one owned fixture scenario");
std::process::exit(2);
}
}
}
Loading
⌂ Proxy