From 2dc9c0ca36e92ca340bb649b3966561528109c1a Mon Sep 17 00:00:00 2001
From: lulan <49630018+ReneeGA2020@users.noreply.github.com>
Date: Thu, 12 Nov 2026 18:16:27 +0800
Subject: [PATCH 01/15] Integrate optional epoch callback deadline onto current
main
Ports the reviewed 2026-11-10 epoch experiment onto origin/main cbac2a6:
opt-in MapDeadlineMode (Clock default, Epoch explicit), the shared
CallbackEpochTicker lease with diagnostics, and the additive
CallbackDeadlineBridge capability gate. A runtime without the epoch
capability fails before author files are opened; no silent downgrade.
The only delta beyond the reviewed snapshot is a whitespace-only EOF fix in
CallbackEpochTicker.cs so the branch is diff --check clean; the archive branch
keeps its original bytes.
Verification: stock build 0 warnings/0 errors, Runtime.Tests 156/156,
epoch tests 5 passed / 19 skipped (matching private runtime absent) / 0 failed.
Epoch enforcement with a matching runtime remains pending.
Assisted-by: Cindy (https://cindy.app)
---
RuneCLR.slnx | 2 +
...nal-epoch-deadline-integration-20261112.md | 47 ++
eng/verify-epoch-integration.py | 126 ++++
src/RuneCLR.Runtime/CallbackDeadlineBridge.cs | 112 ++-
.../CallbackEpochDiagnostics.cs | 23 +
src/RuneCLR.Runtime/CallbackEpochTicker.cs | 391 ++++++++++
src/RuneCLR.Runtime/MapRunOptions.cs | 32 +-
src/RuneCLR.Runtime/MapSession.cs | 44 +-
.../EpochDeadline.Author.csproj | 5 +
tests/EpochDeadline.Author/Scripts.cs | 197 +++++
tests/RuneCLR.EpochDeadline.Tests/Program.cs | 710 ++++++++++++++++++
.../RuneCLR.EpochDeadline.Tests.csproj | 11 +
12 files changed, 1680 insertions(+), 20 deletions(-)
create mode 100644 docs/experiments/optional-epoch-deadline-integration-20261112.md
create mode 100644 eng/verify-epoch-integration.py
create mode 100644 src/RuneCLR.Runtime/CallbackEpochDiagnostics.cs
create mode 100644 src/RuneCLR.Runtime/CallbackEpochTicker.cs
create mode 100644 tests/EpochDeadline.Author/EpochDeadline.Author.csproj
create mode 100644 tests/EpochDeadline.Author/Scripts.cs
create mode 100644 tests/RuneCLR.EpochDeadline.Tests/Program.cs
create mode 100644 tests/RuneCLR.EpochDeadline.Tests/RuneCLR.EpochDeadline.Tests.csproj
diff --git a/RuneCLR.slnx b/RuneCLR.slnx
index 70be0b3..9cfe72c 100644
--- a/RuneCLR.slnx
+++ b/RuneCLR.slnx
@@ -36,6 +36,8 @@
+
+
diff --git a/docs/experiments/optional-epoch-deadline-integration-20261112.md b/docs/experiments/optional-epoch-deadline-integration-20261112.md
new file mode 100644
index 0000000..e187392
--- /dev/null
+++ b/docs/experiments/optional-epoch-deadline-integration-20261112.md
@@ -0,0 +1,47 @@
+# Optional epoch callback deadline — host integration (2026-11-12)
+
+This branch integrates the reviewed 2026-11-10 epoch callback-deadline experiment onto the
+current RuneCLR `origin/main` (cbac2a657793dca7f22b1e1feff4aab26b898b4e). It replaces the
+archive branch `experiment/optional-epoch-deadline-20261112` (base bdbc7f52) as the host
+integration line; that branch stays untouched as the sealed source snapshot.
+
+## What is integrated
+
+- `MapDeadlineMode` (`Clock` default, `Epoch` opt-in) plus the epoch period on `MapRunOptions`.
+- `CallbackEpochTicker` (process-wide lease, single shared ticker) and
+ `CallbackEpochDiagnostics`, ported unchanged from the reviewed experiment.
+- `CallbackDeadlineBridge` gains the additive epoch factory, tick/read delegates and the
+ capability check; `MapSession` leases the ticker before any author file is opened and releases
+ it after the author stack has returned.
+- Epoch tests and the acceptance script from the experiment.
+
+The clock path is unchanged and remains the default. Epoch mode is explicit: a runtime without
+the additive capability (version-1 clock ABI plus capability bit 2 plus the epoch factory/tick/
+read entry points) fails before author files are opened, never silently downgrades.
+
+## Difference from the archive snapshot
+
+- The only source edit beyond the reviewed experiment is whitespace: the trailing blank line at
+ the end of `CallbackEpochTicker.cs` (the archive has a CRLF blank line at EOF) is removed so
+ this branch is `git diff --check` clean. The archive branch keeps its original bytes.
+- No other behaviour changes.
+
+## Verification status
+
+- Stock desktop build: `dotnet build RuneCLR.slnx -c Release` — 0 warnings, 0 errors.
+- Stock regression: `tests/RuneCLR.Runtime.Tests` — 156/156 passed.
+- Epoch tests on stock runtime: 5 passed, 19 skipped (matching private CoreCLR/native runtime not
+ present), 0 failed. Epoch enforcement is therefore **pending a matching runtime build**; the
+ 2026-11-10 campaign numbers come from the archived binaries and do not validate this branch.
+- Native JIT/R2R remains a future direction: this work is an interpreter callback deadline.
+
+## Runtime expectation
+
+Matching runtime must provide, on `System.Runtime.Loader.AssemblyLoadContext`:
+
+- `RuneCLR_GetCallbackDeadlineVersion() -> long` returning 1 (existing clock ABI);
+- `RuneCLR_GetCallbackDeadlineCapabilities() -> int` with bit 2 set for epoch support;
+- `RuneCLR_CreateCallbackDeadlineEpoch(name, resolver, deadlineTicks, pollInterval, cleanupBudget, epochPeriodMicros)`;
+- `RuneCLR_TickCallbackDeadlineEpoch() -> long` and `RuneCLR_ReadCallbackDeadlineEpoch() -> long`.
+
+The native side (reviewer5) owns that runtime delta; this branch is host-only.
diff --git a/eng/verify-epoch-integration.py b/eng/verify-epoch-integration.py
new file mode 100644
index 0000000..41b6c45
--- /dev/null
+++ b/eng/verify-epoch-integration.py
@@ -0,0 +1,126 @@
+#!/usr/bin/env python3
+"""Acceptance for the optional 10 ms epoch callback deadline in the RuneCLR host.
+
+Pins every input before the run, requires the frozen Release runtime outputs to
+equal the layout copies, runs the epoch-deadline test harness against that
+layout, and re-pins afterwards (zero drift required).
+"""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+NL = chr(10)
+
+
+def digest(path):
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def git(root, *args):
+ return subprocess.check_output(["git", "-C", str(root), *args], text=True).strip()
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--host-root", type=Path, default=Path(__file__).resolve().parents[1])
+ parser.add_argument("--layout", required=True, type=Path)
+ parser.add_argument("--runtime-root", required=True, type=Path)
+ parser.add_argument("--source-manifest", required=True, type=Path)
+ parser.add_argument("--output", required=True, type=Path)
+ parser.add_argument("--framework-version", default="12.0.0")
+ parser.add_argument("--build-rid", default="windows.x64.Release")
+ parser.add_argument("--timeout", type=int, default=900)
+ args = parser.parse_args()
+
+ root = args.host_root.resolve()
+ layout = args.layout.resolve()
+ runtime = args.runtime_root.resolve()
+ output = args.output.resolve()
+ if output.exists():
+ raise ValueError("Output must be a new directory.")
+ output.mkdir(parents=True)
+
+ manifest = json.loads(args.source_manifest.read_text(encoding="utf-8"))
+ head = git(runtime, "rev-parse", "HEAD")
+ if head != (manifest.get("head") or manifest.get("baseline_head")):
+ raise ValueError("Runtime HEAD mismatch: " + head)
+ files = manifest.get("dirty_files") or manifest.get("files") or {}
+ status = subprocess.check_output(["git", "-C", str(runtime), "status", "--porcelain", "--untracked-files=normal"],
+ text=True).splitlines()
+ changed = sorted(line[3:].strip() for line in status if line.strip())
+ if changed != sorted(files):
+ raise ValueError("Runtime delta does not equal the source manifest.")
+ for name, value in files.items():
+ if digest(runtime / name) != value:
+ raise ValueError("Source hash mismatch: " + name)
+
+ build = runtime / "artifacts/bin/coreclr" / args.build_rid
+ shared = layout / "shared/Microsoft.NETCore.App" / args.framework_version
+ outputs = {"System.Private.CoreLib.dll": "CoreLib", "coreclr.dll": "coreclr", "clrjit.dll": "clrjit",
+ "clrinterpreter.dll": "clrinterpreter", "corerun.exe": "corerun"}
+ artifact = {}
+ for name in outputs:
+ produced, installed = build / name, shared / name
+ if not produced.is_file():
+ raise ValueError("Runtime artifact output absent (build not terminal): " + str(produced))
+ if not installed.is_file():
+ raise ValueError("Layout is missing " + name)
+ if digest(produced) != digest(installed):
+ raise ValueError("Layout " + name + " does not equal the runtime build output.")
+ artifact[name] = digest(produced)
+
+ harness = root / "tests/RuneCLR.EpochDeadline.Tests/bin/Release/net11.0/RuneCLR.EpochDeadline.Tests.dll"
+ inputs = {harness, Path(__file__).resolve(), root / "RuneCLR.slnx", root / "Directory.Build.props",
+ args.source_manifest}
+ inputs.update(path for path in harness.parent.rglob("*") if path.is_file())
+ for folder in (root / "src", root / "tests"):
+ inputs.update(path for path in folder.rglob("*") if path.is_file()
+ and not {"bin", "obj"}.intersection(path.relative_to(folder).parts))
+ inputs.update(path for path in layout.rglob("*") if path.is_file())
+ inputs.update(build / name for name in outputs)
+ pins = {str(path): digest(path) for path in sorted(inputs) if path.is_file()}
+ write = output / "pins-before.json"
+ write.write_text(json.dumps(pins, indent=2) + NL, encoding="utf-8")
+
+ environment = {k: v for k, v in os.environ.items() if not k.startswith(("DOTNET_", "COMPlus_"))}
+ environment.update({"DOTNET_MULTILEVEL_LOOKUP": "0", "DOTNET_RuneCLRInterpretCollectible": "1",
+ "DOTNET_InterpMode": "0", "DOTNET_ReadyToRun": "1", "DOTNET_TieredCompilation": "0"})
+ command = [str(layout / ("dotnet.exe" if os.name == "nt" else "dotnet")), "exec",
+ "--fx-version", args.framework_version, str(harness)]
+ stdout = output / "tests.stdout.log"
+ stderr = output / "tests.stderr.log"
+ with stdout.open("wb") as out, stderr.open("wb") as err:
+ process = subprocess.run(command, cwd=root, env=environment, stdout=out, stderr=err, timeout=args.timeout)
+ text = stdout.read_text(encoding="utf-8", errors="replace")
+ print(("PASS" if process.returncode == 0 else "FAIL"), "epoch-deadline tests",
+ "exit=" + str(process.returncode), "log=" + stdout.name)
+ if process.returncode != 0:
+ failures = [line for line in text.splitlines() if line.startswith("FAIL ")]
+ print(" " + (failures[0] if failures else "see log"))
+
+ after = {str(path): digest(path) if path.is_file() else None for path in sorted(inputs)}
+ (output / "pins-after.json").write_text(json.dumps(after, indent=2) + NL, encoding="utf-8")
+ drift = [path for path in pins if pins[path] != after[path]]
+ summary = {"harnessExit": process.returncode, "pinCount": len(pins), "drift": drift,
+ "buildRID": args.build_rid, "artifact": artifact,
+ "sourceIdentity": {"head": head, "deltaFiles": len(files), "localUncommitted": True},
+ "layoutFiles": sum(1 for p in layout.rglob("*") if p.is_file())}
+ (output / "summary.json").write_text(json.dumps(summary, indent=2) + NL, encoding="utf-8")
+ if drift:
+ raise RuntimeError("Input drift: " + repr(drift))
+ if process.returncode != 0:
+ raise RuntimeError("Epoch-deadline tests failed.")
+ print("EPOCH_INTEGRATION PASS; pins=" + str(len(pins)) + "; layout=" + str(summary["layoutFiles"]))
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except Exception as error:
+ print("FAIL " + str(error), file=sys.stderr)
+ raise
diff --git a/src/RuneCLR.Runtime/CallbackDeadlineBridge.cs b/src/RuneCLR.Runtime/CallbackDeadlineBridge.cs
index fe4c129..6fd4bd5 100644
--- a/src/RuneCLR.Runtime/CallbackDeadlineBridge.cs
+++ b/src/RuneCLR.Runtime/CallbackDeadlineBridge.cs
@@ -3,19 +3,31 @@
namespace RuneCLR.Runtime;
+/// Binds the private callback-deadline surface. The clock factory and its instance methods
+/// are the original version-1 contract; the epoch factory, ticker delegates and epoch snapshot
+/// fields are additive and are only bound when a session explicitly selects epoch mode.
internal sealed class CallbackDeadlineBridge
{
- private readonly Func, long, int, long, AssemblyLoadContext> _create;
+ private readonly MapDeadlineMode _mode;
+ private readonly Func, long, int, long, AssemblyLoadContext> _createClock;
+ private readonly Func, long, int, long, long, AssemblyLoadContext>? _createEpoch;
private readonly Func _begin;
private readonly Func _end;
private readonly Func _query;
+ private readonly Func? _tickEpoch;
+ private readonly Func? _readEpoch;
- private CallbackDeadlineBridge()
+ private CallbackDeadlineBridge(MapDeadlineMode mode,
+ Func, long, int, long, AssemblyLoadContext> createClock,
+ Func, long, int, long, long, AssemblyLoadContext>? createEpoch,
+ Func? tickEpoch, Func? readEpoch)
{
+ _mode = mode;
+ _createClock = createClock;
+ _createEpoch = createEpoch;
+ _tickEpoch = tickEpoch;
+ _readEpoch = readEpoch;
var type = typeof(AssemblyLoadContext);
- _create = RequiredInterpreterBridge.Method(type, "RuneCLR_CreateCallbackDeadline", true,
- type, typeof(string), typeof(Func), typeof(long), typeof(int), typeof(long))
- .CreateDelegate, long, int, long, AssemblyLoadContext>>();
_begin = RequiredInterpreterBridge.Method(type, "RuneCLR_BeginCallbackDeadline", false, typeof(long))
.CreateDelegate>();
_end = RequiredInterpreterBridge.Method(type, "RuneCLR_EndCallbackDeadline", false, typeof(bool), typeof(long))
@@ -24,27 +36,97 @@ private CallbackDeadlineBridge()
.CreateDelegate>();
}
- public static CallbackDeadlineBridge Bind()
+ internal MapDeadlineMode Mode => _mode;
+
+ public static CallbackDeadlineBridge Bind(MapDeadlineMode mode, int epochPeriodMicros)
{
try
{
- var version = RequiredInterpreterBridge.Method(typeof(AssemblyLoadContext), "RuneCLR_GetCallbackDeadlineVersion", true,
- typeof(long)).CreateDelegate>();
+ var type = typeof(AssemblyLoadContext);
+ var version = RequiredInterpreterBridge.Method(type, "RuneCLR_GetCallbackDeadlineVersion", true, typeof(long))
+ .CreateDelegate>();
if (version() != 1) throw new PlatformNotSupportedException("Callback deadline version 1 is required.");
- return new CallbackDeadlineBridge();
+ if (mode == MapDeadlineMode.Clock)
+ return new CallbackDeadlineBridge(mode, ClockFactory(), null, null, null);
+
+ // Epoch is explicit: an old runtime without the capability rejects here, before files.
+ var capabilities = RequiredInterpreterBridge.Method(type, "RuneCLR_GetCallbackDeadlineCapabilities", true, typeof(int))
+ .CreateDelegate>();
+ if ((capabilities() & 2) == 0)
+ throw new PlatformNotSupportedException("The runtime does not advertise the epoch callback-deadline capability.");
+ if (epochPeriodMicros is < 1 or > 1_000_000)
+ throw new PlatformNotSupportedException("The epoch period is outside the supported 1..1000000 microsecond range.");
+ var tick = RequiredInterpreterBridge.Method(type, "RuneCLR_TickCallbackDeadlineEpoch", true, typeof(long))
+ .CreateDelegate>();
+ var read = RequiredInterpreterBridge.Method(type, "RuneCLR_ReadCallbackDeadlineEpoch", true, typeof(long))
+ .CreateDelegate>();
+ return new CallbackDeadlineBridge(mode, ClockFactory(), EpochFactory(), tick, read);
}
+ catch (PlatformNotSupportedException) { throw; }
catch (Exception error)
{
- throw new PlatformNotSupportedException("PrototypeCallbackDeadline requires matching private CoreLib/native support.", error);
+ throw new PlatformNotSupportedException(
+ "PrototypeCallbackDeadline requires matching private CoreLib/native support.", error);
}
}
+ private static Func, long, int, long, AssemblyLoadContext> ClockFactory()
+ {
+ var type = typeof(AssemblyLoadContext);
+ return RequiredInterpreterBridge.Method(type, "RuneCLR_CreateCallbackDeadline", true,
+ type, typeof(string), typeof(Func), typeof(long), typeof(int), typeof(long))
+ .CreateDelegate, long, int, long, AssemblyLoadContext>>();
+ }
+
+ private static Func, long, int, long, long, AssemblyLoadContext> EpochFactory()
+ {
+ var type = typeof(AssemblyLoadContext);
+ return RequiredInterpreterBridge.Method(type, "RuneCLR_CreateCallbackDeadlineEpoch", true,
+ type, typeof(string), typeof(Func), typeof(long), typeof(int), typeof(long), typeof(long))
+ .CreateDelegate, long, int, long, long, AssemblyLoadContext>>();
+ }
+
+ internal long TickEpoch() => (_tickEpoch ?? throw new InvalidOperationException("Epoch mode is not active."))();
+ internal long ReadEpoch() => (_readEpoch ?? throw new InvalidOperationException("Epoch mode is not active."))();
+
public AssemblyLoadContext Create(string name, Func resolver,
- MapRunOptions options) => _create(name, resolver, options.PrototypeCallbackDeadline!.Value.Ticks,
- options.PrototypeDeadlinePollInterval, options.PrototypeCleanupInstructionBudget);
+ MapRunOptions options)
+ {
+ var deadline = options.PrototypeCallbackDeadline!.Value;
+ if (_mode == MapDeadlineMode.Clock)
+ return _createClock(name, resolver, deadline.Ticks, options.PrototypeDeadlinePollInterval,
+ options.PrototypeCleanupInstructionBudget);
+ try
+ {
+ return _createEpoch!(name, resolver, deadline.Ticks, options.PrototypeDeadlinePollInterval,
+ options.PrototypeCleanupInstructionBudget, options.PrototypeDeadlineEpochPeriodMicros);
+ }
+ catch (ArgumentOutOfRangeException error)
+ {
+ // The native side latches the epoch period process-wide; an externally or earlier
+ // latched different period surfaces as ArgumentOutOfRangeException from the factory.
+ // Only this configuration failure is normalized - resolver/author exceptions are not.
+ throw new PlatformNotSupportedException(
+ $"The runtime epoch period {options.PrototypeDeadlineEpochPeriodMicros} us conflicts with the period already latched by the process.",
+ error);
+ }
+ }
+
public long Begin(AssemblyLoadContext context) => _begin(context);
public bool End(AssemblyLoadContext context, long token) => _end(context, token);
- public CallbackDeadlineSnapshot Snapshot(AssemblyLoadContext context) => new(
- _query(context, 0), _query(context, 1), _query(context, 2), _query(context, 3) != 0,
- checked((int)_query(context, 4)), _query(context, 5), checked((int)_query(context, 6)));
+
+ public CallbackDeadlineSnapshot Snapshot(AssemblyLoadContext context)
+ {
+ var snapshot = new CallbackDeadlineSnapshot(
+ _query(context, 0), _query(context, 1), _query(context, 2), _query(context, 3) != 0,
+ checked((int)_query(context, 4)), _query(context, 5), checked((int)_query(context, 6)));
+ // Clock snapshots never touch the additive fields: an old v1 runtime has no fields 8..10.
+ if (_mode == MapDeadlineMode.Clock) return snapshot;
+ return snapshot with
+ {
+ Mode = (int)MapDeadlineMode.Epoch,
+ EpochBudgetTicks = _query(context, 9),
+ CurrentGlobalEpoch = _query(context, 10)
+ };
+ }
}
diff --git a/src/RuneCLR.Runtime/CallbackEpochDiagnostics.cs b/src/RuneCLR.Runtime/CallbackEpochDiagnostics.cs
new file mode 100644
index 0000000..c4d2f00
--- /dev/null
+++ b/src/RuneCLR.Runtime/CallbackEpochDiagnostics.cs
@@ -0,0 +1,23 @@
+namespace RuneCLR.Runtime;
+
+///
+/// Read-only process-wide epoch ticker scalars for tests and diagnostics. There is no control
+/// surface here: it cannot start, stop, retarget or tick the ticker.
+///
+public static class CallbackEpochDiagnostics
+{
+ /// Number of live sessions currently leasing the shared ticker (0 in clock-only processes).
+ public static int ActiveLeaseCount => CallbackEpochTicker.ActiveLeases;
+
+ /// Host-latched period in microseconds (0 before the first lease).
+ public static int LatchedPeriodMicros => CallbackEpochTicker.LatchedPeriodMicros;
+
+ /// Total successful ticker increments since process start.
+ public static long TotalTicks => CallbackEpochTicker.TotalTicks;
+
+ /// True once the ticker thread captured a fault.
+ public static bool Faulted => CallbackEpochTicker.Faulted;
+
+ /// Captured fault type name, or null. Never an author message.
+ public static string? FaultTypeName => CallbackEpochTicker.FaultType;
+}
diff --git a/src/RuneCLR.Runtime/CallbackEpochTicker.cs b/src/RuneCLR.Runtime/CallbackEpochTicker.cs
new file mode 100644
index 0000000..a116cf8
--- /dev/null
+++ b/src/RuneCLR.Runtime/CallbackEpochTicker.cs
@@ -0,0 +1,391 @@
+using System.Runtime.InteropServices;
+using System.Threading;
+using Microsoft.Win32.SafeHandles;
+
+namespace RuneCLR.Runtime;
+
+///
+/// Process-wide trusted ticker for the opt-in epoch callback deadline. It owns at most one worker
+/// thread, is leased by live epoch sessions, and advances only the native epoch counter. It never
+/// holds an author load context, policy, session callback or author metadata.
+///
+///
+/// Clock/default sessions never touch this type (no thread, no capability probe, no epoch call).
+/// The period is latched permanently by the first acquisition and is never reset, including after a
+/// failed bootstrap or after the last release; the native side latches independently inside the
+/// epoch factory. A fault is persistent for the process: later acquisitions and every live lease
+/// fail closed with the captured type name, which the worker release can never erase.
+/// The final release joins the worker with no timeout because the only bound calls are the trusted,
+/// non-blocking native tick/read entry points and a blocking wait; that is not a general guarantee
+/// for arbitrary delegated work. The host owns the dispose obligation: stop/dispose sessions from
+/// ordinary host code, never from inside the ticker's own path.
+/// Exception contract: configuration/environment failures detected before author files (missing
+/// native capability, unsupported or conflicting period) are PlatformNotSupportedException;
+/// runtime-health failures (a live lease observing a ticker fault, or any later Acquire after the
+/// permanent process fault) are InvalidOperationException carrying the captured type name only.
+///
+internal static class CallbackEpochTicker
+{
+ private static readonly object Gate = new();
+ private static Worker? _worker;
+ private static int _leases;
+ private static long _totalTicks;
+ private static int _latchedPeriodMicros;
+ private static string? _lastFaultType;
+ private static int _liveWorkers;
+ private static int _maxLiveWorkers;
+
+ internal static int ActiveLeases { get { lock (Gate) return _leases; } }
+ internal static int LatchedPeriodMicros { get { lock (Gate) return _latchedPeriodMicros; } }
+ internal static bool Faulted => Volatile.Read(ref _lastFaultType) is not null;
+ internal static string? FaultType => Volatile.Read(ref _lastFaultType);
+ internal static long TotalTicks => Interlocked.Read(ref _totalTicks);
+
+ // Concurrency diagnostics for tests: a regression that allowed two tickers would be visible as
+ // MaxLiveWorkerCount > 1 even though TotalTicks alone cannot prove spacing.
+ internal static int LiveWorkerCount => Volatile.Read(ref _liveWorkers);
+ internal static int MaxLiveWorkerCount => Volatile.Read(ref _maxLiveWorkers);
+
+ private static void NoteWorkerStarted()
+ {
+ int live = Interlocked.Increment(ref _liveWorkers);
+ int max = Volatile.Read(ref _maxLiveWorkers);
+ while (live > max)
+ {
+ int seen = Interlocked.CompareExchange(ref _maxLiveWorkers, live, max);
+ if (seen == max) break;
+ max = seen;
+ }
+ }
+
+ private static void NoteWorkerStopped() => Interlocked.Decrement(ref _liveWorkers);
+
+ /// Leases the shared ticker, starting it (and proving the counter advanced) on first use.
+ internal static Lease Acquire(int periodMicros, Func tick, Func read)
+ {
+ ArgumentNullException.ThrowIfNull(tick);
+ ArgumentNullException.ThrowIfNull(read);
+ if (periodMicros is < 1 or > 1_000_000)
+ throw new ArgumentOutOfRangeException(nameof(periodMicros), "The epoch period must be 1..1000000 microseconds.");
+ lock (Gate)
+ {
+ // A process fault is permanent: no later acquisition may silently restart a ticker.
+ string? latchedFault = Volatile.Read(ref _lastFaultType);
+ if (latchedFault is not null)
+ throw new InvalidOperationException($"The process epoch ticker failed ({latchedFault}).");
+
+ // Permanent host latch: set on the first acquisition and never reset, even when the
+ // bootstrap below fails or the last lease is released.
+ if (_latchedPeriodMicros == 0)
+ _latchedPeriodMicros = periodMicros;
+ else if (_latchedPeriodMicros != periodMicros)
+ throw new PlatformNotSupportedException(
+ $"The process epoch period is latched at {_latchedPeriodMicros} us and cannot serve {periodMicros} us.");
+
+ if (_worker is null)
+ {
+ var worker = new Worker(periodMicros, tick, read);
+ worker.Start(); // rolls back its own resources on failure; not published on throw
+ NoteWorkerStarted();
+ _worker = worker;
+ }
+ else
+ {
+ _worker.ThrowIfFaulted();
+ if (_worker.Read() <= 0)
+ throw new PlatformNotSupportedException("The process epoch ticker did not advance the native counter.");
+ }
+ _leases++;
+ return new Lease(_worker);
+ }
+ }
+
+ private static void Release()
+ {
+ lock (Gate)
+ {
+ if (_leases == 0) return;
+ _leases--;
+ if (_leases != 0 || _worker is null) return;
+ // Stop and join BEFORE any new acquisition can start another ticker, otherwise a
+ // replacement worker would tick alongside the old one (too-short spacing, early
+ // expiry). The worker never takes this gate, so joining here cannot deadlock.
+ if (!_worker.Stop())
+ {
+ // The bound tick is expected to be non-blocking; if the join cannot complete, keep the
+ // worker published and latch a permanent fault so no second ticker can ever start.
+ ReportFault("RuntimeException:ThreadJoinIncomplete");
+ return;
+ }
+ NoteWorkerStopped();
+ _worker = null;
+ }
+ }
+
+ ///
+ /// Test-only, process-wide scoped override of the timer facade. It can be installed only while
+ /// the ticker is idle (no leases, no worker), and disposal restores the facade flags only - it
+ /// never clears the permanent fault latch or the latched period. The override makes Arm fail or
+ /// Wait report the unexpected result, so the worker runs the SAME real fault path as a genuine
+ /// SetWaitableTimer failure / WAIT_FAILED instead of short-circuiting the latch.
+ ///
+ internal static IDisposable InstallTestTimerFault(bool armFails, bool waitFails)
+ {
+ lock (Gate)
+ {
+ if (_leases != 0 || _worker is not null || Volatile.Read(ref _liveWorkers) != 0)
+ throw new InvalidOperationException(
+ "The test timer fault hook requires an idle ticker (no leases and no live worker).");
+ HighResolutionTimer.SetTestFault(armFails, waitFails);
+ return new TestFaultScope();
+ }
+ }
+
+ private sealed class TestFaultScope : IDisposable
+ {
+ private int _disposed;
+
+ public void Dispose()
+ {
+ if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
+ HighResolutionTimer.SetTestFault(false, false); // flags only; latch/period untouched
+ }
+ }
+
+ ///
+ /// Lock-free fault publication. The worker calls this from its fault/exit path, and the last
+ /// release holds Gate while joining the worker, so taking Gate here would deadlock.
+ ///
+ internal static void ReportFault(string typeName)
+ {
+ Interlocked.CompareExchange(ref _lastFaultType, typeName, null);
+ }
+
+ internal sealed class Lease : IDisposable
+ {
+ private readonly Worker _worker;
+ private int _released;
+ private string? _faultType;
+
+ internal Lease(Worker worker) => _worker = worker;
+
+ internal string? FaultType => _faultType ?? _worker.FaultType;
+
+ /// Host-gate fault check. It never rescues an infinite body; it only fails closed.
+ internal void ThrowIfFaulted()
+ {
+ var fault = _faultType ?? _worker.FaultType;
+ if (fault is null) return;
+ _faultType = fault; // preserved on the lease even after the worker is released
+ throw new InvalidOperationException($"The process epoch ticker failed ({fault}).");
+ }
+
+ public void Dispose()
+ {
+ if (Interlocked.Exchange(ref _released, 1) == 0) Release();
+ }
+ }
+
+ internal sealed class Worker
+ {
+ private readonly int _periodMicros;
+ private readonly Func _tick;
+ private readonly Func _read;
+ private readonly CancellationTokenSource _cancel = new();
+ private readonly Thread _thread;
+ private volatile string? _faultType;
+
+ internal Worker(int periodMicros, Func tick, Func read)
+ {
+ _periodMicros = periodMicros;
+ _tick = tick;
+ _read = read;
+ _thread = new Thread(Run) { IsBackground = true, Name = "RuneCLR epoch ticker" };
+ }
+
+ internal int PeriodMicros => _periodMicros;
+ internal string? FaultType => _faultType;
+
+ internal long Read() => _read();
+
+ internal void ThrowIfFaulted()
+ {
+ var fault = _faultType;
+ if (fault is not null)
+ throw new InvalidOperationException($"The process epoch ticker failed ({fault}).");
+ }
+
+ internal void Start()
+ {
+ try
+ {
+ // Bootstrap before any author code exists: one tick plus a positive read proves the
+ // native counter is live, so a callback Begin can never observe epoch 0.
+ long value = _tick();
+ if (value <= 0 || _read() <= 0)
+ throw new PlatformNotSupportedException("The native epoch counter did not start.");
+ // The trusted worker must not inherit the caller's ExecutionContext (policy scopes,
+ // AsyncLocal state) into its thread.
+ if (ExecutionContext.IsFlowSuppressed())
+ _thread.Start();
+ else
+ using (ExecutionContext.SuppressFlow()) _thread.Start();
+ }
+ catch
+ {
+ // Roll back an unstarted worker. No thread is running, so no join is attempted.
+ try { _cancel.Cancel(); } catch (Exception) { }
+ _cancel.Dispose();
+ throw;
+ }
+ }
+
+ private void Run()
+ {
+ SafeWaitHandle? timer = null;
+ try
+ {
+ (timer, var createFault) = HighResolutionTimer.Create();
+ if (createFault is not null)
+ {
+ Fault(createFault);
+ return;
+ }
+ while (!_cancel.IsCancellationRequested)
+ {
+ if (timer is not null)
+ {
+ if (!HighResolutionTimer.Arm(timer, _periodMicros))
+ {
+ Fault(HighResolutionTimer.Describe("SetWaitableTimer"));
+ return;
+ }
+ var outcome = HighResolutionTimer.Wait(timer, _cancel.Token);
+ if (outcome == WaitOutcome.Cancelled) return; // exact cancellation index only
+ if (outcome == WaitOutcome.Failed)
+ {
+ Fault(HighResolutionTimer.Describe("WaitForMultipleObjects"));
+ return;
+ }
+ }
+ else if (_cancel.Token.WaitHandle.WaitOne(Milliseconds(_periodMicros)))
+ {
+ return;
+ }
+ if (_cancel.IsCancellationRequested) return;
+ _tick();
+ Interlocked.Increment(ref _totalTicks);
+ }
+ }
+ catch (Exception error)
+ {
+ // Scalar only: the fault is reported by type name, never by reading an author message.
+ Fault(error.GetType().FullName ?? "Exception");
+ }
+ finally
+ {
+ try { timer?.Dispose(); } catch (Exception) { }
+ }
+ }
+
+ private void Fault(string typeName)
+ {
+ _faultType ??= typeName;
+ CallbackEpochTicker.ReportFault(_faultType!);
+ }
+
+ private static int Milliseconds(int periodMicros) => (periodMicros + 999) / 1000;
+
+ /// Stops and joins the worker; false means the thread is still alive afterwards.
+ internal bool Stop()
+ {
+ try { _cancel.Cancel(); } catch (Exception) { }
+ if (_thread.IsAlive && _thread != Thread.CurrentThread)
+ {
+ try { _thread.Join(); } catch (Exception) { }
+ }
+ bool stopped = !_thread.IsAlive;
+ if (stopped)
+ {
+ try { _cancel.Dispose(); } catch (Exception) { }
+ }
+ return stopped;
+ }
+ }
+
+ private enum WaitOutcome { Tick, Cancelled, Failed }
+
+ ///
+ /// Windows high-resolution waitable timer when the OS supports it; the waiting thread blocks,
+ /// so the normal path never spins. Each iteration re-arms exactly one period: spacing is never
+ /// shorter than declared and a late tick is never replayed as a burst.
+ ///
+ private static class HighResolutionTimer
+ {
+ private const uint HighResolution = 0x00000002;
+ private const uint AllAccess = 0x1F0003;
+ private const uint Infinite = 0xFFFFFFFF;
+ private const int ErrorInvalidParameter = 87;
+
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
+ private static extern SafeWaitHandle CreateWaitableTimerExW(IntPtr attributes, string? name, uint flags, uint access);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool SetWaitableTimer(SafeWaitHandle handle, ref long dueTime, int period,
+ IntPtr completionRoutine, IntPtr completionArg, bool resume);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern uint WaitForMultipleObjects(uint count, IntPtr[] handles, bool waitAll, uint milliseconds);
+
+ private static int s_testArmFails;
+ private static int s_testWaitFails;
+
+ internal static void SetTestFault(bool armFails, bool waitFails)
+ {
+ Volatile.Write(ref s_testArmFails, armFails ? 1 : 0);
+ Volatile.Write(ref s_testWaitFails, waitFails ? 1 : 0);
+ }
+
+ internal static string Describe(string call) =>
+ $"Win32Exception:{call}:{Marshal.GetLastWin32Error()}";
+
+ internal static (SafeWaitHandle? Handle, string? Fault) Create()
+ {
+ if (!OperatingSystem.IsWindows()) return (null, null);
+ try
+ {
+ var handle = CreateWaitableTimerExW(IntPtr.Zero, null, HighResolution, AllAccess);
+ if (!handle.IsInvalid) return (handle, null);
+ int error = Marshal.GetLastWin32Error();
+ handle.Dispose();
+ // ERROR_INVALID_PARAMETER means this OS predates the high-resolution flag; that is
+ // the documented coarse fallback, not a fault.
+ if (error == ErrorInvalidParameter) return (null, null);
+ return (null, $"Win32Exception:CreateWaitableTimerExW:{error}");
+ }
+ catch (Exception error)
+ {
+ return (null, error.GetType().FullName ?? "Exception");
+ }
+ }
+
+ internal static bool Arm(SafeWaitHandle handle, int periodMicros)
+ {
+ // Test override only: same return path as a genuine SetWaitableTimer failure.
+ if (Volatile.Read(ref s_testArmFails) != 0) return false;
+ long due = -(long)periodMicros * 10; // negative = relative, 100 ns units
+ return SetWaitableTimer(handle, ref due, 0, IntPtr.Zero, IntPtr.Zero, false);
+ }
+
+ internal static WaitOutcome Wait(SafeWaitHandle handle, CancellationToken cancel)
+ {
+ // Test override only: same path as WAIT_FAILED (unexpected result -> Fault).
+ if (Volatile.Read(ref s_testWaitFails) != 0) return WaitOutcome.Failed;
+ IntPtr[] handles = [handle.DangerousGetHandle(), cancel.WaitHandle.SafeWaitHandle.DangerousGetHandle()];
+ uint result = WaitForMultipleObjects(2, handles, false, Infinite);
+ if (result == 0) return WaitOutcome.Tick; // WAIT_OBJECT_0: timer
+ if (result == 1) return WaitOutcome.Cancelled; // WAIT_OBJECT_0 + 1: cancellation event
+ return WaitOutcome.Failed; // WAIT_FAILED / abandoned / unexpected
+ }
+ }
+}
diff --git a/src/RuneCLR.Runtime/MapRunOptions.cs b/src/RuneCLR.Runtime/MapRunOptions.cs
index 54c5ec5..30ae7a6 100644
--- a/src/RuneCLR.Runtime/MapRunOptions.cs
+++ b/src/RuneCLR.Runtime/MapRunOptions.cs
@@ -15,6 +15,11 @@ public sealed record MapRunOptions
// Experimental native IR-dispatch budget, not a complete execution-time sandbox.
public long? PrototypeInstructionBudget { get; init; }
public TimeSpan? PrototypeCallbackDeadline { get; init; }
+ // Sampling source for the callback deadline. Clock (the default) is the original v1 clock ABI.
+ // Epoch needs the runtime epoch capability, a process-wide trusted ticker and a process-latched
+ // period; a runtime without the capability fails before any author file, never downgrades.
+ public MapDeadlineMode PrototypeDeadlineMode { get; init; } = MapDeadlineMode.Clock;
+ public int PrototypeDeadlineEpochPeriodMicros { get; init; } = 10_000;
public int PrototypeDeadlinePollInterval { get; init; } = 100;
public long PrototypeCleanupInstructionBudget { get; init; } = 4_096;
// Only MapRunner.Run uses TickCount; pumped sessions advance when the host calls Tick.
@@ -48,6 +53,15 @@ internal void Validate()
if (PrototypeDeadlinePollInterval is not (1 or 100 or 1000))
throw new ArgumentOutOfRangeException(nameof(PrototypeDeadlinePollInterval));
}
+ if (!Enum.IsDefined(PrototypeDeadlineMode))
+ throw new ArgumentOutOfRangeException(nameof(PrototypeDeadlineMode));
+ if (PrototypeDeadlineMode == MapDeadlineMode.Epoch)
+ {
+ if (PrototypeCallbackDeadline is null)
+ throw new ArgumentException("Epoch deadline mode requires PrototypeCallbackDeadline.", nameof(PrototypeDeadlineMode));
+ if (PrototypeDeadlineEpochPeriodMicros is < 1 or > 1_000_000)
+ throw new ArgumentOutOfRangeException(nameof(PrototypeDeadlineEpochPeriodMicros));
+ }
ArgumentOutOfRangeException.ThrowIfNegative(TickCount);
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(TickDuration, TimeSpan.Zero);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(OperationBudgetPerCallback);
@@ -59,6 +73,15 @@ internal void Validate()
}
}
+/// Sampling source for the prototype callback deadline.
+public enum MapDeadlineMode
+{
+ /// Original v1 clock mode; the default and the only mode old runtimes support.
+ Clock,
+ /// Opt-in shared-ticker epoch mode; requires the additive runtime capability.
+ Epoch
+}
+
public enum MapRunOutcome
{
Completed,
@@ -82,7 +105,14 @@ public sealed record MapRunReport(
}
public sealed record CallbackDeadlineSnapshot(long ClockFrequency, long ClockChecks, long AdmittedOperations,
- bool Active, int PollInterval, long LastToken, int Reason);
+ bool Active, int PollInterval, long LastToken, int Reason)
+{
+ // Epoch evidence. Clock snapshots leave these at zero and never query the additive fields,
+ // so an old v1 runtime without fields 8..10 keeps working unchanged.
+ public int Mode { get; init; }
+ public long EpochBudgetTicks { get; init; }
+ public long CurrentGlobalEpoch { get; init; }
+}
// Scalars copied before Unload; no session context, author metadata or exception is retained.
public sealed record PrototypeBudgetSnapshot(
diff --git a/src/RuneCLR.Runtime/MapSession.cs b/src/RuneCLR.Runtime/MapSession.cs
index b35164f..b435edf 100644
--- a/src/RuneCLR.Runtime/MapSession.cs
+++ b/src/RuneCLR.Runtime/MapSession.cs
@@ -18,6 +18,7 @@ public sealed class MapSession : IDisposable
private AssemblyLoadContext? _loadContext;
private TerminalPrototypeBridge? _terminal;
private CallbackDeadlineBridge? _deadline;
+ private CallbackEpochTicker.Lease? _epochLease;
private ReflectionPolicySession? _reflectionPolicy;
private long _deadlineToken;
private string? _deadlineFailure;
@@ -36,12 +37,21 @@ private MapSession(MapPackage package, MapRunOptions options, CallbackDeadlineBr
// Capability failure is a host configuration error, before opening author files.
var required = options.ExecutionPolicy == MapExecutionPolicy.RequireInterpreter
? RequiredInterpreterBridge.Bind() : null;
- _deadline = options.PrototypeCallbackDeadline is not null ? deadlineBridge ?? CallbackDeadlineBridge.Bind() : null;
+ _deadline = options.PrototypeCallbackDeadline is not null
+ ? deadlineBridge ?? CallbackDeadlineBridge.Bind(options.PrototypeDeadlineMode,
+ options.PrototypeDeadlineEpochPeriodMicros)
+ : null;
_terminal = options.PrototypeInstructionBudget is not null || _deadline is not null ? TerminalPrototypeBridge.Bind(required!) : null;
_policyVersion = required is null ? 0 : 1;
if (options.PrototypeApiPolicy is not null) PrototypeReflectionPolicy.Prepare();
try
{
+ // Lease and bootstrap the shared ticker before any author file is opened or loaded.
+ // The native period acknowledgement happens later, inside the epoch factory (op 6);
+ // until then this latch is host-side and two sessions must agree on the period here.
+ if (_deadline is { Mode: MapDeadlineMode.Epoch })
+ _epochLease = CallbackEpochTicker.Acquire(options.PrototypeDeadlineEpochPeriodMicros,
+ _deadline.TickEpoch, _deadline.ReadEpoch);
var resolver = new MapDependencyResolver(package, allowSessionAssemblyNames: options.PrototypeApiPolicy is not null);
var admission = options.PrototypeApiPolicy is { } policy
? new UgcAssemblyAdmission(policy, package, options.PrototypeSharedAssemblies) : null;
@@ -54,10 +64,14 @@ private MapSession(MapPackage package, MapRunOptions options, CallbackDeadlineBr
}
catch
{
- _reflectionPolicy?.Dispose();
+ // Every cleanup step is isolated so the original constructor failure is rethrown, and
+ // the epoch lease is always released even when Dispose/Unload throw.
+ try { _reflectionPolicy?.Dispose(); } catch (Exception) { }
_reflectionPolicy = null;
- _loadContext?.Unload();
+ try { _loadContext?.Unload(); } catch (Exception) { }
_loadContext = null;
+ try { _epochLease?.Dispose(); } catch (Exception) { }
+ _epochLease = null;
throw;
}
}
@@ -331,7 +345,18 @@ private MapRunResult StopCore()
{
_error = Append(_error, "The native prototype state snapshot could not be read.");
}
- finally { _deadline = null; loadContext.Unload(); }
+ finally
+ {
+ _deadline = null;
+ try { loadContext.Unload(); }
+ finally
+ {
+ // Author execution has returned; the final lease always stops and joins the
+ // ticker, even when a native snapshot or Unload above throws.
+ _epochLease?.Dispose();
+ _epochLease = null;
+ }
+ }
}
}
@@ -355,6 +380,7 @@ private void CheckReentry()
private void CheckPrototypeState()
{
+ CheckEpochTicker();
if (_deadlineFailure is not null) throw new InvalidOperationException(_deadlineFailure);
bool terminated;
try { terminated = _terminal?.IsTerminated(_loadContext!) == true; }
@@ -369,6 +395,7 @@ private void CheckPrototypeState()
private void BeginDeadline()
{
+ CheckEpochTicker();
if (_deadlineFailure is not null) throw new InvalidOperationException(_deadlineFailure);
if (_deadline is null) return;
try
@@ -385,6 +412,7 @@ private void BeginDeadline()
private void EndDeadline()
{
+ CheckEpochTicker();
if (_deadlineToken == 0) return;
var token = _deadlineToken;
_deadlineToken = 0;
@@ -399,6 +427,14 @@ private void EndDeadline()
}
}
+ // A persistent ticker fault is reported at host gates only; it never promises to rescue an
+ // infinite author body whose counter keeps advancing (or a ticker that stopped advancing).
+ private void CheckEpochTicker()
+ {
+ if (_epochLease is not { } lease || lease.FaultType is not { } fault) return;
+ FailDeadlineBridge($"The process epoch ticker failed ({fault}).");
+ }
+
private void FailDeadlineBridge(string message)
{
_deadlineFailure ??= message;
diff --git a/tests/EpochDeadline.Author/EpochDeadline.Author.csproj b/tests/EpochDeadline.Author/EpochDeadline.Author.csproj
new file mode 100644
index 0000000..f6bb485
--- /dev/null
+++ b/tests/EpochDeadline.Author/EpochDeadline.Author.csproj
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/tests/EpochDeadline.Author/Scripts.cs b/tests/EpochDeadline.Author/Scripts.cs
new file mode 100644
index 0000000..267d38a
--- /dev/null
+++ b/tests/EpochDeadline.Author/Scripts.cs
@@ -0,0 +1,197 @@
+using RuneCLR;
+
+namespace EpochDeadline.Author;
+
+/// Maintained copy of the measured interpreter workloads (same kernels and sizes
+/// as the sealed measurement campaign).
+public static class Kernel
+{
+ public static long Arithmetic(int units, long seed)
+ {
+ long state = seed | 1;
+ long accumulator = 0;
+ for (var index = 0; index < units; index++)
+ {
+ state ^= state << 13;
+ state ^= (long)((ulong)state >> 7);
+ state ^= state << 17;
+ if ((state & 0x100) != 0) accumulator += state & 0xFFFF;
+ else accumulator -= state & 0xFF;
+ if ((index & 0x3FF) == 0) accumulator ^= state;
+ }
+
+ return accumulator;
+ }
+
+ public static long CallHeavy(int units, int seed)
+ {
+ IWorker worker = new AddWorker();
+ var state = seed | 1;
+ long accumulator = 0;
+ for (var index = 0; index < units; index++)
+ {
+ var value = worker.Step((int)(state & 0xFF));
+ var squared = Square(value);
+ var twisted = Twist(squared);
+ if ((twisted & 1) != 0) accumulator += twisted;
+ else accumulator -= Bias(squared);
+ state = (state * 1103515245 + 12345) & 0x7FFFFFFF;
+ }
+
+ return accumulator;
+ }
+
+ public static long Mixed(int units, int seed)
+ {
+ long accumulator = 0;
+ long state = seed | 1;
+ for (var index = 0; index < units; index++)
+ {
+ state ^= state << 13;
+ state ^= (long)((ulong)state >> 7);
+ state ^= state << 17;
+ accumulator += Square((int)(state & 0xFF));
+ if ((state & 0x1F) == 0) accumulator ^= Twist((int)(state & 0xFF));
+ }
+
+ return accumulator;
+ }
+
+ private static int Square(int value) => (value * value) & 0xFFFF;
+
+ private static int Twist(int value) => ((value << 3) ^ (value >> 2)) & 0xFFFF;
+
+ private static int Bias(int value) => value + 1;
+}
+
+public interface IWorker
+{
+ int Step(int value);
+}
+
+public sealed class AddWorker : IWorker
+{
+ public int Step(int value) => value + 3;
+}
+
+public abstract class Script : IMapScript
+{
+ private long checksum;
+ private int steps;
+ private IMapContext? context;
+
+ protected abstract int Units { get; }
+
+ protected abstract long Run(int units);
+
+ public void OnStart(IMapContext context)
+ {
+ this.context = context;
+ Step();
+ }
+
+ public void OnTick(MapTick tick) => Step();
+
+ public void OnStop() => context = null;
+
+ private void Step()
+ {
+ checksum = unchecked(checksum * 1_000_003 + (Run(Units) ^ (steps * 2_654_435_761L)));
+ steps++;
+ context?.Log("checksum=" + checksum + ";steps=" + steps);
+ }
+}
+
+public abstract class TickOnlyScript : IMapScript
+{
+ protected abstract int Units { get; }
+
+ protected abstract long Run(int units);
+
+ public void OnStart(IMapContext context) { }
+
+ public void OnTick(MapTick tick) => Run(Units);
+
+ public void OnStop() { }
+}
+
+public sealed class ArithmeticSmall : Script
+{
+ protected override int Units => 200_000;
+
+ protected override long Run(int units) => Kernel.Arithmetic(units, 17);
+}
+
+public sealed class MixedSmall : Script
+{
+ protected override int Units => 100_000;
+
+ protected override long Run(int units) => Kernel.Mixed(units, 17);
+}
+
+public sealed class CallHeavySmall : Script
+{
+ protected override int Units => 20_000;
+
+ protected override long Run(int units) => Kernel.CallHeavy(units, 17);
+}
+
+public sealed class TickOnlyLong : TickOnlyScript
+{
+ protected override int Units => 40_000_000;
+
+ protected override long Run(int units) => Kernel.Arithmetic(units, 17);
+}
+
+public sealed class TickOnlyCatchLong : TickOnlyScript
+{
+ protected override int Units => 40_000_000;
+
+ protected override long Run(int units)
+ {
+ long result = 0;
+ try
+ {
+ result += Kernel.Arithmetic(units, 17);
+ }
+ catch (Exception)
+ {
+ result -= 1;
+ }
+ finally
+ {
+ result ^= 3;
+ }
+
+ return result;
+ }
+}
+
+public sealed class CleanupHeavy : IMapScript
+{
+ public void OnStart(IMapContext context) { }
+
+ public void OnTick(MapTick tick) { }
+
+ public void OnStop() => Kernel.Arithmetic(40_000_000, 17);
+}
+
+public sealed class CtorFails : IMapScript
+{
+ public CtorFails() => throw new InvalidOperationException("author constructor failure");
+
+ public void OnStart(IMapContext context) { }
+
+ public void OnTick(MapTick tick) { }
+
+ public void OnStop() { }
+}
+
+public sealed class StartFails : IMapScript
+{
+ public void OnStart(IMapContext context) => throw new InvalidOperationException("author start failure");
+
+ public void OnTick(MapTick tick) { }
+
+ public void OnStop() { }
+}
diff --git a/tests/RuneCLR.EpochDeadline.Tests/Program.cs b/tests/RuneCLR.EpochDeadline.Tests/Program.cs
new file mode 100644
index 0000000..82e0e79
--- /dev/null
+++ b/tests/RuneCLR.EpochDeadline.Tests/Program.cs
@@ -0,0 +1,710 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.Loader;
+using RuneCLR.Runtime;
+
+internal static class Program
+{
+ private static string AuthorPath => Path.Combine(AppContext.BaseDirectory, "epoch-author", "EpochDeadline.Author.dll");
+
+ private static MapRunOptions Options(string mode, int periodMicros = 10_000, int deadlineMs = 1_000, int poll = 100)
+ {
+ var options = new MapRunOptions
+ {
+ ExecutionPolicy = MapExecutionPolicy.RequireInterpreter,
+ PrototypeCallbackDeadline = TimeSpan.FromMilliseconds(deadlineMs),
+ PrototypeDeadlinePollInterval = poll,
+ TickCount = 0,
+ MaxLogMessages = 512
+ };
+ return DeadlineApi.WithMode(options, mode, periodMicros);
+ }
+
+ private static MapRunOptions Off() => new() { TickCount = 0, MaxLogMessages = 512 };
+
+ private static int Main(string[] args)
+ {
+ if (args.Length == 2 && args[0] == "--fault") return FaultMode(args[1]);
+ if (args.Length == 2 && args[0] == "--fault-stop") return FaultDuringLastStop(args[1]);
+ if (args.Length == 2 && args[0] == "--sanity") return Sanity(args[1]);
+ var filter = args.Length > 0 ? args[0] : null;
+ var cases = Cases().Where(item => filter is null || item.Name.Contains(filter, StringComparison.OrdinalIgnoreCase)).ToList();
+ var passed = 0;
+ var skipped = 0;
+ var failed = 0;
+ foreach (var (name, run) in cases)
+ {
+ try
+ {
+ run();
+ passed++;
+ Console.WriteLine("PASS " + name);
+ }
+ catch (SkipException error)
+ {
+ skipped++;
+ Console.WriteLine("SKIP " + name + " :: " + error.Message);
+ }
+ catch (Exception error)
+ {
+ failed++;
+ Console.WriteLine("FAIL " + name + " :: " + error.GetType().Name + ": " + error.Message +
+ " @ " + (error.StackTrace ?? "").Split('\n').FirstOrDefault());
+ }
+ }
+
+ Console.WriteLine("EPOCH_DEADLINE_TESTS passed=" + passed + " skipped=" + skipped + " failed=" + failed);
+ return failed == 0 ? 0 : 1;
+ }
+
+ /// Separate-process deadlock probe: the fault fires while the last lease is
+ /// being stopped. A hang is a failure; the driver also applies a hard watchdog.
+ private static int Sanity(string mode)
+ {
+ if (mode != "clock" && mode != "epoch") { Console.WriteLine("FAIL sanity mode " + mode); return 2; }
+ if (mode == "epoch" && (!DeadlineApi.NativeEpoch || !DeadlineApi.PrivateBridge))
+ { Console.WriteLine("SKIP native epoch is not available"); return 3; }
+ foreach (var deadline in new[] { 100, 1000, 5000 })
+ {
+ using var process = System.Diagnostics.Process.GetCurrentProcess();
+ process.Refresh();
+ var cpuBefore = process.TotalProcessorTime;
+ var watch = System.Diagnostics.Stopwatch.StartNew();
+ using var session = new MapRunner().Start(Package("EpochDeadline.Author.TickOnlyLong"),
+ Options(mode, 10_000, deadlineMs: deadline, poll: 100));
+ var ok = session.Tick();
+ watch.Stop();
+ var result = session.Stop();
+ process.Refresh();
+ var cpu = (process.TotalProcessorTime - cpuBefore).TotalMilliseconds;
+ var snapshot = result.Report.PrototypeDeadline;
+ Console.WriteLine("SANITY mode=" + mode + " deadlineMs=" + deadline +
+ " tripped=" + (!ok) + " wallMs=" + watch.Elapsed.TotalMilliseconds.ToString("F1") +
+ " cpuMs=" + cpu.ToString("F1") +
+ " reason=" + (snapshot?.Reason.ToString() ?? "none") +
+ " modeField=" + (snapshot?.Mode.ToString() ?? "none") +
+ " leases=" + DeadlineApi.ActiveLeaseCount +
+ " live=" + DeadlineApi.LiveWorkers + " max=" + DeadlineApi.MaxLiveWorkers +
+ " latched=" + DeadlineApi.LatchedPeriodMicros);
+ }
+ return 0;
+ }
+ private static int FaultDuringLastStop(string kind)
+ {
+ var armFails = kind == "arm";
+ var waitFails = kind == "wait";
+ if (!armFails && !waitFails) { Console.WriteLine("FAIL unknown fault kind " + kind); return 2; }
+ var ticker = typeof(MapRunOptions).Assembly.GetType("RuneCLR.Runtime.CallbackEpochTicker", throwOnError: false);
+ var gateField = ticker?.GetField("Gate", BindingFlags.NonPublic | BindingFlags.Static);
+ var acquire = ticker?.GetMethod("Acquire", BindingFlags.NonPublic | BindingFlags.Static);
+ var install = ticker?.GetMethod("InstallTestTimerFault", BindingFlags.NonPublic | BindingFlags.Static);
+ if (ticker is null || gateField is null || acquire is null || install is null)
+ {
+ Console.WriteLine("SKIP internal ticker surface is not available");
+ return 3;
+ }
+
+ var tick = typeof(AssemblyLoadContext).GetMethod("RuneCLR_TickCallbackDeadlineEpoch",
+ BindingFlags.NonPublic | BindingFlags.Static)!.CreateDelegate>();
+ var read = typeof(AssemblyLoadContext).GetMethod("RuneCLR_ReadCallbackDeadlineEpoch",
+ BindingFlags.NonPublic | BindingFlags.Static)!.CreateDelegate>();
+ var gate = gateField.GetValue(null)!;
+ Monitor.Enter(gate);
+ try
+ {
+ using var hook = (IDisposable)install.Invoke(null, new object[] { armFails, waitFails })!;
+ var lease = acquire.Invoke(null, new object[] { 10_000, tick, read })!;
+ var faultProperty = lease.GetType().GetProperty("FaultType", BindingFlags.NonPublic | BindingFlags.Instance);
+ var wait = System.Diagnostics.Stopwatch.StartNew();
+ while (wait.Elapsed < TimeSpan.FromSeconds(10))
+ {
+ if (!string.IsNullOrEmpty(faultProperty?.GetValue(lease) as string)) break;
+ Thread.Sleep(10);
+ }
+
+ var observed = faultProperty?.GetValue(lease) as string;
+ var stop = System.Diagnostics.Stopwatch.StartNew();
+ ((IDisposable)lease).Dispose();
+ stop.Stop();
+ var ok = !string.IsNullOrEmpty(observed) && stop.Elapsed < TimeSpan.FromSeconds(5)
+ && DeadlineApi.LiveWorkers == 0 && DeadlineApi.MaxLiveWorkers <= 1
+ && DeadlineApi.ActiveLeaseCount == 0 && DeadlineApi.Faulted
+ && DeadlineApi.LatchedPeriodMicros == 10_000;
+ Console.WriteLine((ok ? "PASS" : "FAIL") + " fault-stop-" + kind +
+ " fault=" + (observed ?? "none") + " disposeMs=" + stop.Elapsed.TotalMilliseconds.ToString("F0") +
+ " live=" + DeadlineApi.LiveWorkers + " max=" + DeadlineApi.MaxLiveWorkers +
+ " leases=" + DeadlineApi.ActiveLeaseCount + " latched=" + DeadlineApi.LatchedPeriodMicros);
+ return ok ? 0 : 1;
+ }
+ finally
+ {
+ Monitor.Exit(gate);
+ }
+ }
+
+ /// Separate-process fault case: install the internal timer fault while idle,
+ /// then require the existing lease and future acquires to fail.
+ private static int FaultMode(string kind)
+ {
+ var armFails = kind == "arm";
+ var waitFails = kind == "wait";
+ if (!armFails && !waitFails) { Console.WriteLine("FAIL unknown fault kind " + kind); return 2; }
+ var install = typeof(MapRunOptions).Assembly.GetType("RuneCLR.Runtime.CallbackEpochTicker", throwOnError: false)?
+ .GetMethod("InstallTestTimerFault", BindingFlags.NonPublic | BindingFlags.Static);
+ if (install is null) { Console.WriteLine("SKIP fault hook is not available"); return 3; }
+ if (!DeadlineApi.NativeEpoch || !DeadlineApi.PrivateBridge) { Console.WriteLine("SKIP native epoch is not available"); return 3; }
+ using var hook = (IDisposable)install.Invoke(null, new object[] { armFails, waitFails })!;
+ try
+ {
+ using var session = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch", 10_000));
+ var threw = Capture(() => session.Tick()) is InvalidOperationException;
+ var acquire = Capture(() => new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch", 10_000)));
+ session.Stop();
+ Check(threw, "an existing lease did not surface the fault as InvalidOperationException");
+ Check(acquire is InvalidOperationException, "a future acquire did not fail after the fault: " + acquire?.GetType().Name);
+ Check(DeadlineApi.Faulted, "the fault was not latched");
+ Check(!string.IsNullOrEmpty(DeadlineApi.FaultTypeName), "no fault type was captured");
+ using var clock = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Clock"));
+ Check(clock.Tick(), "clock mode was affected by the epoch fault");
+ clock.Stop();
+ Console.WriteLine("PASS fault-" + kind + " latched=" + DeadlineApi.FaultTypeName);
+ return 0;
+ }
+ catch (Exception error)
+ {
+ Console.WriteLine("FAIL fault-" + kind + " :: " + error.GetType().Name + ": " + error.Message);
+ return 1;
+ }
+ }
+
+ private static IEnumerable<(string Name, Action Run)> Cases()
+ {
+ yield return ("default Clock starts no thread and reports no deadline evidence", DefaultNoTicker);
+ yield return ("explicit Epoch is refused before the missing author file when native support is absent", EpochRefusedBeforeFile);
+ yield return ("invalid option combinations are rejected", InvalidCombinations);
+ yield return ("clock mode keeps the version-1 contract", ClockOnV1);
+ yield return ("first epoch session sees a positive native epoch", FirstEpochPositive);
+ yield return ("four concurrent sessions share one ticker", FourConcurrent);
+ yield return ("stopping one session does not stop the others", StopOneKeepsOthers);
+ yield return ("last stop joins the ticker", LastStopJoins);
+ yield return ("failure during ctor/OnStart rolls back the lease", FailureRollback);
+ yield return ("a stopped session does not root its ALC", StoppedDoesNotRoot);
+ yield return ("duplicate Stop is idempotent", DuplicateStop);
+ yield return ("period mismatch is rejected before the author file while a ticker is active", PeriodMismatchWhileActive);
+ yield return ("catch/filter cannot resume a terminated callback", CatchCannotResume);
+ yield return ("next good session completes after termination and unloads", NextGoodAfterTermination);
+ yield return ("no public pause/escape API is exposed", NoPauseApi);
+ yield return ("default epoch period is 10000 microseconds", DefaultPeriod);
+ yield return ("clock mode never starts or latches the epoch ticker", ClockKeepsTickerIdle);
+ yield return ("epoch ticker diagnostics reset leases and keep the latched period", TickerDiagnostics);
+ yield return ("last stop racing a new start never overlaps or double-ticks", LastStopRacesStart);
+ yield return ("a conflicting period is rejected before files after the last lease is gone", PeriodLatchedAfterLastLease);
+ yield return ("a failed start leaves no lease behind", FailedStartLeavesNoLease);
+ yield return ("the ticker thread does not inherit the caller ExecutionContext", TickerDoesNotInheritFlow);
+ yield return ("injected ticker faults surface to an existing lease", InjectedFaultVisibility);
+ yield return ("legacy Query fields stay -1 on the clock path", LegacyQueryUnchanged);
+ }
+
+ private static void DefaultNoTicker()
+ {
+ var before = ThreadCount();
+ using var session = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Off());
+ session.Tick();
+ session.Stop();
+ var after = ThreadCount();
+ Check(after <= before + 1, "default run started persistent threads: " + before + " -> " + after);
+ }
+
+ private static void EpochRefusedBeforeFile()
+ {
+ var missing = MissingPackage();
+ var options = Options("Epoch");
+ var error = Capture(() => new MapRunner().Start(missing, options));
+ if (DeadlineApi.NativeEpoch)
+ {
+ Check(error is not PlatformNotSupportedException,
+ "native epoch support is present but the session refused as unsupported");
+ }
+ else
+ {
+ Check(error is PlatformNotSupportedException,
+ "epoch mode without native support must refuse: " + error?.GetType().Name);
+ }
+
+ Check(!File.Exists(missing.AssemblyPath), "refusal opened or created the author path");
+ }
+
+ private static void InvalidCombinations()
+ {
+ var plain = Capture(() => new MapRunner().Start(MissingPackage(),
+ new MapRunOptions { ExecutionPolicy = MapExecutionPolicy.RequireInterpreter }));
+ Check(plain is not ArgumentException,
+ "valid interpreter options were rejected by validation: " + plain?.GetType().Name);
+ if (!DeadlineApi.EpochSupported) return;
+ var noDeadline = DeadlineApi.WithMode(Off(), "Epoch", 10_000);
+ Check(Capture(() => new MapRunner().Start(MissingPackage(), noDeadline)) is ArgumentException,
+ "epoch mode without a deadline must be an ArgumentException");
+ var badPeriod = Options("Epoch", 0);
+ Check(Capture(() => new MapRunner().Start(MissingPackage(), badPeriod)) is ArgumentException,
+ "an out-of-range epoch period must be an ArgumentException");
+ }
+
+ private static void ClockOnV1()
+ {
+ if (DeadlineVersion() != 1) throw new SkipException("the runtime does not expose the version-1 clock bridge");
+ using var session = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Clock"));
+ Check(session.Tick(), "clock session failed on a healthy tick");
+ var result = session.Stop();
+ Check(result.Report.PrototypeDeadline is not null, "clock mode did not report deadline evidence");
+ }
+
+ private static void FirstEpochPositive()
+ {
+ if (!DeadlineApi.EpochSupported || !DeadlineApi.PrivateBridge) throw new SkipException("epoch mode is not available on this runtime");
+ using var session = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch"));
+ Check(session.Tick(), "epoch session failed on a healthy tick");
+ var result = session.Stop();
+ var snapshot = result.Report.PrototypeDeadline;
+ Check(snapshot is not null, "epoch mode did not report deadline evidence");
+ }
+
+ private static void FourConcurrent()
+ {
+ if (!DeadlineApi.EpochSupported || !DeadlineApi.PrivateBridge) throw new SkipException("epoch mode is not available on this runtime");
+ var sessions = Enumerable.Range(0, 4)
+ .Select(_ => new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch")))
+ .ToList();
+ try
+ {
+ foreach (var session in sessions) Check(session.Tick(), "a concurrent session failed a healthy tick");
+ }
+ finally
+ {
+ foreach (var session in sessions) session.Stop();
+ }
+ }
+
+ private static void StopOneKeepsOthers()
+ {
+ if (!DeadlineApi.EpochSupported || !DeadlineApi.PrivateBridge) throw new SkipException("epoch mode is not available on this runtime");
+ var first = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch"));
+ var second = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch"));
+ first.Stop();
+ Check(second.IsRunning, "stopping one session stopped another");
+ Check(second.Tick(), "the surviving session failed a tick");
+ second.Stop();
+ }
+
+ private static void LastStopJoins()
+ {
+ if (!DeadlineApi.EpochSupported || !DeadlineApi.PrivateBridge) throw new SkipException("epoch mode is not available on this runtime");
+ var before = ThreadCount();
+ var session = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch"));
+ session.Tick();
+ session.Stop();
+ Thread.Sleep(200);
+ Check(ThreadCount() <= before + 1, "the ticker thread survived the last stop: " + before + " -> " + ThreadCount());
+ }
+
+ private static void FailureRollback()
+ {
+ if (!DeadlineApi.EpochSupported || !DeadlineApi.PrivateBridge) throw new SkipException("epoch mode is not available on this runtime");
+ foreach (var entry in new[] { "EpochDeadline.Author.CtorFails", "EpochDeadline.Author.StartFails" })
+ {
+ using var session = new MapRunner().Start(Package(entry), Options("Epoch"));
+ Check(!session.IsRunning, entry + " should not stay running");
+ session.Stop();
+ }
+
+ var missing = MissingPackage();
+ var error = Capture(() => new MapRunner().Start(missing, Options("Epoch")));
+ Check(error is not null, "a missing author file must surface an error");
+ }
+
+ private static void StoppedDoesNotRoot()
+ {
+ if (!DeadlineApi.EpochSupported || !DeadlineApi.PrivateBridge) throw new SkipException("epoch mode is not available on this runtime");
+ var weak = RunAndCaptureContext("EpochDeadline.Author.ArithmeticSmall");
+ for (var attempt = 0; attempt < 3 && weak.IsAlive; attempt++)
+ {
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ }
+
+ Check(!weak.IsAlive, "a stopped session still roots its load context");
+ }
+
+ private static void DuplicateStop()
+ {
+ using var session = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Off());
+ var first = session.Stop();
+ var second = session.Stop();
+ Check(ReferenceEquals(first, second), "duplicate Stop returned a different result");
+ }
+
+ private static void PeriodMismatchWhileActive()
+ {
+ if (!DeadlineApi.EpochSupported || !DeadlineApi.PrivateBridge) throw new SkipException("epoch mode is not available on this runtime");
+ using var active = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch", 10_000));
+ var error = Capture(() => new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch", 5_000)));
+ Check(error is not null, "a conflicting period was accepted while the ticker was active");
+ active.Stop();
+ using var restart = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch", 10_000));
+ Check(restart.Tick(), "restart with the same period failed");
+ restart.Stop();
+ }
+
+ private static void CatchCannotResume()
+ {
+ if (!DeadlineApi.EpochSupported || !DeadlineApi.NativeEpoch || !DeadlineApi.PrivateBridge)
+ throw new SkipException("native epoch mode is not available on this runtime");
+ using var session = new MapRunner().Start(Package("EpochDeadline.Author.TickOnlyCatchLong"),
+ Options("Epoch", 10_000, deadlineMs: 50, poll: 100));
+ var ok = session.Tick();
+ Check(!ok, "the catch/filter workload was not terminated");
+ var result = session.Stop();
+ Check(result.Report.Outcome == MapRunOutcome.Failed, "the terminated session did not report failure");
+ Check(result.Report.PrototypeDeadline is { } snapshot && snapshot.Reason == 2,
+ "termination was not the deadline reason 2");
+ }
+
+ private static void NextGoodAfterTermination()
+ {
+ if (!DeadlineApi.EpochSupported || !DeadlineApi.NativeEpoch || !DeadlineApi.PrivateBridge)
+ throw new SkipException("native epoch mode is not available on this runtime");
+ for (var index = 0; index < 2; index++)
+ {
+ using var terminated = new MapRunner().Start(Package("EpochDeadline.Author.TickOnlyLong"),
+ Options("Epoch", 10_000, deadlineMs: 50, poll: 100));
+ Check(!terminated.Tick(), "the long tick was not terminated");
+ terminated.Stop();
+ }
+
+ using var good = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch", 10_000));
+ Check(good.Tick(), "the good session after terminations failed");
+ var result = good.Stop();
+ Check(result.Report.Outcome == MapRunOutcome.Completed, "the good session did not complete");
+ }
+
+ private static void NoPauseApi()
+ {
+ var exposed = typeof(MapRunOptions).Assembly.GetExportedTypes()
+ .SelectMany(type => type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance))
+ .Any(method => method.Name.Contains("Pause", StringComparison.OrdinalIgnoreCase));
+ Check(!exposed, "a public pause/escape API is exposed");
+ }
+
+ private static void DefaultPeriod()
+ {
+ if (!DeadlineApi.EpochSupported || !DeadlineApi.PrivateBridge) throw new SkipException("epoch options are not available on this runtime");
+ Check(DeadlineApi.DefaultPeriodMicros == 10_000,
+ "default epoch period is " + DeadlineApi.DefaultPeriodMicros);
+ }
+
+ private static void ClockKeepsTickerIdle()
+ {
+ if (!DeadlineApi.TickerAvailable || !DeadlineApi.PrivateBridge)
+ throw new SkipException("the production ticker diagnostics or private bridge are not available");
+ var periodBefore = DeadlineApi.LatchedPeriodMicros;
+ using var session = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Clock"));
+ session.Tick();
+ Check(DeadlineApi.ActiveLeases == 0, "clock mode acquired epoch ticker leases");
+ Check(DeadlineApi.LatchedPeriodMicros == periodBefore, "clock mode changed the latched epoch period");
+ session.Stop();
+ }
+
+ private static void TickerDiagnostics()
+ {
+ if (!DeadlineApi.TickerAvailable || !DeadlineApi.NativeEpoch)
+ throw new SkipException("the production ticker or native epoch is not available");
+ DeadlineApi.ResetDiagnostics();
+ for (var index = 0; index < 2; index++)
+ {
+ using var session = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch", 10_000));
+ Check(DeadlineApi.ActiveLeases == 1, "active leases should be 1 while a session runs");
+ Check(DeadlineApi.LatchedPeriodMicros == 10_000,
+ "latched period while active is " + DeadlineApi.LatchedPeriodMicros);
+ Check(session.Tick(), "epoch session failed a healthy tick");
+ session.Stop();
+ }
+
+ Check(DeadlineApi.ActiveLeases == 0, "leases were not released after the last stop: " + DeadlineApi.ActiveLeases);
+ Check(DeadlineApi.TotalTicks > 0, "the ticker published no ticks");
+ Check(DeadlineApi.LatchedPeriodMicros == 10_000,
+ "the latched period should persist after the last stop, got " + DeadlineApi.LatchedPeriodMicros);
+ Check(!DeadlineApi.Faulted, "ticker faulted: " + DeadlineApi.FaultType);
+ var error = Capture(() => new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch", 5_000)));
+ Check(error is not null, "a conflicting period was accepted after the last stop");
+ }
+
+ private static void LastStopRacesStart()
+ {
+ if (!DeadlineApi.NativeEpoch || !DeadlineApi.PrivateBridge) throw new SkipException("native epoch mode is not available");
+ var faults = 0;
+ var before = DeadlineApi.TotalTicks;
+ var clock = System.Diagnostics.Stopwatch.StartNew();
+ for (var round = 0; round < 12; round++)
+ {
+ var first = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch", 10_000));
+ using var barrier = new Barrier(2);
+ Exception? startError = null;
+ var starter = new Thread(() =>
+ {
+ barrier.SignalAndWait();
+ try
+ {
+ using var second = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch", 10_000));
+ second.Tick();
+ second.Stop();
+ }
+ catch (Exception error) { startError = error; }
+ });
+ starter.Start();
+ barrier.SignalAndWait();
+ first.Stop();
+ starter.Join(TimeSpan.FromSeconds(10));
+ if (startError is not null) faults++;
+ }
+
+ clock.Stop();
+ var ticks = DeadlineApi.TotalTicks - before;
+ var seconds = Math.Max(0.001, clock.Elapsed.TotalSeconds);
+ var rate = ticks / seconds;
+ // One ticker at a 10 ms period yields about 100 ticks/s; two tickers would double it.
+ Check(rate <= 200.0, "ticker rate " + rate.ToString("F1") + "/s suggests two tickers");
+ Check(faults == 0, "a racing start failed: " + faults + " rounds");
+ Check(DeadlineApi.ActiveLeaseCount == 0, "leases leaked after the race: " + DeadlineApi.ActiveLeaseCount);
+ Check(!DeadlineApi.Faulted, "the ticker faulted during the race: " + DeadlineApi.FaultTypeName);
+ }
+
+ private static void PeriodLatchedAfterLastLease()
+ {
+ if (!DeadlineApi.NativeEpoch || !DeadlineApi.PrivateBridge) throw new SkipException("native epoch mode is not available");
+ using (var session = new MapRunner().Start(Package("EpochDeadline.Author.ArithmeticSmall"), Options("Epoch", 10_000)))
+ {
+ session.Tick();
+ session.Stop();
+ }
+
+ Check(DeadlineApi.ActiveLeaseCount == 0, "the last lease was not released");
+ var missing = MissingPackage();
+ var error = Capture(() => new MapRunner().Start(missing, Options("Epoch", 5_000)));
+ Check(error is not null, "a conflicting period was accepted after the last lease");
+ Check(!File.Exists(missing.AssemblyPath), "the conflict was rejected only after opening the author file");
+ }
+
+ private static void FailedStartLeavesNoLease()
+ {
+ if (!DeadlineApi.NativeEpoch || !DeadlineApi.PrivateBridge) throw new SkipException("native epoch mode is not available");
+ var before = DeadlineApi.ActiveLeaseCount;
+ foreach (var entry in new[] { "EpochDeadline.Author.CtorFails", "EpochDeadline.Author.StartFails" })
+ {
+ using var session = new MapRunner().Start(Package(entry), Options("Epoch", 10_000));
+ Check(!session.IsRunning, entry + " should not stay running");
+ session.Stop();
+ }
+
+ Check(DeadlineApi.ActiveLeaseCount == before, "a failed start leaked a lease");
+ }
+
+ private static void TickerDoesNotInheritFlow()
+ {
+ if (!DeadlineApi.NativeEpoch || !DeadlineApi.PrivateBridge) throw new SkipException("native epoch mode is not available");
+ var weak = LeaseWithFlowSentinel();
+ for (var attempt = 0; attempt < 5 && weak.IsAlive; attempt++)
+ {
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ }
+
+ Check(!weak.IsAlive, "the ticker thread inherited and rooted the caller ExecutionContext");
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static WeakReference LeaseWithFlowSentinel()
+ {
+ var sentinel = new object();
+ var flow = new AsyncLocal