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 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 16:46:15 +08:00
co-authored by Claude Opus 5.5
parent 1d89392cef
commit 208fb6c811
13 changed files with 983 additions and 0 deletions
@@ -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/<config>.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 <config>`. 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\<name>
```
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 <sync commit> -- <file>`.
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 <config>`, 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.
@@ -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 <config> 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: <Action ...>" 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'
@@ -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\<name>
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
@@ -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 <windows.h>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <mutex>
#include <thread>
#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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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;
}