Merge ConfigDb follow-ups: script FKs + ZTag/SAPID filtered unique indexes, ExternalIdReservation retired (#1040/#1049, migration ScriptForeignKeysAndExternalIdUniqueness with pre-check), SqlNamedQueryInvalid deploy rule (#1058), read-only otopcua-preflight upgrade tool (#1013/#1015/#1021)
# Conflicts: # docs/VirtualTags.md
This commit is contained in:
+2
-1
@@ -85,11 +85,12 @@ 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) |
|
||||
| [v2/dev-environment.md](v2/dev-environment.md) | Dev-box bootstrap + endpoint inventory |
|
||||
| [v2/upgrade-preflight.md](v2/upgrade-preflight.md) | `otopcua-preflight` — read-only pre-upgrade ConfigDb check (migration pre-checks, deploy gate, script gate) |
|
||||
| [v2/redundancy-interop-playbook.md](v2/redundancy-interop-playbook.md) | Redundancy interop playbook |
|
||||
|
||||
### Client tooling
|
||||
|
||||
+1
-1
@@ -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
@@ -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
@@ -362,7 +362,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. A tick that lands within half an interval of the last timer evaluation is dropped too (#1061): Akka's scheduler delivers every tick it missed during a stall of its thread (GC pause, CPU starvation) as one burst when it resumes, which used to run the script once per missed tick. 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)).
|
||||
|
||||
+10
-4
@@ -223,9 +223,11 @@ row:
|
||||
`SELECT`**, with no `INTO` and no `OPENQUERY` / `OPENROWSET` / `OPENDATASOURCE` (they run text on another
|
||||
server or read a file). CTEs, subqueries, window functions, `UNION`, `OPTION (…)` and `@name` parameters
|
||||
are ordinary `SELECT`s and pass. An Odbc statement's positional `?` markers are read as variables for the
|
||||
parse; anything else SQL Server's grammar does not accept — a PostgreSQL `::` cast, `LIMIT`, a T-SQL
|
||||
reserved word used as a bare alias (`AS top`) — is refused on Odbc, so quote or rename it. The lexical
|
||||
rules remain as a second, independent layer.
|
||||
parse; anything else SQL Server's grammar does not accept — a PostgreSQL `::` cast of a literal or an
|
||||
expression (`'a'::text`, `(v)::numeric`), `LIMIT`, `ILIKE`, a T-SQL reserved word used as a bare alias
|
||||
(`AS top`) — is refused on Odbc, so quote or rename it. (`col::type` between two bare identifiers happens
|
||||
to PARSE as T-SQL static-member syntax and is accepted.) The lexical rules remain as a second, independent
|
||||
layer.
|
||||
- **It executes in a read-only transaction where the provider has one** — always rolled back regardless:
|
||||
PostgreSQL and Oracle `SET TRANSACTION READ ONLY`, MySQL a read-only **session** plus `START TRANSACTION
|
||||
READ ONLY` (a smuggled `COMMIT` ends a transaction, not a session; the session is restored afterwards). A
|
||||
@@ -246,7 +248,11 @@ row:
|
||||
**must** connect with a `SELECT`-only login (see [Database login](#database-login-required)).
|
||||
- A tag naming a query the driver config does not declare is **skipped** at Initialize (it reads
|
||||
`BadNodeIdUnknown`, and `/hosts` names the missing query). One unusable `queries` entry **fails the
|
||||
driver** instead, because every tag that names it would otherwise go dark unexplained.
|
||||
driver** instead, because every tag that names it would otherwise go dark unexplained. Since lmxopcua#1058
|
||||
the **deploy gate refuses it first** (`SqlNamedQueryInvalid`, naming the driver instance): it runs the same
|
||||
`SqlNamedQueryRules.Describe` over the same merged config with the instance's provider. Before upgrading
|
||||
a deployment that has Odbc drivers, run the [upgrade preflight](../v2/upgrade-preflight.md), which lists
|
||||
every stored query the new guard refuses.
|
||||
- Query tags read no table, so they need **no catalog gate** — a driver serving only named queries skips
|
||||
the catalog load entirely. Nothing from a Query tag is ever quoted into SQL.
|
||||
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# Upgrade preflight (`otopcua-preflight`)
|
||||
|
||||
A **read-only** check of an OtOpcUa ConfigDb, run from the **new** build **before** its migrations are applied.
|
||||
It reports every row that the upgrade — or the first deploy after it — would refuse, so the clean-up happens
|
||||
before the maintenance window instead of in the middle of it. It issues only `SELECT`s.
|
||||
|
||||
Introduced for the 2026-12-02 review remediation follow-ups lmxopcua#1013, #1015, #1021 and #1058.
|
||||
|
||||
## What it checks
|
||||
|
||||
| Section | What | Severity | Issue |
|
||||
|---|---|---|---|
|
||||
| `schema` | Applied vs pending migrations; tables/columns a pending migration creates (read as empty/default — see below); whether `ALLOW_SNAPSHOT_ISOLATION` is on. | Info / Warning | — |
|
||||
| `migration:ConfigurationGapsIndexesAndRowVersions` | Duplicate `NodeAcl` rows per (cluster, principal, scope kind, scope id) — typically several Cluster-scope rows for one principal — and duplicate `LdapGroupRoleMapping` rows per (group, cluster), incl. system-wide. The migration THROWs on either. | Blocking | #1021 |
|
||||
| `migration:ScriptForeignKeysAndExternalIdUniqueness` | `Script.ScriptId` NULL; a VirtualTag / ScriptedAlarm naming a script that does not exist; a non-blank ZTag or SAPID on more than one equipment (case-insensitive, as the new unique index); any `ExternalIdReservation` row (the table is dropped). The migration THROWs on any of them. | Blocking | #1040, #1049 |
|
||||
| `deploy-gate` | The deploy gate's own rule pass (`DeployGateRules` — the code `AdminOperationsActor` runs): every `DraftValidator` rule, incl. the #978 rules `VirtualTagNameInvalid`, `UnsEffectiveNameInvalid` (illegal VirtualTag names / display-name overrides), `VirtualTagScriptNotFound`, `ScriptedAlarmScriptNotFound` (dangling script references), the #998 rules (`BadDuplicateExternalIdentifier`, `DanglingReference`, `HistorianTagnameDuplicate`), and `SqlNamedQueryInvalid`; the per-cluster topology check; the TagConfig inspection (Warning unless `--tagconfig-mode Error`). | Blocking (rules) / Warning | #1015, #1058 |
|
||||
| `script-gate` | Every script the runtime will compile (enabled VirtualTags, enabled scripted-alarm predicates, Calculation tags, `{{equip}}` resolved) through the Roslyn compile + sandbox allow-list (`RoslynDeployScriptChecker`, as the deploy gate). Also every **unused** stored script, compiled as a value script — a Warning, since binding it later would be refused. | Blocking (Error mode) / Warning | #1013 |
|
||||
|
||||
`SqlNamedQueryInvalid` (#1058) is a deploy-gate rule added with the preflight: the Sql driver checks every named
|
||||
query with `SqlNamedQueryRules.Describe` under its provider at construction and one refused query fails the whole
|
||||
driver. Since #974 that includes a T-SQL ScriptDom parse for SqlServer, Odbc and no-provider configs, so an **Odbc**
|
||||
query written in another dialect (`LIMIT`, `ILIKE`, `'a'::text`, `(x)::numeric`) is refused — the deploy gate now
|
||||
says so before the driver goes dark. (A bare `col::type` parses as T-SQL static-member syntax and is accepted.)
|
||||
|
||||
### Reading an older schema
|
||||
|
||||
The preflight reads the snapshot through **this build's** EF model, but the database is still on the old schema.
|
||||
A table a pending migration creates is mapped to a typed zero-row query (it will be empty right after the
|
||||
migration); a column a pending migration adds is left out of the model (the property keeps its default). The
|
||||
`schema` section lists exactly which. A schema change the tolerance cannot bridge (e.g. a NULL in a column the new
|
||||
model requires) is reported as `deploy-gate/SnapshotUnreadable`; fix the migration pre-check findings and re-run.
|
||||
|
||||
Only v3 ConfigDbs (with `20260715230637_V3Initial` applied) are accepted; anything else exits 2.
|
||||
|
||||
## Running it
|
||||
|
||||
Build or publish it from the **new** source tree (it must carry the new rules and migrations):
|
||||
|
||||
```bash
|
||||
dotnet publish src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight -c Release -o out/preflight
|
||||
# Windows target: add -r win-x64 --self-contained to run it on the box without an SDK
|
||||
```
|
||||
|
||||
Pass the connection string through the environment (a command-line argument is visible in the process list and
|
||||
shell history). A login with `db_datareader` on the ConfigDb is enough.
|
||||
|
||||
```bash
|
||||
export OTOPCUA_CONFIG_CONNECTION='Server=<host>,<port>;Database=<ConfigDb>;User Id=<reader>;Password=<...>;TrustServerCertificate=True'
|
||||
out/preflight/otopcua-preflight # human-readable; Blocking + Warning findings
|
||||
out/preflight/otopcua-preflight --verbose # + Info (pending migrations, clean sections)
|
||||
out/preflight/otopcua-preflight --json > preflight.json
|
||||
```
|
||||
|
||||
| Option | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `--connection "<cs>"` | `OTOPCUA_CONFIG_CONNECTION` | ConfigDb connection string |
|
||||
| `--tagconfig-mode Warn\|Error` | `Warn` | the target's `Deployment:TagConfigValidationMode` |
|
||||
| `--script-gate Error\|Warn\|Off` | `Error` | the target's `Deployment:ScriptCompileGateMode` |
|
||||
| `--no-unused-scripts` | off | skip compiling scripts nothing uses |
|
||||
| `--json` / `--verbose` | off | output format |
|
||||
|
||||
**Exit codes:** `0` nothing blocks the upgrade or the next deploy · `1` at least one Blocking finding · `2` usage
|
||||
error, unreachable database, or not a v3 ConfigDb.
|
||||
|
||||
## Upgrade procedure
|
||||
|
||||
1. On the running (old) build's ConfigDb, run the preflight from the new build. It is read-only and safe to run
|
||||
against a live database; under SNAPSHOT isolation it does not block editors.
|
||||
2. Fix every Blocking finding through the AdminUI (re-point or delete the VirtualTag/ScriptedAlarm, clear the
|
||||
duplicate ZTag, merge the duplicate ACL rows, rewrite the Odbc query, fix the script) — or, for
|
||||
`ExternalIdReservation` rows, export them if their history matters and delete them. Re-run until exit 0.
|
||||
3. Apply the new build (its migrations). A migration that still finds a bad row THROWs (error 50998 / 51049) and
|
||||
changes nothing; re-run the preflight to see why.
|
||||
4. Deploy. The deploy gate runs the same rules the preflight ran.
|
||||
|
||||
## Results recorded
|
||||
|
||||
| Date | Target | Schema at | Result |
|
||||
|---|---|---|---|
|
||||
| 2026-12-03 | docker-dev ConfigDb `OtOpcUa` (read from a copy of the stopped rig's SQL volume; the rig was not touched) | `EnableSnapshotIsolation` (6 pending) | exit 0 — both migration pre-checks clean, deploy gate clean, 3 in-use scripts compile; no Sql drivers |
|
||||
| 2026-12-03 | `10.100.0.35,14330` / `OtOpcUaCfg_gate_scratch` | `V3Initial` (14 pending) | exit 0 — empty config; the NodeAcl duplicate pre-check could not run on the pre-#520 `LdapGroup` column (Warning) |
|
||||
| 2026-12-03 | `10.100.0.35,14330` / `OtOpcUaConfig`, `OtOpcUaConfig_Dev` | v2 schema | exit 2 — not v3 ConfigDbs (nothing to check) |
|
||||
| — | **production (wonder-app-vd03 / vq03 / vq04)** | — | **not run — user-gated.** Remote commands on the wonder boxes are on hold (see `CLAUDE.md`); an operator with SQL access runs step 1 there. |
|
||||
Reference in New Issue
Block a user