4 Commits

Author SHA1 Message Date
Joseph Doherty 8cb8fcdf57 code-reviews: resolve Server-059/060 + Tests-041 (fixed in 9ae6bce)
Dashboard Galaxy summary now copies volatile fields fresh and memoizes only the
O(N) breakdown; added the DI registration-order wiring test and the memoization
regression/guard tests. All modules back to 0 pending.
2026-06-25 13:44:48 -04:00
Joseph Doherty c004b91164 docs(contracts): mark galaxy_repository.proto as intentionally retained for clients
The 2026-06-25 re-review observed that the gateway server no longer uses the
Contracts-generated Galaxy types (it consumes the wire-identical types from the
ZB.MOM.WW.GalaxyRepository package). That made galaxy_repository.proto look like
dead code. It is not: Go/Rust/Java/Python clients compile it by path, the .NET
client consumes Contracts.Proto.Galaxy.* via project reference, and
clients/proto/proto-inputs.json publishes it. Document this at the csproj entry
and in CLAUDE.md so it is not deleted in a future cleanup.
2026-06-25 13:42:48 -04:00
Joseph Doherty 9ae6bce0c8 fix(dashboard): copy Galaxy summary volatile fields fresh; memoize only O(N) breakdown
Resolves Server-059, Tests-041, Server-060 (2026-06-25 re-review).

DashboardSnapshotService memoized the whole Galaxy summary keyed on the cache
Sequence, but the shared library bumps Sequence only on a heavy refresh: the
steady-state tick, the refresh-failure path, and the age-based status getter all
replace the entry via 'previous with { ... }' at the SAME Sequence. The dashboard
therefore froze LastQueriedAt and, during a Galaxy SQL outage, kept showing
Healthy with no error for the whole outage.

Split DashboardGalaxySummaryProjector into ComputeBreakdown (the O(N) template/
category work, the only sequence-bound part) and BuildSummary (cheap volatile
fields copied fresh). ResolveGalaxySummary now memoizes only the breakdown by
Sequence and rebuilds the summary from the current entry each tick. Removed the
redundant DashboardGalaxyProjector wrapper.

Tests: same-sequence status/error/timestamp now reflected (the regression);
memoization-hit and sequence-invalidation guards; GatewayApplicationTests asserts
the DI container resolves IGalaxyBrowseScopeProvider to GatewayBrowseScopeProvider
(pins the registration-order invariant over the library's no-op default).
2026-06-25 13:42:39 -04:00
Joseph Doherty b062cc0440 code-reviews: 2026-06-25 re-review of Galaxy-adoption delta at 3cd7776
Re-review Server + Tests modules over 88915c3..3cd7776 (the
ZB.MOM.WW.GalaxyRepository 0.2.0 adoption + array-write fixes).
Security-critical browse-scope wiring verified sound. 3 new findings:

- Server-059 (Medium): dashboard Galaxy summary memoized only on
  cache Sequence -> status/timestamps freeze during a Galaxy SQL outage.
- Server-060 (Low): no DI test asserts IGalaxyBrowseScopeProvider
  resolves to GatewayBrowseScopeProvider (registration-order invariant).
- Tests-041 (Medium): memoization invalidation path untested.
2026-06-25 13:21:23 -04:00
11 changed files with 414 additions and 75 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ The architecture is a two-process design — read `gateway.md` before making str
- **Gateway** (`src/ZB.MOM.WW.MxGateway.Server`, .NET 10, x64): ASP.NET Core gRPC server. Owns the public API, sessions, auth, the Blazor dashboard, and the Galaxy Repository SQL browse RPCs. The Galaxy-browse implementation comes from the shared **`ZB.MOM.WW.GalaxyRepository`** package (`AddZbGalaxyRepository`/`MapZbGalaxyRepository`), not inline code; mxaccessgw adds `GatewayBrowseScopeProvider` (per-key browse-subtree scoping) and a host-side dashboard summary projector. See `A2-galaxyrepository-adoption-handoff.md`. **Never instantiates MXAccess COM directly.**
- **Worker** (`src/ZB.MOM.WW.MxGateway.Worker`, .NET Framework 4.8, **x86**): one process per session. Owns one MXAccess COM instance on a dedicated STA, pumps Windows messages, and converts COM events to protobuf.
- **IPC**: gateway↔worker uses one bidirectional named pipe per worker (`mxaccess-gateway-{gatewayPid}-{sessionId}`) with length-prefixed `WorkerEnvelope` protobuf frames. Gateway hosts the pipe server and launches the worker. **gRPC is not used inside the worker** — .NET Framework 4.8 doesn't have a first-class gRPC stack.
- **Contracts** (`src/ZB.MOM.WW.MxGateway.Contracts`): multi-targets `net10.0;net48` and owns the `.proto` files (`mxaccess_gateway.proto`, `mxaccess_worker.proto`, `galaxy_repository.proto`). All other projects consume the generated types from here. Do not hand-edit anything under `Generated/`.
- **Contracts** (`src/ZB.MOM.WW.MxGateway.Contracts`): multi-targets `net10.0;net48` and owns the `.proto` files (`mxaccess_gateway.proto`, `mxaccess_worker.proto`, `galaxy_repository.proto`). All other projects consume the generated types from here. Do not hand-edit anything under `Generated/`. Note `galaxy_repository.proto` is intentionally kept here as the generation source for the language clients even though the gateway server consumes the wire-identical Galaxy types from the `ZB.MOM.WW.GalaxyRepository` package — it is not dead code; deleting it breaks all five clients.
The worker must do all MXAccess COM calls on its dedicated STA thread, and the STA loop must pump Windows messages (`MsgWaitForMultipleObjectsEx` + `PeekMessage`/`DispatchMessage`) so MXAccess events deliver. A plain blocking queue on an STA is not enough.
+5 -2
View File
@@ -17,8 +17,8 @@ Each module's `findings.md` is the source of truth; this file is generated from
| [Client.Rust](Client.Rust/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 40 |
| [Contracts](Contracts/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 25 |
| [IntegrationTests](IntegrationTests/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 33 |
| [Server](Server/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 58 |
| [Tests](Tests/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 40 |
| [Server](Server/findings.md) | Claude Code | 2026-06-25 | `3cd7776` | Re-reviewed | 0 | 60 |
| [Tests](Tests/findings.md) | Claude Code | 2026-06-25 | `3cd7776` | Re-reviewed | 0 | 41 |
| [Worker](Worker/findings.md) | Claude Code | 2026-06-16 | `8df5ab3` | Re-reviewed | 0 | 28 |
| [Worker.Tests](Worker.Tests/findings.md) | Claude Code | 2026-06-18 | `88915c3` | Re-reviewed | 0 | 36 |
@@ -133,6 +133,7 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Server-054 | Medium | Resolved | Design-document adherence | `docs/DesignDecisions.md` (Session Reconnect / Event Subscribers / Later Revisit Items §470-471), `CLAUDE.md` (Repository-Specific Conventions) |
| Server-056 | Medium | Resolved | Concurrency & thread safety | `src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionEventDistributor.cs:296-310,449-453,629-635` |
| Server-057 | Medium | Resolved | Correctness & logic bugs | `src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs:976-1000` (`NormalizeOutboundCommand`), `:1085-1095` (`MapCommand` tracking), `gateway.md` (array-write ergonomics section), `clients/*/README.md` |
| Server-059 | Medium | Resolved | Correctness & logic bugs | `src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs:109-128` |
| Tests-003 | Medium | Resolved | Performance & resource management | `src/MxGateway.Tests/Security/Authentication/SqliteAuthStoreTests.cs:170-176`, `src/MxGateway.Tests/Security/Authentication/ApiKeyAdminCliRunnerTests.cs:252-258` |
| Tests-004 | Medium | Resolved | Testing coverage | `src/MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs` |
| Tests-005 | Medium | Resolved | Testing coverage | `src/MxGateway.Tests/Gateway/Grpc/EventStreamServiceTests.cs:239-261`, `src/MxGateway.Tests/Gateway/Sessions/SessionManagerTests.cs` |
@@ -143,6 +144,7 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Tests-026 | Medium | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/EventStreamServiceTests.cs`, `src/ZB.MOM.WW.MxGateway.Server/Grpc/EventStreamService.cs:123-126` |
| Tests-027 | Medium | Resolved | Concurrency & thread safety | `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceTests.cs:199-240`, `src/ZB.MOM.WW.MxGateway.Server/Metrics/GatewayMetrics.cs:8,73,246-251` |
| Tests-032 | Medium | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.Server/Alarms/GatewayAlarmMonitor.cs:435-441`, `src/ZB.MOM.WW.MxGateway.Tests/Alarms/GatewayAlarmMonitorProviderModeTests.cs`, `src/ZB.MOM.WW.MxGateway.Tests/Alarms/AlarmFailoverEndToEndTests.cs` |
| Tests-041 | Medium | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardSnapshotServiceTests.cs`, `src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs:109-128` |
| Worker-004 | Medium | Resolved | Correctness & logic bugs | `src/MxGateway.Worker/Ipc/WorkerPipeSession.cs:565-588` |
| Worker-005 | Medium | Resolved | Error handling & resilience | `src/MxGateway.Worker/MxAccess/MxAccessStaSession.cs:205-258` (production alarm poll loop) |
| Worker-006 | Medium | Resolved | Correctness & logic bugs | `src/MxGateway.Worker/Ipc/WorkerPipeSession.cs:117-124`, `src/MxGateway.Worker/MxAccess/MxAccessStaSession.cs:386-491` |
@@ -382,6 +384,7 @@ Findings with status `Resolved`, `Won't Fix`, or `Deferred`.
| Server-053 | Low | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.Tests/Alarms/AlarmWatchListResolverTests.cs`, `src/ZB.MOM.WW.MxGateway.Tests/Alarms/GatewayAlarmMonitorProviderModeTests.cs` |
| Server-055 | Low | Resolved | Correctness & logic bugs | `src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs:842-851,1841-1871` |
| Server-058 | Low | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ConstraintEnforcerTests.cs` |
| Server-060 | Low | Resolved | Testing coverage | `src/ZB.MOM.WW.MxGateway.Server/GatewayApplication.cs:95-99`, `src/ZB.MOM.WW.MxGateway.Tests/Gateway/GatewayApplicationTests.cs` |
| Tests-007 | Low | Resolved | Code organization & conventions | `src/MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceTests.cs:682`, `src/MxGateway.Tests/Gateway/Grpc/GalaxyRepositoryGrpcServiceTests.cs:324`, `src/MxGateway.Tests/Gateway/GatewayEndToEndFakeWorkerSmokeTests.cs:460`, `src/MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs:233` |
| Tests-008 | Low | Resolved | mxaccessgw conventions | `src/MxGateway.Tests/Gateway/Sessions/WorkerAlarmRpcDispatcherTests.cs:1-9`, `src/MxGateway.Tests/Gateway/Sessions/NotWiredAlarmRpcDispatcherTests.cs:1-3`, `src/MxGateway.Tests/Gateway/Sessions/SessionManagerAlarmAutoSubscribeTests.cs:1` |
| Tests-009 | Low | Resolved | Documentation & comments | `src/MxGateway.Tests/Gateway/Sessions/SessionManagerTests.cs:36-37,99,365` |
+80 -2
View File
@@ -4,13 +4,56 @@
|---|---|
| Module | `src/ZB.MOM.WW.MxGateway.Server` |
| Reviewer | Claude Code |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Review date | 2026-06-25 |
| Commit reviewed | `3cd7776` |
| Status | Re-reviewed |
| Open findings | 0 |
## Checklist coverage
### 2026-06-25 re-review (commit 3cd7776)
Scoped re-review of the Galaxy-library adoption + array-write fix delta
(`git diff 88915c3..3cd7776 -- src/ZB.MOM.WW.MxGateway.Server`, commits
`8e196a7`/`80bf4ac`/`8678b6c` for the adoption and `2671639` for the array-write
finding fixes). The big change deletes all inline `Galaxy/*` and `Grpc/Galaxy*`
code (−2961 LOC) and adopts `ZB.MOM.WW.GalaxyRepository` 0.2.0 via
`AddZbGalaxyRepository("MxGateway:Galaxy")` + `MapZbGalaxyRepository()`; the
mxaccessgw-only pieces reviewed hardest are `GatewayBrowseScopeProvider` (NEW),
the registration order in `GatewayApplication.cs`, the galaxy request-type rebind
in `GatewayGrpcScopeResolver`, and the host-side `DashboardGalaxySummaryProjector`
+ the `DashboardSnapshotService` summary memo.
Security wiring verified sound: the gateway registers
`AddSingleton<IGalaxyBrowseScopeProvider, GatewayBrowseScopeProvider>()` **before**
`AddZbGalaxyRepository`, and the lib's default is `TryAddSingleton<…,
NullGalaxyBrowseScopeProvider>` (confirmed in lib source), so the gateway provider
wins and per-key browse scoping is NOT silently disabled. All five lib galaxy RPC
request types (`TestConnectionRequest`, `GetLastDeployTimeRequest`,
`DiscoverHierarchyRequest`, `WatchDeployEventsRequest`, `BrowseChildrenRequest`)
map to `MetadataRead`; the switch default is `Admin` (fail-closed, not permissive).
The global authz interceptor authenticates/authorizes and pushes the ambient
identity before the lib service runs (it is a global gRPC interceptor that wraps
the continuation), so `GatewayBrowseScopeProvider.ResolveBrowseSubtrees` reads the
correct identity; a constrained key always carries non-empty `BrowseSubtrees`, so
it can never be widened. The array-write fixes (Server-057 resolution) are correct:
`AddBufferedItem`/`AddItemBulk` are now normalized at the outbound choke point and
re-normalized (or, for bulk, read from the worker-echoed `SubscribeResult.TagAddress`)
at the tracking site so registrations match the write-capable handle the worker bound.
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | Issues found: Server-059 (`DashboardSnapshotService` memoizes the Galaxy summary by `entry.Sequence` only, but the lib mutates `Status`/`LastQueriedAt`/`LastSuccessAt`/`LastError` via `previous with {…}` and the `Current` age-based `ProjectStatus` **without** bumping `Sequence`, so the dashboard serves a stale summary). Array-write fixes verified correct. |
| 2 | mxaccessgw conventions | No issues found — file-scoped namespaces, `sealed`, `Async` suffixes, primary constructors, MXAccess-aligned names; gateway never touches COM; no UI component libraries; no secrets/tag-values logged; generated code untouched. |
| 3 | Concurrency & thread safety | No issues found — the summary memo is a `Volatile` read/write of an immutable record reference; concurrent recompute is benign (pure projection, identical content per sequence). Array-write normalization mutates deep-cloned command copies, never client state. |
| 4 | Error handling & resilience | No issues found — invalid sparse-array payloads still surface as `RpcException(InvalidArgument)`; the lib refresh degrades to Stale/Unavailable; the scope provider returns empty only when no identity is present (documented, unreachable under the global interceptor). |
| 5 | Security | No issues found — scope-provider registration order, the lib `TryAddSingleton` default, the five-RPC → `MetadataRead` mapping, the fail-closed `Admin` default, and the ambient-identity invariant all verified; `ConstraintEnforcer` rebind is namespace-only; the dashboard browse passes `browseSubtreeGlobs: null` intentionally (LDAP operator UI, not an API-key-scoped client). |
| 6 | Performance & resource management | No issues found — the summary memo restores O(1)-per-tick for the common case; the projector allocates only on a sequence change. |
| 7 | Design-document adherence | No issues found in Server source — implementation matches `A2-galaxyrepository-adoption-handoff.md` and the updated `CLAUDE.md`. (Observation, out of Server scope: `ZB.MOM.WW.MxGateway.Contracts` still carries the now-unused `galaxy_repository.proto` + generated code; CLAUDE.md line 14 still lists it as Contracts-owned — a Contracts-module cleanup.) |
| 8 | Code organization & conventions | No issues found — new types live under `Security/Authorization/` and `Dashboard/`; the registration is explicit and commented. (`DashboardGalaxyProjector` now trivially forwards to the public `DashboardGalaxySummaryProjector`; harmless, not filed.) |
| 9 | Testing coverage | Issues found: Server-060 (no test resolves `IGalaxyBrowseScopeProvider` from the gateway DI container to assert `GatewayBrowseScopeProvider` — not the lib's no-op default — wins; the registration-order invariant is the highest-blast-radius wiring in this delta yet is guarded only by manual construction in `GalaxyRepositoryHostWiringTests`). The Server-059 memo path is also untested. Otherwise strong: `GatewayBrowseScopeProviderTests`, `GalaxyRepositoryHostWiringTests`, `DashboardGalaxySummaryProjectorTests`. |
| 10 | Documentation & comments | No issues found beyond Server-059 — the `DashboardSnapshotService` memo comment ("an unchanged sequence means the entry … is unchanged") is inaccurate and is the root justification for that bug; captured under Server-059. |
### 2026-05-20 review (commit 1cd51bb)
This row summarizes the 2026-05-20 review pass at commit `1cd51bb`. Findings from
@@ -1131,3 +1174,38 @@ Additionally, `GatewayAlarmMonitor.ApplyProviderModeChangeAsync` increments the
**Recommendation:** Add a `CheckReadTagAsync` (and a `CheckWriteHandleAsync`) case where the bare/suffixed array attribute resolves but the configured `ReadTagGlobs`/`WriteSubtrees` exclude it, asserting a `read_scope`/`write_scope` `ConstraintFailure` is still returned; and a `CheckWriteHandleAsync` case asserting `MaxWriteClassification` is enforced against the array attribute's `SecurityClassification` via the suffixed registration address.
**Resolution:** 2026-06-18 — Added three `ConstraintEnforcerTests` cases (the test fixture gained a second array attribute `Pump_001.Setpoints[]` with `SecurityClassification = 2` to exercise the classification path): `CheckReadTagAsync_WithBareArrayName_OutOfScope_StillDeniedReadScope` (bare array resolves via the `[]` fallback but is denied `read_scope` when out of `ReadTagGlobs` — guards that the fallback widened resolution, not authorization), `CheckWriteHandleAsync_WithSuffixedArrayRegistration_OutOfScope_StillDeniedWriteScope` (an array handle whose registration `TagAddress` is the suffixed `Pump_001.Levels[]` resolves through `ResolveTarget` and is denied `write_scope`), and `CheckWriteHandleAsync_WithSuffixedArrayRegistration_ClassificationTooHigh_StillDenied` (in-scope suffixed array handle denied `max_write_classification` when the attribute's `SecurityClassification` exceeds `MaxWriteClassification`). Tests-only change; no production code touched.
### Server-059
| Field | Value |
|---|---|
| Severity | Medium |
| Category | Correctness & logic bugs |
| Location | `src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs:109-128` |
| Status | Resolved |
**Description:** `ResolveGalaxySummary` memoizes the projected dashboard Galaxy summary keyed **only** on `entry.Sequence` and returns the cached summary whenever the sequence is unchanged. The comment asserts "an unchanged sequence means the entry (and therefore its summary) is unchanged," but that is false for the adopted `ZB.MOM.WW.GalaxyRepository` 0.2.0 cache: `Sequence` is bumped **only on a heavy refresh that detects a deploy change** (`GalaxyHierarchyCache.RefreshCoreAsync`, `nextSequence = previous.Sequence + 1`). Three other paths replace `_current` via `previous with { … }` **preserving the same `Sequence`** while changing fields the dashboard summary surfaces:
- The no-deploy-change tick (the common steady-state path) updates `LastQueriedAt`/`LastSuccessAt` (and clears `LastError`) every interval at the same sequence.
- The refresh-failure path sets `Status = Stale`/`Unavailable` and `LastError = exception.Message` at the same sequence.
- The `Current` getter's age-based `ProjectStatus` returns `snapshot with { Status = Stale }` at the same sequence.
Because the memo keys on `Sequence` alone, the dashboard serves a stale summary: `LastQueriedAt`/`LastSuccessAt` appear frozen at the last heavy-refresh time even though refreshes keep succeeding, and — most importantly — when the Galaxy SQL database goes unreachable the panel keeps showing `Healthy` with no error for the entire outage (the sequence cannot advance because no heavy refresh can succeed). The Galaxy health indicator, whose purpose is to surface Stale/Unavailable, is defeated exactly when it is needed. Impact is limited to the operator dashboard display (the gRPC browse RPCs and `ConstraintEnforcer` read `cache.Current` directly and are unaffected), but it is a regression from the pre-adoption code, which projected `_galaxyHierarchyCache.Current` on every snapshot tick.
**Recommendation:** Do not memoize the cheap, per-tick-volatile fields. Memoize only the O(N)-to-compute parts that genuinely change with `Sequence` — the `TopTemplates` and `ObjectCategories` lists derived from `entry.Objects` — keyed on `Sequence`, and build the `DashboardGalaxySummary` fresh each call from the current entry's `Status`, `LastQueriedAt`, `LastSuccessAt`, `LastDeployTime`, `LastError`, and the precomputed counts (all cheap copies). Add a `DashboardSnapshotServiceTests` case that swaps the cache's `Current` to a new entry with the **same** `Sequence` but a changed `Status`/`LastError`/`LastQueriedAt` and asserts the next `GetSnapshot().Galaxy` reflects the change. Correct the misleading memo comment.
**Resolution:** Resolved in `9ae6bce` (2026-06-25). Split `DashboardGalaxySummaryProjector` into `ComputeBreakdown` (the O(N) template/category work, the only sequence-bound part) and `BuildSummary` (cheap volatile fields). `ResolveGalaxySummary` now memoizes only the breakdown by `Sequence` and rebuilds the summary from the current entry's `Status`/timestamps/`LastError`/counts on every tick, so a same-sequence outage surfaces `Unavailable`/`LastError`. Memo comment corrected; the redundant `DashboardGalaxyProjector` wrapper was removed. Regression test `DashboardSnapshotServiceTests.GetSnapshot_WhenGalaxyEntryChangesAtSameSequence_ReflectsVolatileStatusAndError` added (plus memoization-hit and invalidation guards).
### Server-060
| Field | Value |
|---|---|
| Severity | Low |
| Category | Testing coverage |
| Location | `src/ZB.MOM.WW.MxGateway.Server/GatewayApplication.cs:95-99`, `src/ZB.MOM.WW.MxGateway.Tests/Gateway/GatewayApplicationTests.cs` |
| Status | Resolved |
**Description:** The per-key browse-subtree scoping depends entirely on the gateway's `AddSingleton<IGalaxyBrowseScopeProvider, GatewayBrowseScopeProvider>()` being registered **before** `AddZbGalaxyRepository(...)`, so that the library's `TryAddSingleton<IGalaxyBrowseScopeProvider, NullGalaxyBrowseScopeProvider>` (no scoping → full hierarchy) loses. This is the highest-blast-radius wiring in the adoption delta: if it ever regressed (the gateway line moved after `AddZbGalaxyRepository`, or the lib switched its default to a plain `AddSingleton`), **all per-API-key browse scoping would silently disable** with no error — a metadata-scoped key would see the entire Galaxy. The provider itself is well covered in isolation (`GatewayBrowseScopeProviderTests`) and end-to-end via manual construction (`GalaxyRepositoryHostWiringTests`), but **no test builds the gateway DI container and asserts `GetRequiredService<IGalaxyBrowseScopeProvider>()` resolves to `GatewayBrowseScopeProvider` rather than `NullGalaxyBrowseScopeProvider`** — the registration-order invariant is guarded only by the inline comment. (The Server-059 memo path is likewise untested; see that finding.)
**Recommendation:** Add a `GatewayApplicationTests` case that runs `GatewayApplication.CreateBuilder([])`, builds the service provider, and asserts `GetRequiredService<IGalaxyBrowseScopeProvider>()` is a `GatewayBrowseScopeProvider`. This pins the registration order and the lib's `TryAdd`-default contract so a future reorder or a lib-default change fails a fast unit test instead of silently widening data exposure.
**Resolution:** Resolved in `9ae6bce` (2026-06-25). Added `GatewayApplicationTests.Build_RegistersGatewayBrowseScopeProviderOverLibraryDefault`, which builds the gateway via `GatewayApplication.Build([])` and asserts `GetRequiredService<IGalaxyBrowseScopeProvider>()` resolves to `GatewayBrowseScopeProvider`, pinning the registration-order invariant over the library's `TryAddSingleton` no-op default.
+77 -2
View File
@@ -4,13 +4,38 @@
|---|---|
| Module | `src/ZB.MOM.WW.MxGateway.Tests` |
| Reviewer | Claude Code |
| Review date | 2026-06-18 |
| Commit reviewed | `88915c3` |
| Review date | 2026-06-25 |
| Commit reviewed | `3cd7776` |
| Status | Re-reviewed |
| Open findings | 0 |
## Checklist coverage
### 2026-06-25 re-review (commit `3cd7776`)
Re-review of the `88915c3..3cd7776` diff. Primary change is the Galaxy library adoption
reconciliation: eight `Galaxy/*Tests.cs` files and `Grpc/GalaxyRepositoryGrpcServiceTests.cs`
deleted (code moved to `ZB.MOM.WW.GalaxyRepository` library and its own test suite).
Replacements: `Grpc/GalaxyRepositoryHostWiringTests.cs` (new), `Security/Authorization/GatewayBrowseScopeProviderTests.cs` (new),
`Dashboard/DashboardGalaxySummaryProjectorTests.cs` (new), `DashboardSnapshotServiceTests.cs`
(updated for projector-driven Galaxy summary). Secondary change: `GatewayArrayWriteWiringTests.cs`
(+438 lines: six missing write-expansion wiring tests from Tests-040 resolution, plus
`AddItem2`, `AddBufferedItem`, `AddItemBulk` normalization tests) and `ConstraintEnforcerTests.cs`
(+126 lines: three new authz-path tests for array-address denial).
| # | Category | Result |
|---|---|---|
| 1 | Correctness & logic bugs | No issues found. `GalaxyRepositoryHostWiringTests.BrowseChildren_BrowseSubtreesConstraintThroughHostWiring_FiltersChildren` correctly asserts 2 children unconstrained (phase 1) and 0 children under a non-matching scope (phase 2) — non-tautological. `DashboardGalaxySummaryProjectorTests` and `ConstraintEnforcerTests` new additions all assert concrete post-conditions; no swallowed exceptions or trivially-green assertions found. |
| 2 | mxaccessgw conventions | No issues found. New files use file-scoped namespaces, `sealed` classes, target-typed `new()`, and PascalCase `Method_Condition_Result` names. `DashboardSnapshotServiceTests` uses non-sealed `FakeApiKeyAdminStore` / `CountingApiKeyAdminStore` as intentional base classes for the inheritance chain (`SequencedApiKeyAdminStore`); acceptable in context. |
| 3 | Concurrency & thread safety | No issues found. `GatewayRepositoryHostWiringTests` and `GatewayBrowseScopeProviderTests` are synchronous or use immediate stubs; no new `Task.Delay` or wall-clock timing. `DashboardSnapshotServiceTests` new watch-snapshot tests use `CancellationTokenSource(TimeSpan.FromSeconds(2))` bounds, consistent with the existing suite. |
| 4 | Error handling & resilience | No issues found. |
| 5 | Security | No issues found. `GalaxyRepositoryHostWiringTests` proves the security-critical authz filter chain end-to-end: `GatewayRequestIdentityAccessor.Push` → `GatewayBrowseScopeProvider.ResolveBrowseSubtrees` → lib `GalaxyRepositoryGrpcService` → filtered `BrowseChildren`. `GatewayBrowseScopeProviderTests` covers happy path (non-empty `BrowseSubtrees`) and no-identity fallback (empty list = no scoping, as documented — safe behind the global auth interceptor). The deleted `GalaxyRepositoryGrpcServiceTests.BrowseChildren_BrowseSubtreesConstraint_FiltersChildren` (which passed `GatewayRequestIdentityAccessor` directly rather than through the `GatewayBrowseScopeProvider` wrapper) is now superseded by a stricter test that threads through the actual production seam. |
| 6 | Performance & resource management | No issues found. |
| 7 | Design-document adherence | No issues found. Galaxy test deletions match the `A2-galaxyrepository-adoption-handoff.md` adoption description. All eight deleted `Galaxy/*Tests.cs` files covered lib-owned types now in `scadaproj/ZB.MOM.WW.GalaxyRepository`; their test equivalents are confirmed present in the library's test suite (`GalaxyHierarchyCacheTests`, `GalaxyHierarchyRefreshServiceTests`, `GalaxyBrowseProjectorTests`, `GalaxyDeployNotifierTests`, `GalaxyHierarchyProjectorTests`, `GalaxyAlarmAttributeMappingTests`, `GalaxyHierarchySnapshotStoreTests`). `GalaxyProtoMapperTests` and `GalaxyHierarchyIndexTests` have no direct lib-side equivalent — the types are lib-owned; the index is exercised indirectly through `GalaxyBrowseProjectorTests` and `GalaxyHierarchyProjectorTests`; this is a lib-side gap, not a host-module finding. |
| 8 | Code organization & conventions | No issues found. |
| 9 | Testing coverage | Issue found: Tests-041 (`DashboardSnapshotServiceTests` does not assert the memoization-by-sequence invalidation path in `DashboardSnapshotService.ResolveGalaxySummary` — a new sequence bumps the cached summary; all tests use a fixed-sequence `StubGalaxyHierarchyCache` so a bug that never invalidates the memoized summary (always returning the first computed result) would pass). |
| 10 | Documentation & comments | No issues found. New test files carry accurate class-level `<summary>` docs; `GalaxyFilterInputSafetyTests.cs` class summary correctly updated to reference `ZB.MOM.WW.GalaxyRepository` lib types and notes that the `RegexCacheCapacity` counter is now lib-internal. |
### 2026-06-15 re-review (commit `410acc9`)
Re-review of the `42b0037..410acc9` diff (≈57 files), scoped to the alarm-provider
@@ -756,3 +781,53 @@ The cancellation tests for `WorkerClient` in `WorkerClientTests` *do* exercise t
**Recommendation:** Add one wiring test per uncovered variant (or a single `[Theory]` over the six command kinds), constructing the matching command type with a `SparseArrayValue` and asserting `worker.LastCommand!.Command.<Variant>.Value.KindCase == MxValue.KindOneofCase.ArrayValue` after `session.InvokeAsync`. The `SparseArrayExpanderTests` already pin the expander logic exhaustively; the wiring tests need only check that the choke point invokes expansion for each variant, not the expansion semantics themselves. The four secured variants (`WriteSecured`, `Write2`, `WriteSecured2`, `WriteSecured2Bulk`) can reuse the same `CapturingWorkerClient` stub.
**Resolution:** 2026-06-18 — root cause confirmed: the six arms (`WriteSecured`, `Write2`, `WriteSecured2`, `Write2Bulk`, `WriteSecuredBulk`, `WriteSecured2Bulk`) each had a `case` in `NormalizeOutboundCommand` calling `ExpandValue` but no wiring test. Server-057's additions (`AddItemBulk`, `AddBufferedItem`) covered address-normalization tests only, not the missing write-expansion variants. Added six tests to `GatewayArrayWriteWiringTests.cs` — one per uncovered arm — each constructing the matching command with a 4-element `SparseArrayValue` (Integer, single element set), driving it through `GatewaySession.InvokeAsync`, and asserting `worker.LastCommand.Command.<Variant>.Value.KindCase == ArrayValue` and the expected element positions. Tests: `WriteSecured_SparseArrayValue_ExpandedBeforeReachingWorker`, `Write2_SparseArrayValue_ExpandedBeforeReachingWorker`, `WriteSecured2_SparseArrayValue_ExpandedBeforeReachingWorker`, `Write2Bulk_SparseArrayEntryValue_ExpandedBeforeReachingWorker`, `WriteSecuredBulk_SparseArrayEntryValue_ExpandedBeforeReachingWorker`, `WriteSecured2Bulk_SparseArrayEntryValue_ExpandedBeforeReachingWorker`. All 13 `GatewayArrayWriteWiring` tests pass (7 pre-existing + 6 new).
### Tests-041
| Field | Value |
|---|---|
| Severity | Medium |
| Category | Testing coverage |
| Location | `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardSnapshotServiceTests.cs`, `src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs:109-128` |
| Status | Resolved |
**Description:** `DashboardSnapshotService.ResolveGalaxySummary` introduced a lock-free
memoization cache keyed on `GalaxyHierarchyCacheEntry.Sequence` (lines 109-128):
on a matching sequence the cached `DashboardGalaxySummary` is returned without
recomputing; on a new sequence it recomputes and stores the replacement. This
restores the pre-adoption O(1)-per-tick behavior (the library bumps `Sequence`
only on a heavy refresh).
`DashboardSnapshotServiceTests.GetSnapshot_ProjectsGalaxySummaryFromHierarchyCache`
verifies that a first `GetSnapshot()` returns the correct derived summary, but the
`StubGalaxyHierarchyCache` is immutable — it always returns the same entry with the
same `Sequence`. No test:
1. Calls `GetSnapshot()` twice with an unchanged entry and verifies the second call
returns the same summary (memoization hit); a test could observe this via a
counting stub that increments on each `Project` call.
2. Swaps the cache stub to a new entry with an incremented `Sequence`, then calls
`GetSnapshot()` and asserts the snapshot reflects the **new** entry's templates
and categories (invalidation). A bug that inverts the sequence check — e.g.
`cached is not null && cached.Sequence != sequence` — would always return the
first-computed summary, causing the dashboard Galaxy section to freeze after the
initial load regardless of subsequent cache refreshes. This regression passes all
existing tests because no test ever presents two entries with different sequences.
**Recommendation:** Add two tests:
1. `GetSnapshot_WhenGalaxyCacheSequenceUnchanged_ReusesProjectedSummary`: create a
`CountingProjectorCache` or a `SequenceChangingGalaxyHierarchyCache` that allows
controlled sequence changes. Call `GetSnapshot()` twice with the same entry
(same `Sequence`); assert the second snapshot's `Galaxy` object is reference-equal
to (or at minimum observably the same as) the first, and that the projector was
invoked only once (e.g. via a counting stub wrapping `DashboardGalaxyProjector`).
2. `GetSnapshot_WhenGalaxyCacheSequenceChanges_RecomputesGalaxySummary`: present
entry A (Sequence = 1, one template), call `GetSnapshot()`, then swap the cache
to entry B (Sequence = 2, different templates), call `GetSnapshot()` again, and
assert the second snapshot reflects entry B's template set, not entry A's. A
`MutableGalaxyHierarchyCache` with a settable `Current` property suffices; the
existing `StubGalaxyHierarchyCache` pattern is a single-line extension.
**Resolution:** Resolved in `9ae6bce` (2026-06-25). Added a `MutableGalaxyHierarchyCache` stub (settable `Current`) and three `DashboardSnapshotServiceTests` cases: `GetSnapshot_WhenGalaxyEntryChangesAtSameSequence_ReflectsVolatileStatusAndError` (the Server-059 regression), `GetSnapshot_WhenSequenceUnchanged_ReusesExpensiveTemplateBreakdown` (memoization hit — Objects swapped at the same `Sequence` stay frozen), and `GetSnapshot_WhenSequenceChanges_RecomputesTemplateBreakdown` (invalidation on `Sequence` change). The fix memoizes only the O(N) breakdown, so the assertions now target that rather than whole-summary identity.
@@ -26,6 +26,11 @@
<Compile Remove="Generated\**\*.cs" />
<Protobuf Include="Protos\mxaccess_gateway.proto" ProtoRoot="Protos" OutputDir="Generated" GrpcOutputDir="Generated" GrpcServices="Both" />
<Protobuf Include="Protos\mxaccess_worker.proto" ProtoRoot="Protos" OutputDir="Generated" GrpcServices="None" />
<!-- galaxy_repository.proto is intentionally retained even though the gateway SERVER now consumes
the wire-identical Galaxy types from the ZB.MOM.WW.GalaxyRepository package. This proto is
still the generation source of truth for the language clients (Go/Rust/Java/Python compile it
by path; the .NET client consumes Contracts.Proto.Galaxy.* via this project reference) and for
clients/proto/proto-inputs.json. Removing it breaks all five clients — do not delete. -->
<Protobuf Include="Protos\galaxy_repository.proto" ProtoRoot="Protos" OutputDir="Generated" GrpcOutputDir="Generated" GrpcServices="Both" />
</ItemGroup>
@@ -1,14 +0,0 @@
using ZB.MOM.WW.GalaxyRepository;
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
/// <summary>Projects the shared-library Galaxy cache entry into a dashboard Galaxy summary.</summary>
internal static class DashboardGalaxyProjector
{
/// <summary>Projects the cache entry to a dashboard Galaxy summary.</summary>
/// <param name="entry">The Galaxy hierarchy cache entry.</param>
public static DashboardGalaxySummary Project(GalaxyHierarchyCacheEntry entry)
{
return DashboardGalaxySummaryProjector.Project(entry);
}
}
@@ -2,8 +2,10 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
/// <summary>
/// Snapshot of the Galaxy Repository (ZB) browse state surfaced on the dashboard.
/// Populated by <see cref="GalaxySummaryCache"/> on a background refresh cadence so
/// the dashboard never blocks on SQL.
/// Built by <see cref="DashboardGalaxySummaryProjector"/> from the shared-library Galaxy
/// hierarchy cache on each dashboard snapshot; the projector memoizes only the O(N)
/// <see cref="GalaxyObjectBreakdown"/> on the cache sequence while copying the volatile
/// status/timestamp fields fresh, so the dashboard never blocks on SQL.
/// </summary>
public sealed record DashboardGalaxySummary(
DashboardGalaxyStatus Status,
@@ -46,3 +48,18 @@ public enum DashboardGalaxyStatus
public sealed record DashboardGalaxyTemplateUsage(string TemplateName, int InstanceCount);
public sealed record DashboardGalaxyCategoryCount(int CategoryId, string CategoryName, int ObjectCount);
/// <summary>
/// The O(N)-computed template-usage and category breakdown of a Galaxy hierarchy cache entry —
/// the only part of <see cref="DashboardGalaxySummary"/> that changes with the cache sequence
/// and is therefore safe to memoize on it.
/// </summary>
public sealed record GalaxyObjectBreakdown(
IReadOnlyList<DashboardGalaxyTemplateUsage> TopTemplates,
IReadOnlyList<DashboardGalaxyCategoryCount> ObjectCategories)
{
/// <summary>Gets the empty breakdown (no templates, no categories).</summary>
public static GalaxyObjectBreakdown Empty { get; } = new(
Array.Empty<DashboardGalaxyTemplateUsage>(),
Array.Empty<DashboardGalaxyCategoryCount>());
}
@@ -27,53 +27,82 @@ public static class DashboardGalaxySummaryProjector
public static DashboardGalaxySummary Project(GalaxyHierarchyCacheEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
return BuildSummary(entry, ComputeBreakdown(entry));
}
IReadOnlyList<DashboardGalaxyTemplateUsage> topTemplates;
IReadOnlyList<DashboardGalaxyCategoryCount> objectCategories;
/// <summary>
/// Computes the O(N) template-usage and category breakdown from the entry's objects.
/// This is the only part of the summary that changes with the cache
/// <see cref="GalaxyHierarchyCacheEntry.Sequence"/> — the shared library replaces the object
/// set only on a heavy refresh that bumps the sequence — so callers may memoize the result
/// on the sequence. The cheap, per-tick-volatile fields are re-read fresh via
/// <see cref="BuildSummary"/> and must never be memoized.
/// </summary>
/// <param name="entry">The shared-library cache entry to project.</param>
/// <returns>The template/category breakdown of <paramref name="entry"/>'s objects.</returns>
public static GalaxyObjectBreakdown ComputeBreakdown(GalaxyHierarchyCacheEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
if (entry.Objects.Count == 0)
{
topTemplates = Array.Empty<DashboardGalaxyTemplateUsage>();
objectCategories = Array.Empty<DashboardGalaxyCategoryCount>();
return GalaxyObjectBreakdown.Empty;
}
else
Dictionary<int, int> objectsByCategory = new();
Dictionary<string, int> templateUsage = new(StringComparer.OrdinalIgnoreCase);
foreach (GalaxyObject obj in entry.Objects)
{
Dictionary<int, int> objectsByCategory = new();
Dictionary<string, int> templateUsage = new(StringComparer.OrdinalIgnoreCase);
objectsByCategory.TryGetValue(obj.CategoryId, out int categoryCount);
objectsByCategory[obj.CategoryId] = categoryCount + 1;
foreach (GalaxyObject obj in entry.Objects)
if (obj.TemplateChain.Count > 0)
{
objectsByCategory.TryGetValue(obj.CategoryId, out int categoryCount);
objectsByCategory[obj.CategoryId] = categoryCount + 1;
if (obj.TemplateChain.Count > 0)
string immediate = obj.TemplateChain[0];
if (!string.IsNullOrWhiteSpace(immediate))
{
string immediate = obj.TemplateChain[0];
if (!string.IsNullOrWhiteSpace(immediate))
{
templateUsage.TryGetValue(immediate, out int templateCount);
templateUsage[immediate] = templateCount + 1;
}
templateUsage.TryGetValue(immediate, out int templateCount);
templateUsage[immediate] = templateCount + 1;
}
}
topTemplates = templateUsage
.OrderByDescending(usage => usage.Value)
.ThenBy(usage => usage.Key, StringComparer.OrdinalIgnoreCase)
.Take(MaxTopTemplates)
.Select(usage => new DashboardGalaxyTemplateUsage(usage.Key, usage.Value))
.ToArray();
objectCategories = objectsByCategory
.OrderByDescending(category => category.Value)
.ThenBy(category => category.Key)
.Select(category => new DashboardGalaxyCategoryCount(
category.Key,
ResolveCategoryName(category.Key),
category.Value))
.ToArray();
}
IReadOnlyList<DashboardGalaxyTemplateUsage> topTemplates = templateUsage
.OrderByDescending(usage => usage.Value)
.ThenBy(usage => usage.Key, StringComparer.OrdinalIgnoreCase)
.Take(MaxTopTemplates)
.Select(usage => new DashboardGalaxyTemplateUsage(usage.Key, usage.Value))
.ToArray();
IReadOnlyList<DashboardGalaxyCategoryCount> objectCategories = objectsByCategory
.OrderByDescending(category => category.Value)
.ThenBy(category => category.Key)
.Select(category => new DashboardGalaxyCategoryCount(
category.Key,
ResolveCategoryName(category.Key),
category.Value))
.ToArray();
return new GalaxyObjectBreakdown(topTemplates, objectCategories);
}
/// <summary>
/// Assembles a <see cref="DashboardGalaxySummary"/> from an entry's cheap, per-tick-volatile
/// fields (status, timestamps, last error, counts) and a precomputed
/// <paramref name="breakdown"/>. The volatile fields are copied fresh on every call so a
/// memoized breakdown never freezes the dashboard's health or timestamps between heavy
/// refreshes — the library mutates those fields in place at the same sequence on steady-state
/// ticks and on refresh failure.
/// </summary>
/// <param name="entry">The cache entry whose volatile fields to copy.</param>
/// <param name="breakdown">The precomputed template/category breakdown.</param>
/// <returns>The assembled dashboard summary.</returns>
public static DashboardGalaxySummary BuildSummary(GalaxyHierarchyCacheEntry entry, GalaxyObjectBreakdown breakdown)
{
ArgumentNullException.ThrowIfNull(entry);
ArgumentNullException.ThrowIfNull(breakdown);
return new DashboardGalaxySummary(
Status: MapDashboardStatus(entry.Status),
LastQueriedAt: entry.LastQueriedAt,
@@ -85,8 +114,8 @@ public static class DashboardGalaxySummaryProjector
AttributeCount: entry.AttributeCount,
HistorizedAttributeCount: entry.HistorizedAttributeCount,
AlarmAttributeCount: entry.AlarmAttributeCount,
TopTemplates: topTemplates,
ObjectCategories: objectCategories);
TopTemplates: breakdown.TopTemplates,
ObjectCategories: breakdown.ObjectCategories);
}
private static DashboardGalaxyStatus MapDashboardStatus(GalaxyCacheStatus status) => status switch
@@ -30,12 +30,13 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
private readonly ILogger<DashboardSnapshotService> _logger;
private readonly SemaphoreSlim _apiKeySummaryRefreshGate = new(1, 1);
private IReadOnlyList<DashboardApiKeySummary> _apiKeySummaries = Array.Empty<DashboardApiKeySummary>();
// Memoizes the projected Galaxy summary against the immutable cache sequence. The shared
// library bumps Sequence only on a heavy refresh, so an unchanged sequence means the entry
// (and therefore its summary) is unchanged and the O(N) projection can be reused. This keeps
// the ~1s snapshot tick O(1) for Galaxy, restoring the pre-adoption behavior where the
// summary was computed once per refresh rather than once per tick.
private GalaxySummaryCache? _galaxySummaryCache;
// Memoizes ONLY the O(N) template/category breakdown against the cache sequence. The shared
// library bumps Sequence only on a heavy refresh that replaces the object set, so an unchanged
// sequence means the breakdown is unchanged and can be reused — keeping the ~1s snapshot tick
// O(1) for Galaxy. The summary's cheap volatile fields (status, timestamps, last error, counts)
// are NOT memoized: the library mutates them in place at the same sequence on steady-state ticks
// and on refresh failure, so they are copied fresh on every snapshot (see Server-059).
private GalaxyBreakdownCache? _galaxyBreakdownCache;
/// <summary>Initializes a new instance of the DashboardSnapshotService class.</summary>
/// <param name="sessionRegistry">Registry of active gateway sessions.</param>
@@ -111,21 +112,26 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
GalaxyHierarchyCacheEntry entry = _galaxyHierarchyCache.Current;
long sequence = entry.Sequence;
// Lock-free reuse: a matching sequence means the entry is unchanged, so the previously
// projected summary is still correct. A racing recompute for a new sequence is harmless —
// the projection is pure, so any winner stores identical content for that sequence.
GalaxySummaryCache? cached = Volatile.Read(ref _galaxySummaryCache);
// Lock-free reuse of the O(N) breakdown only: a matching sequence means the object set is
// unchanged, so the previously computed breakdown is still correct. A racing recompute for a
// new sequence is harmless — the computation is pure, so any winner stores identical content
// for that sequence. The cheap volatile fields are always taken from the current entry below.
GalaxyBreakdownCache? cached = Volatile.Read(ref _galaxyBreakdownCache);
GalaxyObjectBreakdown breakdown;
if (cached is not null && cached.Sequence == sequence)
{
return cached.Summary;
breakdown = cached.Breakdown;
}
else
{
breakdown = DashboardGalaxySummaryProjector.ComputeBreakdown(entry);
Volatile.Write(ref _galaxyBreakdownCache, new GalaxyBreakdownCache(sequence, breakdown));
}
DashboardGalaxySummary summary = DashboardGalaxyProjector.Project(entry);
Volatile.Write(ref _galaxySummaryCache, new GalaxySummaryCache(sequence, summary));
return summary;
return DashboardGalaxySummaryProjector.BuildSummary(entry, breakdown);
}
private sealed record GalaxySummaryCache(long Sequence, DashboardGalaxySummary Summary);
private sealed record GalaxyBreakdownCache(long Sequence, GalaxyObjectBreakdown Breakdown);
/// <summary>
/// Watches dashboard snapshots at regular intervals asynchronously.
@@ -218,7 +218,7 @@ public sealed class DashboardSnapshotServiceTests
{
// The shared-library cache entry no longer carries a precomputed dashboard summary;
// DashboardSnapshotService derives templates/categories from the entry's objects via
// DashboardGalaxyProjector. Seed objects that yield $Pump x2 / $Area x1 templates and
// DashboardGalaxySummaryProjector. Seed objects that yield $Pump x2 / $Area x1 templates and
// categories UserDefined(10) x2 / Area(13) x1, matching the asserted summary.
GalaxyObject[] objects =
[
@@ -280,6 +280,111 @@ public sealed class DashboardSnapshotServiceTests
Assert.Contains(snapshot.Galaxy.ObjectCategories, c => c.CategoryName == "Area" && c.ObjectCount == 1);
}
/// <summary>
/// Regression for Server-059: the shared library replaces the cache entry via
/// <c>previous with { ... }</c> at the <b>same</b> Sequence on a steady-state tick and on a
/// refresh failure (Status → Unavailable, LastError set). The dashboard summary must reflect
/// those per-tick-volatile fields, not a summary frozen at the last heavy-refresh sequence —
/// otherwise the Galaxy health indicator keeps showing Healthy throughout a SQL outage.
/// </summary>
[Fact]
public void GetSnapshot_WhenGalaxyEntryChangesAtSameSequence_ReflectsVolatileStatusAndError()
{
GalaxyHierarchyCacheEntry healthy = GalaxyHierarchyCacheEntry.Empty with
{
Status = GalaxyCacheStatus.Healthy,
Sequence = 5,
LastQueriedAt = DateTimeOffset.Parse("2026-04-28T11:00:00Z", CultureInfo.InvariantCulture),
LastSuccessAt = DateTimeOffset.Parse("2026-04-28T11:00:00Z", CultureInfo.InvariantCulture),
};
MutableGalaxyHierarchyCache cache = new(healthy);
using GatewayMetrics metrics = new();
DashboardSnapshotService service = CreateService(new SessionRegistry(), metrics, galaxyHierarchyCache: cache);
Assert.Equal(DashboardGalaxyStatus.Healthy, service.GetSnapshot().Galaxy.Status);
// SQL outage: no heavy refresh can succeed, so Sequence cannot advance; the library
// mutates the entry in place to Unavailable with an error at the same Sequence.
cache.Current = healthy with
{
Status = GalaxyCacheStatus.Unavailable,
LastError = "SQL unreachable",
LastQueriedAt = DateTimeOffset.Parse("2026-04-28T11:00:05Z", CultureInfo.InvariantCulture),
};
DashboardGalaxySummary summary = service.GetSnapshot().Galaxy;
Assert.Equal(DashboardGalaxyStatus.Unavailable, summary.Status);
Assert.Equal("SQL unreachable", summary.LastError);
Assert.Equal(
DateTimeOffset.Parse("2026-04-28T11:00:05Z", CultureInfo.InvariantCulture),
summary.LastQueriedAt);
}
/// <summary>
/// Verifies the O(N) template/category breakdown is memoized on the cache Sequence: in
/// production the object set only changes when the library bumps Sequence on a heavy refresh,
/// so the breakdown is reused at an unchanged Sequence. Proves the memo keys on Sequence by
/// swapping Objects at the same Sequence and asserting the breakdown does not recompute.
/// </summary>
[Fact]
public void GetSnapshot_WhenSequenceUnchanged_ReusesExpensiveTemplateBreakdown()
{
GalaxyObject[] first =
[new GalaxyObject { GobjectId = 1, BrowseName = "Pump01", CategoryId = 10, TemplateChain = { "$Pump" } }];
GalaxyHierarchyCacheEntry entry = GalaxyHierarchyCacheEntry.Empty with
{
Status = GalaxyCacheStatus.Healthy,
Sequence = 9,
Objects = first,
Index = GalaxyHierarchyIndex.Build(first),
ObjectCount = 1,
};
MutableGalaxyHierarchyCache cache = new(entry);
using GatewayMetrics metrics = new();
DashboardSnapshotService service = CreateService(new SessionRegistry(), metrics, galaxyHierarchyCache: cache);
Assert.Equal("$Pump", Assert.Single(service.GetSnapshot().Galaxy.TopTemplates).TemplateName);
GalaxyObject[] second =
[new GalaxyObject { GobjectId = 2, BrowseName = "Valve01", CategoryId = 10, TemplateChain = { "$Valve" } }];
cache.Current = entry with { Objects = second, Index = GalaxyHierarchyIndex.Build(second) };
// Same Sequence (9) → breakdown reused → still "$Pump", not "$Valve".
Assert.Equal("$Pump", Assert.Single(service.GetSnapshot().Galaxy.TopTemplates).TemplateName);
}
/// <summary>
/// Verifies that a changed cache Sequence invalidates the memoized template breakdown and the
/// next snapshot reflects the new object set. Guards against an inverted sequence check that
/// would freeze the Galaxy section after its first load (Tests-041).
/// </summary>
[Fact]
public void GetSnapshot_WhenSequenceChanges_RecomputesTemplateBreakdown()
{
GalaxyObject[] first =
[new GalaxyObject { GobjectId = 1, BrowseName = "Pump01", CategoryId = 10, TemplateChain = { "$Pump" } }];
GalaxyHierarchyCacheEntry entry = GalaxyHierarchyCacheEntry.Empty with
{
Status = GalaxyCacheStatus.Healthy,
Sequence = 9,
Objects = first,
Index = GalaxyHierarchyIndex.Build(first),
ObjectCount = 1,
};
MutableGalaxyHierarchyCache cache = new(entry);
using GatewayMetrics metrics = new();
DashboardSnapshotService service = CreateService(new SessionRegistry(), metrics, galaxyHierarchyCache: cache);
Assert.Equal("$Pump", Assert.Single(service.GetSnapshot().Galaxy.TopTemplates).TemplateName);
GalaxyObject[] second =
[new GalaxyObject { GobjectId = 2, BrowseName = "Valve01", CategoryId = 10, TemplateChain = { "$Valve" } }];
cache.Current = entry with { Sequence = 10, Objects = second, Index = GalaxyHierarchyIndex.Build(second) };
// New Sequence (10) → breakdown recomputed → now "$Valve".
Assert.Equal("$Valve", Assert.Single(service.GetSnapshot().Galaxy.TopTemplates).TemplateName);
}
/// <summary>
/// Verifies snapshot watcher cancels cleanly when subscriber cancels.
/// </summary>
@@ -452,6 +557,22 @@ public sealed class DashboardSnapshotServiceTests
public Task WaitForFirstLoadAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
private sealed class MutableGalaxyHierarchyCache(GalaxyHierarchyCacheEntry current) : IGalaxyHierarchyCache
{
/// <summary>Gets or sets the current Galaxy hierarchy cache entry, swappable between snapshots.</summary>
public GalaxyHierarchyCacheEntry Current { get; set; } = current;
/// <summary>Refreshes the cache asynchronously.</summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Completed task.</returns>
public Task RefreshAsync(CancellationToken cancellationToken) => Task.CompletedTask;
/// <summary>Waits for the first cache load asynchronously.</summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Completed task.</returns>
public Task WaitForFirstLoadAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
private class FakeApiKeyAdminStore : IApiKeyAdminStore
{
/// <inheritdoc />
@@ -41,6 +41,25 @@ public sealed class GatewayApplicationTests
Assert.Equal("SerilogLoggerFactory", factory.GetType().Name);
}
/// <summary>
/// Verifies that Build registers the gateway's browse-scope provider so it wins over the
/// shared library's no-op default (Server-060). The per-API-key browse-subtree scoping
/// depends on <c>AddSingleton&lt;IGalaxyBrowseScopeProvider, GatewayBrowseScopeProvider&gt;</c>
/// running before <c>AddZbGalaxyRepository</c>, whose <c>TryAddSingleton</c> default
/// (NullGalaxyBrowseScopeProvider → full hierarchy) must lose. If this registration order ever
/// regressed, every metadata-scoped key would silently see the entire Galaxy hierarchy.
/// </summary>
[Fact]
public async Task Build_RegistersGatewayBrowseScopeProviderOverLibraryDefault()
{
await using WebApplication app = GatewayApplication.Build([]);
ZB.MOM.WW.GalaxyRepository.Grpc.IGalaxyBrowseScopeProvider scopeProvider =
app.Services.GetRequiredService<ZB.MOM.WW.GalaxyRepository.Grpc.IGalaxyBrowseScopeProvider>();
Assert.IsType<ZB.MOM.WW.MxGateway.Server.Security.Authorization.GatewayBrowseScopeProvider>(scopeProvider);
}
/// <summary>Verifies that Build registers the gateway metrics service.</summary>
[Fact]
public async Task Build_RegistersGatewayMetrics()