From 208fb6c811e84d6d909ef5e3d173e663f464fb3b Mon Sep 17 00:00:00 2001 From: "Mark.lin" Date: Mon, 30 Nov 2026 16:46:15 +0800 Subject: [PATCH] Add a frame-hold verification skill and TLA+ model shared by Claude Code and Codex - Add GVFG_SDK/sdk/gvfg/formal: a TLA+ model of one channel's frame-hold protocol (read, release, stop, start and signal-change recovery) and six TLC configs: the shipped code with the reader joined before stop/start and with it running across them, and four mutations that must fail. - Add .agents/skills/verify-gvfg-frame-hold: check.ps1 runs every config against its expected result, prints counterexamples with -Trace, and reports when the covered code moves past the sync commit; f1-hardware-repro.ps1 stages a stop and start during a read on a real card. - Add a Claude Code entry in .claude/skills that points to the shared copy, and notes on which steps must run outside the Codex Windows sandbox. Validation: git diff --cached --check passed. check.ps1 met all six expectations and reported the model in step with 1d89392. f1-hardware-repro.ps1 reproduced the stuck channel against b47f27b and passed against 1d89392 on a GIGABYTE SDI VFG100. TLC needs Java 17+ and tla2tools 1.7.4; check.ps1 -Install fetches the jar into the git-ignored formal/tools. Not yet run from Codex. Co-Authored-By: Claude Opus 5.5 --- .../skills/verify-gvfg-frame-hold/SKILL.md | 172 +++++++++ .../verify-gvfg-frame-hold/scripts/check.ps1 | 142 +++++++ .../scripts/f1-hardware-repro.ps1 | 37 ++ .../scripts/f1_hardware_repro.cpp | 193 ++++++++++ .../skills/verify-gvfg-frame-hold/SKILL.md | 10 + GVFG_SDK/sdk/gvfg/formal/.gitignore | 4 + GVFG_SDK/sdk/gvfg/formal/CaptureFrameHold.tla | 347 ++++++++++++++++++ .../sdk/gvfg/formal/MC_ConcurrentReader.cfg | 13 + GVFG_SDK/sdk/gvfg/formal/MC_Contract.cfg | 13 + .../gvfg/formal/MC_Mut_NoRecoveryCheck.cfg | 13 + .../sdk/gvfg/formal/MC_Mut_NoRestartWait.cfg | 13 + .../gvfg/formal/MC_Mut_NoRunGeneration.cfg | 13 + .../gvfg/formal/MC_Mut_NoRunningRecheck.cfg | 13 + 13 files changed, 983 insertions(+) create mode 100644 .agents/skills/verify-gvfg-frame-hold/SKILL.md create mode 100644 .agents/skills/verify-gvfg-frame-hold/scripts/check.ps1 create mode 100644 .agents/skills/verify-gvfg-frame-hold/scripts/f1-hardware-repro.ps1 create mode 100644 .agents/skills/verify-gvfg-frame-hold/scripts/f1_hardware_repro.cpp create mode 100644 .claude/skills/verify-gvfg-frame-hold/SKILL.md create mode 100644 GVFG_SDK/sdk/gvfg/formal/.gitignore create mode 100644 GVFG_SDK/sdk/gvfg/formal/CaptureFrameHold.tla create mode 100644 GVFG_SDK/sdk/gvfg/formal/MC_ConcurrentReader.cfg create mode 100644 GVFG_SDK/sdk/gvfg/formal/MC_Contract.cfg create mode 100644 GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRecoveryCheck.cfg create mode 100644 GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRestartWait.cfg create mode 100644 GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRunGeneration.cfg create mode 100644 GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRunningRecheck.cfg diff --git a/.agents/skills/verify-gvfg-frame-hold/SKILL.md b/.agents/skills/verify-gvfg-frame-hold/SKILL.md new file mode 100644 index 0000000..b2263cc --- /dev/null +++ b/.agents/skills/verify-gvfg-frame-hold/SKILL.md @@ -0,0 +1,172 @@ +--- +name: verify-gvfg-frame-hold +description: "Model-check the GVFG capture frame-hold protocol (gvfg_read_channel_frame / gvfg_release_channel_frame against stop, start and signal-change recovery) with TLA+/TLC, and reproduce the stop->start race on real hardware. Use it before and after any change to gvfg_capture.cpp's channel read/release/stop/start, or to GigabyteCaptureSession's wait_frame, release_frame, start_stream, stop_stream, handle_signal_event or restart_stream_after_signal_change." +--- + +# Verify the GVFG frame-hold protocol + +## What is verified + +**Property.** While an application holds a frame whose data is the backend capture buffer: +(1) `HeldFrameIsCurrent`: the buffer still belongs to the driver stream that is running now, so no recovery +restart and no stop/start has replaced it; (2) `ReleaseWillSucceed`: the application's single mandated +`gvfg_release_channel_frame()` will succeed. + +**Harm if broken.** In zero-copy mode, the application reads a buffer that the driver is refilling, which gives +torn or foreign video. In every mode, the release returns `GVFG_ESTATE` and the channel stays "frame held", so +every later read fails with "previous frame has not been released" until the app stops the channel. + +**Model.** The model is `GVFG_SDK/sdk/gvfg/formal/CaptureFrameHold.tla`. It has three threads: the app's video +reader (read, OSD branch, deliver, release), the app's lifecycle thread (stop and start, serialized as the +customer docs require), and the session event thread (format change or plug-in, followed by the recovery +restart). Each action is one mutex-protected section, or one atomic access, in the code, and its comment names +the function. A ghost `epoch` counts `GvfgStartCapture` calls, so "same buffer" means "same epoch". + +**Tool.** TLA+ with TLC 1.7.4 (pinned and SHA256-checked). The question is whether events can happen in a bad +order across threads, and an exhaustive model checker over the protocol answers that. The C++ cannot be model +checked directly, because it sits on Win32 events and the vendor GvfgSdk. A small hardware program +(`scripts/f1_hardware_repro.cpp`) stages the one interleaving that matters most on a real card. + +## Scope and bounds + +- One channel. The configs use at most 4 stop/start calls, 2 signal events and 4 read attempts. At those bounds + `MC_Contract` covers 45,655 distinct states and `MC_ConcurrentReader` 237,899. A one-off run at 6/3/6 also + passed, with 361,278 and 2,822,739 states. +- Out of scope: audio frames, unplug events (they bump the generation but never restart), the vendor driver + itself (`GvfgGetVideoFrame*`, `GvfgStart/StopCapture` are taken as atomic and correct), the OSD processor's + internals (only its keep-hold versus early-release branch is modelled), multi-channel handles, + open/close/destroy, and timeouts (a timed-out wait is the same as a failed wait here). +- A Pass covers this model under these bounds, not the whole SDK. + +## Run it + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File .agents\skills\verify-gvfg-frame-hold\scripts\check.ps1 +``` + +It needs Java 17 or later (installed on the dev PC: Eclipse Temurin 21, from +`winget install --id EclipseAdoptium.Temurin.21.JDK -e`) and tla2tools.jar 1.7.4. The script looks for the jar in +`$env:TLA2TOOLS_JAR`, then `GVFG_SDK/sdk/gvfg/formal/tools/` (git-ignored, inside the workspace so a sandboxed +agent can read it), then `%USERPROFILE%\.tools\tla`. Pass `-Install` once to download it into `formal/tools/`. +All six configs take a few seconds together. TLC runs with one worker, +so the first violation it reports is the same on every run. Logs go to +`GVFG_SDK/sdk/gvfg/formal/out/.log` (git-ignored). Use `-Only MC_Contract` to run a single config. + +| Config | What it is | Expected | +| --- | --- | --- | +| `MC_Contract.cfg` | Shipped code. The app pauses or joins its reader before every stop/start (srcroot `GvfgSource::stop` does). | Pass | +| `MC_ConcurrentReader.cfg` | Shipped code. The reader keeps running across stop then start. | Pass (F1 fixed) | +| `MC_Mut_NoRestartWait.cfg` | Mutation: recovery restart no longer waits for `frame_held_`. | Violation: HeldFrameIsCurrent | +| `MC_Mut_NoRecoveryCheck.cfg` | Mutation: capture ignores `recovery_pending_` and the generation. | Violation: HeldFrameIsCurrent | +| `MC_Mut_NoRunGeneration.cfg` | Mutation: delivery checks only `running`. This is the code before the F1 fix. | Violation: HeldFrameIsCurrent | +| `MC_Mut_NoRunningRecheck.cfg` | Mutation: delivery checks only the run generation. | Violation: ReleaseWillSucceed | + +The script exits 0 only when every config matches its expected result and the covered code is unchanged since +the sync commit. Exit 3 (`STALE`) means the model passed but nobody has confirmed it against the changed code. +That is not a pass, so follow "Keeping it in step". + +Read a violation with `check.ps1 -Trace `. It reruns that config and prints the shortest counterexample, +one row per step: the action, then the variables that step changed. Map each action to code with the table under +"Code-to-model map". In Claude Code, the pstack **statechart** skill (`/pstack:statechart`) can also draw the +trace, and on a pass it draws how the protocol moves between states. Use its current instructions, and do not +copy its commands into this skill. + +## Running it from Codex + +Codex reads this skill from `.agents/skills/` (repo scope). Its Windows sandbox (`[windows] sandbox = "elevated"`) +runs commands as a separate low-privilege user on a private desktop. + +- `check.ps1` and `check.ps1 -Trace` only need Java (under `C:\Program Files`) and the jar in `formal/tools/`, so + they should run inside the sandbox. `-Install` needs network access. +- `f1-hardware-repro.ps1` needs the capture card and the MSVC toolchain. Run it outside the sandbox: approve + the escalation when Codex asks, or use full access for that command. +- The behaviour above follows the Codex docs. It has not been tried in Codex yet, so if a step fails in the + sandbox, rerun that one command outside it before you suspect the code. + +## Hardware check for F1 + +On a PC with a GVFG card and a live signal on channel 0, with no viewer holding the card: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File .agents\skills\verify-gvfg-frame-hold\scripts\f1-hardware-repro.ps1 -GvfgBuildDir GVFG_SDK\build\ +``` + +It compiles `f1_hardware_repro.cpp` against that build's `gvfg.lib`. It attaches a frame processor through the +exported `gvfg_control_frame_processor` (the hook OSD uses), which parks one read between capture and delivery. +It then calls `gvfg_stop_channel` and `gvfg_start_channel`, and lets the read finish. Exit 0 means the read was +rejected and the next read works. Exit 1 means F1 reproduced. Exit 2 means it could not be verified here, and +exit 3 means the race could not be staged. + +## Finding F1: fixed in `1d89392` + +**Before the fix.** The trigger is `gvfg_stop_channel()` followed by `gvfg_start_channel()` while +`gvfg_read_channel_frame()` sits between getting the frame and delivering it. The delivery check looked only at +`running`, which start had set back to true. So the read handed out a frame from the stopped stream as valid. +Its release then failed with `GVFG_ESTATE` ("Capture frame release rejected: no frame is held"), because +stop/start had reset `frame_held_`. `releaseFrame` returns before clearing `frameHeld`, so every later read +failed with "previous frame has not been released". On the dev PC this reproduced on hardware with the code +before the fix (3.2.0 at `b47f27b`, built from `git archive`) and with the older 3.1.0 build. + +**The fix**, in `gvfg_capture.cpp` (`gvfg_channel_session_t`): + +- `start()` increments `runGeneration` and sets `running` in one `frameMutex` section. +- `readFrame()` records `runGeneration` when it marks the read in progress. +- Delivery rejects the frame when `running` is false or the generation moved. It releases the backend hold if + the session still has one, and returns `GVFG_ESTATE` with "capture stopped or restarted during the read". + +**Verified.** `MC_ConcurrentReader` passes. `MC_Mut_NoRunGeneration` (the old check) still fails, which shows the +check can fail. The hardware program exits 0 against the fixed build (`GVFG_SDK/build/verify-f1`) and 1 against +`b47f27b`. srcroot's capture journey passes on the fixed SDK. + +**Still open, related.** `readAudioFrame` has the same `running`-only check. A stop->start during an audio read +can deliver one PCM chunk from before the restart. There is no backend hold for audio, so the channel does not +get stuck. Audio is outside this model. + +## Telling a real bug from a modeling error + +Map each step of the trace to the code named in the action's comment. Then ask whether the code really allows +that step at that moment: are the mutexes the same, and is the check the same? If it does, the trace is a real +interleaving. Report it in the code's words, as F1 does. If it does not, the model is wrong. Fix the action so it +matches the code. Never weaken an invariant and never drop a thread to get a pass. + +## Code-to-model map (keep in step) + +| Code (gvfg_capture.cpp = C, gigabyte_capture_session.cpp = S) | Model action / guard | +| --- | --- | +| C `readFrame`: `if (!running)` before the lock | `RBegin` | +| C `readFrame`, first `frameMutex` section: held / in-progress checks, record `runGeneration` | `RBeginLock` | +| S `wait_frame`: `running_`, `frame_held_`, generation snapshot | `RWaitCheck` | +| S `wait_frame`: WaitForMultipleObjects (stop, recovery, frame) | `RWakeFail`, `RWakeFrame` | +| S `wait_frame` capture section under `capture_mutex_`: `recovery_pending_` / generation check | `RCapture`, guard `CaptureRejectsDuringRecovery` | +| C `readFrame` OSD: keep the backend hold, or `release_frame` early | `ROsdKeep`, `ROsdEarlyRelease` | +| C `readFrame` delivery under `frameMutex`: `running` recheck and `runGeneration` comparison | `RDeliver`, guards `DeliverRechecksRunning`, `DeliverChecksRunGeneration` | +| C `readFrame` `stoppedWhileWaiting` release | `RStopRelease` | +| C `releaseFrame` (calls S `release_frame` inside `frameMutex`) | `RRelease` | +| C `stop`: `running = false`, `releaseHeldFrameForStop`, then S `stop_stream` | `UStop`, `UStopFrames`, `UStopBackend`, `UStopStream`, `UStopJoin` | +| C `start`: S `start_stream`, then `++runGeneration; running = true` under `frameMutex` | `UStartSession`, `UStartChannel` | +| S `handle_signal_event` first block (generation++, `recovery_pending_`) | `ESignal` | +| S restart decision (format compare) | `EDecide` (nondeterministic) | +| S `restart_stream_after_signal_change`: wait for `!frame_held_ \|\| !running_` | `EWaitHold`, guard `RestartWaitsForRelease` | +| S restart Stop/StartCapture under `capture_mutex_` | `ERestart` (epoch + 1) | +| S `handle_signal_event` end (`recovery_pending_ = false`) | `EFinish` | + +**Coverage record.** The covered files are `GVFG_SDK/sdk/gvfg/src/gvfg_capture.cpp` (`gvfg_channel_session_t`: +`start`, `stop`, `readFrame`, `releaseFrame`, `releaseHeldFrameForStop`), and +`GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.cpp` with its `.h` (`start_stream`, `stop_stream`, +`wait_frame`, `release_frame`, `handle_signal_event`, `restart_stream_after_signal_change`, +`wait_for_recovery`). **Sync commit: `1d89392`** (the F1 fix, on master). The model +was last confirmed against the code at this commit. + +### Keeping it in step + +1. `check.ps1` prints `STALE` when a covered file differs from the sync commit, working tree included. Read the + diff of the covered functions: `git diff -- `. +2. For each changed check, lock, or ordering, update the matching action in the table, or its guard in the + `Guards` set of `MC_Contract.cfg` and `MC_ConcurrentReader.cfg` when the change removes a guarded check. + Add any new step as a new action, with its function named in a comment. +3. Run `check.ps1`. A violation in `MC_Contract` or `MC_ConcurrentReader` means the change breaks the property. + Read the trace with `check.ps1 -Trace `, and report it with the steps in code words. Do not loosen + the model. + When the change touches the read, stop or start path, also run the hardware check. +4. Move the sync commit (here and in `check.ps1`) forward only after you have confirmed that the model describes + the code at the new commit. diff --git a/.agents/skills/verify-gvfg-frame-hold/scripts/check.ps1 b/.agents/skills/verify-gvfg-frame-hold/scripts/check.ps1 new file mode 100644 index 0000000..30bcca3 --- /dev/null +++ b/.agents/skills/verify-gvfg-frame-hold/scripts/check.ps1 @@ -0,0 +1,142 @@ +<# +Model-checks GVFG_SDK/sdk/gvfg/formal/CaptureFrameHold.tla with TLC and compares every config with its expected result. +Also reports whether the covered code changed since the sync commit (then the model needs another look). + + powershell -NoProfile -ExecutionPolicy Bypass -File .agents\skills\verify-gvfg-frame-hold\scripts\check.ps1 [-Only MC_Contract] [-Install] + powershell -NoProfile -ExecutionPolicy Bypass -File .agents\skills\verify-gvfg-frame-hold\scripts\check.ps1 -Trace MC_Mut_NoRunGeneration + +-Trace runs one config and prints its counterexample as a table: each step's action and the variables it changed. +Map each action to code with the table in SKILL.md. + +Exit 0: every config matched its expectation and the covered code is unchanged since the sync commit. +1: a mismatch (read the log it names). 2: Java or TLA+ tools missing. +3: expectations met, but covered code changed since the sync commit, so update the model first (SKILL.md). + +tla2tools.jar is looked up in $env:TLA2TOOLS_JAR, then GVFG_SDK\sdk\gvfg\formal\tools (git-ignored, inside the +workspace so sandboxed agents can read it), then %USERPROFILE%\.tools\tla. -Install downloads the pinned v1.7.4 +(SHA256 checked) into formal\tools. Java must be installed separately, e.g. +winget install --id EclipseAdoptium.Temurin.21.JDK -e. +#> +param([string[]]$Only, [switch]$Install, [string]$Trace) +$ErrorActionPreference = 'Stop' +$repo = (Resolve-Path (Join-Path $PSScriptRoot '..\..\..\..')).Path +$formal = Join-Path $repo 'GVFG_SDK\sdk\gvfg\formal' +$outDir = Join-Path $formal 'out' + +# ---- tools ----------------------------------------------------------------- +$jarVersion = '1.7.4' +$jarName = "tla2tools-$jarVersion.jar" +$jarSha256 = '936A262061C914694DFD669A543BE24573C45D5AA0FF20A8B96B23D01E050E88' +$workspaceJar = Join-Path $formal "tools\$jarName" +$jar = @($env:TLA2TOOLS_JAR, $workspaceJar, (Join-Path $env:USERPROFILE ".tools\tla\$jarName")) | + Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1 +if (-not $jar) { + if (-not $Install) { Write-Host "Missing $jarName. Rerun with -Install (downloads ~2 MB from github.com/tlaplus into $workspaceJar)."; exit 2 } + New-Item -ItemType Directory -Force (Split-Path $workspaceJar) | Out-Null + Invoke-WebRequest -UseBasicParsing -OutFile $workspaceJar ` + -Uri "https://github.com/tlaplus/tlaplus/releases/download/v$jarVersion/tla2tools.jar" + $jar = $workspaceJar +} +if ((Get-FileHash $jar -Algorithm SHA256).Hash -ne $jarSha256) { Write-Host "SHA256 mismatch for $jar"; exit 2 } + +$java = $null +if ($env:JAVA_HOME -and (Test-Path "$env:JAVA_HOME\bin\java.exe")) { $java = "$env:JAVA_HOME\bin\java.exe" } +if (-not $java) { + $java = Get-ChildItem 'C:\Program Files\Eclipse Adoptium' -Directory -ErrorAction SilentlyContinue | + Sort-Object Name -Descending | ForEach-Object { Join-Path $_.FullName 'bin\java.exe' } | + Where-Object { Test-Path $_ } | Select-Object -First 1 +} +if (-not $java) { $java = (Get-Command java -ErrorAction SilentlyContinue).Source } +if (-not $java) { Write-Host 'Java not found. Install it: winget install --id EclipseAdoptium.Temurin.21.JDK -e'; exit 2 } + +# ---- expectations ---------------------------------------------------------- +# Pass : TLC must report "No error has been found". +# Violation:X : TLC must report invariant X violated (mutations prove the check can fail; findings are known bugs). +$expect = [ordered]@{ + 'MC_Contract' = 'Pass' # shipped code, app quiesces reader before stop/start + 'MC_ConcurrentReader' = 'Pass' # shipped code, reader runs across stop->start (F1 fixed) + 'MC_Mut_NoRestartWait' = 'Violation:HeldFrameIsCurrent' # mutation: restart does not wait for frame_held_ + 'MC_Mut_NoRecoveryCheck' = 'Violation:HeldFrameIsCurrent' # mutation: capture ignores recovery_pending_/generation + 'MC_Mut_NoRunGeneration' = 'Violation:HeldFrameIsCurrent' # mutation: delivery checks only running (F1, code before the fix) + 'MC_Mut_NoRunningRecheck' = 'Violation:ReleaseWillSucceed' # mutation: delivery checks only the run generation +} + +function Invoke-Tlc([string]$Config) { + $log = Join-Path $outDir "$Config.log" + $meta = Join-Path $outDir "meta-$Config" + # One worker keeps the search order, and so the first violated invariant, the same on every run. + & $java -XX:+UseParallelGC -cp $jar tlc2.TLC -config "$Config.cfg" -metadir $meta -workers 1 -cleanup CaptureFrameHold.tla 2>&1 | + ForEach-Object { "$_" } | Set-Content -Encoding UTF8 $log + Remove-Item -Recurse -Force $meta -ErrorAction SilentlyContinue + return $log +} + +function Show-Trace([string]$LogPath) { + # TLC prints each state as "State N: " followed by "/\ var = value" lines. + $text = Get-Content $LogPath + $violation = $text | Where-Object { $_ -match 'Invariant \w+ is violated|Deadlock reached' } | Select-Object -First 1 + if (-not $violation) { 'No counterexample in ' + $LogPath + ' (the config passed or TLC failed; read the log).'; return } + $violation.Trim() + $prev = @{}; $cur = $null; $action = $null; $step = 0 + $states = New-Object System.Collections.ArrayList + foreach ($line in $text) { + if ($line -match '^State (\d+): <(\w+)') { + if ($cur) { [void]$states.Add(@($step, $action, $cur)) } + $step = [int]$matches[1]; $action = $matches[2]; $cur = [ordered]@{} + } + elseif ($cur -and $line -match '^/\\ (\w+) = (.+)$') { $cur[$matches[1]] = $matches[2] } + } + if ($cur) { [void]$states.Add(@($step, $action, $cur)) } + foreach ($s in $states) { + $vars = $s[2] + $changed = foreach ($k in $vars.Keys) { if (-not $prev.Contains($k) -or $prev[$k] -ne $vars[$k]) { "$k=$($vars[$k])" } } + '{0,3} {1,-16} {2}' -f $s[0], $s[1], ($changed -join ' ') + $prev = $vars + } +} + +New-Item -ItemType Directory -Force $outDir | Out-Null +Push-Location $formal +try { + if ($Trace) { + if (-not (Test-Path "$Trace.cfg")) { Write-Host "No config $Trace.cfg in $formal"; exit 2 } + Show-Trace (Invoke-Tlc $Trace) + exit 0 + } + $failed = $false + foreach ($cfg in $expect.Keys) { + if ($Only -and $cfg -notin $Only) { continue } + $sw = [Diagnostics.Stopwatch]::StartNew() + $log = Invoke-Tlc $cfg + $sw.Stop() + $text = Get-Content $log -Raw + $got = if ($text -match 'Model checking completed\. No error has been found') { 'Pass' } + elseif ($text -match 'Invariant (\w+) is violated') { "Violation:$($matches[1])" } + elseif ($text -match 'Deadlock reached') { 'Deadlock' } + else { 'ToolError' } + # TLC also prints progress lines with partial counts; the final summary is the last one. + $final = [regex]::Matches($text, '(\d+) distinct states found') + $states = if ($final.Count) { $final[$final.Count - 1].Groups[1].Value } else { '?' } + $ok = $got -eq $expect[$cfg] + if (-not $ok) { $failed = $true } + '{0,-24} expected {1,-30} got {2,-30} {3,8} states {4,6:n1}s {5}' -f $cfg, $expect[$cfg], $got, $states, $sw.Elapsed.TotalSeconds, $(if ($ok) { 'OK' } else { "MISMATCH -> $log" }) + } +} +finally { Pop-Location } + +# ---- is the verification still in step with the code? --------------------- +$syncCommit = '1d89392' +$covered = @('GVFG_SDK/sdk/gvfg/src/gvfg_capture.cpp', 'GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.cpp', + 'GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.h') +$changed = git -C $repo diff --name-only $syncCommit -- @covered +if ($changed) { + Write-Host "STALE: covered code changed since sync commit ${syncCommit}: $($changed -join ', ')" + Write-Host " Re-read the changed functions against the model before trusting a Pass (see SKILL.md, 'Keeping it in step')." +} else { + Write-Host "In step: covered code unchanged since sync commit $syncCommit." +} + +if ($failed) { 'RESULT: MISMATCH'; exit 1 } +# A pass against a model nobody re-checked after the code moved proves nothing about the new code. +if ($changed) { 'RESULT: STALE - expectations met by the model, but the model is not confirmed against the changed code'; exit 3 } +'RESULT: ALL EXPECTATIONS MET' diff --git a/.agents/skills/verify-gvfg-frame-hold/scripts/f1-hardware-repro.ps1 b/.agents/skills/verify-gvfg-frame-hold/scripts/f1-hardware-repro.ps1 new file mode 100644 index 0000000..9c6df10 --- /dev/null +++ b/.agents/skills/verify-gvfg-frame-hold/scripts/f1-hardware-repro.ps1 @@ -0,0 +1,37 @@ +<# +Builds and runs f1_hardware_repro.cpp against one GVFG SDK build, on a PC with a GVFG card and a live signal on +channel 0. No viewer may hold the card while it runs. + + powershell -NoProfile -ExecutionPolicy Bypass -File .agents\skills\verify-gvfg-frame-hold\scripts\f1-hardware-repro.ps1 -GvfgBuildDir GVFG_SDK\build\ + +The build dir must contain bin\gvfg.dll and lib\gvfg.lib. Exit codes are the program's: 0 fixed, 1 F1 reproduced, +2 not verifiable here, 3 unexpected. +#> +param([Parameter(Mandatory)][string]$GvfgBuildDir) +$ErrorActionPreference = 'Stop' +$repo = (Resolve-Path (Join-Path $PSScriptRoot '..\..\..\..')).Path +$sdk = Join-Path $repo 'GVFG_SDK\sdk\gvfg' +$build = (Resolve-Path $GvfgBuildDir).Path +foreach ($f in 'bin\gvfg.dll', 'lib\gvfg.lib') { + if (-not (Test-Path (Join-Path $build $f))) { Write-Host "Missing $f in $build"; exit 3 } +} +if (Get-Process qt6_viewer, GVFG_CardTest -ErrorAction SilentlyContinue) { Write-Host 'A viewer or card test holds the card; close it first.'; exit 2 } + +$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' +$vs = & $vswhere -products * -latest -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +$env:PATH = (Split-Path $vswhere) + ';' + $env:PATH +cmd /c "`"$(Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat')`" >nul 2>&1 && set" | ForEach-Object { + if ($_ -match '^([^=]+)=(.*)$') { [Environment]::SetEnvironmentVariable($matches[1], $matches[2]) } +} + +$out = Join-Path $env:TEMP ("gvfg-f1-repro-" + (Split-Path $build -Leaf)) +New-Item -ItemType Directory -Force $out | Out-Null +$exe = Join-Path $out 'f1_hardware_repro.exe' +& cl.exe /nologo /std:c++17 /EHsc /O2 /utf-8 "/I$sdk\include" "/I$sdk\src" (Join-Path $PSScriptRoot 'f1_hardware_repro.cpp') ` + "/Fe:$exe" "/Fo:$out\\" /link "/LIBPATH:$build\lib" gvfg.lib | Out-Null +if ($LASTEXITCODE -ne 0) { Write-Host 'Compile failed'; exit 3 } + +$env:PATH = (Join-Path $build 'bin') + ';' + $env:PATH +Write-Host "SDK build: $build" +& $exe +exit $LASTEXITCODE diff --git a/.agents/skills/verify-gvfg-frame-hold/scripts/f1_hardware_repro.cpp b/.agents/skills/verify-gvfg-frame-hold/scripts/f1_hardware_repro.cpp new file mode 100644 index 0000000..0cb3ff9 --- /dev/null +++ b/.agents/skills/verify-gvfg-frame-hold/scripts/f1_hardware_repro.cpp @@ -0,0 +1,193 @@ +// F1 on real hardware, deterministically: stop + start while a read sits between +// capture and delivery. A frame processor (the hook OSD uses) parks the reader in +// exactly that window, so no timing luck is needed. +// +// Exit 0: fixed behaviour (the read is rejected, the next read works). +// Exit 1: F1 reproduced (stale frame delivered, release rejected or channel stuck). +// Exit 2: not verifiable here (no device / no signal). Exit 3: unexpected result. +#include + +#include +#include +#include +#include +#include + +#include "gvfg_capture.h" +#include "gvfg_frame_processor.h" + +namespace +{ + std::mutex g_mutex; + std::condition_variable g_cv; + bool g_armed = false; + bool g_parked = false; + bool g_resume = false; + + gvfg_status_t parkerCreate(void **context) + { + *context = nullptr; + return GVFG_OK; + } + + void parkerDestroy(void *) {} + + gvfg_status_t parkerProcess(void *, const gvfg_frame_t &in, gvfg_frame_t &out, bool &applied, + gvfg_debug_osd_frame_timing_t *, uint8_t *, bool *inPlace) + { + out = in; + applied = false; // keep the backend hold, like OSD off / in-place OSD + if (inPlace) + *inPlace = false; + std::unique_lock lock(g_mutex); + if (g_armed) + { + g_armed = false; + g_parked = true; + g_cv.notify_all(); + g_cv.wait(lock, [] { return g_resume; }); + } + return GVFG_OK; + } + + gvfg_status_t parkerControl(void *, const void *) { return GVFG_OK; } + + const gvfg_frame_processor kParker{parkerCreate, parkerDestroy, parkerProcess}; + + const char *name(gvfg_status_t status) { return gvfg_strerror(status); } + + void lastError(gvfg_handle handle, const char *label) + { + char message[512] = {}; + gvfg_get_channel_last_sdk_error_detail(handle, GVFG_CHANNEL_0, message, sizeof(message)); + std::printf(" %-16s last SDK error: %s\n", label, message[0] ? message : "(none)"); + } +} + +int main() +{ + std::printf("GVFG SDK %s\n", gvfg_get_version()); + if (gvfg_enumerate_devices(nullptr, 0) < 1) + { + std::puts("NOT VERIFIED: no GVFG device"); + return 2; + } + + gvfg_handle handle = nullptr; + if (gvfg_create(&handle) != GVFG_OK || gvfg_open_channel(handle, 0, GVFG_CHANNEL_0) != GVFG_OK) + { + std::puts("NOT VERIFIED: cannot open device 0 channel 0"); + return 2; + } + gvfg_status_t st = gvfg_start_channel(handle, GVFG_CHANNEL_0); + if (st != GVFG_OK) + { + std::printf("NOT VERIFIED: start failed (%s); is a signal connected?\n", name(st)); + gvfg_destroy(handle); + return 2; + } + st = gvfg_control_frame_processor(handle, GVFG_CHANNEL_0, &kParker, true, parkerControl, nullptr, + "attach parker failed"); + if (st != GVFG_OK) + { + std::printf("UNEXPECTED: cannot attach frame processor (%s)\n", name(st)); + gvfg_destroy(handle); + return 3; + } + + // Warm up: capture really flows before the race. + int warm = 0; + for (int i = 0; i < 20 && warm < 5; ++i) + { + gvfg_frame_t frame{}; + if (gvfg_read_channel_frame(handle, GVFG_CHANNEL_0, &frame, 1000) == GVFG_OK) + { + ++warm; + gvfg_release_channel_frame(handle, GVFG_CHANNEL_0, &frame); + } + } + if (warm < 5) + { + std::puts("NOT VERIFIED: frames are not flowing"); + gvfg_destroy(handle); + return 2; + } + + { + std::lock_guard lock(g_mutex); + g_armed = true; + } + gvfg_status_t readStatus = GVFG_ETIMEOUT; + gvfg_status_t releaseStatus = GVFG_ETIMEOUT; + bool released = false; + std::thread reader([&] { + gvfg_frame_t frame{}; + readStatus = gvfg_read_channel_frame(handle, GVFG_CHANNEL_0, &frame, 2000); + if (readStatus == GVFG_OK) + { + released = true; + releaseStatus = gvfg_release_channel_frame(handle, GVFG_CHANNEL_0, &frame); + } + }); + + bool parked = false; + { + std::unique_lock lock(g_mutex); + parked = g_cv.wait_for(lock, std::chrono::seconds(5), [] { return g_parked; }); + } + gvfg_status_t stopStatus = GVFG_ETIMEOUT; + gvfg_status_t startStatus = GVFG_ETIMEOUT; + if (parked) + { + stopStatus = gvfg_stop_channel(handle, GVFG_CHANNEL_0); + startStatus = gvfg_start_channel(handle, GVFG_CHANNEL_0); + } + { + std::lock_guard lock(g_mutex); + g_resume = true; + } + g_cv.notify_all(); + reader.join(); + lastError(handle, "after race:"); + + gvfg_status_t nextRead = GVFG_ETIMEOUT; + gvfg_status_t nextRelease = GVFG_ETIMEOUT; + for (int i = 0; i < 5 && nextRead != GVFG_OK; ++i) + { + gvfg_frame_t frame{}; + nextRead = gvfg_read_channel_frame(handle, GVFG_CHANNEL_0, &frame, 1000); + if (nextRead == GVFG_OK) + nextRelease = gvfg_release_channel_frame(handle, GVFG_CHANNEL_0, &frame); + else if (nextRead == GVFG_ESTATE) + break; // ESTATE here means the channel is stuck; retrying will not help + } + lastError(handle, "after next read:"); + + std::printf("parked in window : %s\n", parked ? "yes" : "no"); + std::printf("stop / start : %s / %s\n", name(stopStatus), name(startStatus)); + std::printf("racing read : %s\n", name(readStatus)); + std::printf("its release : %s\n", released ? name(releaseStatus) : "(not called: no frame)"); + std::printf("next read : %s (release %s)\n", name(nextRead), + nextRead == GVFG_OK ? name(nextRelease) : "-"); + + gvfg_stop_channel(handle, GVFG_CHANNEL_0); + gvfg_destroy(handle); + + if (!parked || stopStatus != GVFG_OK || startStatus != GVFG_OK) + { + std::puts("RESULT: UNEXPECTED (race not staged)"); + return 3; + } + if (readStatus == GVFG_OK && (releaseStatus != GVFG_OK || nextRead != GVFG_OK)) + { + std::puts("RESULT: F1 REPRODUCED (stale frame delivered after stop->start)"); + return 1; + } + if (readStatus != GVFG_OK && nextRead == GVFG_OK && nextRelease == GVFG_OK) + { + std::puts("RESULT: FIXED (racing read rejected, channel keeps working)"); + return 0; + } + std::puts("RESULT: UNEXPECTED"); + return 3; +} diff --git a/.claude/skills/verify-gvfg-frame-hold/SKILL.md b/.claude/skills/verify-gvfg-frame-hold/SKILL.md new file mode 100644 index 0000000..6bf95f7 --- /dev/null +++ b/.claude/skills/verify-gvfg-frame-hold/SKILL.md @@ -0,0 +1,10 @@ +--- +name: verify-gvfg-frame-hold +description: "Model-check the GVFG capture frame-hold protocol (gvfg_read_channel_frame / gvfg_release_channel_frame against stop, start and signal-change recovery) with TLA+/TLC, and reproduce the stop->start race on real hardware. Use it before and after any change to gvfg_capture.cpp's channel read/release/stop/start, or to GigabyteCaptureSession's wait_frame, release_frame, start_stream, stop_stream, handle_signal_event or restart_stream_after_signal_change." +--- + +# verify-gvfg-frame-hold (Claude Code entry) + +The skill lives in `.agents/skills/verify-gvfg-frame-hold/` at the GVFG_Standalone repository root, so Claude Code +and Codex share one copy. Read `.agents/skills/verify-gvfg-frame-hold/SKILL.md` and follow it. Its scripts are in +that folder. Do not copy them here. diff --git a/GVFG_SDK/sdk/gvfg/formal/.gitignore b/GVFG_SDK/sdk/gvfg/formal/.gitignore new file mode 100644 index 0000000..89e76ab --- /dev/null +++ b/GVFG_SDK/sdk/gvfg/formal/.gitignore @@ -0,0 +1,4 @@ +out/ +states/ +*.st +tools/ diff --git a/GVFG_SDK/sdk/gvfg/formal/CaptureFrameHold.tla b/GVFG_SDK/sdk/gvfg/formal/CaptureFrameHold.tla new file mode 100644 index 0000000..f8820f3 --- /dev/null +++ b/GVFG_SDK/sdk/gvfg/formal/CaptureFrameHold.tla @@ -0,0 +1,347 @@ +--------------------------- MODULE CaptureFrameHold --------------------------- +(***************************************************************************) +(* The frame-hold protocol of one GVFG capture channel. *) +(* *) +(* Promise checked: while the application holds a frame whose data is the *) +(* backend capture buffer, (1) that buffer still belongs to the running *) +(* driver stream -- no recovery restart and no stop/start has replaced it *) +(* -- and (2) the one gvfg_release_channel_frame() the application must *) +(* make will succeed. *) +(* *) +(* Harm if broken: the application reads a zero-copy buffer the driver is *) +(* refilling (torn or foreign video), and/or its release returns *) +(* GVFG_ESTATE and the channel stays "frame held", so every later read is *) +(* rejected until stop. *) +(* *) +(* Threads: R = application video worker (read / release), *) +(* U = application lifecycle thread (stop / start, serialized), *) +(* E = session event thread (signal change -> recovery restart). *) +(* Each action is one indivisible step in the code: a section under one *) +(* mutex, or one atomic access. Code references name the function in *) +(* C = GVFG_SDK/sdk/gvfg/src/gvfg_capture.cpp (gvfg_channel_session_t) *) +(* S = GVFG_SDK/sdk/gvfg/src/gigabyte/gigabyte_capture_session.cpp *) +(***************************************************************************) +EXTENDS Naturals + +CONSTANTS + AppQuiescesReader, \* TRUE: app joins/pauses its reader before stop/start (srcroot GvfgSource::stop does) + Guards, \* code checks present; the shipped code has all of them (see MC .cfg files) + MaxLifecycleOps, \* bound on stop/start calls + MaxSignalEvents, \* bound on format-change / plug-in events + MaxReads \* bound on read attempts + +AllGuards == {"RestartWaitsForRelease", "CaptureRejectsDuringRecovery", + "DeliverRechecksRunning", "DeliverChecksRunGeneration"} +ASSUME Guards \subseteq AllGuards + +VARIABLES + \* --- channel, C: gvfg_channel_session_t ------------------------------- + running, \* C running (std::atomic) + readInProgress, \* C readInProgress (frameMutex) + frameHeld, \* C frameHeld (frameMutex) + heldNeedsBackend, \* C heldFrameNeedsBackendRelease (frameMutex) + heldEpoch, \* ghost: driver stream epoch of the buffer in heldSessionFrame + runGen, \* C runGeneration (frameMutex): +1 on every successful start + \* --- session, S: GigabyteCaptureSession ------------------------------- + sRunning, \* S running_ + sFrameHeld, \* S frame_held_ (state_mutex_) + recoveryPending, \* S recovery_pending_ + generation, \* S signal_generation_ + epoch, \* ghost: +1 on every GvfgStartCapture (driver buffers handed out anew) + monitoring, \* S monitoring_ (event thread alive) + \* --- threads --------------------------------------------------------- + rpc, rGen, rRunGen, rEpoch, rNeeds, reads, + upc, uNeeds, ops, readerPaused, + epc, signals, + releaseFailed \* ghost: app's release of a held frame returned GVFG_ESTATE + +chanVars == <> +sessVars == <> +rVars == <> +uVars == <> +eVars == <> +vars == <> + +RStates == {"idle", "begin_lock", "wait_check", "waiting", "capture", "osd", "deliver", + "stop_release", "holding", "fail"} +UStates == {"idle", "quiesce", "choose", "stop_frames", "stop_backend", + "stop_stream", "stop_join", "start_session", "start_channel"} +EStates == {"idle", "decide", "wait_hold", "restart", "finish"} + +TypeOK == + /\ running \in BOOLEAN /\ readInProgress \in BOOLEAN /\ frameHeld \in BOOLEAN + /\ heldNeedsBackend \in BOOLEAN /\ heldEpoch \in Nat /\ runGen \in Nat + /\ sRunning \in BOOLEAN /\ sFrameHeld \in BOOLEAN /\ recoveryPending \in BOOLEAN + /\ generation \in Nat /\ epoch \in Nat /\ monitoring \in BOOLEAN + /\ rpc \in RStates /\ rGen \in Nat /\ rRunGen \in Nat /\ rEpoch \in Nat + /\ rNeeds \in BOOLEAN /\ reads \in Nat + /\ upc \in UStates /\ uNeeds \in BOOLEAN /\ ops \in Nat /\ readerPaused \in BOOLEAN + /\ epc \in EStates /\ signals \in Nat + /\ releaseFailed \in BOOLEAN + +\* Channel open and started once: C start() -> S start_stream() succeeded. +Init == + /\ running = TRUE /\ readInProgress = FALSE /\ frameHeld = FALSE + /\ heldNeedsBackend = FALSE /\ heldEpoch = 0 /\ runGen = 1 + /\ sRunning = TRUE /\ sFrameHeld = FALSE /\ recoveryPending = FALSE + /\ generation = 0 /\ epoch = 1 /\ monitoring = TRUE + /\ rpc = "idle" /\ rGen = 0 /\ rRunGen = 0 /\ rEpoch = 0 /\ rNeeds = FALSE /\ reads = 0 + /\ upc = "idle" /\ uNeeds = FALSE /\ ops = 0 /\ readerPaused = FALSE + /\ epc = "idle" /\ signals = 0 /\ releaseFailed = FALSE + +(***************************************************************************) +(* R: gvfg_read_channel_frame / gvfg_release_channel_frame *) +(***************************************************************************) + +\* C readFrame: `if (!running)` before taking frameMutex. +RBegin == + /\ rpc = "idle" /\ reads < MaxReads + /\ ~(AppQuiescesReader /\ readerPaused) + /\ running + /\ rpc' = "begin_lock" /\ reads' = reads + 1 + /\ UNCHANGED <> + +\* C readFrame, first frameMutex section: reject if held or another read; record the run. +RBeginLock == + /\ rpc = "begin_lock" + /\ IF frameHeld \/ readInProgress + THEN rpc' = "idle" /\ UNCHANGED <> + ELSE readInProgress' = TRUE /\ rRunGen' = runGen /\ rpc' = "wait_check" + /\ UNCHANGED <> + +\* S wait_frame entry: running_ check; state_mutex_: snapshot generation, reject if held. +RWaitCheck == + /\ rpc = "wait_check" + /\ IF ~sRunning \/ sFrameHeld + THEN rpc' = "fail" /\ UNCHANGED rGen + ELSE rGen' = generation /\ rpc' = "waiting" + /\ UNCHANGED <> + +\* S wait_frame: WaitForMultipleObjects(stop, recovery, frame events). +\* stop_event set (stop_stream) -> ESTATE; recovery_event -> wait_for_recovery -> non-OK. +RWakeFail == + /\ rpc = "waiting" /\ (~sRunning \/ recoveryPending) + /\ rpc' = "fail" + /\ UNCHANGED <> + +\* A frame event fires while the driver stream runs. +RWakeFrame == + /\ rpc = "waiting" /\ sRunning + /\ rpc' = "capture" + /\ UNCHANGED <> + +\* S wait_frame capture section, one step under capture_mutex_: re-check, get the buffer, frame_held_ = true. +RCapture == + /\ rpc = "capture" + /\ IF ~sRunning + \/ ("CaptureRejectsDuringRecovery" \in Guards /\ (recoveryPending \/ rGen # generation)) + THEN rpc' = "fail" /\ UNCHANGED <> + ELSE sFrameHeld' = TRUE /\ rEpoch' = epoch /\ rpc' = "osd" + /\ UNCHANGED <> + +\* C readFrame frame processor: no OSD, or in-place OSD, keeps the backend hold ... +ROsdKeep == + /\ rpc = "osd" + /\ rNeeds' = TRUE /\ rpc' = "deliver" + /\ UNCHANGED <> + +\* ... OSD into a separate SDK buffer releases the backend frame now (S release_frame). +ROsdEarlyRelease == + /\ rpc = "osd" + /\ IF sFrameHeld + THEN sFrameHeld' = FALSE /\ rNeeds' = FALSE /\ rpc' = "deliver" + ELSE rpc' = "fail" /\ UNCHANGED <> + /\ UNCHANGED <> + +\* C readFrame delivery, frameMutex: deliver unless capture stopped, or stopped and +\* restarted, since the read began. +Stale == + \/ ("DeliverRechecksRunning" \in Guards /\ ~running) + \/ ("DeliverChecksRunGeneration" \in Guards /\ rRunGen # runGen) + +RDeliver == + /\ rpc = "deliver" + /\ IF Stale + THEN /\ readInProgress' = FALSE + /\ rpc' = IF rNeeds THEN "stop_release" ELSE "idle" + /\ UNCHANGED <> + ELSE /\ frameHeld' = TRUE /\ heldNeedsBackend' = rNeeds /\ heldEpoch' = rEpoch + /\ readInProgress' = FALSE /\ rpc' = "holding" + /\ UNCHANGED <> + +\* C readFrame stoppedWhileWaiting: session->release_frame() (clears the hold if still held). +RStopRelease == + /\ rpc = "stop_release" + /\ sFrameHeld' = FALSE /\ rpc' = "idle" + /\ UNCHANGED <> + +\* C releaseFrame, one step under frameMutex (calls S release_frame inside). +RRelease == + /\ rpc = "holding" + /\ rpc' = "idle" + /\ CASE ~frameHeld -> \* invalidated by stop: ESTATE, documented + UNCHANGED <> + [] frameHeld /\ heldNeedsBackend /\ ~sFrameHeld -> \* S rejects; C returns before clearing + /\ releaseFailed' = TRUE + /\ UNCHANGED <> + [] OTHER -> + /\ frameHeld' = FALSE /\ heldNeedsBackend' = FALSE + /\ sFrameHeld' = IF heldNeedsBackend THEN FALSE ELSE sFrameHeld + /\ UNCHANGED releaseFailed + /\ UNCHANGED <> + +RFail == + /\ rpc = "fail" + /\ readInProgress' = FALSE /\ rpc' = "idle" + /\ UNCHANGED <> + +(***************************************************************************) +(* U: gvfg_stop_channel / gvfg_start_channel, serialized by the app *) +(***************************************************************************) + +UBegin == + /\ upc = "idle" /\ ops < MaxLifecycleOps + /\ IF AppQuiescesReader + THEN readerPaused' = TRUE /\ upc' = "quiesce" + ELSE upc' = "choose" /\ UNCHANGED readerPaused + /\ UNCHANGED <> + +\* App protocol (docs/GVFG_FRAME_FLOW_AND_STATE.md section 5): reader released its frame and is joined. +UQuiesced == + /\ upc = "quiesce" /\ rpc = "idle" + /\ upc' = "choose" + /\ UNCHANGED <> + +\* C stop: running = false. +UStop == + /\ upc = "choose" /\ running + /\ running' = FALSE /\ ops' = ops + 1 /\ upc' = "stop_frames" + /\ UNCHANGED <> + +\* C releaseHeldFrameForStop, frameMutex: invalidate the app's frame. +UStopFrames == + /\ upc = "stop_frames" + /\ uNeeds' = (frameHeld /\ heldNeedsBackend) + /\ frameHeld' = FALSE /\ heldNeedsBackend' = FALSE + /\ upc' = "stop_backend" + /\ UNCHANGED <> + +\* C releaseHeldFrameForStop: session->release_frame(). +UStopBackend == + /\ upc = "stop_backend" + /\ sFrameHeld' = IF uNeeds THEN FALSE ELSE sFrameHeld + /\ upc' = "stop_stream" + /\ UNCHANGED <> + +\* S stop_stream: running_ = false, events set, frame_held_ = false. +UStopStream == + /\ upc = "stop_stream" + /\ sRunning' = FALSE /\ recoveryPending' = FALSE /\ sFrameHeld' = FALSE + /\ monitoring' = FALSE /\ upc' = "stop_join" + /\ UNCHANGED <> + +\* S stop_stream: join the event thread, GvfgStopCapture. +UStopJoin == + /\ upc = "stop_join" /\ epc = "idle" + /\ upc' = "idle" /\ readerPaused' = FALSE + /\ UNCHANGED <> + +\* C start: no-op while running. S start_stream: GvfgStartCapture, +\* frame_held_ = false, running_ = true, event thread started. +UStartSession == + /\ upc = "choose" /\ ~running + /\ ops' = ops + 1 + /\ IF sRunning + THEN UNCHANGED <> + ELSE /\ sRunning' = TRUE /\ sFrameHeld' = FALSE /\ recoveryPending' = FALSE + /\ epoch' = epoch + 1 /\ monitoring' = TRUE + /\ upc' = "start_channel" + /\ UNCHANGED <> + +\* C start, frameMutex: ++runGeneration; running = true. +UStartChannel == + /\ upc = "start_channel" + /\ runGen' = runGen + 1 /\ running' = TRUE + /\ upc' = "idle" /\ readerPaused' = FALSE + /\ UNCHANGED <> + +(***************************************************************************) +(* E: S event_thread_proc -> handle_signal_event (format change / plug-in) *) +(***************************************************************************) + +\* S handle_signal_event first block, under capture_mutex_ + state_mutex_. +ESignal == + /\ epc = "idle" /\ monitoring /\ sRunning /\ signals < MaxSignalEvents + /\ generation' = generation + 1 /\ recoveryPending' = TRUE + /\ signals' = signals + 1 /\ epc' = "decide" + /\ UNCHANGED <> + +\* S handle_signal_event: restart only if the input format really changed. +EDecide == + /\ epc = "decide" + /\ epc' \in {"wait_hold", "finish"} + /\ UNCHANGED <> + +\* S restart_stream_after_signal_change: wait for !frame_held_ || !running_. +EWaitHold == + /\ epc = "wait_hold" + /\ ("RestartWaitsForRelease" \notin Guards \/ ~sFrameHeld \/ ~sRunning) + /\ epc' = "restart" + /\ UNCHANGED <> + +\* S restart_stream_after_signal_change under capture_mutex_: GvfgStopCapture + GvfgStartCapture. +ERestart == + /\ epc = "restart" + /\ epoch' = IF sRunning THEN epoch + 1 ELSE epoch + /\ epc' = "finish" + /\ UNCHANGED <> + +\* S handle_signal_event end: recovery done. +EFinish == + /\ epc = "finish" + /\ recoveryPending' = FALSE /\ epc' = "idle" + /\ UNCHANGED <> + +(***************************************************************************) + +Terminated == + /\ rpc = "idle" /\ epc = "idle" /\ upc = "idle" /\ ops = MaxLifecycleOps + +Next == + \/ RBegin \/ RBeginLock \/ RWaitCheck \/ RWakeFail \/ RWakeFrame \/ RCapture + \/ ROsdKeep \/ ROsdEarlyRelease \/ RDeliver \/ RStopRelease \/ RRelease \/ RFail + \/ UBegin \/ UQuiesced \/ UStop \/ UStopFrames \/ UStopBackend \/ UStopStream + \/ UStopJoin \/ UStartSession \/ UStartChannel + \/ ESignal \/ EDecide \/ EWaitHold \/ ERestart \/ EFinish + \/ (Terminated /\ UNCHANGED vars) + +Spec == Init /\ [][Next]_vars + +(***************************************************************************) +(* Properties *) +(***************************************************************************) + +\* (1) The buffer the app holds belongs to the driver stream that is running now. +HeldFrameIsCurrent == (frameHeld /\ heldNeedsBackend) => heldEpoch = epoch + +\* (2) The app's single release of that frame will succeed (S still records the hold). +ReleaseWillSucceed == (frameHeld /\ heldNeedsBackend) => sFrameHeld + +\* (2') Consequence observed by the app. +NoFailedRelease == ~releaseFailed +============================================================================= diff --git a/GVFG_SDK/sdk/gvfg/formal/MC_ConcurrentReader.cfg b/GVFG_SDK/sdk/gvfg/formal/MC_ConcurrentReader.cfg new file mode 100644 index 0000000..c2d9db9 --- /dev/null +++ b/GVFG_SDK/sdk/gvfg/formal/MC_ConcurrentReader.cfg @@ -0,0 +1,13 @@ +\* See the verify-gvfg-frame-hold skill for what each config proves. +SPECIFICATION Spec +CONSTANTS + AppQuiescesReader = FALSE + Guards = {"RestartWaitsForRelease", "CaptureRejectsDuringRecovery", "DeliverRechecksRunning", "DeliverChecksRunGeneration"} + MaxLifecycleOps = 4 + MaxSignalEvents = 2 + MaxReads = 4 +INVARIANTS + TypeOK + HeldFrameIsCurrent + ReleaseWillSucceed + NoFailedRelease diff --git a/GVFG_SDK/sdk/gvfg/formal/MC_Contract.cfg b/GVFG_SDK/sdk/gvfg/formal/MC_Contract.cfg new file mode 100644 index 0000000..52fb2da --- /dev/null +++ b/GVFG_SDK/sdk/gvfg/formal/MC_Contract.cfg @@ -0,0 +1,13 @@ +\* See the verify-gvfg-frame-hold skill for what each config proves. +SPECIFICATION Spec +CONSTANTS + AppQuiescesReader = TRUE + Guards = {"RestartWaitsForRelease", "CaptureRejectsDuringRecovery", "DeliverRechecksRunning", "DeliverChecksRunGeneration"} + MaxLifecycleOps = 4 + MaxSignalEvents = 2 + MaxReads = 4 +INVARIANTS + TypeOK + HeldFrameIsCurrent + ReleaseWillSucceed + NoFailedRelease diff --git a/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRecoveryCheck.cfg b/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRecoveryCheck.cfg new file mode 100644 index 0000000..a431ce2 --- /dev/null +++ b/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRecoveryCheck.cfg @@ -0,0 +1,13 @@ +\* See the verify-gvfg-frame-hold skill for what each config proves. +SPECIFICATION Spec +CONSTANTS + AppQuiescesReader = TRUE + Guards = {"RestartWaitsForRelease", "DeliverRechecksRunning", "DeliverChecksRunGeneration"} + MaxLifecycleOps = 4 + MaxSignalEvents = 2 + MaxReads = 4 +INVARIANTS + TypeOK + HeldFrameIsCurrent + ReleaseWillSucceed + NoFailedRelease diff --git a/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRestartWait.cfg b/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRestartWait.cfg new file mode 100644 index 0000000..183a367 --- /dev/null +++ b/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRestartWait.cfg @@ -0,0 +1,13 @@ +\* See the verify-gvfg-frame-hold skill for what each config proves. +SPECIFICATION Spec +CONSTANTS + AppQuiescesReader = TRUE + Guards = {"CaptureRejectsDuringRecovery", "DeliverRechecksRunning", "DeliverChecksRunGeneration"} + MaxLifecycleOps = 4 + MaxSignalEvents = 2 + MaxReads = 4 +INVARIANTS + TypeOK + HeldFrameIsCurrent + ReleaseWillSucceed + NoFailedRelease diff --git a/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRunGeneration.cfg b/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRunGeneration.cfg new file mode 100644 index 0000000..66f57fb --- /dev/null +++ b/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRunGeneration.cfg @@ -0,0 +1,13 @@ +\* See the verify-gvfg-frame-hold skill for what each config proves. +SPECIFICATION Spec +CONSTANTS + AppQuiescesReader = FALSE + Guards = {"RestartWaitsForRelease", "CaptureRejectsDuringRecovery", "DeliverRechecksRunning"} + MaxLifecycleOps = 4 + MaxSignalEvents = 2 + MaxReads = 4 +INVARIANTS + TypeOK + HeldFrameIsCurrent + ReleaseWillSucceed + NoFailedRelease diff --git a/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRunningRecheck.cfg b/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRunningRecheck.cfg new file mode 100644 index 0000000..36a3803 --- /dev/null +++ b/GVFG_SDK/sdk/gvfg/formal/MC_Mut_NoRunningRecheck.cfg @@ -0,0 +1,13 @@ +\* See the verify-gvfg-frame-hold skill for what each config proves. +SPECIFICATION Spec +CONSTANTS + AppQuiescesReader = FALSE + Guards = {"RestartWaitsForRelease", "CaptureRejectsDuringRecovery", "DeliverChecksRunGeneration"} + MaxLifecycleOps = 4 + MaxSignalEvents = 2 + MaxReads = 4 +INVARIANTS + TypeOK + HeldFrameIsCurrent + ReleaseWillSucceed + NoFailedRelease