--- /dev/null
+:PROPERTIES:
+:CUSTOM_ID: scheduler-specification
+:END:
+#+SETUPFILE: ~/.emacs.d/org-styles/html/darksun.theme
+#+TITLE: GI Scheduler Specification - Aukio 3D
+#+LANGUAGE: en
+#+LATEX_HEADER: \usepackage[margin=1.0in]{geometry}
+#+LATEX_HEADER: \usepackage{parskip}
+#+LATEX_HEADER: \usepackage[none]{hyphenat}
+
+#+OPTIONS: H:20 num:20
+#+OPTIONS: author:nil
+
+#+HTML_HEAD: <link rel="stylesheet" href="../../style.css"/>
+
+[[file:../index.html#outline-container-progressive-gi][<- Back to Global illumination]]
+
+* Why this page
+:PROPERTIES:
+:CUSTOM_ID: why-this-page
+:END:
+
+The parent page describes /what/ the progressive bake computes. This
+page specifies /how the scheduler behaves concurrently/ — what happens
+when the camera moves mid-bake, when in-flight work is abandoned, and
+which interleavings of workers, barriers, snapshot rebuilds and
+catch-up are legal — and checks that specification mechanically with
+TLA+/TLC. It assumes basic TLA+ literacy (states, actions, invariants,
+fairness, PlusCal).
+
+The trigger: the prose contract in the parent page leaves these
+questions open, and the implementation currently answers them
+implicitly (for example: the work queue is sorted near-to-far once at
+snapshot build and never re-sorted, so a fast-moving camera leaves
+workers chewing a stale order). Our GI bug history is a list of
+interleaving bugs found empirically — =inFlight= decremented negative,
+catch-up racing =Lightmap.refine()=, stale-phase graduations. Each of
+those is a counterexample trace TLC prints in seconds once the model
+exists.
+
+The discipline this buys us: *anything not written in the spec is not
+specified.* Every "what happens when the user moves during stage 3?"
+must become an explicit action in the model — the loose ends in the
+parent page are, literally, missing actions.
+
+Scope cut: the model covers scheduling state in
+[[file:../../../src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/GlobalIllumination.java][GlobalIllumination]]
+— stages, queues, cursors, barriers, eligibility masks, snapshot
+epochs, catch-up. It does NOT model radiometry, rays, or convergence
+thresholds; those are numeric properties for the probe harnesses.
+
+* What we model
+:PROPERTIES:
+:CUSTOM_ID: what-we-model
+:END:
+
+The art of TLA+ modeling is choosing what to leave out. TLC explores
+ALL behaviors, so a small faithful skeleton beats a large detailed
+one: interleaving bugs already show up with 2 workers and a handful of
+entries, and growing the instance mostly adds hours.
+
+*In the model:*
+
+| Model element | Java counterpart |
+|--------------------------------------------+-----------------------------------------|
+| 2 fair worker processes | =e3d-gi-*= threads |
+| 4–6 abstract entries | lightmapped triangles / block triangles |
+| =gen= counter, queue, =cursor=, =inFlight= | the generation bake loop |
+| =eligible= mask per entry | =TriangleBvh.Entry.eligibleStages= |
+| environment process | camera movement, geometry/light changes |
+| =snap= epoch + rebuild flag | snapshot rebuild single-flight |
+| catch-up queue | =catchUpQueue= + =runCatchUp= |
+
+*Out of the model, replaced by nondeterminism or nothing:*
+
+- *Rays and radiometry.* "Processing an entry" is just
+ =done[e] := gen=. No light is computed.
+- *Convergence.* "Mean delta below threshold" becomes
+ =either terminate or run another generation= — TLC checks BOTH
+ outcomes, so the spec covers every possible convergence timing.
+- *Real time.* =minRebuildMs= and the 500 ms composite cadence become
+ ordering constraints only ("at most one rebuild in flight"), not
+ milliseconds.
+- *The JVM memory model.* PlusCal steps are atomic and see the latest
+ values; volatile-handoff correctness in Java stays a matter for code
+ review and stress tests, separately from this model.
+
+* Shape of the model
+:PROPERTIES:
+:CUSTOM_ID: shape-of-the-model
+:END:
+
+Three kinds of processes:
+
+| Process | Count | Role |
+|---------------------------+-------+---------------------------------------------------------------|
+| =Worker= | 2 | grab entries, "process" them, advance the barrier |
+| =Camera= | 1 | nondeterministically re-center the rings (rewrite =eligible=) |
+| =World= (later milestone) | 1 | bump the snapshot epoch (geometry/light change) |
+
+Sketch of the core loop (P-syntax; verified to translate with
+=pcal.trans= 1.11 — illustrative, the maintained TLC-checked version
+will live in =Model/GiScheduler.tla=):
+
+#+BEGIN_SRC text
+(* --algorithm GI
+
+variables
+ gen = 0, \* current global generation
+ cursor = 1, \* next queue slot to grab
+ inFlight = 0, \* entries being processed now
+ done = [e \in Entries |-> 0], \* last finished generation per entry
+ eligible = [e \in Entries |-> TRUE]; \* ring membership (camera-driven)
+
+fair process W \in Workers
+ variable e = 0;
+begin
+w1: while (TRUE) do
+ await cursor <= MaxEntry; \* wait for work this generation
+ e := cursor; cursor := cursor + 1; inFlight := inFlight + 1;
+w2: if eligible[e] then
+ done[e] := gen; \* "trace the rays": abstract work
+ end if;
+w3: inFlight := inFlight - 1;
+ if inFlight = 0 /\ cursor > MaxEntry then
+ gen := gen + 1; \* last worker out advances the barrier
+ cursor := 1; \* (re-filter / re-sort happens here)
+ end if;
+ e := 0;
+ end while;
+end process;
+
+process Cam = 0 \* the user, flying around
+begin
+c1: while (TRUE) do
+ with f \in SUBSET Entries do
+ eligible := f; \* camera move re-centers the rings
+ end with;
+ end while;
+end process;
+
+end algorithm; *)
+#+END_SRC
+
+Design decisions embedded in the sketch:
+
+- The barrier is "last worker out advances", mirroring
+ =advanceGeneration= under =genLock= in the real code.
+- The =Camera= process can fire between ANY two worker steps. That is
+ the whole point: the underspecified question "what if the user moves
+ mid-generation?" becomes explicit state space TLC must handle.
+- The camera process is deliberately NOT fair — a forever-moving
+ camera is a legal behavior the scheduler must survive (safety), but
+ convergence properties are stated for a resting camera (liveness).
+- Atomicity granularity is the main modeling judgment: one label per
+ real synchronization point in the Java code (atomic cursor grab,
+ publish, barrier under lock). Too coarse hides races; too fine
+ explodes the state space. When in doubt, go finer.
+
+* Properties to check
+:PROPERTIES:
+:CUSTOM_ID: properties
+:END:
+
+Safety invariants (must hold in EVERY reachable state), in the order
+they pay rent:
+
+1. *TypeOK* — variables keep their shapes (cursor in range, counters
+ non-negative). Catches the =inFlight=-goes-negative class.
+2. *Barrier integrity* — no entry is more than one generation behind:
+ =done[e] >= gen - 1= (relaxed to "or was ineligible at the barrier"
+ once rings enter the model).
+3. *No double-count* — each generation's contribution folds into an
+ entry's total at most once. Modeled by tracking the SET of folded
+ generations per entry and asserting the new one is not already in.
+4. *Snapshot isolation* — a worker holding a replaced snapshot's epoch
+ never writes into the new snapshot's state (writes carry their
+ epoch; the barrier only accepts current-epoch completions).
+5. *Catch-up locality* — catch-up processing never changes =gen= and
+ never touches the barrier.
+
+Liveness, under weak fairness on workers only:
+
+- *Convergence at rest* — if the camera eventually stops moving, every
+ entry inside a stage's ring eventually completes that stage
+ ("stable eligibility leads-to baked"). Checked by letting the
+ environment move any finite number of times, then requiring
+ convergence — a behavior where the camera never moves again is legal
+ in the model, so TLC must prove convergence there too.
+
+When one of these breaks, TLC prints the exact step sequence — which
+worker did what, when the camera moved — which is precisely the
+information we dug out of bugreports by hand.
+
+* Movement policy experiments
+:PROPERTIES:
+:CUSTOM_ID: movement-policy
+:END:
+
+The open design question from the parent page — what the bake should
+do when the camera moves while computation is unfinished — is a CHOICE
+TLA+ cannot make for us. What TLA+ does is make each candidate policy
+a few lines of model and then show, with traces, what each one costs
+and guarantees. The candidates:
+
+1. *Never abort + re-sort at barriers.* In-flight generations always
+ finish; the barrier re-filters AND re-sorts the queue from the live
+ camera; late near-field entrants wait for post-convergence
+ catch-up. Smallest change from today's code (today the order is
+ frozen at snapshot build; only the filter follows the camera).
+ Expect: safety trivially holds; convergence-at-rest holds;
+ near-field latency under movement is NOT bounded — the honest cost,
+ documented as a rule.
+2. *Bounded abandon.* Workers may drop remaining current-generation
+ entries that fell out of all rings; their partial state is
+ discarded. Faster near-field response while moving. New things to
+ prove: a dropped entry that becomes eligible again is eventually
+ re-served (no lost entry), and discarding partial state cannot
+ double-count or lose the fold.
+3. *Ring shrink as skip.* An entry terminal-displays at whatever stage
+ its current ring allows; rings may shrink mid-bake, freezing
+ entries at their current stage. Mostly today's radius-gating
+ semantics — the model pins down the per-entry state lifecycle
+ (keep / freeze / discard) that the prose leaves open.
+
+Current leaning: 1 + 3 combined — never abort in-flight generations
+(keeps the barrier invariant trivially true), add barrier re-sort, and
+treat ring membership as the only skip mechanism. Variant 2 is a later
+optimization, only if measurements demand it.
+
+DECISION PENDING: the user picks the policy; the chosen one gets
+written here as normative rules, and the model must prove the
+invariants under it.
+
+* Building it in steps
+:PROPERTIES:
+:CUSTOM_ID: building-in-steps
+:END:
+
+The model grows in milestones, each one small enough to hold in your
+head, each one gated by TLC. The working rhythm per milestone: write
+the invariant FIRST, watch TLC break the naive model, fix the model
+(or the design) — the same loop our GI bugs went through, except TLC
+finds them before the code exists.
+
+1. *M1 — core loop.* Workers + cursor + barrier + generations, no
+ camera. Invariants: TypeOK, barrier integrity, no double-count.
+2. *M2 — rings and camera.* Eligibility masks + camera action +
+ barrier re-filter/re-sort. Adds convergence-at-rest liveness.
+3. *M3 — snapshot epochs.* Rebuild single-flight + harvest/restore of
+ centroid values (abstract: a =restored= flag). Adds snapshot
+ isolation.
+4. *M4 — catch-up.* Post-convergence queue + local bake for late
+ entrants. Adds catch-up locality.
+5. *M5 — policy variants.* Wire movement policies 1–3 as alternative
+ configurations; record which invariants survive each; write the
+ chosen policy into the Movement policy section as normative prose.
+
+M1 is about one session; each later milestone roughly another. First
+green checks are 2–3 hobby sessions away, not weeks.
+
+* Running TLC
+:PROPERTIES:
+:CUSTOM_ID: running-tlc
+:END:
+
+Tooling (pick one):
+
+- *TLA+ Toolbox* — the desktop IDE from the
+ [[https://github.com/tlaplus/tlaplus][tlaplus/tlaplus]] releases:
+ PlusCal translation, TLC, and trace explorer in one.
+- *VS Code TLA+ extension* — same engine, lighter.
+- *Command line* — =tla2tools.jar= from the same releases; a single
+ Java jar, which fits this project.
+
+Files (once written, versioned next to this page):
+
+- =Model/GiScheduler.tla= — the spec: PlusCal source inside a comment
+ block plus its TLA+ translation.
+- =Model/GiScheduler.cfg= — the model configuration: 2 workers, 4
+ entries, which invariants and temporal properties to check.
+
+Run:
+
+#+BEGIN_SRC sh
+java -jar tla2tools.jar -config Model/GiScheduler.cfg Model/GiScheduler.tla
+#+END_SRC
+
+Seconds to minutes at this size. The workflow rule: model change → TLC
+green → prose on this page updated → probes and goldens verify the
+Java side implements the prose. TLC red is treated like a broken test.
+
+* Pitfalls
+:PROPERTIES:
+:CUSTOM_ID: pitfalls
+:END:
+
+- *State-space explosion.* Keep constants tiny (2 workers, 4 entries).
+ Interleaving bugs do not need scale to appear; scale only buys
+ runtime. Symmetry reduction exists if we ever need it.
+- *Atomicity granularity.* One label per real synchronization point.
+ A barrier modeled as one step can hide the very race we are hunting.
+- *Spec drift.* The model is a repo artifact. A scheduler change
+ without a model change is a specification violation; keep TLC in the
+ same mental gate as the golden renders.
+- *TLA+ proves the design, not the Java.* Conformance of
+ =GlobalIllumination.java= to this contract is enforced by the probe
+ harnesses and code review, not by TLC.
+- *Nondeterminism is a feature.* Replacing numeric conditions
+ ("delta < 0.5") with free choice feels like cheating; it is what
+ lets one small model stand for every possible timing of the real
+ system.
+- *PlusCal syntax.* P-syntax and C-syntax differ in the process
+ binder: no parentheses in P-syntax (=process W \in Workers=),
+ parentheses in C-syntax (=process (W \in Workers) { ... }=). Mixing
+ them is a parse error (verified with =pcal.trans= 1.11).