ByteTerrace/Puck / .claude/skills/rendering
rendering
VerifiedMaps Puck's SDF renderer and GPU code: mapCore, mesh bake, HLSL kernels, sdf-isa.hlsli, SdfOp, C#/HLSL layouts, world.shaders.reload, field scopes, GPU cost and occupancy. Sculpting: sdf-authoring.
references/runtime-contracts.md
View on GitHub# Render-graph runtime contracts
These five invariants govern the frame-graph runtime (`RenderGraphRuntime` and
its partials in `src/Puck.Shaders/Graph`, `ShaderPipelineRenderNode*.cs`, the
scheduling types in `src/Puck.Hosting/Graph`) and every package, producer and
host that feeds it. A change to the runtime keeps each one, and a review of such
a change hunts each one's violations. Each section states the rule, how the code
holds it, the laws that pin it, and where the code is weaker than the rule. The
mechanism detail stays in [Frame graphs](../../../../docs/reference/shaders.md#frame-graphs); this file
does not repeat it.
## 1. Image lifetime is leased per image and per reader
**Rule.** An image is disposed only after its owner has dropped it and every
submission that reads it has completed. Each reader holds its own lease from
the moment it binds the image until the fence of the submission that read it,
and each lease retires exactly once.
**How the code holds it.**
- An external or sampled image reaches a pass as a `GpuImageLease`
(`src/Puck.Hosting/GpuImageLease.cs`). A recording holds it in its frame
slot's `LeaseRetireList` (`Hold`, `MoveTo`, `RetireAll`), which retires it
after that slot's fence.
- A node's own published image (a `HeldResource` in
`ShaderPipelineRenderNode.Retirement.cs`) is disposed at the fence of the
submission made `RetirementLag` (2) submissions after it stopped being
published. A replaced graph is retired once the queue finishes the node's
latest submission, never through a device drain. `GpuRetirementQueue` keys those
objects on the node's submission count; `WaitSlot` advances its completed count
before a slot fence can be reused. Publications wait separately: an installed
borrowed owner can take over the exact allocation, or a displaced publication
waits for the reader lag or a completion notification held by the frame's final
submitter. Retired graphs never retain reusable fences. An instance a
reconfiguration retires, and the graph of an instance nothing names, wait for
the latest submission of the first frame rendered after they left, which the
frame's last submitter holds a notification for
(`RenderGraphRuntime.Retiring.cs`); an unnamed instance named again first
keeps its graph.
- At reconfiguration, a producer removed while a kept consumer still reads it
is held whole (`RetiredProducer`, counted in `RetiredProducers`) until the
consumer's replacement installs, and `ShaderPipelineRenderNode.HoldBinding`
holds a binding's lease.
**Laws.** `RenderGraphRuntimeLawTests.Leases`
(`ALeaseARecordingHoldsRetiresAfterItsFrameSlotsFence`),
`ShaderPipelineRenderNodeLawTests` (retirement and disposal counts),
`RenderGraphRuntimeLawTests.Reconfigure`.
**Where the code is weaker.** The runtime wraps owned images in `GpuImageLeases` and
leases each consumer, capture and display read (`RenderGraphRuntime.Leases.cs`). An
owner's retirement lag therefore does not replace reader lifetime protection. A node
used outside that runtime still needs its host to supply equivalent reader ownership.
`GpuImageLease.Retire` invokes its callback directly; table-issued leases use a generation
to reject repeated retirement, while other callbacks still depend on their holder's discipline.
**Violations to hunt.** An image disposed or overwritten while a submission
that reads it is pending: a paused or slow reader, a capture, the display after
present when no submission follows, a swapchain resize, device loss and
teardown order. A lease never retired: a frame slot whose submission is never
made, a cancelled capture, a reconfiguration in the middle of a capture. A
lease retired twice. A steady frame that allocates lease bookkeeping.
**A frame's submissions reach the queue as one batch.** `RenderGraphRuntime`
opens a batch around its renders (`IGpuQueueSubmitter.BeginBatch`,
`FlushBatch`). Both backends defer through one implementation,
`GpuSubmissionBatch<TEntry>` with its fences' shared states in
`GpuBatchedSubmissionFence`: the nodes' submissions reach the queue in one
`vkQueueSubmit` or one `ExecuteCommandLists`, and every fence they arm signals
only once the whole batch retires, so a lease, a retirement or a readback keyed
on a node's fence completes no earlier than the frame's last submission. Anything
that must see deferred work first splits the batch (the deferred work goes to the
queue and the batch stays open): a wait on a deferred fence, `SubmitAndWait`, the
device's wait for idle, an external wait on Direct3D 12, and every other native
queue operation (an upload, a readback, an export's signal, a release's drain,
presentation), which reads the queue through its one door:
`DirectXDeviceContext.CommandQueueHandle` or `VulkanLogicalDevice.GraphicsQueue`
and `PresentQueue` (a queue family alone is `GraphicsQueueFamilyIndex`, which
splits nothing). A new path that keeps its own copy of the queue gets around that
door. A batch owner whose submit failed before it was armed is abandoned, so its
fences report nothing outstanding instead of waiting on a signal nothing queued.
Direct3D 12 uses enhanced buffer barriers independent of decay, and its image
barriers take the caller-stated layout.
An alias of an abandoned, unarmed owner never reads or waits on that owner's
native fence. Disposing a deferred or armed fence first waits through the same
shared fence state, so disposal cannot announce completion ahead of GPU work or
free a signal a later split still needs. Device loss during disposal is retained
for aliases of that generation, rather than reported as successful completion.
`GpuSubmissionBatchLawTests` holds these failure and disposal interleavings;
the Direct3D 12 WARP and Vulkan recording-driver batch laws hold empty fenced
submissions and empty `SubmitAndWait` boundaries. The latter drains earlier work
on both backends, even with no new command buffers. An external wait whose fence
already reached its value is dropped before it can split anything
(`GpuExternalWait.IsReached`); `world.counters gpu.queue` names every split's
cause.
**A node's frame is one record job.** `ShaderPipelineRenderNode.RenderFrame` runs
`PrepareFrame` (the slot's fence wait, lease and region binding, the cadence
checkpoint), `RecordFrame` (the slot's lists) and `CommitFrame` (submission,
history commit, publication, readbacks, export completion). The slot's lists
belong to one recording from `BeginFrameCommands` until `SubmitCounted` hands
them over or `AbandonRecording` gives them up; every path that records into
them (a frame, a re-presented selection, a capture pin) passes those two doors,
and a second begin while one is active throws. A recording that fails before its
submission is abandoned: its open lists are ended (or their pool replaced) so
the slot's next begin can reset them, the cadence rolls back, the frame's held
leases retire unsampled, nothing is published or captured, and the instance is
refused with `LastRecordError` until a later recording commits. A device loss
still propagates to the host's recovery. `gpu.faults record <n>` fails the nth
recording partway through its list to exercise this.
**A package's shared frame work precedes every record job.** Once the frame is
scheduled, inside its batch and before any node renders, the runtime asks the
factory of every package pass of every scheduled render to prepare it
(`IRenderGraphPackageFactory.PrepareRender`, `RenderGraphRuntime.PackagesPrepareRenders`);
a render a held capture withholds is skipped. The SDF factories stage the
residency there (`SdfWorldResidency.Stage`): the frame's upload, including its
wait on the previous upload's fence, and the background pump after it. `Stage`
is the one place the upload is submitted, latched once a frame; recorders read
the staged tables through `SdfWorldResidency.Staged`, which stages and counts a
`late-stagings` (in `world.residency`) only for a residency the preparation did
not reach, such as a graph installed during the frame with a package the
schedule did not name. `render.record.packages-microseconds` times the
preparation apart from the jobs. The jobs still run serially on the frame
thread: the pipeline cache and the counting recorder share host state across
nodes, so recording on workers needs those made safe first
([the job system's R1](../../../../docs/plans/engine-job-system.md#6-build-order)).
## 2. Nothing resolves silently to nothing
**Rule.** A read, alias, package, source or capture that cannot be served
either refuses by name, with a code and a message naming the instance, pass,
input or producer, or binds a stand-in that is recorded and reported. It never
yields an empty, default or stale result that the frame presents as success.
**How the code holds it.**
- `RenderGraphInstanceSet.TryCreate` refuses an invalid set with a
`RenderGraphInstanceRefusal` whose code is a `RenderGraphInstanceRefusalCode`.
- `RenderGraphRuntime.TryReconfigure` refuses with a
`RenderGraphRuntimeRefusal` whose code is a `RenderGraphRuntimeRefusalCode`
(`GraphCount`, `Root`, `OutputKind`, `PackageUnserved`, `InputVersion`,
`InputProducer`, `InputKind`, `InputSize`, `ExternalProducer`,
`StandingChain`, `MutableInput`, `InputOutput`, `TransferInput`).
- At frame time, an image input whose producer has no output binds a
transparent-black stand-in (`RenderGraphRuntime.Bind`,
`RenderGraphRuntime.StandIns.cs`), recorded per instance. A capture waits on
that instance, and `RenderGraphRuntime.UnservedCaptureReasonOf` names the
producer. A buffer input with no output does not render.
- A package pass that draws nothing publishes its input in its output's place
only where that is sound; otherwise `ShaderPipelineRenderNode.AliasRefusalOf`
refuses it by name.
- A pipeline source with no stored package and no compiler is refused as
`SHADERPKG_ABSENT` (`ShaderSourceClosure`), beside the other `SHADERPKG_*`
codes.
- `SdfWorldResidency.NotReadyReason` names a pending build or a refused table
build.
**Laws.** `RenderGraphRuntimeLawTests.Lifetime`
(`ACaptureNoRootOutputServesIsRefusedByNameAndThenDropped`),
`RenderGraphRuntimeLawTests.Alias`
(`APassWhoseOutputAnotherPassReadsIsRefusedByNameWhenItDrawsNothing`,
`AnOutputCannotStandForAPreviousFrameInputAndIsRefusedByName`),
`RenderGraphRuntimeLawTests.UnboundReads`. The `pipeline-package` and
`no-device-compile` canaries that held it on the real World are quarantined
under `experimental/tests/Puck.World.Canaries` with every other canary.
**Violations to hunt.** A path that returns null, empty or a default handle and
lets the frame present; a stand-in bound without being recorded; a refusal
whose message omits the name a reader needs; a released or retired producer
whose readers still bind its last image; a package recorder that binds a buffer
port by its version name and leaves a name it does not map on the dummy. A
preserving forward version (`PreservesPredecessor`) reaches a recorder's
context under its storage root's name, not its own, so a recorder that maps
only the forward's name binds the dummy and reads zeros
(`SdfWorldPassRecorder.ReadMemberOf` maps both of the shade bins' names).
## 3. A capture's pixels are pinned or copied
**Rule.** A capture reads pixels that cannot change before its readback
completes: the image of the frame it was served from, held by the node that
rendered it until the readback finishes, or a copy into an image the capturing
node owns. A capture never reads a handle that a later frame of another
instance can overwrite.
**How the code holds it.** `ShaderPipelineRenderNode.CaptureIfPending` reads the
node's own last surface, which the node's retirement rule (§1) holds. The
runtime forwards a capture to a node only when the node is ready, the
instance read no stand-in or tainted input, and each same-frame input is current
under the completion rules (§4). An input still rebuilding holds the request;
a permanently refused input fails it by name. Paused and other deliberately
standing completed inputs remain eligible. A capture waits while a preview
builds, while the root has not yet presented at the requested extent
(`ShownAtItsExtent`), and while its readback encoder (`SurfaceEncoder`) builds. Both
rendered hosts hold their clock at an armed, unserved capture, and the scheduler
refuses it as `unserved` when the hold budget runs out (`WorldCaptureScheduler.BuildHoldBudgetSeconds`
while the world is not ready, `HoldBudgetSeconds` once it is). A root frame that drew
nothing captures its input version in that version's layout.
**Laws.** `WorldCaptureHoldLawTests`
(`NoTickIsSteppedWhileACaptureIsArmedAndUnservedOffscreen`),
`WorldPipelineResizedWaitLawTests`
(`AResizedWaitHoldsUntilTheGraphAtTheNewExtentInstallsPausedOrRunning`),
`RenderGraphRuntimeLawTests.RootCapture`,
`RenderGraphRuntimeLawTests.CompletionCapture`,
`RenderGraphRuntimeLawTests.UnboundReads`
(`ACaptureWaitsForAScheduledUnboundScreenReadToHaveAnOutput`),
`RenderGraphRuntimeLawTests.Alias`
(`ARootCaptureOfAFrameThatDrewNothingReadsTheInputVersionInItsLayout`).
A presented capture (`FrameCaptureMode.Presented`,
`RenderGraphRuntime.Presented.cs`) is the one capture no node serves: the
runtime keeps it, forwards it nowhere, begins no convergence and holds no
residency frame, and after each frame's renders and batch flush reads back the
captured instance's latest output resolved through what it stands for, the
image `ProduceFrame` hands the display, through that instance's node
(`ShaderPipelineRenderNode.TryReadPresented`). The readback waits for the GPU,
so the image cannot change under it. A frame on which `ReasonOf` names a reason
or the output is tainted is skipped, never read, and the burst's presentation
indices show the gap. It skips, besides, the renders retained state it had
discarded needs to converge again (one `SdfWorldPackage.TemporalPeriod`, below), so
the burst reads the steady image. It counts as pending (`PendingCapturePath`) until its
last PNG is written, so the capture gate fills, capture frames re-render
tainted instances and `world.wait captures` fences the files, but not as
holding (`HoldsPresentation`), so the presenter does not pin interpolation and
the capture scheduler holds no clock for it. A `CaptureRequestSlot` refuses to
arm one.
**Every capture can complete over retained external content.** Retained package
state can hold external pixels that no fill replaces by itself: a temporal
history blends what it read into every later render, and a lighting source
(the sky environment's projection, the screen emission's reduction) stands
until something records it again. On every capture frame of a capture still
to be served, settled or presented, before anything renders, the capture-frame
walk asks every package of every instance the capture reads to discard such
state (`IRenderGraphPackageFactory.DiscardTaintedState`,
`RenderGraphRuntime.DiscardCaptureTaint`): `SdfWorldPasses` resets tainted
history (§5) and has tainted lighting sources derived again from the fills on
their next recording (`SdfWorldTables.ProjectTaintedSourcesAgain`), which
stand reported as tainted until then. Because it runs every frame, taint that
comes back (a source a frame late, a reload, a lights change) is discarded
again rather than holding the capture. A read the capture frame cannot render
again is withheld instead (`RenderGraphRuntime.Withholds`): a previous-frame
read, and a read of an instance the frame does not render, such as a portal's
innermost level that nothing shown reaches and that its outer level reads only
as a screen source; on a capture frame its tainted latest output binds nothing
(a stand-in, or an unbound screen), so a stale image from before the capture
armed can hold no capture
(`RenderGraphRuntimeLawTests.ACaptureWithholdsAnUnrenderedTaintedScreenSourceAndCompletes`).
A capture still waiting names the state
in its reason (`IRenderGraphPackageFactory.TaintOf`, followed through the
instances that passed it on), so `world.wait ready` says what holds it. The SDF
package tells a views render that itself read external content this frame
(`the latest views render, which read …`, naming the lighting source or the
read instance) from history carrying an earlier read (`the temporal history,
which read …`): the first is a source the fills do not reach, which no discard
can cure, the second what the discard restarts. The glass fragment
(`SdfWorldPackage.WithGlass`) keeps the same taint and discard
(`SdfWorldPassesLawTests.ACaptureOfTheGlassFragmentDiscardsTaintedHistoryAndCompletes`).
`RenderGraphRuntime.OfferCaptureSource` offers an aliased output under its own
lease. A node serving it without rendering copies it before readback
(`ShaderPipelineRenderNode.CapturePin.cs`); a node that renders releases the
offer and captures its new output.
**Violations to hunt.** A capture served from an image a later frame
overwrites; a capture served at the wrong extent or from a frame of another
tick; a capture that waits forever on a condition no frame can clear.
## 4. Render completion is Rendered, NotYetRenderable or Refused
**Rule.** A frame's outcome is one of three. *Rendered*: the image shows this
frame's scheduled work. *Not yet renderable*: a condition that waiting ends,
such as a cold build or a pending upload. *Refused*: a condition no wait ends,
such as a refused package or build, a source that has ended, or a view with no
camera. A permanent condition is always refused, so a host that waits on "not
yet" never waits forever, and a refused frame names its reason.
**How the code holds it.** `IRenderRoot.ProduceFrame` returns a `RootFrame`: the
surface and a `FrameRender` whose `FrameCompletion` is `Rendered`,
`NotYetRenderable` or `Refused`, with a reason naming what waits or refused. The
runtime reads it from `RenderGraphRuntime.Render`: the root is rendered only
when it rendered and every instance it reads within the frame did too (a
previous-frame read, a refresh divisor, an unchanged view or a paused node
stands on purpose). `MarkUnproduced` (`RenderGraphRuntime.Completion.cs`) is the
one place a graph instance's refusal becomes `Refused` (a package's
`RefusalOf`, a refused build, a missing graph); every other unproduced instance
is waiting. A producer or an upload answers the same three ways
(`MarkProduction`), and a waiting or refused producer holds or refuses every
instance that reads it within the frame, up to the root. An external source
(`WorldImageFeedProducer`: a desktop capture, a camera, a probe) whose feed has
no image of its own therefore answers as its capture fill does
(`WorldCaptureGate.FillsFeed`), showing the fill instead, so a minimized or
closed window never holds the World's frame, readiness or captures; the fill
waits only while it converts. The offscreen host paces by `HostPacing.OneTickPerFrame` and
`FixedStepPump.TryStep`, steps the next tick only once the root reports the
frame rendered, and holds the tick (composing it again, stepping none) while it
is not yet renderable; a refused frame releases the tick. Both rendered hosts
also hold their clock at an armed, unserved capture.
**Laws.** `RenderGraphRuntimeLawTests.Completion`, `OffscreenTickPacingLawTests`,
`WorldCaptureHoldLawTests`,
`WorldCaptureFillLawTests.AnExternalSourceWithNoImageShowsItsFillAndNeverHoldsTheRoot` and `SdfPipelineBuildLivenessLawTests` (the pump never
blocks on pipeline creation).
**Where the code is weaker.** The classification is only as good as each
condition's classifier: a new condition that is permanent but reported as
waiting holds an offscreen tick, and an armed capture's hold budget is then the
only backstop. A change that adds a condition classifies it by whether a wait
can end it.
**Violations to hunt.** A permanent condition reported as waiting: a source
with no frames, a disabled view, a portal past its nesting limit, a world with
no camera, a capture feed that ended. A live external source, which may never
deliver a frame, answering anything but its fill's answer while it has no
image. A "rendered" result carrying an older
tick's image. Commands landing on a different tick when a host holds or
retries a frame.
## 5. History epochs reset only for unseen views, never for cadence gaps
**Rule.** Temporal history (accumulated samples, reprojected frames) resets when
its previous samples are wrong for this view: a cut, a binding change, an
output extent or reconstruction ceiling change, an enable or debug toggle, a pose the view did
not render, a view shown again after it went unseen, or samples holding external
content the capture gate did not fill when a capture must read the view (a
settled capture's convergence and a presented capture's discard, §3). A gap the view's
cadence scheduled (a refresh divisor, a standing consumer, a budget skip) is
continuity and never resets history.
Every render-graph history resource follows one successful-write rule. A
previous-frame read creates no writer demand, including a P11 self-reference.
A slot advances only when its writer records and submits successfully; a
failed or skipped write leaves the preceding history intact. Device loss
discards the ring and starts with no history. Publication and export remain
allowed, and a failure in an export handoff after submission keeps the
committed write. No consumer uses a private advancement mode.
**How the code holds it.** `SdfTemporalHistory` (`src/Puck.SdfVm`) continues
history while `Continues(epoch, previousPoses)` holds: the frame's
`SdfTemporalEpoch` (`Binding`, `Cut`, `Width`, `Height`, `Ceiling`, `Enabled`,
`Debug`, `Temporal`, `Unread`) equals the last one, and the previous poses are the ones the instance
last rendered. Any difference resets the epoch. A frame gap with an unchanged
epoch and unchanged poses continues it. `SdfWorldPasses.EpochOf` sets `Enabled`
while the view resolves temporally or a capture converges. The runtime counts
only frames outside displayed outputs, including held consumer outputs, in
`Unread`. A dynamic render-grid change restarts settling without discarding
the history ring. `ShaderPipelineRenderNode` reserves a ring instance for a
recording writer and commits its cursor at submission; its recovery restores
the existing access tracker on failure. `IRenderGraphPackageRecorder.Submitted`
commits the temporal sample metadata, and `SdfResolveRecorder` caches history
descriptors by their bound handles as well as their slot and tables.
`SdfWorldPasses` marks an instance's history tainted when a views render read
an unfilled external source or tainted history (`SubmittedTaint`), and
`DiscardTaintedState` resets only such history: a settled capture's
`BeginConvergence` and every capture frame call it (§3), and clean history
keeps its samples. The window shows the reset as one period of reconvergence
(a single-sample image refining over eight frames) of a view that had an
external screen in it, while that screen shows its capture fill.
**Laws.** `SdfWorldPassesLawTests.Temporal`, the runtime's convergence laws,
`RenderGraphRuntimeLawTests.RetainedCapture` and
`RenderGraphSchedulerLawTests.History`.
**Verification boundary.** CPU laws hold scheduling, cursor recovery and
submission callbacks on a fake device. Nothing automated holds the backend
recordings and pixels while the temporal and device-loss canaries are
quarantined and no parity world exists; a change here shows its backends'
captures.
**Violations to hunt.** History reset every refresh period by a divisor (the
view never converges); history kept across a cut, a crossing into another
residency, a resize, or a return to view; a counter that overflows or never
resets; a reconfiguration that loses or keeps the count wrongly.
Also hunt a history read that demands its writer, a cursor moved by a skipped
or refused submission, temporal metadata committed during recording, and a
cached descriptor that still names a submission slot's former history.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |