mirror of
https://github.com/gadgethd/ukmesh.git
synced 2026-12-06 03:14:09 +00:00
329 lines
19 KiB
Markdown
329 lines
19 KiB
Markdown
# Public packet visibility convergence
|
||
|
||
Migration `074_prefix_visibility_row_fence.sql` replaces 066's prefix statement
|
||
triggers with a row trigger. Empty INSERT/UPDATE/DELETE statements, including
|
||
the empty FK cascade generated by deleting a public node, cannot invalidate.
|
||
An UPDATE that changes only `updated_at` or assigns the same policy values also
|
||
leaves the generation alone. Actual direct prefix changes and cascades that
|
||
remove prefixes still advance only the public generation. TRUNCATE retains a
|
||
conservative statement trigger. The FK remains intact.
|
||
|
||
Numbered 074 rather than 071: the backend-schema branch that production already
|
||
applies owns 071-073 in the ledger, so the never-applied row fence moved to the
|
||
next free slot instead of forcing a renumber of shipped migration history.
|
||
|
||
`public_visibility_state.prefix_fence_xid` coalesces those invalidations within
|
||
one transaction using PostgreSQL's full transaction ID. It rolls back with the
|
||
data, including at savepoints; later transactions invalidate independently.
|
||
If materialization becomes current again inside the same transaction, a later
|
||
prefix edit invalidates it again. A real cascading row deletion has no surviving
|
||
parent and remains fail closed. Nested maintenance of a surviving node retains
|
||
migration 056's asynchronous queue without an independent invalidation.
|
||
Installing 074 (or its post-move replacement 134) does not repair an existing generation gap or rewrite history.
|
||
Alias changes and completed node-scoped worker passes carry materialization
|
||
forward only when it was already current; neither repairs an unrelated gap.
|
||
|
||
Use convergence when the public and materialized generations differ, the
|
||
materialized row is missing, or pending/failed work needs a verified full pass.
|
||
The command also reports stored flags that differ from current prefix policy.
|
||
It operates on **all retained rows in both `packets` and `packet_paths`**, including
|
||
compressed history. It does not alter privacy choices, delete rows, migrate the
|
||
database, manage services, or refresh derived chart/path snapshots.
|
||
|
||
## Generation health
|
||
|
||
The read-only generation reconciler observes a single database snapshot:
|
||
|
||
| Field | Authoritative source / meaning |
|
||
| --- | --- |
|
||
| `desiredGeneration` | `public_visibility_state.generation`: current policy generation. |
|
||
| `materializedGeneration` | `packet_visibility_materialization_state.visibility_generation`: the stored packet-flag certificate. |
|
||
| `appliedGeneration` | Generation admissible to the **global public-read gate**: the materialized generation only when it equals desired and no pending/processing/failed rematerialization exists; otherwise `null`. |
|
||
|
||
There are two persisted privacy generation records in this repository. Applied
|
||
is a derived admission result, not a third durable record, an in-memory cache
|
||
stamp, a chart generation or CoreScope's replay cursor. This signal does not
|
||
claim to verify a downstream consumer's independently applied generation.
|
||
It matches global batch admission (`loadCurrentPublicPrivacyPolicy`); individual
|
||
SQL packet reads additionally have node-scoped queue filtering. Pending work
|
||
can therefore make this signal unhealthy while unaffected SQL rows remain readable.
|
||
|
||
`meshcore_privacy_generation_healthy` is a single unlabelled boolean gauge:
|
||
`1` means all three reported generations agree and the queue is inactive;
|
||
`0` means divergence, missing/invalid state, active work, or a failed/timed-out
|
||
observation. Generations remain decimal strings in diagnostics so comparisons
|
||
never round large integers; values unsupported by the public reader fail closed.
|
||
Each observation emits one JSON log with `event: "privacy_generation_health"`,
|
||
the same `healthy` value, a bounded `reason`, the generation triple and
|
||
`queueActive`. It contains no node identities, packet data or raw DB errors.
|
||
|
||
The health-worker `/metrics` scrape drives observations,
|
||
independently of dashboard queries or cleanup. The cached `/api/health` overview
|
||
also observes the same reconciler and adds the critical incident
|
||
`privacy_generation_unhealthy`; public responses expose only its code and
|
||
severity. Detailed operator health includes `privacy_visibility`. Liveness and
|
||
dependency `/readyz` retain their existing meaning. No new CLI is required.
|
||
|
||
The probe issues one SELECT: two singleton lookups and queue `EXISTS` using the
|
||
status index. It does not count/scan packet history, prefixes, charts or queue
|
||
contents. Observations return within two seconds, abort the application's DB
|
||
query on timeout, and share at most one pending read across scrapes/health.
|
||
If pool acquisition is still draining after timeout, observations remain
|
||
unhealthy until it settles; no additional queries accumulate. A later fresh
|
||
observation can recover the signal. No generation, timestamp, queue status or
|
||
packet flag is changed, and no repair function is called.
|
||
|
||
The existing Prometheus rule file adds `PrivacyGenerationUnhealthy` when the
|
||
health-worker gauge stays zero **or absent** for five minutes. This holdoff allows
|
||
short rematerialization work to settle; the gauge and health incident change
|
||
immediately. Alert resolution requires a successful healthy observation.
|
||
The existing health-worker scrape target and rule mount already provide wiring;
|
||
activation requires the normal reviewed release of code and monitoring rules.
|
||
This change does not deploy or reload either one.
|
||
|
||
On an alert:
|
||
|
||
1. Inspect the structured event and internal health detail. A missing relation,
|
||
read failure or absent metric is unavailable evidence, never proof of convergence.
|
||
2. For `desired_ahead`/`materialized_ahead` with `queueActive: false`, investigate
|
||
recent policy changes and confirm migration 074 or its post-move replacement 134 is installed through normal
|
||
operator procedures. An empty queue does not certify packet flags.
|
||
3. For `queue_active`, inspect the existing rematerialization backlog/worker
|
||
diagnostics. Do not reset a processing claim or copy generation numbers.
|
||
4. An authorized operator may run the read-only inventory described below to
|
||
audit stored flags. Any repair is a separately reviewed maintenance action.
|
||
5. Verify the gauge returns to `1`, the health incident clears and the alert
|
||
resolves. This check certifies the generation fence, not correctness of all
|
||
historical flags or downstream replay freshness.
|
||
|
||
## Owner ACL readiness convergence
|
||
|
||
The packet-history repair below is separate from the **owner MQTT ACL**
|
||
generation used by the `/readyz` owner inventory baseline. Owner public-feed
|
||
switches change that ACL, not the packet materialization certificate.
|
||
|
||
Owner ACL generations hash the emitted policy, including retained global and
|
||
unmanaged rules. Unused render options and comments do not change the generation.
|
||
The startup, periodic and public-feed reconciliation paths converge against
|
||
fresh owner grants and feed settings. A verified unchanged render performs no
|
||
ACL/artifact/state writes or broker reload. A desired/rendered-only bump can be
|
||
recovered from the current applied certificate and exact file readback; other
|
||
drift uses the normal validated apply/reload/readback path. An incomplete apply
|
||
keeps `OWNER_ACL_APPLY_PENDING` until verification finishes, so a crash or failed
|
||
reload cannot be mistaken for an unchanged, verified policy.
|
||
|
||
A reconciliation request arriving after a pass has captured its inputs marks
|
||
the drain dirty. The caller awaits a trailing pass that reads the committed
|
||
settings again, including requests arriving during that trailing pass. Requests
|
||
before input capture coalesce. Failed passes reject waiting callers; subsequent
|
||
startup, periodic or explicit requests retry. This process-local drain does not
|
||
claim to coordinate multiple backend writers or persist an in-flight request
|
||
across crashes; startup's authoritative pass remains the recovery mechanism.
|
||
|
||
In apply mode, readiness also requests that same pass when the persisted
|
||
generation triple is unsettled or has an error. Concurrent probes share the
|
||
attempt, failed attempts are spaced at least ten seconds apart, and readiness
|
||
re-reads the state afterward. Startup still awaits reconciliation before the
|
||
listener opens. Recovery does not rewrite the baseline or repair packet history.
|
||
|
||
`/readyz` returns only coarse database/MQTT checks. The rebaseline consumer must
|
||
not read owner fields from that public response. On degraded readiness it reads
|
||
the versioned `/local-api/owner-authorization` response, protected by the existing
|
||
local-only operator authentication. This endpoint uses the same evidence loader
|
||
as readiness. Supply `OWNER_BASELINE_OPERATOR_TOKEN` (or `OPERATOR_SITE_TOKEN`)
|
||
to the timer/tool's environment; it is never sent to the public probe, printed,
|
||
or forwarded across redirects. Healthy readiness needs no token. Missing
|
||
credentials or unavailable diagnostics abort refresh without changing a baseline.
|
||
|
||
The baseline validator used for inventory exports stays strict. Readiness may
|
||
admit a different settled generation only when both applied artifacts have valid
|
||
hashes/markers and use the same renderer, the latest matches the current file,
|
||
and their permissions are identical or differ exclusively in public-feed reads.
|
||
Changes to owner inventory,
|
||
non-feed directives, renderer version or missing/corrupt evidence still fail
|
||
closed. Existing baselines and historical applied artifacts must be retained:
|
||
the policy-hash transition changes generation IDs once, and readiness uses those
|
||
artifacts to prove that unchanged permissions remain safe.
|
||
|
||
New inventory exports retain the verified applied ACL certificate inside the
|
||
baseline checksum. This optional v1 field preserves compatibility with existing
|
||
baselines. Export rejects an embedded certificate unless its generation, current
|
||
settled state, renderer, hash, marker and exact ACL bytes agree. If only the
|
||
historical SQL row is lost, readiness may use this retained certificate with the
|
||
same permission-delta validation. A corrupt existing SQL certificate is never
|
||
silently replaced by the fallback; a current applied certificate is still required.
|
||
|
||
For a legacy baseline with no retained evidence, readiness remains closed and
|
||
returns `repair` identifying the missing generation, old baseline checksum and
|
||
current generation. The auto-rebaseline consumer refuses this repair request.
|
||
Obtain a deterministic read-only plan in the backend's normal authenticated
|
||
database environment (do not run these commands against an unreviewed database):
|
||
|
||
```sh
|
||
npm run owner-auth:inventory -- --baseline=/path/to/original.json --repair-plan --show-details
|
||
```
|
||
|
||
This mode cannot be combined with `--export` and never modifies a baseline.
|
||
Restore the named historical applied artifact from a trusted backup. If that
|
||
evidence is unavailable, review the complete current ACL and get explicit
|
||
approval to establish a new baseline; export it to a **new** path using
|
||
`--export=/path/to/new.json`, retain the original, and separately select the
|
||
reviewed replacement through normal configuration management. No rebaseline,
|
||
configuration change, restart or fabricated historical certificate is automatic.
|
||
|
||
See [the 2026-10-28 review](reviews/2026-10-28-l3-ukmesh-privacy-fence.md) for source
|
||
locations, reproduction and exact test results. None of this invokes
|
||
`privacy:converge --apply` automatically.
|
||
|
||
## Inventory and repair
|
||
|
||
### Deferred: unattended global-gap recovery (L3-04)
|
||
|
||
Design only; no coordinator, service, timer or automatic apply is implemented
|
||
in the 2026-11-01 owner-ACL fix wave. The numeric public-visibility fence remains
|
||
separate from owner ACL hashes and continues using the reviewed repair below.
|
||
|
||
A future coordinator should enqueue one durable job keyed to the observed
|
||
desired/materialized generation pair. A lease and compare-and-swap claim must
|
||
exclude competing repairs; expiry must allow recovery after a crash. Use the
|
||
existing current-policy recomputation and readback checks, never a counter copy.
|
||
Bound lock waits, per-batch runtime, retry count and backoff. For large histories,
|
||
checkpoint batches with their input generation and restart invalidated work if
|
||
policy changes. Before publishing, recheck the complete retained-row verification,
|
||
current policy and queue under the existing publication locks. Never certify
|
||
incomplete work or an unrelated node-scoped pass as a global repair.
|
||
|
||
Expose job state, lag, attempts and bounded failure reasons on authenticated
|
||
diagnostics. Test competing claims, expired leases, crashes at every checkpoint,
|
||
policy changes during repair, compressed history, exhausted retries and atomic
|
||
publication. Rollback disables scheduling and preserves jobs/evidence; it must
|
||
not roll generation numbers backward. This work needs its own implementation
|
||
and operational review.
|
||
|
||
Use the reviewed backend build with migration 074 (or post-move replacement 134) applied through the normal
|
||
migration process. From `backend/`, with `DATABASE_URL` already configured for
|
||
the intended database:
|
||
|
||
```sh
|
||
npm run build
|
||
npm run privacy:converge
|
||
```
|
||
|
||
The default uses a read-only repeatable-read transaction. JSON reports the
|
||
generation pair, queue counts by status, row/mismatch counts for each packet
|
||
store, and `needsConvergence`. It prints no packet contents or node identities.
|
||
The default statement timeout is 30 seconds; larger inventories may use
|
||
`--statement-timeout-ms=900000` (allowed range: 1000–3600000 milliseconds).
|
||
|
||
Review that the current prefix policy is intentional, especially after an
|
||
actual prefix/node deletion. Repair means applying the **current** policy; it
|
||
cannot restore a deleted privacy preference. Retaining deleted private
|
||
identities would require a separately designed tombstone policy.
|
||
|
||
Schedule a maintenance window with enough time, free disk and WAL capacity for
|
||
a full historical reclassification. Apply blocks node, prefix, alias, queue,
|
||
packet and path writers for its transaction. Ordinary readers can continue;
|
||
existing privacy fences remain effective until the repair commits. Lock waits
|
||
are bounded to five seconds. Deadlock/lock timeout aborts safely; let the
|
||
competing transaction finish, inventory again, and retry. Ingest may queue or
|
||
retry while locks are held; production load/duration must be evaluated by the
|
||
operator before use.
|
||
|
||
Pass the exact positive `generation` reported by the inventory:
|
||
|
||
```sh
|
||
npm run privacy:converge -- --apply --expected-generation=42
|
||
npm run privacy:converge
|
||
```
|
||
|
||
Replace `42` with the reviewed value. Apply defaults to a 15-minute timeout per
|
||
statement and accepts the same timeout option. Unknown/duplicate options,
|
||
conflicting modes, invalid generations and out-of-range timeouts fail before
|
||
connecting. A changed generation or missing public state aborts without writes.
|
||
Do not repair by setting the materialized generation manually.
|
||
|
||
Apply acquires the policy/data locks, checks the reviewed generation, refuses
|
||
any `processing` claim, and computes both stored flags from current prefixes and
|
||
path validity. It normalizes legacy lowercase hashes before prefix matching.
|
||
Unknown path sizes and NULL hops are hidden; nullable validity is never treated
|
||
as public or written into a non-null flag.
|
||
After complete readback verification, it marks pending/failed work done and
|
||
publishes a newly incremented generation pair in the same transaction. Exhausted
|
||
failed attempts do not require a manual queue reset. Failure before commit rolls
|
||
back flags, queue and generations together; rerun inventory after an uncertain
|
||
connection failure. A second successful apply with no
|
||
drift changes nothing, including timestamps.
|
||
|
||
A `processing` row requires waiting for the active worker to finish. An orphaned
|
||
processing claim requires operator investigation; this tool does not guess that
|
||
a worker is dead, reset claims or manage worker services. After repair, verify
|
||
`needsConvergence: false`, equal generations, zero mismatches, and no active
|
||
queue entries. Derived snapshots are invalidated by the new generation and
|
||
rebuild through their existing workers.
|
||
|
||
The command uses `SET LOCAL max_parallel_workers_per_gather = 0` because the
|
||
CI-pinned TimescaleDB 2.25.1 can report `subplan ... was not initialized` during
|
||
a parallel readback after compressed DML. This is transaction local; server and
|
||
later pooled-query settings are preserved. The compressed DML budget is removed
|
||
only inside the repair transaction, so it cannot silently skip compressed rows.
|
||
|
||
The runtime image omits npm. The equivalent command there is
|
||
`node dist/tools/convergePacketVisibility.js`, with the same arguments and
|
||
environment. This document does not authorize deployment or live execution.
|
||
|
||
## Local reproduction and regression tests
|
||
|
||
Install the committed backend dependencies, then from the repository root:
|
||
|
||
```sh
|
||
cd backend
|
||
npm ci
|
||
cd ..
|
||
bash scripts/test-privacy-fence.sh
|
||
```
|
||
|
||
The script owns one temporary loopback-only, tmpfs-backed container using the
|
||
CI-pinned TimescaleDB image. It creates an isolated test database, executes the
|
||
full base schema/migration chain, and stops only its own container on exit. It
|
||
does not load application `.env`, application Compose or `DATABASE_URL`.
|
||
The test executes rollback SQL to reproduce the old empty cascade (`1/1` to
|
||
`2/1`, statement-trigger depth 1 with zero prefix rows), then upgrades through
|
||
the real migration runner and proves the fixed empty cascade stays `1/1`.
|
||
It reproduces 066's value-identical UPDATE invalidation, tests transaction
|
||
deduplication, savepoint/full rollback and concurrent transactions, and observes
|
||
the empty-queue latch through the read-only generation reconciler. It also
|
||
checks real prefix changes, private-node
|
||
cascades, public read gates, dry-run with a SELECT-only role, concurrency,
|
||
rollback/readback failures, and compressed history above the old 100k budget.
|
||
|
||
CI runs `npm run test:privacy-integration` against its explicit loopback test
|
||
service. Developers may use an owned local fixture through
|
||
`TEST_PRIVACY_DATABASE_URL`; the suite creates/drops only its uniquely named
|
||
database and creates a uniquely named SELECT-only test role that it removes
|
||
after dropping that database. The ordinary unit suite excludes integration tests.
|
||
|
||
## Rollback
|
||
|
||
The forward migration is additive; historical migration files are unchanged.
|
||
The executable inverse is
|
||
`backend/src/db/rollback/074_prefix_visibility_row_fence.sql`. It has its own
|
||
transaction and timeouts, restores 066's transition-table statement triggers,
|
||
and leaves packet data, queue data and generation values alone. It removes the
|
||
dedup marker column and restores value-identical UPDATE invalidations. The
|
||
older 066 rollback is retained for the original bug reproduction only.
|
||
The worker's conditional advancement and the convergence command are compatible
|
||
with either trigger layout; retain the worker guard when possible.
|
||
|
||
Do not erase the production migration ledger to roll back. The runner will
|
||
retain the recorded 074/134 checksums and will not reapply them automatically;
|
||
a later forward rollout needs a reviewed migration or explicit reapplication
|
||
of the reviewed SQL. The disposable fixture removes its own fence ledger rows
|
||
solely to reproduce the old layout and test the real runner's 066-to-074/134
|
||
upgrade. Failed migration transactions are also tested to leave the
|
||
prior complete trigger layout intact.
|
||
|
||
Convergence has no automatic data reversal: its only changes are verified
|
||
current-policy flags, completed pending/failed work and a new generation.
|
||
If privacy policy must change, edit it through the normal authorized path and
|
||
rematerialize again. Never roll generations backward or copy stale flags back.
|