Skip to content

Clear the driver latch on reconnect, and measure the quiet gap against the turnaround - #11

Open
totoantibes wants to merge 17 commits into
shurkanTwo:masterfrom
totoantibes:fix/clear-the-driver-latch-on-reconnect
Open

totoantibes wants to merge 17 commits into
shurkanTwo:masterfrom
totoantibes:fix/clear-the-driver-latch-on-reconnect

Conversation

@totoantibes

Copy link
Copy Markdown

Three commits. The first turns a session-ender into a reconnect; the second makes the
quiet-gap setting measure the interval it claims to measure; the third corrects the
settings text, which the second commit made untrue.

This stacks on #10. Its base is master, the same base #10 uses, so GitHub shows
#10's commits alongside these three. The new ones are 6b34b86, ee504fb, 2a90128.

A reconnect now clears a driver that stopped responding

NativeCallExecutor gives a native call 30 seconds, and on timeout calls Stop().
After that every later call threw The Sony driver stopped responding, for the rest of
the process - so one bad frame cost the whole session and only a NINA restart recovered
it. A reconnect now clears that state.

Proven on the rig. On 2026-11-20 at 16:59:55 the camera reconnected inside the same
NINA session - log 20261120-161857, 42 minutes of process uptime - after a shutter
jam, two download timeouts, a live-view exception, and the body leaving the USB bus and
returning with a different product ID. No restart.

The quiet gap was never applied to lights

The guard returned early whenever the exposure was at least as long as the gap:

if (exposureTime * 1000.0 >= required) { return; }   // deleted

The intent was that a long exposure is its own rest. It isn't - the shutter is open
during an exposure, not resting - and the arithmetic had two consequences. A 2-second
frame against a 2000 ms gap got no rest at all, and a 30-second light was never gated
under any setting. The whole feature was inert for the frames people actually shoot.

The gap is now measured from MarkImageRetrieved(), the moment the image finishes
downloading, to the top of the next Start(), and only the shortfall is waited out:

int required = Math.Max(0, minCaptureIntervalMs());
if (required == 0 || !haveCaptureEnd) { return; }
while (true) {
    double waited = clock.GetElapsedTime(lastCaptureEndTimestamp).TotalMilliseconds;
    int remaining = required - (int)waited;
    if (remaining <= 0) { break; }
    sleep(Math.Min(remaining, 50));
}

Waited 2794ms before this exposure and Waited 3097ms on 30-second frames are the
first such lines that have ever appeared in a log. The wait also reports the gap it
used, not the gap currently configured, so a setting changed mid-wait cannot make the
log lie.

Shutter and retrieval are sequential, not parallel, which is what makes the turnaround
the right thing to measure: both run on the same native worker thread - one per camera,
with a single task slot - so they cannot overlap. Thread 14556, then 12860, carried
both in the logs.

Be clear what the gap is for

Earlier work in this repository treats the inter-exposure gap as the thing that
prevents the capture jam. It does not, and this PR does not claim it does. Against
that belief: a 6-second gap bought a long clean run once, dropping it to 2 seconds
halved the turnaround with no change in failures, and one failure arrived on the first
frame of a session, where no inter-frame rest exists to have been too short.

The root cause has since been found, and it is the camera body. On 2026-11-21 the
shutter jammed in exactly the way it jams on USB while the body was driven over Wi-Fi
through an unrelated ASCOM driver - no USB cable, no SonyMTPCamera.dll and none of
this plugin in the path. No gap setting prevents that.

So this change is not a fix for the jam. It makes a setting measure what its own
description says it measures, which the previous version did not.

Verification

Run in this session, on this branch at 2a90128:

dotnet test Tests\CaptureController.Tests.csproj
Passed!  - Failed: 0, Passed: 122, Skipped: 0, Total: 122

Three existing tests were inverted rather than deleted, because their old assertions
encoded the bug - AnExposureLongerThanTheGapStillWaits,
AnExposureExactlyTheLengthOfTheGapStillWaits and
ALongExposureWaitsOnlyTheShortfallOfTheGap. TheReportedGapIsTheOneTheWaitUsed is
new, and the harness gained a hook that changes the configured interval mid-wait so
that test can fail.

Known-left, deliberately

  • The wait-out guard trusts the clock, so a system time change during a wait misleads
    it.
  • The failure cap counts consecutive failures but not busy refusals, so a run of
    refusals does not trip it.
  • Reopening the camera while it still holds an undownloaded frame loses that frame.
  • Sony.SonyMTPCameraDll.GetPreviewImage passes a null IntPtr straight to
    Marshal.Copy, throwing ArgumentNullException whenever the driver legitimately has
    no preview to give - the same class of defect as the native null-property crash, but
    managed, so it raises an error instead of killing the process.

🤖 Generated with Claude Code

https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d

totoantibes and others added 17 commits October 31, 2026 18:53
… view

Short exposures taken one after another leave the camera reporting
capturing (1) and never leaving it. Every later start is then refused,
and because native cancel is off by default nothing clears the state:
the camera has to be disconnected and reconnected to take another frame.

Observed on an a7S flat run. The exposure search that chose the time
succeeded at 0.0078s and 0.0157s, then the capture run wedged on its
first frame at 0.01174s. The difference is spacing, not exposure: the
search's steps were seconds apart because each one is a round trip,
while the capture run issues frames back to back.

    08:09:30.88  Starting Exposure - 0.01174s
    08:09:31.01  Capture status created (0) -> capturing (1)
                 ... 20s ...
    08:09:50.92  AbortExposure requested; native cancel unavailable
    08:09:50.94  Camera Timeout - did not set image as ready
    08:09:51.02  Cannot start exposure: camera still busy (capturing (1))

Two changes, both off unless asked for:

  MinCaptureIntervalMs enforces a quiet gap after a capture ends before
  the next one starts. Default 0, because the gap a camera needs has to
  be measured rather than assumed. The wait happens outside captureLock
  so a concurrent abort is not downgraded to a soft cancel for its
  duration.

  A busy status at start now gets one live-view attempt before being
  rejected. Live view is a read the driver already supports and clears
  the stuck state in practice, where the native cancel that would
  otherwise be needed crashes the driver. The status is re-read
  afterwards, so a capture that is genuinely still running is rejected
  exactly as before.

Both reach the hardware through delegates, so CaptureController stays
testable without a camera: the clock is a TimeProvider and the wait is
an injected sleep, letting the tests assert the gap rather than wait it
out.

Verified: 92 CaptureController tests, 24 temperature, 15 integration,
all passing; plugin builds with 0 errors and only the pre-existing
NU1701 legacy-package warnings. Not yet run against a camera.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
The gap existed to stop back-to-back short exposures wedging the camera,
but it was charged to every capture. On a 30s sub that is a seventh of
the night spent waiting for a camera that has already had thirty seconds
of quiet.

An exposure at least as long as the gap now skips it. The wedge is a
short-exposure failure - flats and bias - so the wait falls there and
light frames are untouched.

That makes a non-zero default safe, so the guard is on at 4s rather than
off. The number is deliberately generous rather than measured: it costs
nothing on a light frame and a few seconds across a flat run, against a
wedged camera costing the whole sequence and a reconnect. Set it to 0 to
disable, or lower once a camera's real threshold is known.

Two existing tests used a 1s exposure and so no longer wait; they now use
0.01s, which is the case the guard is for. Added three covering the rule
itself: longer than the gap, exactly the gap, shorter than the gap.

Verified: 95 CaptureController tests, 24 temperature, 15 integration, all
passing; plugin builds with 0 errors and only the pre-existing NU1701
warnings. Still not run against a camera.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
Two corrections after the first deployment.

NINA refused to load the plugin outright:

    Version string portion was too short or too long. (Parameter 'input')

The file version had been set to 1.0.0.5.1 purely so this build could be
told apart from the three other 1.0.0.5 builds in NINA's plugin list.
NINA parses it with System.Version, which takes at most four parts, so a
fifth component stops the assembly loading at all. Reverted, with the
constraint recorded next to the attribute so it is not tried again. The
builds are told apart by file size instead.

The guard also logged nothing when it waited, so a loop test could only
be read by doing arithmetic on capture timestamps - which is inference,
not evidence. It now reports the wait it actually performed, and only
when there was one.

Measured on the rig afterwards, 15 consecutive 0.1s exposures: no
"Cannot start exposure", no camera timeout, intervals settling to a
median of 5.80s in a 5.57-5.92s band. That sequence used to wedge on its
first frame and need a reconnect.

The live-view recovery is still unexercised: nothing wedged, which is
what the guard is for, but it means half of this is unproven against
hardware.

Verified: 97 CaptureController tests, plugin builds with 0 errors.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
The 4s gap exists to keep the next shutter release off the previous frame's
download. It was measured from the wrong event, so it protected nothing.

NINA drives a frame through three separate calls, and the plugin handles them
in three separate methods: StartExposure runs WaitForQuietGap,
WaitUntilExposureIsReady polls until the native status reads Complete, and
only then does DownloadExposure call GetLastImage, which is where the 12.4MB
actually moves. MarkCaptureEnded was the only setter of the timestamp the gap
is measured from, and it fired on Complete -- before a single byte had been
transferred. The gap therefore elapsed inside the transfer.

Measured on an a7S at 0.0125s with the native driver at log level 2: the
retrieval began at 13:08:38.495 and was still being polled at 13:08:42.669,
4.17s later, by which time the 4s gap had already released the next frame. The
native driver logs "There's a pre-existing download, attempting to clean up",
fires the shutter, and then never reports an Image Buffer Status Update or a
Step 4 retrieval for the new frame -- it polls "Nothing yet" every 1.3s
forever and only a reconnect clears it. One frame of ten survived a 0.0125s
series; a 30s sub always finishes its download long before the next frame and
has never wedged.

Mark the retrieval in DownloadExposure instead, in a finally because the
camera is done either way and a stale timestamp would let the next frame start
immediately. The Complete, Cancelled and Failed marks stay as a floor so a
frame NINA abandons without downloading still records an end.

This does not claim to fix the underlying race in the native driver: the same
"pre-existing download" cleanup preceded a frame that succeeded. It stops the
plugin handing the camera a shutter release while a download is in flight,
which is what the gap was written to do.

Tests: the new TheGapIsMeasuredFromTheImageRetrievalNotFromTheExposureEnding
fails without the production change (waits 0ms instead of 4000ms), and
ALongExposureIsStillNotDelayedOnceTheImageIsRetrieved guards the other
direction so lights keep their cadence. 99 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
Abort has six exits and the log said the same thing for all the ones
that matter: "native cancel unavailable; letting capture finish". On the
rig today, with native cancel switched ON and the setting confirmed as
True in the profile, that line still appeared and the camera wedged -
and there was no way to tell from the log whether the setting read had
come back false or the capture lock had simply not been free.

Both are plausible. WaitUntilReady takes captureLock to poll the driver,
and during an exposure that poll goes through the driver's single worker
thread, so the poller can hold the lock for long stretches of exactly
the window in which a cancel needs it. Guessing between the two would
have meant another deploy either way.

Abort now reports its reason through an onAbortDecision callback, wired
to the NINA log in CameraDriver, naming the setting, the lock timeout or
the capture status as the case may be. AbortExposure also logs its
outcome for every result rather than only the soft one, since a capture
that nothing ever cancels is what turns a lost frame into a lost night.
No control flow changed.

Test suite: 96 of 99 pass. Three fail, and none of them is caused by
this change - two of the three (ConcurrentStartsCannotBothEnterNativeStart,
CancellationAfterPollingBeginsInterruptsWaitWithoutAToken) fail
identically on a clean tree, and the third (NativeCallsNeverOverlap,
which touches nothing in this diff) passed once and failed twice across
three identical runs in isolation. They are load-sensitive thread
scheduling tests. Leaving them: making them deterministic is a piece of
work in its own right and does not belong in a logging change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
With native cancel switched on, an abort got through on one attempt and
timed out on the next. The log line added in the previous commit named
the cause on its first outing:

  Abort decision: native cancel is on, but the capture lock could not be
  taken within 1000ms, so nothing was sent; the status poller holds that
  lock while it reads the driver.

WaitUntilReady held captureLock across getStatus(). It reacquires ten
times a second, and during an exposure each read goes through the native
driver's single worker thread, so the lock was held for most of the
window in which a cancel needs it. Whether an abort reached the camera
was luck - and when it lost, the capture stayed outstanding and every
later frame was refused until the camera was reconnected. That is the
difference the two rig runs showed: at 14:24:14 the cancel went through
and the next frame saved 34s later with no reconnect; at 14:26:19 it did
not, and nothing worked again until a disconnect.

The read is now outside the lock. That is safe because it is a read -
the native driver guards its own state, and what captureLock protects
here is the decision that the status belongs to OUR exposure. That
decision is still taken under the lock, after the read, so a capture
that superseded ours mid-read cannot be mistaken for our own ending.

The new test pins it deterministically rather than by timing: a gate
holds the poller inside getStatus, and the abort raised at that moment
must still reach the native cancel. Against the previous code it fails
with exactly the production symptom - expected NativeCancelRequested,
actual SoftCancelRequested - and it uses a dedicated thread because
other tests in this assembly block pool threads for tens of seconds.

Suite: 99 of 100 on the last run, 97 of 100 on the one before. The
difference is the three load-sensitive tests noted in the previous
commit, which come and go on an otherwise unchanged tree; this change's
own test passed in both.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
The native driver runs one operation at a time, so a start that waits for
the camera to release its previous photo holds captureLock for as long as
that takes. An abort in that window could not take the lock and was simply
dropped: it reported SoftCancelRequested, NINA told the user the camera
would finish the frame, and nothing ever cancelled the capture.

That is the window where an abort matters most. Measured on the rig today
with the previous build: a 20s exposure aborted 6s in logged "the capture
lock could not be taken within 1000ms" while the driver reported "busy
with another operation" for the next 22 seconds; the capture was never
cancelled and all three frames afterwards were refused as "camera is
still busy".

Abort already records its intent on the request before it tries the lock,
so the fix is to honour that record where the lock is already held - at
the end of Start, once the native start has returned. The decision itself
moves into CancelUnderHeldLock so both callers make it the same way and
log the same lines.

AbortResult gains NativeCancelDeferred for that case, and the driver logs
it without the warning popup: the cancel is being delivered, just not
from the aborting thread, so telling the user the camera will finish the
exposure would be wrong.

AbortDuringBlockedNativeStartReturnsWithoutCallingNativeCancel asserted
the old behaviour. What still has to hold is that the abort returns inside
its timeout and does not reach into the driver while the start is in
flight, so it now asserts that and is named for it. The new test fails
against the old code with Cancels 0 instead of 1.

101 of 101 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
The deferred cancel was delivered and then declined. Measured on the rig
2026-11-03 with the previous build: the abort was correctly deferred at
16:33:17, the native start returned at 16:33:41 after 31 seconds in the
driver, and the status read at that moment said 0x0000 - Created - so the
"not busy, nothing to cancel" guard sent nothing. Six seconds later the
plugin logged "Camera reports a capture still running with nothing of
ours in flight" and all three frames afterwards were refused as "camera
is still busy".

Created is the one idle status that can be a lie. The driver does not move
a capture to Capturing until its worker picks it up, so a status read
taken immediately after our own native start can still say Created while
the shutter is already committed. Cancelled, Complete and Failed are not
ambiguous, and the deferred path still keeps its hands off those - as do
the unreadable and in-transfer guards, unchanged.

Two tests cover it: the Created case, which fails against the old code
with Cancels 0 instead of 1, and a theory over the three statuses that
must still be left alone.

Also fixes the two load-flaky tests, which my new tests pushed over the
edge from intermittent to frequent:

- CancellationAfterPollingBeginsInterruptsWaitWithoutAToken bounded a
  Task.Delay continuation at two seconds. It asserts that an abort
  interrupts the wait, not how fast, so the bound is now 30s.
- NativeCallsNeverOverlap fired twelve pool callers into Invoke, which
  blocks its caller while the work it queued needs a pool thread of its
  own. Twelve of them starve the pool they are waiting on, the pool
  injects roughly one thread a second, and the run reached Invoke's 30s
  timeout. The callers are dedicated threads now.

105 of 105 tests pass, four consecutive full-suite runs, and the suite
went from 7-31s to 2-5s.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
Cancelling a capture the driver still reports as Created takes NINA down.
Measured on the rig 2026-11-03: the deferred cancel went out at
16:56:07.50 with status 0x0000 and the process died in the same second -
SonyMTPCamera.dll 1.0.1.25, 0xc0000005 at offset 0x1fd79. The previous
commit was wrong to send it, and the guard it relaxed was load-bearing.

The driver's reason is in CancelCapture: it frees the capture task and
its parameters as soon as Cancel reports success, and while the status is
still Created the task has not started reading them. That is a defect in
the driver and is worth fixing there; this commit stops the plugin
walking into it.

So the deferred cancel now waits for the status to tell the truth and
then decides exactly as it always did - every guard back as it was. The
wait is bounded at ten seconds and ends the moment the capture appears,
and if it never appears nothing is sent. Blocking there is acceptable:
NINA has already abandoned the frame, and each status read is itself a
queued native call.

Both halves are covered: one test proves the wait finds a capture
announced on the third read and cancels it, the other proves a capture
that is never announced is never cancelled. Both fail without the wait.

106 of 106 tests pass, three consecutive full-suite runs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
Cancelling a capture does not close a shutter the camera has already
opened, and the shutter speed cannot be changed while it is open. So the
next capture's exposure-time change fails, the plugin refuses to shoot at
the wrong shutter - correctly - and that refusal leaves NINA believing an
exposure is still running, after which it drops every later capture
request without logging anything at all.

That is the whole of what was left after an abort. Measured on the rig
2026-11-03 with driver 1.0.1.26, which cancels cleanly: a 20s exposure
was cancelled 105ms after the shutter opened at 17:28:30.3, the next
frame was attempted at 17:28:38.6 and gave up at 17:28:51.5 reporting
"camera reports 0x00C8000A" - 20s, the shutter still open. The camera
freed itself around 17:28:50.3, one second before the attempt expired.
The two frames after it were never logged as starting.

So the next start now waits for the cancelled exposure to finish. The
bound is that exposure's own length, so it costs nothing that was not
already being spent, and only a cancel that was actually sent arms it: a
frame that ended by itself has already put its image down, and an abort
that sent nothing never interrupted anything.

The wait is reported on its own log line rather than the quiet gap's. Two
different reasons to wait that the log could not tell apart is what made
this fault take as long as it did.

The timestamp is taken after the native start returns, because that call
changes the exposure time first - walking the camera's shutter ladder
from 1/80 to 20s is about thirty seconds of stepping, and the exposure
only begins once it is done. That stepping is also what the deferred
abort has been waiting through all along.

109 of 109 tests pass. The new test fails without the wait.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
… latches

This is the gap that ended the night of 2026-11-03. At 23:23 an exposure
stopped announcing its image. The abort worked correctly, the sequence's
error behaviour is ContinueOnError, so NINA started another, which failed
the same way - every 50 seconds for twenty minutes. Around 23:44 a native
call finally exceeded NativeCallExecutor's 30s timeout, which latches the
driver dead for the rest of the process. After that the camera could not
even be enumerated, so a reconnect could no longer have recovered the
session even once the body came back.

Two changes, and the second matters more than the first.

A failed exposure now makes the next start reopen the camera first. A
close and reopen is the only recovery that has ever cleared this body: it
was done by hand three times on 2026-11-03 and worked every time,
including on a capture the camera was holding open. The swap happens
inside the connection lock, so NINA never sees the camera as
disconnected - a camera it believes has dropped ends the sequence, which
is the opposite of the point. It is attempted once per failed exposure
rather than in a loop, and a reopen that fails or throws still lets the
exposure run: it is an attempt, not a precondition.

After MaxConsecutiveCaptureFailures exposures in a row deliver nothing -
three by default - the plugin stops driving the camera at all. The frames
are lost either way; what this protects is the driver. Refusing makes no
native calls, so the executor cannot latch, and one reconnect at any
later time brings the whole session back instead of none of it.

An image coming off the camera is the only thing that clears the count,
which is why MarkCaptureSucceeded is separate from MarkImageRetrieved -
that one times the quiet gap and runs even when the retrieval threw.

NINA's download timeout and a user abort are indistinguishable at the
plugin's cancellation path, so both count. A user abort therefore costs
one reopen, which is harmless.

116 of 116 tests pass. Five of the new ones fail without this change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
Measured on the rig 2026-11-04, minutes after the previous commit. The
reopen itself worked exactly as designed:

  10:14:14  WaitUntilExposureIsReady cancelled
  10:14:30  Waited 12110ms for a cancelled exposure to finish
  10:14:32  Camera recovery: reopened the camera after 1 failed exposure(s)

and then the exposure that followed it never delivered an image:

  10:15:12  Camera Timeout - Camera did not set image as ready after
            exposuretime + 20 seconds

The same abort-then-reshoot, on the previous build without the reopen,
landed three frames out of three on two consecutive runs earlier the same
morning. So the reopen costs the frame it exists to save. Something about
a freshly reopened handle stops the next capture delivering - the plugin's
cached shutter ladder and camera settings belong to the old handle, which
is the first thing to check - and until that is understood this must not
run.

EnableCameraReopenOnFailure defaults to false. The code and its tests stay,
so the investigation has something to work from.

The failure cap is untouched and stays on. It is the half that cannot have
this problem, because refusing to start makes no native calls at all, and
it is the half that protects the driver from the 30s timeout that latched
it dead and made last night unrecoverable.

116 of 116 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
…ody tried

The cap as shipped was a trap rather than a guard. Only an image coming
off the camera cleared the count, and once the cap refused every start no
image could be taken, so the camera stayed refused until NINA restarted.
Measured on the rig 2026-11-04: the cap tripped at 10:31:29, a full
disconnect and reconnect followed at 10:34:44, and the next start was
still refused. The claim in the previous commit that one reconnect brings
the session back was simply false.

Connect now clears the count. A reconnect is the operator - or a recovery
trigger - saying try again, and it is also the only thing that has ever
cleared this body, so it gets a clean slate.

Also: a disabled reopen now reports nothing instead of "could not reopen
the camera", which read as a failed attempt when nothing was attempted.
The controller asks whether recovery is enabled before invoking the
callback rather than letting the callback answer false. That phrasing is
the same dishonest-status trap this plugin has spent the week removing.

118 of 118 tests pass. Note what they do and do not cover:
ResetFailureCount is tested directly, but nothing here proves Connect
calls it - CameraDriver needs NINA's services to construct, so that
wiring is verified on the rig, not in the suite.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
NINA died twice on the rig 2026-11-04 while connecting to a camera that
had stopped functioning - 11:57:56 and 12:09:40, both an access violation
inside coreclr.dll at the same fault offset 0x3596cf. An AV in the managed
runtime means the heap was already corrupt before the fault, and the
driver log says what the camera was doing at the time:

  Failed executing GetErrorValue (hr = x8007001f)      ERROR_GEN_FAILURE
  Unable to read WORD value as it would extend beyond end of data
  Unable to read DWORD value as it would extend beyond end of data
  Unable to read DWORD value as it would extend beyond end of data

GetPropertyList is where that becomes corruption. It is a size-then-fill
native call with three defects, all of which need the camera to answer
with nonsense before they matter:

  - (int)listSize * sizeof(UInt32) overflows for a large count, so the
    allocation can be far smaller than the copy that follows.
  - listSize is passed by reference to the second call as well, so the
    camera can report more than was allocated and Marshal.Copy runs off
    the end of the buffer.
  - the buffer leaks on both throw paths.

Now: the probed count is rejected above a generous bound, the second call
gets its own copy of the size so the allocation it is measured against
cannot change underneath, the copy is clamped to what was allocated, and
the free is in a finally. GetPropertyValueOptions gets the same bound,
because that loop is driven by a count from the camera too and can
otherwise fire millions of native calls at a device that is not
answering.

The bounds are 4096, which is two orders of magnitude above what an a7S
advertises. They exist to catch nonsense, not to constrain real hardware.

A camera in this state should fail to connect with a message naming the
cause. It should not take the host process down.

118 of 118 tests pass, though none of them reach this code: it P/Invokes
the DLL directly and there is no seam. Verification is on the rig, which
currently reproduces the crash deterministically.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
The executor shuts itself permanently when a native call times out, and the
driver shuts it too when the camera answers three native calls with errors.
Neither could be cleared. Every later call threw "the Sony driver stopped
responding" for the life of the process, so a camera that was demonstrably
back was still unreachable.

Measured on the rig on 20 November: the body returned to the USB bus at
01:22:06, NINA's own USB watcher logged it, and a connect at 01:24:15 was
refused in 34ms. The driver log was not written at all - no native call was
attempted. The night ended on a NINA restart.

This is the same shape as the capture failure cap, which refused every start
until a reconnect was taught to clear it.

The reason for the latch is real and is kept. A call that timed out was
abandoned, not cancelled: it is still running and still inside the DLL, and
letting a second caller in while it is there is how the driver corrupts
itself. So the abandoned call is now tracked, and TryResume is refused while
it has not returned. A stop with nothing abandoned - the consecutive-error
case, where every call returned - is cleared at once.

Connect asks for the resume before opening, and attempts the open either
way: when the resume is refused, the open's own exception carries the reason.
Resuming also drops the stale handle, because OpenCamera refuses while a
camera is still recorded as open, and no native call is made on this path -
the reopen is what talks to the device, inside its own bounded operation.

The user-facing message changes with the behaviour: reconnect first, restart
NINA only if that does not clear it.

Three tests: a stop with nothing abandoned resumes and calls work again; a
resume on a working executor changes nothing; a timed-out call refuses the
resume until it has returned, then allows it. The existing test that a
timeout blocks later calls even after the worker returns is unchanged and
still passes - clearing it takes an explicit resume.

121 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
The guard skipped its wait entirely whenever the exposure was at least as
long as the gap:

    if (exposureTime * 1000.0 >= required) {
        return;
    }

The reasoning was that such a frame had already given the camera that much
time. It had not. During an exposure the shutter is open, not resting, and
the curtain only rests between frames.

Measured on the rig 2026-11-20 17:07. 2s frames with the gap set to 2000ms
satisfied that test exactly, so no wait was ever logged and the frames ran
0.8-1.2s apart, image-off to next shutter release. The same body had stuck
its shutter curtain at a 3.15s turnaround twenty minutes earlier. Worse,
the rule never gated a long frame at all: the three 30s subs lost overnight
on 2026-11-19 - shutter pressed and released, frame never announced, driver
polling "Nothing yet" until the body left the bus - were exactly the frames
it exempted.

The wait already measures elapsed time since MarkImageRetrieved, so
removing the short-circuit charges only the shortfall. A 30s sub whose
turnaround is already 3s pays 3s to reach a 6s gap, not 6s - about 9% of
throughput, not the "seventh of the night" the old comment feared.

Also: onWaited now carries the gap the wait used instead of leaving the
logger to re-read the setting. The rig logged "Waited 3482ms before this
exposure: the previous one ended less than 2000ms ago" at 16:42:53, because
the setting was changed while the wait was running. The wait itself was
correct - required is read once - but the message named a value it never
used, which is misleading in precisely the situation that produces it.

Verification, all against this tree:

    CaptureController.Tests   122 passed, 0 failed
    Temperature.Tests          24 passed, 0 failed
    PluginIntegration.Tests    15 passed, 0 failed
    Release build              0 errors

Three existing tests asserted the behaviour removed here and are inverted,
with the rig measurements in their comments:

    AnExposureLongerThanTheGapIsNotDelayed
      -> AnExposureLongerThanTheGapStillWaits
    AnExposureExactlyTheLengthOfTheGapIsNotDelayed
      -> AnExposureExactlyTheLengthOfTheGapStillWaits
    ALongExposureIsStillNotDelayedOnceTheImageIsRetrieved
      -> ALongExposureWaitsOnlyTheShortfallOfTheGap

The second of those is the 2s-against-2000ms case from the rig. Added
TheReportedGapIsTheOneTheWaitUsed, which changes the setting from inside
the sleep and asserts that neither the wait nor the reported gap moves.

Not verified: nothing here has run against the camera. The behaviour change
is a wait that now happens where it previously did not, so the risk is
throughput rather than correctness, and the shortfall arithmetic is covered
by ALongExposureWaitsOnlyTheShortfallOfTheGap rather than by measurement on
the rig.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
The behaviour changed in the previous commit and both user-facing
descriptions still stated the rule that was removed:

  "Only exposures shorter than this wait are delayed, so light frames
   are unaffected."

That is now false - every frame is owed the gap - and it was the one
sentence a reader would use to decide what to set the value to. The pane
also timed the gap "after one exposure finishes", where it is measured
from the image finishing its download off the camera, several seconds
later on a 12.4MB frame.

Both now say that every frame waits and why - the shutter is open during
an exposure rather than resting - and that only the shortfall is charged,
so a frame whose own turnaround already exceeds the gap costs nothing.

Text only. Release build 0 errors, CaptureController.Tests 122 passed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VA3wkVae3G3PSxPpxioG9d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant