fix(deploy): #1024 warm the script compile gate at AdminOperations start; deploy trigger gets a 45 s ask timeout

This commit is contained in:
Joseph Doherty
2026-12-03 14:54:51 -05:00
parent cc7155e5e9
commit 29c44d1f04
6 changed files with 127 additions and 13 deletions
+1 -1
View File
@@ -67,7 +67,7 @@ The deploy gate compiles every script the deployment will run before the deploym
| `Warn` | Logged and appended to the accepted deployment message; the deploy succeeds. |
| `Off` | The gate does not run. |
Absent, blank or unrecognised values mean `Error` — a typo never silently weakens the gate. **Why `Error` by default** (unlike `TagConfigValidationMode`, default `Warn`): a refused script never runs — its tag is Bad for as long as it is deployed, and one refused predicate takes every scripted alarm on the node dark — so blocking such a deploy blocks no working behaviour. A tolerated TagConfig typo used to *run* (silently defaulted), which is why that gate stayed `Warn`. Cost: the first deploy after a restart compiles each distinct in-use script once (tens to hundreds of ms each, more for the very first Roslyn compile in the process); the AdminUI waits 10 s for a deploy answer, so on a very large fleet the first deploy after a restart can report a timeout while it carries on — the next is cached.
Absent, blank or unrecognised values mean `Error` — a typo never silently weakens the gate. **Why `Error` by default** (unlike `TagConfigValidationMode`, default `Warn`): a refused script never runs — its tag is Bad for as long as it is deployed, and one refused predicate takes every scripted alarm on the node dark — so blocking such a deploy blocks no working behaviour. A tolerated TagConfig typo used to *run* (silently defaulted), which is why that gate stayed `Warn`. Cost: the first deploy after a restart compiles each distinct in-use script once (tens to hundreds of ms each, more for the very first Roslyn compile in the process); the singleton warms the checker in the background as it starts (#1024) and the AdminUI waits 45 s for a deploy answer (10 s for ack/shelve), so only a very large fleet deployed within seconds of a restart can still report an `OutcomeUnknown` timeout while the deploy carries on — the next is cached.
#### Known resource limits (accepted trade-offs)
@@ -10,28 +10,47 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Clients;
/// <summary>
/// <see cref="IAdminOperationsClient"/> backed by the cluster singleton registered in
/// <c>AddOtOpcUaControlPlane</c>. Resolves the singleton proxy from <see cref="ActorRegistry"/>
/// at construction time; each call <c>Ask</c>s the proxy with a 10s timeout.
/// at construction time; each call <c>Ask</c>s the proxy with a 10s timeout (45s for the deploy trigger, #1024).
/// </summary>
public sealed class AdminOperationsClient : IAdminOperationsClient
{
private static readonly TimeSpan DefaultAskTimeout = TimeSpan.FromSeconds(10);
/// <summary>The general ask timeout (ack / shelve / probes).</summary>
internal static readonly TimeSpan DefaultAskTimeout = TimeSpan.FromSeconds(10);
/// <summary>
/// #1024: the deploy trigger's own ask timeout. The compose runs the Roslyn script compile gate, and on a
/// large fleet a COLD checker (first deploy after a central restart) can take well past 10 s; the singleton
/// warms the checker at start, but the first deploy may still race that. A timeout is still
/// <see cref="StartDeploymentOutcome.OutcomeUnknown"/>, never a failure — this just makes it rarer.
/// </summary>
internal static readonly TimeSpan DefaultDeployAskTimeout = TimeSpan.FromSeconds(45);
private readonly IActorRef _proxy;
private readonly TimeSpan AskTimeout;
private readonly TimeSpan DeployAskTimeout;
/// <summary>Initializes a new instance of the AdminOperationsClient.</summary>
/// <param name="registry">The actor registry to resolve the admin operations singleton proxy.</param>
public AdminOperationsClient(ActorRegistry registry) : this(registry, DefaultAskTimeout)
public AdminOperationsClient(ActorRegistry registry) : this(registry, DefaultAskTimeout, DefaultDeployAskTimeout)
{
}
/// <summary>Test seam: the same client with a caller-chosen ask timeout.</summary>
/// <summary>Test seam: the same client with a caller-chosen ask timeout (also used for the deploy trigger).</summary>
/// <param name="registry">The actor registry to resolve the admin operations singleton proxy.</param>
/// <param name="askTimeout">How long to wait for the singleton's reply.</param>
internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout)
internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout) : this(registry, askTimeout, askTimeout)
{
}
/// <summary>Test seam: caller-chosen general and deploy-trigger ask timeouts.</summary>
/// <param name="registry">The actor registry to resolve the admin operations singleton proxy.</param>
/// <param name="askTimeout">How long to wait for the singleton's reply to ack/shelve.</param>
/// <param name="deployAskTimeout">How long to wait for the singleton's reply to StartDeployment.</param>
internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout, TimeSpan deployAskTimeout)
{
_proxy = registry.Get<AdminOperationsActorKey>();
AskTimeout = askTimeout;
DeployAskTimeout = deployAskTimeout;
}
/// <inheritdoc />
@@ -48,10 +67,10 @@ public sealed class AdminOperationsClient : IAdminOperationsClient
var correlationId = CorrelationId.NewId();
var msg = new StartDeployment(createdBy, correlationId, deploymentId);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct);
linked.CancelAfter(AskTimeout);
linked.CancelAfter(DeployAskTimeout);
try
{
return await _proxy.Ask<StartDeploymentResult>(msg, AskTimeout, linked.Token);
return await _proxy.Ask<StartDeploymentResult>(msg, DeployAskTimeout, linked.Token);
}
catch (Exception ex) when (ex is AskTimeoutException
|| (ex is OperationCanceledException && !ct.IsCancellationRequested))
@@ -60,7 +79,7 @@ public sealed class AdminOperationsClient : IAdminOperationsClient
StartDeploymentOutcome.OutcomeUnknown,
deploymentId,
RevisionHash: null,
Message: $"No reply from the deployment service within {AskTimeout.TotalSeconds:0} s, so it is not known " +
Message: $"No reply from the deployment service within {DeployAskTimeout.TotalSeconds:0} s, so it is not known " +
$"whether the deployment was created. If it was, it carries id {deploymentId.Value}; check the " +
"deployment history (or GET /api/deployments/" + deploymentId.Value + ") before retrying.",
correlationId);
@@ -33,6 +33,8 @@ public sealed class AdminOperationsActor : ReceiveActor
private readonly ScriptCompileGateMode _scriptCompileGateMode;
private readonly bool _warmScriptGateOnStart;
/// <summary>
/// The coordinator's apply deadline. A <c>Dispatching</c> row with no expected-ack rows that is older
/// than this is a lost dispatch, closed by the in-flight check (fix round 1 / I7).
@@ -66,6 +68,7 @@ public sealed class AdminOperationsActor : ReceiveActor
/// <param name="alarmVerdictWindow">#950: how long an <c>/alerts</c> ack/shelve waits for the nodes' verdicts; defaults to <see cref="AlarmCommandVerdictCollector.DefaultWindow"/>.</param>
/// <param name="scriptChecker">lmxopcua#971 follow-up: the deploy-time script compile gate, or <see langword="null"/> to skip it.</param>
/// <param name="scriptCompileGateMode">How a refused script is treated (Error default | Warn | Off).</param>
/// <param name="warmScriptGateOnStart">#1024: when true the checker's cache is warmed in the background as the actor starts (production wiring), so the first deploy after a restart is not a cold Roslyn compile.</param>
/// <returns>Props configured to create an AdminOperationsActor.</returns>
public static Props Props(
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
@@ -76,10 +79,11 @@ public sealed class AdminOperationsActor : ReceiveActor
TimeSpan? applyDeadline = null,
TimeSpan? alarmVerdictWindow = null,
IDeployScriptChecker? scriptChecker = null,
ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error) =>
ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error,
bool warmScriptGateOnStart = false) =>
Akka.Actor.Props.Create(() =>
new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline,
alarmVerdictWindow, scriptChecker, scriptCompileGateMode));
alarmVerdictWindow, scriptChecker, scriptCompileGateMode, warmScriptGateOnStart));
/// <summary>Initializes a new instance of the AdminOperationsActor.</summary>
/// <param name="dbFactory">Factory for creating config database contexts.</param>
@@ -91,6 +95,7 @@ public sealed class AdminOperationsActor : ReceiveActor
/// <param name="alarmVerdictWindow">#950: the <c>/alerts</c> verdict collection window.</param>
/// <param name="scriptChecker">lmxopcua#971 follow-up: the deploy-time script compile gate, or <see langword="null"/> to skip it.</param>
/// <param name="scriptCompileGateMode">How a refused script is treated (Error default | Warn | Off).</param>
/// <param name="warmScriptGateOnStart">#1024: warm the checker's cache in the background on start.</param>
public AdminOperationsActor(
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
IActorRef coordinator,
@@ -100,8 +105,10 @@ public sealed class AdminOperationsActor : ReceiveActor
TimeSpan? applyDeadline = null,
TimeSpan? alarmVerdictWindow = null,
IDeployScriptChecker? scriptChecker = null,
ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error)
ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error,
bool warmScriptGateOnStart = false)
{
_warmScriptGateOnStart = warmScriptGateOnStart;
_scriptChecker = scriptCompileGateMode == ScriptCompileGateMode.Off ? null : scriptChecker;
_scriptCompileGateMode = scriptCompileGateMode;
_alarmVerdictWindow = alarmVerdictWindow ?? AlarmCommandVerdictCollector.DefaultWindow;
@@ -127,6 +134,19 @@ public sealed class AdminOperationsActor : ReceiveActor
Receive<ShelveAlarmCommand>(HandleShelveAlarm);
}
/// <summary>
/// #1024: warms the script compile gate's cache off the actor thread as the singleton starts (and on every
/// failover re-spawn), so the FIRST deploy after a central restart is not a cold Roslyn compile of the whole
/// fleet's scripts racing the AdminUI's ask timeout. Fire-and-forget; the warm-up is best-effort and a
/// concurrent deploy shares the in-flight compiles (the checker's per-key lazy).
/// </summary>
protected override void PreStart()
{
base.PreStart();
if (_warmScriptGateOnStart && _scriptChecker is { } checker)
_ = Task.Run(() => WarmScriptCompileGateAsync(checker));
}
/// <summary>
/// The reply text for an unexpected server-side failure (R03:4.1): a fixed sentence plus the request's
/// correlation id, never <c>ex.Message</c> — a SqlException or UriFormatException message carries
@@ -157,7 +157,8 @@ public static class ServiceCollectionExtensions
// is past the coordinator's deadline, so the two must never drift.
return AdminOperationsActor.Props(dbFactory, coordinator, probes, mode, meshRouter,
applyDeadline: DeployTimings.ApplyDeadline,
scriptChecker: scriptChecker, scriptCompileGateMode: scriptMode);
scriptChecker: scriptChecker, scriptCompileGateMode: scriptMode,
warmScriptGateOnStart: true);
},
singletonOptions);
@@ -65,6 +65,38 @@ public sealed class AdminOperationsClientDeployTimeoutTests : TestKit
.DeploymentId.ShouldBe(result.DeploymentId.Value.Value);
}
/// <summary>
/// #1024: the deploy trigger has its own, longer ask timeout — a cold Roslyn compile on a large fleet can
/// outlast the 10 s used for ack/shelve. A compose slower than the short timeout but inside the deploy one
/// is a normal Accepted, not an OutcomeUnknown.
/// </summary>
[Fact]
public async Task Deploy_uses_its_own_longer_timeout_so_a_slow_compose_is_still_Accepted()
{
var gated = new GatedFactory(AclScopeTestDb.Factory($"deploy-longer-{Guid.NewGuid():N}"));
var coordinator = CreateTestProbe("coordinator");
var actor = Sys.ActorOf(AdminOperationsActor.Props(gated, coordinator.Ref, Enumerable.Empty<IDriverProbe>()));
var registry = new ActorRegistry();
registry.Register<AdminOperationsActorKey>(actor);
var client = new AdminOperationsClient(registry, TimeSpan.FromMilliseconds(300), TimeSpan.FromSeconds(30));
gated.Hold();
var pending = client.StartDeploymentAsync("ci", CancellationToken.None);
await Task.Delay(800, TestContext.Current.CancellationToken); // past the short timeout
pending.IsCompleted.ShouldBeFalse();
gated.Release();
(await pending).Outcome.ShouldBe(StartDeploymentOutcome.Accepted);
}
/// <summary>The production default for the deploy trigger is longer than the general ask timeout.</summary>
[Fact]
public void Default_deploy_timeout_exceeds_the_general_ask_timeout()
{
AdminOperationsClient.DefaultDeployAskTimeout.ShouldBeGreaterThan(AdminOperationsClient.DefaultAskTimeout);
AdminOperationsClient.DefaultDeployAskTimeout.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(30));
}
/// <summary>A caller-initiated cancellation is still a cancellation, not an unknown outcome.</summary>
[Fact]
public async Task Caller_cancellation_still_throws()
@@ -256,6 +256,48 @@ public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneAct
checker.Calls.First().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit));
}
/// <summary>#1024: with warm-on-start the checker is exercised the moment the singleton starts — before any deploy.</summary>
[Fact]
public void Warm_on_start_compiles_the_scripts_before_any_deploy_arrives()
{
var checker = new RecordingChecker();
Sys.ActorOf(AdminOperationsActor.Props(
SeedDraft(new Seed()), CreateTestProbe().Ref, Enumerable.Empty<IDriverProbe>(),
scriptChecker: checker, warmScriptGateOnStart: true));
AwaitAssert(() => checker.Calls.Count.ShouldBe(1), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
checker.Calls.Single().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit));
checker.Calls.Single().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.AlarmPredicate, LegitPredicate));
}
/// <summary>#1024: warm-on-start is off by default and never runs with the gate Off.</summary>
[Fact]
public void Warm_on_start_is_not_run_when_the_gate_is_off_or_not_requested()
{
var checker = new RecordingChecker();
var db = SeedDraft(new Seed());
Sys.ActorOf(AdminOperationsActor.Props(db, CreateTestProbe().Ref, Enumerable.Empty<IDriverProbe>(), scriptChecker: checker));
Sys.ActorOf(AdminOperationsActor.Props(db, CreateTestProbe().Ref, Enumerable.Empty<IDriverProbe>(),
scriptChecker: checker, scriptCompileGateMode: ScriptCompileGateMode.Off, warmScriptGateOnStart: true));
Thread.Sleep(500);
checker.Calls.ShouldBeEmpty();
}
/// <summary>#1024: a throwing warm-up never takes the actor down — a deploy still works.</summary>
[Fact]
public void A_throwing_start_warm_up_does_not_break_the_next_deploy()
{
var dbFactory = SeedDraft(new Seed());
var coordinator = CreateTestProbe();
var checker = new RecordingChecker(@throw: true);
var actor = Sys.ActorOf(AdminOperationsActor.Props(
dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>(),
scriptChecker: checker, scriptCompileGateMode: ScriptCompileGateMode.Warn, warmScriptGateOnStart: true));
AwaitAssert(() => checker.Calls.Count.ShouldBeGreaterThanOrEqualTo(1), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
actor.Tell(new StartDeployment("joe", CorrelationId.NewId()));
ExpectMsg<StartDeploymentResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
[Fact]
public async Task Collected_uses_resolve_equip_exactly_as_the_compose_seams_do()
{