fix(config): #1040 #1049 script FKs, unique ZTag/SAPID indexes, reservation ledger retired

One migration, ScriptForeignKeysAndExternalIdUniqueness:
- FK_VirtualTag_Script / FK_ScriptedAlarm_Script (Restrict) onto Script.ScriptId, which becomes
  NOT NULL and an alternate key (unique constraint UX_Script_LogicalId replaces the index).
- UX_Equipment_ZTag / UX_Equipment_SAPID filtered UNIQUE indexes (blank = no identifier, the
  deploy gate's reading) replace the non-unique IX_ ones.
- ExternalIdReservation + sp_ReleaseExternalIdReservation dropped (decision: retire — no writer
  since the generation model; uniqueness is gate + indexes). The /reservations page, query,
  ReservationKind, DraftSnapshot.ActiveReservations and the reservation pre-flight rule go too.
- A read-only pre-check THROWs 51049 naming every offending row class (NULL ScriptId, dangling
  VirtualTag/ScriptedAlarm script, duplicated ZTag/SAPID, any reservation row) and changes
  nothing; Down restores the previous shape.

Authoring mirrors so the constraints are never the first to say no: UnsTreeService refuses a
missing script for VirtualTag/ScriptedAlarm create/update, and a ZTag/SAPID another equipment
holds on create/update/import (owner named; import keeps the clean rows); values stored trimmed.
ScriptEdit maps a concurrent-bind FK refusal to a message. Migration pre-check, Down round-trip,
FK and index behaviour pinned against real SQL with positive controls.
This commit is contained in:
Joseph Doherty
2026-12-03 15:14:26 -05:00
parent 682ab34137
commit 90de55535d
34 changed files with 3002 additions and 624 deletions
+1 -1
View File
@@ -85,7 +85,7 @@ Integration-test fixtures: [Modbus](drivers/Modbus-Test-Fixture.md) · [S7](driv
| [ServiceHosting.md](ServiceHosting.md) | Single fused `OtOpcUa.Host` binary install/uninstall with role gating, Traefik, script-worker isolation |
| [security.md](security.md) | Transport security profiles, LDAP (AdminUI), data-plane API keys, ACLs, role grants, OTOPCUA0001 analyzer |
| [Redundancy.md](Redundancy.md) | `RedundancyStateActor`, `ServiceLevelCalculator`, per-cluster meshes, deploy acks, Prometheus metrics |
| [Reservations.md](Reservations.md) | Fleet-wide ZTag / SAPID external-ID reservations — publish-time claim, release flow |
| [Reservations.md](Reservations.md) | Fleet-wide ZTag / SAPID uniqueness — authoring check, deploy gate, unique indexes (reservation ledger retired, #1049) |
| [v2/admin-ui.md](v2/admin-ui.md) | AdminUI spec |
| [StatusDashboard.md](StatusDashboard.md) | Pointer — superseded by [v2/admin-ui.md](v2/admin-ui.md) |
| [ui-consistency-validation.md](ui-consistency-validation.md) | Shared UI consistency validation record (2026-11) |
+1 -1
View File
@@ -150,7 +150,7 @@ The parent links of the config tables (Tag→Device/TagGroup, Device→DriverIns
**logical** foreign keys only, and the service-layer "is it empty?" delete checks are not serialised against a concurrent add. The deploy gate
(`DraftValidator.ValidateDanglingReferences`) therefore names every orphan as `DanglingReference` instead of letting each composer silently skip a
row with no path. Also enforced at the gate: fleet-wide `Equipment.ZTag` / `SAPID` uniqueness (`BadDuplicateExternalIdentifier`; see
`docs/Reservations.md`) and duplicate owned historian tagnames (`HistorianTagnameDuplicate`, `.claude/rules/historian.md`). The never-firing
`docs/Reservations.md`; since #1049 also the filtered unique indexes `UX_Equipment_ZTag` / `UX_Equipment_SAPID`) and duplicate owned historian tagnames (`HistorianTagnameDuplicate`, `.claude/rules/historian.md`). The never-firing
`PathTooLong` and `EquipmentUuidImmutable` rules were deleted (the UnsSegment charset already bounds the path at 164 chars; no prior-generation
table exists to diff).
+22 -145
View File
@@ -1,154 +1,31 @@
# External-ID Reservations
# External-ID (ZTag / SAPID) uniqueness
> **Status (lmxopcua#998, 2026-12): the reservation ledger has no writer.** `sp_PublishGeneration`, the only code
> that inserted `ExternalIdReservation` rows, was retired with the generation model (it now only `RAISERROR`s), so the
> table stays empty and the pre-flight below can only fire against rows an operator inserted by hand. **Fleet-wide
> ZTag / SAPID uniqueness is now enforced by the deploy gate itself**: `DraftValidator.ValidateEquipmentExternalIdUniqueness`
> groups every equipment row in the (whole-DB) draft snapshot by trimmed, case-insensitive ZTag and by SAPID and
> reports each duplicate as `BadDuplicateExternalIdentifier` naming the other equipment (same cluster or not).
> Blank values mean "no identifier". The permanent-claim semantics described below (a retired asset's id staying
> reserved) are **not** provided; the table, `/reservations` page and release procedure remain for any rows that
> already exist. The equipment page's field hint says "rejected when you deploy", matching this. A filtered unique
> index on `Equipment.ZTag` / `SAPID` was not added (needs a duplicate pre-clean migration); the gate is the authority.
> **The reservation ledger is retired (lmxopcua#1049, 2026-12).** `ExternalIdReservation`, the `/reservations`
> page, `sp_ReleaseExternalIdReservation` and the deploy gate's reservation pre-flight are gone. The ledger's only
> writer, `sp_PublishGeneration`, was retired with the generation model, so the table stayed empty and the
> pre-flight could never fire (review 2026-12-02, C-3). The permanent "a retired asset's id stays claimed" semantics
> of decision #124 were therefore never in force in v3, and are not provided now.
The reservation subsystem guarantees that an asset's **external identifiers**
— its `ZTag` and `SAPID` — belong to exactly one piece of equipment across the
entire fleet, for all time. It is the mechanism that stops two pieces of
equipment (in the same cluster or different clusters, in the current generation
or an old one) from silently claiming the same plant tag.
An equipment's **external identifiers** — its `ZTag` (ERP id) and `SAPID` (SAP PM id) — are unique **fleet-wide**:
no two `Equipment` rows, in the same cluster or different clusters, may carry the same value. Both are optional; a
blank value means "no identifier".
This is **decision #124** in `docs/v2/plan.md`.
## Where it is enforced
## What a reservation is
| Layer | What | Comparison |
|---|---|---|
| Authoring (`UnsTreeService`) | Equipment create / update / CSV import refuse a value another equipment holds and name that equipment; an import names each clashing row (against the DB or an earlier row of the same file) and still imports the clean rows. Values are stored trimmed; blank is stored as `NULL`. | Trimmed; the DB's case-insensitive collation |
| Deploy gate (`DraftValidator.ValidateEquipmentExternalIdUniqueness`) | The authority: every duplicate in the whole-DB draft snapshot is reported as `BadDuplicateExternalIdentifier`, naming the other equipment. | Trimmed, case-insensitive, blank = none |
| Storage (`UX_Equipment_ZTag`, `UX_Equipment_SAPID`) | Filtered UNIQUE indexes, `WHERE [ZTag] IS NOT NULL AND [ZTag] <> N''` (same for `SAPID`) — the backstop for a concurrent save or a hand edit. Never stricter than the gate. | Column collation (case-insensitive) |
An `ExternalIdReservation` row is a permanent, fleet-wide claim on one
identifier value by one `EquipmentUuid`. There are two kinds
(`ReservationKind`):
## Upgrading a populated ConfigDb
| Kind | What it is |
|---------|------------|
| `ZTag` | The plant's tag identity for a physical asset. |
| `SAPID` | The asset's SAP record ID. |
An `Equipment` row may carry a `ZTag`, a `SAPID`, both, or neither. Whenever it
carries one and the generation is published, a reservation is created for that
value.
## Why it sits outside the generation flow
Every other part of the configuration is **generation-versioned** — authored in
a draft, promoted by publish, superseded by the next publish, and reversible by
rollback. Reservations deliberately are **not**.
The reason: a single ZTag can legitimately appear in many places at once — the
current published generation, several superseded generations, and a piece of
equipment that has since been disabled. A per-generation uniqueness index would
fail the instant you roll back to an older generation or re-enable disabled
equipment, because the "old" copy of the identifier is still on disk.
So the reservation table is a flat, fleet-wide ledger that lives *beside* the
generation flow. It is append-mostly: rows are created, their `LastPublishedAt`
is refreshed, and they are eventually *released* — but never silently deleted.
## The table
`ExternalIdReservation` (Config DB):
| Column | Notes |
|--------------------|-------|
| `ReservationId` | Surrogate PK (`NEWSEQUENTIALID()`). |
| `Kind` | `ZTag` or `SAPID`. |
| `Value` | The reserved identifier string. |
| `EquipmentUuid` | The equipment that owns the claim. Stays bound even when that equipment is disabled. |
| `ClusterId` | The first cluster to publish the reservation. |
| `FirstPublishedAt` / `FirstPublishedBy` | When and by whom the claim was first made. |
| `LastPublishedAt` | Refreshed on every subsequent publish that re-asserts the same `(Kind, Value, EquipmentUuid)`. |
| `ReleasedAt` / `ReleasedBy` / `ReleaseReason` | Non-null once an Administrator explicitly releases the claim. `ReleasedBy` is the LDAP operator name (passed explicitly as `@ReleasedBy`; not `SUSER_SNAME()`). A row with `ReleasedAt IS NULL` is *active*. |
There is no foreign key from `EquipmentUuid` / `ClusterId` to their tables — by
design, so a reservation survives the deletion or disabling of the equipment
that owns it.
## Lifecycle
### 1. Authoring
You give an `Equipment` row a `ZTag` and/or `SAPID` in a **draft** generation —
either by hand in the draft editor or via equipment CSV import. Nothing is
reserved yet; the draft is just a proposal.
> Equipment CSV import does **not** pre-check reservation conflicts (tracked as
> task #197). A conflict introduced by import surfaces at publish time, below.
### 2. Publish precheck
`sp_PublishGeneration` runs the draft validation first. If a `ZTag` or `SAPID`
in the draft is already reserved — `ReleasedAt IS NULL` — by a **different**
`EquipmentUuid`, the publish is rejected:
```
BadDuplicateExternalIdentifier: a ZTag in the draft is reserved by a
different EquipmentUuid
```
The same value owned by the *same* `EquipmentUuid` is fine — that is just the
asset keeping its identifier across generations.
### 3. Publish (the reservation is created)
When the publish succeeds, `sp_PublishGeneration` runs a `MERGE` into
`ExternalIdReservation` for every `ZTag`/`SAPID` in the published generation:
- **New** `(Kind, Value, EquipmentUuid)` → a reservation row is **inserted**.
`FirstPublishedBy` is the publishing user; `ClusterId` is the publishing
cluster.
- **Already present** → only `LastPublishedAt` is bumped.
So the *first* publish of an equipment carrying a ZTag is what claims that ZTag
for the fleet. After that the claim is permanent — it survives the equipment
being disabled, the generation being superseded, or a rollback.
### 4. Release
Reusing an identifier for a **different** piece of equipment requires an
Administrator to explicitly release the existing claim. Release runs
`sp_ReleaseExternalIdReservation`, which:
- Requires a non-empty **reason** — a hard audit invariant; the procedure
raises an error without one.
- Requires a non-empty **`@ReleasedBy`** — the LDAP operator name supplied
by the caller; the procedure raises an error without it.
- Stamps `ReleasedAt`, `ReleasedBy` (the supplied operator name), and
`ReleaseReason` rather than deleting the row, so the history is preserved.
- Once released, the `(Kind, Value)` pair is free — a different
`EquipmentUuid` can claim it on a future publish.
Release the claim **only** when the physical asset is permanently retired and
its identifier genuinely needs to be reused. A reservation is meant to be
permanent for the life of the asset.
## The Admin page
`/reservations` (Admin UI) is the operator surface. It requires authentication
(`[Authorize]`) but is not restricted to a specific Admin UI role — any signed-in
user can view it.
The page is a **read-only list** of `ExternalIdReservation` rows, ordered by Kind
then Value. It shows Kind, Value, owning `EquipmentUuid`, and Cluster. Since
#996 (review A-8) it lists **active** rows by default (a "Show released" toggle
adds the released ones and a Released column), reads only the displayed columns
(`ReservationListQuery`) and shows at most 200 rows with a "Showing N of M"
header — released rows accumulate for the life of the database. There is no
Release action and no Release dialog on this page.
You cannot *create* a reservation from this page — reservations only ever come
into existence as a side-effect of publishing a generation. The release flow
is described in `docs/v2/admin-ui.md` § "Release an external-ID reservation"
and runs via `sp_ReleaseExternalIdReservation`.
Migration `ScriptForeignKeysAndExternalIdUniqueness` creates the unique indexes and drops the ledger. It refuses
(error 51049, nothing changed) while any non-blank ZTag or SAPID is duplicated, or while `ExternalIdReservation`
still holds rows (export them if their history matters, then delete them). Run the upgrade preflight first — it lists
exactly those rows: [docs/v2/upgrade-preflight.md](v2/upgrade-preflight.md).
## Related
- `docs/v2/plan.md` — decision #124 (reservations outside the generation flow).
- `docs/v2/admin-ui.md` — § "Release an external-ID reservation".
- `docs/v2/config-db-schema.md` — full Config DB schema.
- `OpcUaServer.md` — generations, draft/publish flow.
- `docs/v2/plan.md` — decision #124 (the original reservation design, historical).
- `docs/Raw.md` — the other deploy-gate uniqueness rules (#998).
+1 -1
View File
@@ -344,7 +344,7 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT
- **AdminUI.** The script editor's completion/hover catalog (`ScriptTagCatalog`) lists each VirtualTag under its key instead of its bare leaf name.
- Pinned by `VirtualTagToVirtualTagFlowTests` (Host.Tests: real mux + host + Roslyn evaluator; value, change and disabled-upstream propagation), `VirtualTagOutputRoutingTests` (Runtime.Tests: mux pinning/replay/release, host routing, re-assert exclusion, runtime cycle backstop) and `DraftValidatorVirtualTagCycleTests`.
- **Supervision restart re-applies.** A restart of `VirtualTagHostActor` builds a host with no children and no definitions; its `PostRestart` tells the parent `VirtualTagHostRestarted` and `DriverHostActor` re-sends the last `ApplyVirtualTags` (mirroring the scripted-alarm host's `ScriptedAlarmHostRestarted`), so VirtualTags resume without waiting for the next deploy. Pinned by `DriverHostActorVirtualTagTests.After_a_supervision_restart_the_virtual_tag_host_is_re_applied`.
- **Names and scripts are gated (lmxopcua#978).** A VirtualTag `Name` is its UNS NodeId leaf (`{EquipmentId}/{Name}`), so the modal, `UnsTreeService` and the deploy gate (`VirtualTagNameInvalid`) all apply `V3NodeIds.ValidateSegment` (no `/`, no leading/trailing whitespace). Every VirtualTag `ScriptId` and ScriptedAlarm `PredicateScriptId` must name an existing script (`VirtualTagScriptNotFound` / `ScriptedAlarmScriptNotFound`, disabled rows included), and the `/scripts/{id}` delete refuses a script still used by a VirtualTag, ScriptedAlarm or Calculation tag, naming them (`ScriptUsage`; there is no FK, so a concurrent bind is caught by the gate). As a backstop for an artifact that bypassed the gate, `VirtualTagHostActor` skips a plan whose NodeId cannot be built (logged at Error) instead of crashing the host — which used to stop every VirtualTag on the node with nothing re-applying — and `AddressSpaceApplier.MaterialiseEquipmentVirtualTags` counts it as a failed node (degraded apply) instead of aborting the pass. Pinned by `DraftValidatorUnsLeafNameAndScriptTests`, `UnsLeafNameAuthorityTests`, `VirtualTagHostActorTests.An_illegal_name_is_skipped_and_the_good_tags_keep_working` and `ScriptEditLifecycleTests.A_script_in_use_is_not_deleted_and_the_user_is_named`.
- **Names and scripts are gated (lmxopcua#978).** A VirtualTag `Name` is its UNS NodeId leaf (`{EquipmentId}/{Name}`), so the modal, `UnsTreeService` and the deploy gate (`VirtualTagNameInvalid`) all apply `V3NodeIds.ValidateSegment` (no `/`, no leading/trailing whitespace). Every VirtualTag `ScriptId` and ScriptedAlarm `PredicateScriptId` must name an existing script (`VirtualTagScriptNotFound` / `ScriptedAlarmScriptNotFound`, disabled rows included), and the `/scripts/{id}` delete refuses a script still used by a VirtualTag, ScriptedAlarm or Calculation tag, naming them (`ScriptUsage`). Since lmxopcua#1040 the database refuses it too: `FK_VirtualTag_Script` / `FK_ScriptedAlarm_Script` (Restrict) onto the `Script.ScriptId` alternate key, so a concurrent bind cannot leave a dangling row and an in-use delete fails; `UnsTreeService` refuses a missing script by name before the FK would. Calculation tags name their script inside `TagConfig` JSON, so only the delete guard and the gate (`CalculationScriptNotFound`) cover them. As a backstop for an artifact that bypassed the gate, `VirtualTagHostActor` skips a plan whose NodeId cannot be built (logged at Error) instead of crashing the host — which used to stop every VirtualTag on the node with nothing re-applying — and `AddressSpaceApplier.MaterialiseEquipmentVirtualTags` counts it as a failed node (degraded apply) instead of aborting the pass. Pinned by `DraftValidatorUnsLeafNameAndScriptTests`, `UnsLeafNameAuthorityTests`, `VirtualTagHostActorTests.An_illegal_name_is_skipped_and_the_good_tags_keep_working` and `ScriptEditLifecycleTests.A_script_in_use_is_not_deleted_and_the_user_is_named`.
- **Timer-driven evaluation (lmxopcua#783).** `VirtualTag.TimerIntervalMs` re-evaluates the tag on a fixed cadence (minimum 50 ms, clamped) via an Akka scheduler owned by `VirtualTagActor` — started in `PreStart`, cancelled in `PostStop`, so a stop or a redeploy respawn never leaves a ticker. `ChangeTriggered=false` makes the timer the only trigger (dependencies are still tracked). A tick that lands while a script run is in flight is dropped rather than stashed, so a slow script never builds a backlog of runs. Before this the field was stored, validated and edited but never consumed, so a timer-only tag sat at `BadWaitingForInitialData` forever. The deploy gate `VirtualTagNoEffectiveTrigger` (mirror of `CalculationNoEffectiveTrigger`) rejects a tag with neither a timer nor a change-trigger with a literal `ctx.GetTag` read. Pinned by `VirtualTagActorTimerTests` and `DraftValidatorVirtualTagTriggerTests`.
- **Calculation tags and scripted alarms still evaluate one script at a time per driver / per engine (deliberately, for now).** Neither blocks a thread — both await the run — but a slow script still delays its siblings. Running independent scripts in parallel was considered for #779 and not done, because it is not semantics-neutral: for Calculation, the single pump is what bounds a driver to one pool thread of script work (per-tag lanes would let N slow tags hold N pool threads, the pool Akka's dispatchers also run on, so it needs a bounded-parallelism knob), it would reorder publishes across tags, and the timer path would need per-tag exclusion with the pump; for scripted alarms, the engine gate is also the consistency boundary of the Part 9 state machine, persist-before-update and ack/shelve/load, a predicate's transition time is sampled just before its own run, and a store failure mid-batch today leaves later predicates un-run (in parallel they would already have run, moving their run-guard strike streaks and writing script logs for results that are then discarded). The out-of-process runner's batch-submit `IScriptRunner` (#750) is where that concurrency belongs, with the runner owning the bound.
- **`IHistoryWriter`** — the equipment-namespace path threads `Historize` end-to-end and `VirtualTagHostActor` invokes the injected writer on historized results (H5); the writer is resolved through `DriverHostActor` DI with a `NullHistoryWriter` default. No *durable* writer ships on this seam — durable continuous historization now flows through the separate `ContinuousHistorizationRecorder` → HistorianGateway `WriteLiveValues` path (see the `IHistoryWriter` section above and [Historian.md](Historian.md)).
+4 -2
View File
@@ -447,7 +447,9 @@ CREATE INDEX IX_Equipment_Generation_MachineCode
ON dbo.Equipment (GenerationId, MachineCode);
```
**Note on ZTag/SAPID uniqueness**: per-generation indexes above are non-unique (only `IX_*`, not `UX_*`). Fleet-wide uniqueness lives in the `ExternalIdReservation` table (see below). Per-generation indexes exist only for fast lookup; uniqueness is enforced at publish time against the reservation table, which is rollback-safe.
> **Current (v3, lmxopcua#1049):** the reservation ledger below is retired and dropped. Uniqueness is enforced by `UnsTreeService`, the deploy gate (`BadDuplicateExternalIdentifier`) and the filtered unique indexes `UX_Equipment_ZTag` / `UX_Equipment_SAPID` — see `docs/Reservations.md`.
**Note on ZTag/SAPID uniqueness (historical v2 design)**: per-generation indexes above are non-unique (only `IX_*`, not `UX_*`). Fleet-wide uniqueness lives in the `ExternalIdReservation` table (see below). Per-generation indexes exist only for fast lookup; uniqueness is enforced at publish time against the reservation table, which is rollback-safe.
**Identifier responsibilities** — equipment carries five distinct identifiers, each with a different audience:
@@ -572,7 +574,7 @@ The migrations widen `NodeAcl.ScopeKind` to 32 characters for mapping-specific g
The database stores references for outbound connection credentials. See
[Data connections](../DataConnections.md) for authorization and credential provisioning.
### `ExternalIdReservation`
### `ExternalIdReservation` (retired — dropped by migration `ScriptForeignKeysAndExternalIdUniqueness`, lmxopcua#1049)
```sql
CREATE TABLE dbo.ExternalIdReservation (