34 KiB
Fixed CUDA f32 matrix-vector requirements
Bounded requirements delta for served item STRA-140, parent STRA-102,
read fresh on 2026-10-08. Written against source revision
b9519f967af43514331e29e778bd2605d8e4b98b before implementation. The active MCP
item and project charter are the business/specification
authority; this file is the task's reviewable requirements artifact, not a second
project backlog or an assertion that implementation has passed qualification.
The bootstrap contract owns driver loading, platform, copy staging and resource ownership. The vector-add contract owns the existing fixed operation. STRA-140 adds one bounded fixed matvec action without changing either historical qualification receipt. Production remains independent of Python, Strata and a CUDA Toolkit runtime dependency.
Scope, actor and outcome
An internal engine developer explicitly enables cuda-driver, loads the driver,
creates a private context and supplies three owned device buffers and dimensions
to Context::matvec_f32. The matrix is contiguous row-major f32, the vector has
one value per column, and the output has one value per row. Success means the
attempted kernel completed and the caller's previous context was restored.
Using Context::matvec_f32, the developer can compute the recurrence below over
valid owned buffers, yielding a completed output or structured failure. Invalid
inputs must yield failure before any CUDA mutation. After uncertain completion
or restoration, future work on the context must yield refusal without native work.
This unit is an application/library deliverable with executable automated verification. It introduces no serving endpoint, deployment integration, model loader, inference, tensor view/stride, transposition, batching, quantization, arbitrary executable, caller stream or caller launch geometry. Default feature admission stays off. It establishes neither model compatibility nor a speed/SLO claim; the serial column recurrence is a correctness baseline.
FR-MATVEC-1 — exact shapes, bounds and ownership
The public interface takes an immutable matrix buffer, immutable vector buffer,
exclusive mutable output buffer, and host usize row/column dimensions. Dimensions
are checked before conversion to the private ABI; no truncating cast is allowed.
| Quantity | Required admission bound / meaning |
|---|---|
Rows M |
1 <= M <= u32::MAX (4,294,967,295) |
Columns N |
1 <= N <= u32::MAX (4,294,967,295) |
| Matrix elements | Checked M * N; product need not fit u32 |
| Matrix bytes | Checked 4 * M * N, exactly the matrix buffer length |
| Vector bytes | Checked 4 * N, exactly the vector buffer length |
| Output bytes | Checked 4 * M, exactly the output buffer length |
| Every byte length | Nonzero, fits host usize, and <= isize::MAX |
| Allocation capacity | Existing context byte budget bounds actual live allocations; matvec allocates no device buffer implicitly |
| Launch | Fixed block (128, 1, 1); checked grid.x = ceil(M / 128), 1 <= grid.x <= i32::MAX; grid y/z one |
| Addressing | 64-bit row/index/byte offsets; checked allocation address ranges cannot wrap |
These are representation and ownership limits, not a promise that the GPU has
enough memory or will admit the fixed launch. On Linux64 the matrix constraint
is M * N <= floor(isize::MAX / 4) = 2,305,843,009,213,693,951 elements,
further restricted by actual owned allocation sizes and the caller's context
budget. The three buffers normally require 4 * (M*N + N + M) live bytes,
alongside other context allocations. When the two inputs share one allocation,
charge that allocation once, as the existing allocation accounting does.
The safe API currently exposes only whole owned allocations: DeviceBuffer::len
is an exact byte length, with no distinct logical length, spare capacity,
subslice, offset view, cloned handle or raw/imported pointer API. Consequently an
oversized buffer is invalid even if it could contain the requested tensor.
Check each expected byte length for exact equality; do not accept a prefix.
Also reject odd/nonmultiple-four lengths. Shape and overflow refusal must be
possible without allocating a giant test buffer or executing CUDA.
Both inputs and output must belong to this exact Context instance. Equal device
ordinals or separate contexts on the same device do not suffice. Reject poisoned
contexts and absent/released resource handles before push/load/lookup/launch.
No validation refusal changes output bytes, allocation accounting or cache state.
Output alias contract
Inputs may share the same immutable allocation when exact shape checks permit
it; for whole buffers that means M = 1. A caller may reuse an output allocation
between completed calls, but output must be a distinct allocation from both
inputs during each call. Rust's immutable input and exclusive mutable output
borrows prevent a safe caller from passing the same buffer as input and output.
Defensively reject equality of output/input device allocation identities before
native mutation, matching the existing vector-add check. Do not create a public
unsafe bypass to test that defense.
Distinct valid live whole allocations from the same CUDA allocator do not overlap. The present API therefore needs no tensor-view overlap semantics. A future imported pointer or view API would require a separately specified range overlap contract before it could consume this operation. Validate non-wrapping address extents in the private boundary so arithmetic does not rely on silent u64 wrapping; invalid synthetic address extents must never be launched. Private alias tests exercise allocation-identity refusal; they do not invent a public view/import facility.
FR-MATVEC-2 — deterministic arithmetic and access
For every row r = 0 .. M-1, define binary32 recurrence:
s = +0.0_f32
for c = 0 .. N-1 in ascending order:
p = round_nearest_even_f32(matrix[r*N + c] * vector[c])
s = round_nearest_even_f32(s + p)
output[r] = s
Use a separate mul.rn.f32 followed by add.rn.f32 for every column. No FMA,
floating-point MAD, reassociation, parallel/warp/tree reduction, approximate
operation, saturation, .ftz, or f64 accumulator may replace this recurrence.
The accumulator starts at positive zero, including for N = 1; it does not
initialize from the first product. All f32 bit patterns are valid inputs.
Signed zeros, subnormals, overflow and infinities follow these operations. NaN
results are compared by classification; NaN payload and sign are not guaranteed.
The arithmetic follows NVIDIA's archived PTX definitions for multiply and add. Explicit rounding modifiers preserve the required separate operation semantics; assembler acceptance alone does not demonstrate installed-driver execution.
One thread owns one row, checks r < M before any memory access, loops columns
in order and stores output once after the last addition. Other threads may
process other rows independently. Compute r, r*N+c and scaled offsets with
64-bit arithmetic, including threads in the last partial block. The loop must
terminate correctly at N = u32::MAX; increments and comparisons may not wrap
into another iteration. Matrix/vector are never written. Threads beyond M
perform no read or write. No atomics, shared-memory reductions, external symbols
or indirect calls participate.
FR-MATVEC-3 — trusted executable and fixed launch ABI
Embed one bounded NUL-terminated matvec PTX image containing exactly the fixed
matvec entry leleka_matvec_f32. Preserve the existing image's PTX 7.0,
sm_75, and .address_size 64 baseline; incompatible driver/target combinations
return explicit failures. No fallback or external PTX lookup is allowed.
The private kernelParams table has five entries, in this order:
| Position | Value stored in owned host argument storage | ABI width |
|---|---|---|
| 0 | Matrix device allocation address | u64 |
| 1 | Vector device allocation address | u64 |
| 2 | Output device allocation address | u64 |
| 3 | Rows M |
u32 |
| 4 | Columns N |
u32 |
Each table entry points to its typed host scalar, not directly to a device
address interpreted as a host pointer. Shared bytes are zero; stream and
extra are null. Geometry comes only from FR-MATVEC-1. The existing fixed
16-symbol loader suffices; no new driver symbol, caller executable/name,
function/module handle, callback or launch option enters the public API.
Cache only a fully loaded/validated matvec module and non-null function under its owner context. Repeated successful calls reuse that cache; separate contexts never share it. The matvec cache adds at most one usable module/function per context. It must coexist with the existing vector-add cache without replacing, misidentifying or invalidating vector-add's function. Cache topology and shared cleanup integration require the ARCH decision below before implementation.
FR-MATVEC-4 — completion, argument lifetime and faults
Create and stabilize all scalar storage and its five-entry pointer table before CUDA mutation. Maintain the existing raw-owned stable allocation discipline: moving the argument owner must not move or retag referenced storage. No caller host pointer is retained. Scalars/table stay live through mandatory completion.
Push the owned context, check load/lookup and non-null success handles, attempt the launch once, then synchronize after every attempted launch, even a launch returning failure. Preserve primary and subsequent sync/pop errors in operation order. Load/lookup failure does not count as an attempted launch. After every successful push, attempt pop and verify it popped the owned handle.
Return success only when launch, synchronization and restoration all succeed. After native execution failure, output is unspecified and cannot be presented as a successfully computed result. A launch failure followed by successful sync and restoration follows existing policy; it does not by itself imply poisoning. Never retry a failed launch automatically.
Failed sync makes completion uncertain: poison the context, permanently retain all potentially referenced host argument storage, keep buffers/module contained by the context, and refuse future allocate/copy/sync/kernel work without native calls. Do not reclaim retained argument storage merely because a later destroy succeeds. A failed or mismatched pop likewise poisons the context; successful sync alone cannot justify a success result after restoration failure. Existing copy staging and thread/borrow safety remain part of the contract.
FR-MATVEC-5 — cache cleanup and teardown
On lookup failure after load, consume the local usable module handle before its single unload attempt in the owned current context. Preserve lookup, unload and pop failures in order. Failed unload poisons the context; no retry, cache publication, handle reuse or healthy cache reinitialization is allowed.
Healthy teardown unloads each usable owned fixed module at most once after work completed, before context destruction. Pending/uncertain work or a poisoned context must never be followed by explicit module unload or buffer free. Any unload/restoration failure must suppress further unsafe cleanup mutations; context destruction remains the final containment attempt. Explicit fallible close reports errors; drop stays best effort and nonpanicking. Failed destroy retains the loaded library. Permanently failed driver cleanup is not a cleanup success; repeated poisoned contexts may accumulate resources, so this unit cannot claim process-wide recovery or bounded serving memory.
Security and non-functional acceptance
| Dimension | Metric / threshold | Verification |
|---|---|---|
| Critical usability | One typed synchronous operation, structured failure, no public raw launch surface | API/source review and synthetic caller |
| Reliability / performance | Success requires launch+sync+restoration; zero automatic retries; one mandatory completion sync per attempted launch; no latency/throughput assertion | ABI and fault traces |
| Capacity / concurrency | Checked bounds above; whole allocations within context budget; creating thread only; at most one additional usable matvec cache/context | Boundary, accounting, cache and compile gates |
| Security / tenancy | In-process context isolation; no network/tenant admission is introduced; zero foreign-context/aliased-output launches; only private fixed executable | Ownership, adversarial alias and ABI review |
| Audit / retention | Only synthetic fixtures; generated traces/artifacts outside Git; record exact source/tool identities and cleanup | Artifact and tracked-file inspection |
| Observability | Fixed operation names and driver codes; preserve primary/cleanup order; errors disclose no pointer/PTX dumps | Error assertions/review |
| Accessibility / i18n | No UI surface or new locale; structured errors remain available to the existing caller | Public-surface review |
| Rate / admission | Synchronous operation on one owning thread with the existing byte budget; no process recovery/rate SLA | API, budget and poison checks |
| Deploy / rollback | Existing opt-in default off; no production consumer or new runtime dependency; caller can omit the new operation | Feature/dependency/consumer inspection |
| Support | Load/lookup/launch/sync/cleanup failures diagnosable; no new production SLA | Fault matrix and documented residuals |
| AI dependence | Zero model/LLM calls in this operation | Consumer/source inspection |
| Integrity / consistency | Inputs unchanged; exact recurrence; no success for partial/uncertain output; only bounded fixed cache persists | Oracle, canary and trace checks |
| Backup / recovery | No durable data created; uncertain teardown retained/reported, never claimed recovered | Fault/source review |
| Privacy | No PII/model/request data in committed fixtures or gate evidence | Fixture/artifact review |
| Maintainability | Existing 16-symbol ABI; bounded fixed matvec module; no new normal dependency | Source/ABI/dependency review |
| Compatibility | Linux64 explicit opt-in; preserve bootstrap/vector-add and ownership behavior; static-musl loader stays unqualified | Existing regression and platform gates |
| Cost / efficiency | CPU-only fixture and offline assembly for this unit; no GPU/device/driver/model access | Recorded container guards and commands |
Acceptance mapping and planned verification
Expected values come from this recurrence, independently recorded fixtures and the official ABI, not from wrapper code or PTX parsing. The fake driver witnesses host argument/dataflow and cleanup; it does not execute PTX. The mock's arithmetic and oracle must have contraction/reassociation disabled and establish binary32 rounding at each multiply and add; a tolerant f64 dot product is not the oracle. Declare zero finite-bit tolerance against this reference before verification; compare signed zero bits and non-finite classifications, excluding NaN payloads.
| Served acceptance criterion | Requirement(s) | Required positive and adversarial evidence |
|---|---|---|
| AC-1: checked typed operation | FR-MATVEC-1 | Exact shapes, rectangular matrix and whole-allocation ownership; zero M/N; each dimension u32 max/max+1; checked product/scaling/isize/address/grid bounds; one-byte short/long and nonmultiple4 lengths for each buffer; foreign context on same device; output aliases each input; accepted immutable same-input case M=1; poisoned/refused handles. Refusals produce zero new CUDA trace entries and unchanged accounting/output/cache. Giant limits use pure/private admission instruments, not giant allocations. |
| AC-2: trusted executable | FR-MATVEC-3, FR-MATVEC-5 | Exact PTX bytes/hash and entry; five argument widths/order/values; fixed grid/block/shared/stream/extra; cache reuse and separate contexts; interleave matvec/vector-add; missing fixed symbols fail pre-init; no public arbitrary PTX/name/geometry API. |
| AC-3: column order and separate rounding | FR-MATVEC-2 | Distinct rows/columns detect transpose/stride errors; M=1 and N=1; M=127/128/129 and larger partial block; varying N; input/canary preservation; independent order/FMA-sensitive fixtures; PTX instruction/control-flow inspection plus pinned offline assembly and inspectable emitted instruction evidence. |
| AC-4: lifetime and poison/cleanup | FR-MATVEC-4, FR-MATVEC-5 | Delayed mock reads retained five-argument table/scalars at sync and containment after failed sync, with allocator churn; push/load/lookup/null-success/launch/sync/pop/wrong-pop/unload/destroy faults; launch+sync+pop and lookup+unload combinations; no unload/free while pending; no retry/reuse; preserved error order; healthy unload before destroy and one unload attempt per module. |
| AC-5: CPU and GPU-hidden gates | All | Preserve existing bootstrap/vector-add mock, default/platform, thread/lifetime compile, format and enabled-FFI lint gates; run new ABI/oracle/boundary/fault checks in disposable Linux CPU fixture; pinned offline PTX assembly with no installed driver calls or exposed GPU/device. Report actual counts and receipts; no GPU/model/quality/speed inference. |
Arithmetic adversaries must include the row [2^24, 1, -2^24] with all-one
vector (ascending recurrence yields positive zero; a reordered sum can yield
one), and row [-1, 1+2^-23] with vector [1, 1-2^-23] (separate rounding yields
positive zero; fusing the second multiply/add yields -2^-46). Add signed-zero,
subnormal, ties, overflow, infinity and NaN-classification fixtures. These are
fixture expectations, not measured GPU results.
The offline gate must record exact PTX (including its embedded NUL) and assembler output hashes, pinned image/tool version, target/flags, full argv, source/commit, host/container architecture, environment/device guards, test counts, exit codes, and cleanup. Inspect executable instructions/control flow, not comments or the mere presence of opcode substrings. Establish the ascending loop and separate multiply/add/no FMA in the recorded offline artifact; its claim is limited to that tool/target. Installed-driver JIT/numerical execution remains separate. Keep generated artifacts out of Git and remove only owned disposable resources.
sequenceDiagram
participant Caller as Internal caller
participant Context as Owned Rust context
participant Driver as Fixed Driver ABI
Caller->>Context: matvec_f32(matrix, vector, output, M, N)
Context->>Context: Validate shape, ownership, alias, poison and bounds
alt Validation refusal
Context-->>Caller: Structured error, no CUDA mutation
else Valid
Context->>Context: Own stable five-argument storage
Context->>Driver: Push owned context
Driver-->>Context: Push result
alt Push failure
Context-->>Caller: Structured push error, no launch
else Owned context entered
opt Cache absent
Context->>Driver: Load trusted matvec, look up fixed entry
Driver-->>Context: Handles or load/lookup failure
end
alt Kernel available
Context->>Driver: Attempt fixed launch once
Driver-->>Context: Launch result
Context->>Driver: Mandatory synchronize, including launch error
Driver-->>Context: Completion result
opt Completion uncertain
Context->>Context: Poison and retain referenced storage/resources
end
else No kernel
Context->>Driver: Single safe partial-module cleanup if needed
end
Context->>Driver: Pop, verify owned handle
Driver-->>Context: Restoration result
Context-->>Caller: Success only if launch, sync and restoration succeeded
end
end
Lifecycle and architecture inputs
Design need: architectural. The new public buffer operation crosses the safe
Rust ownership/validation boundary into private FFI and fixed executable code,
and adds a second fixed-kernel lifetime under the existing context poison and
teardown state. This classification comes from served AC-2/AC-4 and the existing
Context::kernel, fixed_kernel, unload_kernel, LaunchArguments and
DeviceBuffer source at the pinned revision. It requires an ARCH pass before DEV.
This BA artifact does not select cache topology or author an architecture option
matrix.
ARCH must confirm the single-thread-per-row, ascending-column mapping and checked u64 addresses meet the caps; five stable host arguments preserve raw ownership; matvec and vector-add retain distinct function identities; the additional cache stays bounded; and an unload/pop fault while tearing down either operation prevents unsafe subsequent unload/free while preserving final destruction/error reporting. Return any incompatible requirement for refinement before code changes.
BA has resolved the served row/column and output-alias questions from the fixed u32 launch convention and exact whole-buffer ownership surface, with overflow checks above. No user clarification remains for those routine constraints. Architecture confirmation remains outstanding. No new business-rule conflict was found with the referenced bootstrap/vector-add/charter invariants.
Lifecycle inputs for root coordination: clarification deliverable is this contract; design needs the ARCH decision; backend deliverable is the bounded typed operation and private PTX/FFI integration; testing deliverable is executable automated CPU and offline assembly evidence. No frontend, visual-composition, marketing or deployment/runtime-operation artifact is requested. Those scope observations are not lifecycle waivers or stage closures; root records applicable stages and gate evidence through the active served process. Existing task estimates are not re-estimated by this BA unit.
No active host-local .leasevibe.yaml pointer was supplied and none is present in
this worktree; host settings are unavailable, never inferred or copied. Root
owns coordination records. This BA unit writes only this file, performs no build,
test suite, assembly, GPU, inference, server, commit or publication operation,
and reports no implementation gate as passed. Static-musl loading, installed
driver/JIT execution, whole-model quality/protocol and paired performance remain
the separate qualification boundaries named in the foundation contracts.
Standing Defaults (§0.10): report honestly, do not cut corners, follow applicable rules, continue the authorized backlog through root coordination, and be concise.
Architecture decision
Status: selected for implementation. This decision is bounded to STRA-140 at
b9519f967af43514331e29e778bd2605d8e4b98b. The user authorized completion and
autonomous routine implementation choices; root confirmed that authorization for
these reversible local seams. It selects no new technology, serving topology or
model scope. FR-MATVEC-1 through FR-MATVEC-5 remain the governing contract.
Drivers and alternatives
Workload archetype: synchronous, explicitly enabled, single-thread-owned numerical library operation. RPS, latency SLO and production recovery are unspecified because this unit has no serving consumer or throughput claim.
| Driver | Evidence / constraint | Design consequence |
|---|---|---|
| Correctness and completion | Charter priorities; FR-MATVEC-2/-4 | Serial ascending recurrence and mandatory completion before success |
| Capacity / concurrency | FR-MATVEC-1/-3; existing Context and Rc ownership |
Two bounded fixed caches per context, creating thread only |
| Isolation and operability | Existing enter, CurrentGuard, combine, destroy |
One context poison state; ordered fallible cleanup and final containment |
| Cost / deployment | Existing cuda-driver opt-in, fixed16 ABI and libc dependency |
No new runtime dependency or installed Toolkit requirement |
| Data / organization | Three transient owned buffers; existing Rust/FFI boundary | Data Model: N/A for this operation; no durable state, UI or new team/process boundary |
| Option | Workload / scale | Latency / cold load | Operations / cost | Debugging / readiness | Isolation | Portability / lock-in |
|---|---|---|---|---|---|---|
| A: two named cache slots, closed private operation selector | Exact two-operation bound | Each image loads once on first valid use | Two modules maximum; existing cleanup machinery | Distinct identities, localized source changes | Context owns both; shared poison | Existing Driver/PTX limits only |
| B: one combined image and two functions | Bounded, but couples existing operation to new image | One module load; matvec bytes load for vector-add callers | One unload, broader regression surface | Changes historical vector-add image identity | Same owner and poison | Same Driver/PTX limits |
| C: replaceable single cache or generic kernel registry | Replacement causes reload; registry adds unnecessary growth policy | Reloads or generalized lookup | More invalidation/ownership policy | More state and generic dispatch to audit | Requires extra eviction/lifetime rules | Encourages a future arbitrary executable surface |
- A pros: preserves vector-add executable identity, isolates lazy initialization, and makes the two-module bound explicit. Cons: cleanup must sequence two slots.
- B pros: one module lifecycle. Cons: changes the already qualified image and couples vector-add admission to matvec loading; rejected for this bounded delta.
- C pros: replacement can cap one module, and a registry can accommodate future operations. Cons: adds reloads or speculative generality; rejected because the requirements need coexistence of exactly two trusted operations.
Architecture Decision: A. Architecture Alternatives Considered: B and C with the rejection reasons above. The architecture-strategy user-decision step is satisfied by the existing implementation authorization confirmed by root; there is no new unresolved external architecture choice to request.
Selected source seams and invariants
In crates/cuda-driver/src/lib.rs, retain FixedKernel and introduce two named
Cell<Option<FixedKernel>> slots for vector-add and matvec. A private closed
FixedOperation enum selects only those slots and their trusted FFI bindings.
It carries no caller bytes, names, handles or launch options. Publish a slot only
after module load and non-null function lookup both succeed. Cache reuse is
per-operation and per-context; no process/global map or eviction is introduced.
Keep safe validation and orchestration in lib.rs; all raw pointer handling
stays in ffi.rs. Add a pure checked matvec shape helper producing three expected
byte lengths, ABI rows/columns and row grid. Require exact buffer lengths and
exact context identity, live context/buffer handles, and output allocation
inequality before native calls. Use checked dimensions/product/scaling and
valid_size; compute ceil(M/128) in u64 before bounded conversion. Add a private
FFI extent check using checked u64 base-plus-byte-length for each live buffer;
synthetic wraparound refuses before enter. Inputs sharing the same whole
allocation remain valid when M=1. A structured matvec shape/range error may be
added; ownership, alias and poison errors retain their existing meanings and
driver errors retain operation/code and combine ordering.
In ffi.rs, embed matvec.ptx with a final NUL alongside the unchanged vector-add
image. The closed selector matches each image and fixed C entry name explicitly.
Extend both enabled and unsupported API implementations consistently; keep the
existing sixteen symbol resolutions and their pre-init missing-symbol behavior.
Keep vector-add's four-argument launch unchanged; add a private matvec launch
with the same fixed geometry/shared/stream/extra policy and five-argument owner.
Do not introduce a public or crate-generic raw parameter launch interface.
Matvec argument storage contains three u64 addresses, two separate u32 scalars
(rows, columns), and five host parameter pointers. Convert its allocation with
Box::into_raw before forming field pointers using raw projections; its moving
owner contains only NonNull and never recreates a reference to the whole
allocation while the pointers are live. Populate every scalar/table entry before
enter. Reconstruct the Box exactly once before any launch or after successful
sync; on failed sync permanently forget the owner, including its pointer table.
Moving the owner or borrowing the owner for launch must not move/retag the
storage. A later successful destroy never reclaims forgotten arguments.
matvec.ptx uses the fixed five-entry ABI and PTX7.0/sm_75/address64 baseline.
Compute row as wide block-index times 128 plus widened thread-index, guard row
against widened M before memory access, and use u64 for N, column counter,
row*N+column and byte offsets. A u64 counter allows N=u32::MAX to terminate
without wrap. Begin with positive-zero bits, issue separate mul.rn.f32 then
add.rn.f32 for each ascending column, and store once. This is a correctness
baseline; neither source shape nor offline assembler acceptance proves installed
driver execution or performance.
Both operations use the same poisoned cell and CurrentGuard. After an attempted
launch, synchronize exactly once even on launch error, then attempt and verify
pop after every successful push. Compose launch, sync and pop errors in that
order. Lookup failure consumes its local module before one unload attempt;
unload failure poisons the shared context, and no partial cache is published.
Load/lookup failure has no launch sync. No automatic launch or unload retry occurs.
Refactor unload_kernel into a bounded slot-cleanup helper and sequential
unload_kernels: vector-add slot first, then matvec slot. Each helper consumes
its usable slot before an unload attempt, checks shared poison before push,
unloads only with the owned context current, then finishes the guard. A push,
unload, failed pop or wrong-pop failure poisons the context before another slot
can mutate CUDA. Thus failure in the first cleanup suppresses second unload;
failure in the second still suppresses later explicit frees. A poisoned slot is
only discarded as a usable Rust handle; its native resource remains contained
by the context. destroy always performs the final owned non-current context
destruction attempt and preserves earlier cleanup errors; failed destroy retains
the library. Existing buffer free admission through enter supplies the shared
poison defense. Drop stays nonpanicking. This is containment, not recovery.
The level above this change comprises typed owned resources in lib.rs, private
Driver bindings and argument ownership in ffi.rs, and trusted executable bytes
in PTX; Context orchestrates those boundaries. This change belongs inside those
existing units because they own shape admission, module lifetime and completion.
A serving/model layer or public general kernel executor would be appropriate
only if separately authorized consumer/launch contracts existed; neither does.
No durable-state capability or persistence-layer change is introduced.
Handoff and revisit conditions
Required DEV paths are crates/cuda-driver/src/lib.rs (API, checked admission,
cache and teardown, inline pure boundary tests), crates/cuda-driver/src/ffi.rs
(closed fixed bindings, extent validation and argument ownership, inline private
tests), new crates/cuda-driver/src/matvec.ptx, and
scripts/test-cuda-fixed-ptx.sh (extend existing pinned offline gate, including
inspectable instruction/control-flow evidence). Automated fixture integration
belongs to the separately routed test owner in existing
crates/cuda-driver/tests/mock_cuda.c,
crates/cuda-driver/tests/mock_driver.rs and
scripts/test-cuda-driver-bootstrap.sh; this decision does not transfer its claim.
No DevOps/IaC work, dependency, CI topology or new child task is implied.
FR-MATVEC acceptance cases remain mandatory. In addition to shape/rounding cases, the cross-operation witnesses must interleave add/matvec/add and matvec/add/matvec, prove distinct function/module identity and one lazy load per slot, and inject each slot's unload/pop failure with both caches populated. After any poison, attempt the other operation, allocation, copy, sync and releases: none may call CUDA. Delayed mock reads must dereference all five arguments at sync and pending containment after owner movement/allocator churn; no unload/free may precede uncertain completion. Pure boundary tests cover address wrap and giant geometry without allocating giant buffers. The independent oracle retains zero finite-bit tolerance, signed-zero bits and non-finite classification limits declared above.
The safe Rust to private native execution crossing merits §809 review; root records the canonical served threat-model artifact before DESIGN closes, using the trust-boundary input returned with this decision. No committed threat-model copy substitutes for that served carrier. LIGHT/FULL, implementation and GPU gates remain root-coordinated; this section reports no such gate as passed.
Revisit only when a separately specified third fixed operation needs generalized reuse, asynchronous completion is introduced, or views/imported pointers create range overlap. First specify its admission/ownership/cleanup contract, then extend or replace these seams under a new decision and qualification gates. Rollback for this unit is omission of the new API/image changes and restoration of the existing vector-add cache path; no stored data migration is needed. Screened companion decisions (argument layout, u64 counter, fixed teardown order) are reversible local choices or directly required by FR-MATVEC, so none satisfies all three grounds for an additional durable ADR. No BA correction is required; installed-driver/JIT, static-musl loading, model quality and paired performance remain separately qualified boundaries. No implementation ambiguity remains.