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,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;
}