Table of Contents

Tick Control: Pause, Step, Time Scale

Hold the tick loop at a fenced boundary, step exactly N ticks, slow the simulation down or run it unpaced — one engine API that applications, the Workbench and tests all call.

Status: ✅ Implemented · Visibility: Public · Level: 🔵 Core · Category: Runtime

🎯 What it solves

A game server, a simulation tool and a test suite all need the same three things from the tick loop: stop it (debugging, an admin pause, a single-player "pause" menu), advance it by an exact number of ticks (stepping through a bug, a deterministic test), and change its speed (slow motion to watch a fight, fast forward to soak a world for an hour). Without engine support every application fakes them — a paused flag checked in every system while ticks keep running, dt × scale in every integration while tick-counted logic keeps its pace, a polling loop to stop "at tick X" — and every fake is partial. Tick control is the one real implementation: a hold that runs nothing, steps that run exactly N ticks, and a time scale that slows everything together.

⚙️ How it works (in brief)

  • A hold is a hard hold. Pause() closes the tick entry on the same gate a graceful Shutdown uses and waits for the tick in flight to finish — its systems, its fence, its flush, its publish. Afterwards nothing ticks: the tick number stays put, no system runs, the tick thread parks (no polling). A held engine holds no epoch, no unit of work and no transaction; checkpoints, the WAL and deadlines keep running on wall time.
  • Resume() starts the next tick at once, with no catch-up for the time held.
  • Step(n) runs exactly n ticks and holds again. From a hold they run back-to-back, unpaced; while running, they are the next n paced ticks that start after the call, and the last one's frame tells clients the server is about to hold.
  • TimeScale stretches the wall interval between ticks, never the simulation step. At 0.5 the 60 Hz loop ticks every 33 ms; at 4, every 4 ms; at double.PositiveInfinity (unpaced) back-to-back. ctx.DeltaTime stays 1 / BaseTickRate on every tick, so tick-counted logic (cooldowns in ticks, divisors, dormancy) and dt-based logic slow down and speed up together. The overload response (time dilation, see Overload Management) is the same mechanism: wall interval = base × multiplier ÷ scale.
  • RunState (NotStarted, Running, Paused, Stepping, Stopped, Faulted) is the pull surface; OnRunStateChanged the push. Stopped and Faulted are terminal: no Resume or Step ever runs another tick after a shutdown, an aborted tick or a failed fence.

💻 Usage

Pause, resume, step

var outcome = runtime.Pause();          // Held: the tick in flight finished; nothing ticks now
await runtime.Step(10);                 // exactly 10 ticks, back-to-back, then held again
runtime.Resume();                       // the next tick starts at once

runtime.RequestPause();                 // never blocks — from a system, a hook, a command handler
runtime.OnRunStateChanged += (rt, change) =>
    Console.WriteLine($"{change.Previous} -> {change.Current} at tick {change.TickNumber} ({change.Source})");

Pause() called from inside a tick (a system body, OnFirstTick, OnTickAborted, an in-tick work item) cannot wait for its own tick: it returns PauseOutcome.Requested at once and the next tick simply does not start.

A deterministic driver for tests and tools

using var runtime = TyphonRuntime.Create(dbe, Configure, new RuntimeOptions { StartPaused = true });
runtime.Start();                        // threads up, held before tick 0

var result = await runtime.Step(100);   // exactly ticks 0..99; OnFirstTick ran on tick 0
Assert.That(runtime.CurrentTickNumber, Is.EqualTo(100));

No wall-clock waits, no SpinWait.SpinUntil(… CurrentTickNumber …): the task completes at the fenced boundary after the last tick, with StepResult(FirstTick, LastTick, Executed, Preempted).

Slow motion, fast forward, unpaced

runtime.TimeScale = 0.25;                       // slow motion
runtime.TimeScale = 10;                         // fast forward (up to RuntimeOptions.MaxTimeScale)
runtime.TimeScale = double.PositiveInfinity;    // unpaced: as fast as the ticks complete

var achieved = runtime.AchievedTimeScale;       // what the CPU actually sustains (0 while held)

Scale 0 is refused — there is one way to hold, Pause() — and so is anything outside [1/MaxTimeScale, MaxTimeScale]. Fast forward beyond what the CPU sustains runs ticks back-to-back and never escalates the overload response (each tick is still measured against the base budget); AchievedTimeScale reports the truth.

Editing a held world

runtime.Pause();
var placed = runtime.WriteInTick((tx, tick) => tx.Spawn<Rock>(Rock.Pos.Set(at)), DurabilityMode.GroupCommit);
await runtime.Step();                   // the write runs at the start of the stepped tick, then its systems, fence and flush

Writes from outside the tick go through WriteInTick / InTick exactly as when running — a hold widens nothing: off-tick SingleVersion, Transient and spatial writes still throw. A stepped tick drains at most RuntimeOptions.InTickMaxItemsPerTick (256) items, like any tick, so a step stays faithful to the running engine; ReadStats().InTickQueueDepth says how many still wait — step until it reads 0. Never await the task on the thread that would step or resume the runtime.

Relaying "pause" from clients

A paused engine drains no commands, so a client's "resume" would wait for a tick that never comes. Declare the control command OffTick: it is handled on the receive thread, after its role, rate and pre-check, instead of in a tick.

subs.Command<PauseRequest>(c => c
    .Roles(SessionRole.Operator)        // required: an off-tick command must name who may send it
    .Rate(2, burst: 2)
    .OffTick((SessionId session, in PauseRequest cmd) =>
    {
        if (cmd.Pause) runtime.RequestPause();
        else runtime.Resume();
    }));

subs.Command<Attack>(c => c.Roles(SessionRole.Player).WhileHeld(CommandWhileHeld.Reject));   // stale once the world resumes: refuse it while held

An off-tick handler may call RequestPause, Resume, Step (without awaiting it) and set TimeScale — never block, never touch the database.

What clients see

  • The last frame before a hold, and every stepped frame, carries the TICK flag PAUSED ("the server will not advance on its own after this frame"). While held, the server sends a header-only PAUSED keepalive on each transition and every 500 ms, so sessions stay open and a joining client learns the state.
  • A change of tick period — the time scale, overload dilation, or the time held — reaches clients as PERIOD; the SDK clocks absorb it. Their Clock.IsPaused stops render time at the newest frame (no extrapolation past it), and Clock.TimeScale reports the server's speed.
  • A command declared WhileHeld(Reject) sent during a hold is answered with ACK reason PAUSED in the first frame after it.
Option Default Effect
RuntimeOptions.StartPaused false Start() holds before tick 0; nothing ticks until Step or Resume
RuntimeOptions.MaxTimeScale 64 Largest finite TimeScale accepted, and the inverse of the smallest: 64 allows ×64 fast forward down to 1/64 slow motion (+∞ is always accepted)
RuntimeOptions.MaxCatchUpTicks -1 (BaseTickRate / 4) Ticks of lateness repaid back-to-back after a stall (a GC pause, a debugger break); the rest is dropped and counted in ReadStats().MissedTicks. 0 never catches up
RuntimeOptions.InTickMaxItemsPerTick 256 In-tick work items one tick — stepped or not — runs

Controlling from the Workbench

A Workbench attached to the live profiler port can pause, step and change the speed of the engine — opt-in, off by default. Each command is the engine's own Pause / Step / TimeScale, recorded with source Remote, and the UI shows only what the engine echoes.

Key (typhon.telemetry.json or TYPHON__PROFILER__*) Default Effect
Typhon:Profiler:AllowControl false Accept control frames on the live port
Typhon:Profiler:AllowNonLoopbackControl false Also when the port is bound to a routable address (needs ControlToken)
Typhon:Profiler:ControlToken — 64 hexadecimal characters (256 bits). A malformed value disables control, with the reason shown in the Workbench
Typhon:Profiler:ControlLeaseMs 10 000 (min 1 500) A hold made from the Workbench is released this long after the Workbench goes silent
  • Authentication. On a loopback bind the engine writes a fresh token per start to a file readable only by its own OS user ($XDG_RUNTIME_DIR/typhon when set, else <$XDG_DATA_HOME or ~/.local/share>/Typhon/runtime; %LOCALAPPDATA%\Typhon\runtime on Windows), which a Workbench running as the same user on the same machine reads by itself. An engine running under a service account is another user: give it a ControlToken and paste that. A configured ControlToken is accepted besides the file — it is also the token to paste when the port is reached through a tunnel (scripts/attach-remote.ps1): the port looks local, the token file is on the far machine. A non-loopback bind accepts the configured token alone. A wrong token leaves the session read-only and the Workbench says token refused; an engine that does not allow control says why (control unavailable: …).
  • The token never travels, but the channel is not encrypted. The hello proves the token with HMAC-SHA256 over a nonce fresh per connection, so a captured hello cannot be replayed. Everything else — the profiler stream, the commands — is cleartext: prefer a tunnel (SSH, SSM) over a routable bind. Every accepted or refused hello is logged at Warning with the peer's address.
  • A Workbench hold is leased. If the Workbench dies or disconnects, its own pause is released after ControlLeaseMs. An application's Pause or Step is never released by a lease, even when a Workbench paused on top of it.
  • A pause no one watches releases itself — by design. The Workbench keeps its lease alive only while a tab shows the session (an open profiler or runtime stream). A pause made through the Workbench's REST API by a script with no stream open, and every pause once the last tab closes, resumes after ControlLeaseMs, even though the Workbench is still running. To hold longer, keep a runtime stream open, or pause from the application.
  • Keep ControlToken out of Environment= in a systemd unit: systemctl show prints Environment= to any local user. Put it in an EnvironmentFile= readable by the service account alone (mode 0600) as TYPHON__PROFILER__CONTROLTOKEN=…, or use LoadCredential= — the engine does not read credential files itself, so the host reads $CREDENTIALS_DIRECTORY/<name> and passes it as ProfilerLaunchConfig.ControlToken. The same holds for any process manager that exposes a unit's inline environment.

⚠️ Guarantees & limits

  • A hold never splits a tick: Pause() returns after the tick in flight's fence and flush. Writes made by that tick are fenced and durable like any tick's.
  • Move entities by DeltaTime / AmortizedDeltaTime, never by WallDeltaTime. DeltaTime is the fixed simulation step on every tick; WallDeltaTime is the measured wall time since the previous tick (the time held included, flagged by HeldBefore) — integrating by it teleports entities after a pause and under overload. Use it for wall-clock logic only (a real-time rate limit).
  • No catch-up debt crosses a hold, a step or a scale change; a real stall repays at most MaxCatchUpTicks ticks.
  • Terminal states win: after Shutdown, FatalStop, an aborted tick or a failed fence, Resume() returns false, Step() returns a faulted task, Pause() returns Terminal. Pending steps are cancelled by a stop and faulted by a fault.
  • In-tick control calls never block. OnRunStateChanged may fire on the tick thread — never block in it.
  • A hold is the whole tick loop. There is no "simulation-only" pause in which engine tracks keep ticking: tick-counted state (dormancy, divisors, identity quarantine) freezes with the tick number.
  • Under sustained overload or fast forward beyond the CPU, simulation time runs behind the wall clock — the time-dilation trade, by design.
  • Not supported: rewind, snapshot-restore, a view served to a client that joins while held (it gets WELCOME and a PAUSED keepalive), and tick control in host mode (embedding without the runtime) — use StartPaused + Step instead.

🧪 Tests