# ZKTecoSyncService-V2 — Service Quality Roadmap Living checklist. Update the Status column in the same commit that changes the work. Written 2026-10-11, the morning a config copy silenced delivery for ten hours, because that incident re-ordered every priority below it. --- ## The one lesson that sets the order The service failed on 2026-10-11 in the worst possible way: it was **down and looked up**. Upload was disabled, yet the host connected to all five devices, validated every window, wrote every punch to the ledger, and emitted healthy `DUAL_HEALTH` lines all night. 530 punches (508 people) never reached MySQL, `upload_attempts=0` on all of them, and not one log line, not one of the 105 tests, and no existing metric said so. So the ordering rule for everything here is: **make "it stopped delivering" impossible to miss before making anything else faster or nicer.** --- ## Phase 0 — Explain the live latency **Status: DONE** (commit `69da9ca`, `9c2438f`) Question was whether the reported 12-34s live delay was a COM message-pump problem or per-device clock skew. Answer, measured from the service's own `RT` line, which already carries both the host time at the raw COM callback and the device-supplied y/m/d/h/m/s: | device | clock offset behind host | spread | |---|---|---| | 172.20.30.220 | 95-96s | 1s | | 172.20.30.221 | 106-108s | 2s | | 172.26.30.17 | 107s | 1s | | phase1-test-01 | 113s | 0s | Both hypotheses were wrong in the end. The 12-34s delay **never existed**: that analysis assumed one global 84s device-host skew, and 95-84=11, 107-84=23, 113-84=29 reproduce the "latencies" exactly. Retracted in `69da9ca`. Callback -> durable SQLite, measured directly via `INGRESS_WRITE`: **0.1-0.9s** upper bound, 100% under 1s, queue depth always 0, SQLite upsert 0-32ms. The live path is genuinely live. Clock skew is documented in `DeviceClock` with the measured per-device values. Direction is safe (a device running behind widens the watermark window, so nothing is skipped) and `OverlapMinutes=10` dwarfs the 18s spread. **Not treated as critical** — decision taken 2026-10-11. Correctness gap for cross-device comparison only; fix by per-device measurement or NTP, never by one global constant. --- ## Phase 1 — Delivery watchdog and internal counters **Status: DONE — deployed and verified in production (commits `ce3a0ef`, `4c82d89`, `df9f0f0`)** The incident made this the top priority rather than an observability nicety. Shipped: `DeliveryWatchdog`, deliberately **outside** the upload loop, because the 2026-10-11 failure was "the uploader never ran at all" and a detector inside that loop could not have fired. It samples the ledger every 30s per device and raises `UPLOAD_STALL` after 10 consecutive growing samples (~5 min), then `UPLOAD_STALL_CLEARED` when growth stops. Predicate is **growth, not occupancy** — the ledger legitimately holds 27 permanent year-2033 `Pending` rows, so any `pending > 0` test would alarm forever on a healthy host. Started unconditionally in `Program.cs`: it must not be switchable by the same misconfiguration it exists to report. Also emits `DELIVERY_METRICS` every 5 min so routine health is visible. 4 tests; suite 109/109. Deployed 2026-10-12 01:32 and confirmed by evidence, not by assumption: `DELIVERY_WATCHDOG_START` at 01:32:19, first `DELIVERY_METRICS` at 01:37:19 (`samples=10`), reporting `pending=7` / `pending=20` on the two devices that hold the year-2033 garbage and 0 elsewhere — 27 total, and **no `UPLOAD_STALL`**, which is the correct verdict on a healthy host. Had the deploy silently skipped the Host binary — as the old script was built to do — neither line would exist. Corrected 2026-10-12 (`4c82d89`) after self-review found the watchdog blind to the most likely failure: it counted **Pending only**, but the state machine is `PENDING -> SENDING -> SENT | RETRY -> SENDING...`, so a genuinely broken delivery CLAIMS Pending every cycle and parks it in Retry. Pending then drains back to ~0 while Retry grows unbounded — the watchdog would have watched a shrinking, healthy-looking backlog while attendance piled up undelivered. It now measures **Pending + Sending + Retry** (`owed=`) and the alarm states its own shape: `RETRY_DOMINATED` (endpoint refused) vs `PENDING_DOMINATED` (nothing attempted). Verified live 2026-10-12 11:04: `owed=7,pending=7,retry=0` / `owed=20,pending=20,retry=0` across five devices — the 27 known 2033 rows, `retry=0`, no `UPLOAD_STALL`. Deliberately not built (decision, not omission): the device-side read counters and the COM-op budget. The COM op budget is already logged as `COM_OP_SLOW`, and nothing about read volume is a delivery risk. Still open from this phase, the device-side and budget half: - Is the device side working? (reads, full reads, busy ms, live events) - Did we exceed a budget? (COM op > 5s, device duty cycle > 2%) Deliberately NOT in scope yet: per-device clock-skew compensation. Measured, documented, parked. --- ## Phase 4 — Config validation and effective-plan print **Status: DONE — deployed 2026-10-12 10:59 and verified (commits `9c2438f`, `167544b`, `df9f0f0`)** `config/phase1.device.json` and `publish/config/phase1.device.json` are two files with divergent contents and no guard between them. A deploy overwrote the live one with the acquisition-only template and nothing objected. Done in `9c2438f`: - `UPLOAD_INACTIVE` is a Warning that states the consequence instead of an `info` line reading like a mode selection - `deploy_livefirst.ps1` refuses to overwrite a live config that has delivery enabled with a staging copy that does not (verified by dry-run) Done in `167544b`: - `ConfigValidator` reads the RAW JSON, not the typed model — the typed model is what discards the evidence. Rejects unknown keys (with the nearest known key suggested), non-positive cadences, an inverted backoff ceiling, a case-mismatched `read.mode`, and `upload.enabled=true` with no usable endpoint. `$`-prefixed keys are always allowed so `$comment` documentation can never fail a deploy. - runs BEFORE the SCM handshake, so a refused config never reports `SERVICE_RUNNING` - `EffectivePlan` prints the resolved plan at startup: delivery on/off first, then endpoint, acquisition, the three read cadences, retention, watchdog budget The two silent-ignore mechanisms this closes, both found by reading the code: `System.Text.Json` ignores unmodelled properties, and `DeviceWorker` maps an unknown `read.mode` to `Auto` via an **ordinal** switch — so "Timewindow" and "timewindow" were both silently not-TimeWindow. The validator is case-sensitive for exactly that reason. 19 tests. One of them asserts that the actually-deployed `publish\config` passes, so this cannot brick the live host on its next restart. 128/128. Verified live at 10:59:00 — `EFFECTIVE_PLAN_BEGIN … EFFECTIVE_PLAN_END` printed, **no `CONFIG_INVALID`, no `CONFIG_REJECTED`** (the real config passed), and `EFFECTIVE_PLAN_DELIVERY enabled=YES endpoint=http://localhost/api/v1/sync/punches`. That line immediately earned its keep: it showed that the configured `baseAddress` path `/AttendanceHub/public` is discarded, because `batchPath` is an absolute path (`/api/v1/sync/punches`) which RFC 3986 resolution replaces whole. Delivery works, so the route is correct — but the effective URL was never visible before, and now it is stated at every startup. Deploy-script hardening, after the 2026-10-11 23:27 incident (self-inflicted): the script called `Stop-Service`, copied immediately, and died on "file in use" because the host process had not exited when the service reported Stopped. `$ErrorActionPreference = 'Stop'` then killed the script **before the start step**, leaving the service Stopped with nothing deployed and nobody watching. Capture was down for the duration. The script now waits for the process to actually exit (90s), force-kills the orphan, retries the copy, and starts the service in a `finally` block so a copy failure can never leave the host down. Also copies `AttendanceHub.Sync.Host.dll`/`.exe`, which it had been silently skipping — a "successful" deploy could have shipped library changes and none of the Host changes. `_deployment/deploy_now.bat` is the one-click elevated path. --- ## Phase 3 — Ingest validation, dead-letter, cleanup **Status: DROPPED by decision 2026-10-12 — closed, not forgotten** Dropped after a risk/benefit review, on the reasoning that **the largest remaining risk is no longer a missing feature; it is touching a healthy system.** - 27 rows permanently `Pending`, all dated 2033, all `source=Reconciliation`. Correctly withheld from delivery; they never reach MySQL and change no output. - 42 future-dated rows (max 2033-12-03). `NormalizedPunch.ClassifyTime` only rejects years outside 2000-2100, so a device clock set to 2033 sails through. Cleaning them buys no correctness and costs a migration that deletes rows. If they ever become annoying, retention prunes on age and nothing else is needed. Re-open only if a future report is actually polluted by them. --- ## Phase 5 — Tests that assert cost and delivery **Status: STOPPED 2026-10-12 — the bar that mattered was met** 129/129 passing. The suite stayed green through all three production failures this week, because nothing in it asserted that a punch reaches a destination. - [x] a delivery test: something must complain when nothing is delivering. `DeliveryWatchdogTests` covers both shapes that matter — a growing backlog with no delivery, and a backlog that fails into Retry — plus the complements (fixed backlog stays silent, draining clears and reports). - [x] the deployed production config must validate (`ConfigValidatorTests`), so config validation can never brick the live host. - [ ] end-to-end test asserting at the upload client — not started. - [ ] budget test that fails rather than logs — not started. The two unchecked items remain unstarted **on purpose**: both are regression protection for code that is already verified in production, and writing them means more code in a system that is currently correct. --- ## Phase 2 — Fix the live-path root delay **Status: CANCELLED** Cancelled 2026-10-11. The delay it was created to fix did not exist; it was an arithmetic error in an analysis, not a property of the system. Recorded here so it is not resurrected from an old plan. --- ## Commercialization blockers — agreed 2026-10-14 Defensible for this site, presentable, **not yet a product**. The verdict that produced this list: measured availability over the period was ~99.86% (one ~12h outage), not 99.99%, and nothing was measuring it at the time. Four blockers. ### Blocker 1 — Report liveness to the backend **Status: DONE — deployed and verified 2026-10-15 (`e8bec80`, `6b8a5b0`, `7cf4b3f`)** Laravel already had `POST /api/v1/sync/heartbeat`, `devices.last_seen_at`, `connection_status`, `DeviceSyncState` and `ProductionMonitorService` — every one of them documented as fed by a "heartbeat from C# Service" that never existed. All 67 devices sat at `last_seen_at = 2026-09-22`, so all five active devices read OFFLINE. `HeartbeatReporter` is an independent loop, like `DeliveryWatchdog`: no COM or SDK call, no ledger write, own `HttpClient`, rate-limited failure logging, status derived only from the acquisition snapshot — `error` is reserved for a device that is connected but unreadable. Identity is `Supervisor.Ip:Port`, not `WorkerId`: the backend resolves by `devices.ip` + port, so `phase1-test-01` would have 404'd on exactly one device. Verified from artifacts, not from the deploy banner — live Host.dll sha == staging (`6DAF85F1…`), beats `sent=5 failed=0`, `last_seen_at` moved from 2026-09-22 to seconds ago, `Device::isOnline()` 0/5 -> 4/5, and `HEARTBEAT_RECOVERED` lines proving recovery after the web stack returned. It earned itself within the hour: **172.20.30.221 has been unreachable since 2026-10-14 05:55, `connect_failures n=1097`** — a fault nobody could see before. Two defects it surfaced, both fixed: - **Timestamps crossed the boundary as UTC** (`7cf4b3f`). The backend records those digits where it reads site-local time, so a read that had just succeeded was reported 210 minutes old and `/v1/health` answered `status=critical healthy=0` for all five devices. Stored digits, reported staleness and the UTC-to-local shift were all exactly 210 minutes. Now sent as local wall clock, matching the convention `punch_time` already uses. The test pins both halves and was mutation-tested: reverting the fix fails it with `Expected 03:30:00 / Actual 00:00:00`. - **Read-stale devices were counted by nobody** (`2684c23`). The monitor's `elseif ($isReadStale)` branches pushed alerts and incremented no counter, so a reachable device with stale reads fell out of the summary and `healthy` came out short of `total`. Read-stale is now its own bucket, and the five buckets are verified to sum to `total` (5 = 2+0+1+2+0). Same commit raised the read thresholds from 5/10 to 45/90 minutes because they sat *below* the service's own `fullReconcileMinutes=30`: `172.30.70.5` (firmware rejects `ReadTimeGLogData`, named in the service config) reads exactly every 30 minutes with `consecFail=0` — healthy — and was flagged critical for 25 of every 30 minutes. A permanently red dashboard is one nobody reads. ### Blocker 2 — Measured availability **Status: IN PROGRESS — availability now MEASURED (2026-10-16); SCM non-crash restart ladder still open** No uptime telemetry, so availability can only be reconstructed after the fact. First concrete defect found while doing blocker 1: **`/v1/health` returned `status=critical` / HTTP 503 for 23 days on a single alert: `upload.no_success`** — fixed in `16fa638`, verified HTTP 200. The live delivery path is `POST /api/v1/sync/punches` -> `PunchUploadController::upload`, which writes `raw_attendance_logs` and a DLQ and **never writes `device_sync_logs`** — the only table the monitor's `upload` section reads. The writers of that table are `/sync/realtime` and `/sync/batch`, legacy routes the service stopped calling on 2026-09-22. So the pipeline was healthy (`owed` draining, `retry=0`, no `UPLOAD_STALL`) while the top-level status said the opposite, permanently. That is the 2026-10-11 incident in mirror image: then the system was down and looked up; now it was up and reported down. Either way the alarm cannot be trusted, and an alarm nobody trusts is worse than no alarm. Fix shape: severity follows whether the legacy path is actually in use (a row in `device_sync_logs` within the last hour). Idle -> reported as info, with the message naming the table it reads. Active -> unchanged WARNING/CRITICAL. It flips back by itself if `/sync/realtime` or `/sync/batch` is ever re-enabled. Deliberately not a new signal: liveness of the real pipeline is already `checkServiceHealth()`'s `SERVICE_STOPPED` (critical), fed by the 60-second heartbeat from blocker 1, which runs whether or not anyone punches — unlike a table that only moves when there is something to deliver. A per-batch row in `device_sync_logs` was rejected as insufficient on its own: the service only posts when it has >=1 record, so that metric would go quiet every night and raise the same false alarm. **Done 2026-10-16 — availability is now MEASURED, not reconstructed.** `uptime_samples`: one row per scheduled `monitor:production-health` run — `service_up` from the same heartbeat that drives SERVICE_STOPPED (so the dashboard and the telemetry cannot disagree about what "up" means), the report's overall status, and device counts for context. `UptimeTracker::summary()` answers any window by counting: uptime %, longest outage, and — honestly — gaps, because the sampler lives inside the app, so a Laravel outage produces *no rows* and is reported as unknown time, never as uptime or downtime. A gap also ends an outage run: what happened before the silence is a separate question from what happened after it. One down sample = one nominal five-minute interval (the instrument's resolution, stated rather than implied), and "no samples" is null rather than 0 or 100 — both of those would be claims. 400-day retention pruned inside the write path, and the recording wears its own try/catch so telemetry can never fail the health check that produces it. The human-format `monitor:production-health` gained an AVAILABILITY section; the `--json` payload stayed the health report itself. Measurement starts with the first live sample (2026-10-17 00:19 local); before that date availability remains reconstruction and the tool says so by having no earlier rows to count. The guard earned its keep on day one: the four scheduled runs before the production migration (00:00, 00:05, 00:10, 00:15) each logged `monitor.uptime.record_failed` loudly instead of dying, and the first sample after the migration went in at 00:19. `UptimeTrackerTest` 10 cases (record, gap marking, the never-heartbeat sentinel's overflow, nominal-interval outage arithmetic, gap-breaks-the-run, windows, null-on-empty, retention, command wiring). Still open under this blocker: - `FAILURE_ACTIONS_ON_NONCRASH_FAILURES=FALSE`: the SCM restart ladder covers crashes only, and what a config rejection does to service availability has never been observed. Enabling it is one elevated line; the real decision is WHICH recovery actions the service should get. - the sampler is internal by design: an outage of the app itself shows up as a gap (unknown time), not as downtime. An external prober would close that; deliberately not faked here. ### Blocker 3 — Tell a human **Status: DONE — `117872c`, panel channel added and verified 2026-10-15** The destination question was resolved by moving the channel instead of waiting for one: reports live **inside the panel**, which is what was actually asked for (Telegram/Slack explicitly not wanted). `MONITOR_ALERT_WEBHOOK_URL` may stay empty indefinitely; a webhook remains supported as an optional extra on top, never a precondition for anyone being told. Identified as blocker 1's sibling: visibility nobody can act on is only half a monitor. Blocker 1 made the state *visible*; it did not notify anyone. `SERVICE_STOPPED` was already CRITICAL and `172.20.30.221` had been unreachable for 31 hours, and both lived in a JSON blob and a log file nobody opens unless they already suspect something. Every detector was working correctly while a device sat down for a day and a half. `monitor:production-health` already ran every 5 minutes, so the notifier is wired into it rather than added as a parallel schedule that would have to re-derive the same verdict. `MonitorNotifier` POSTs JSON to `MONITOR_ALERT_WEBHOOK_URL` and records **every** outcome in `monitor_alert_notifications` — deliberately not `notification_logs`, which requires `tenant_id` and cascades on delete, so a pipeline outage would be attributed to a tenant and its evidence deleted along with it. Four behaviours, each earned from a failure observed while testing: - **Change-based, not per-run.** One chronically offline device would otherwise post 288 messages a day until the channel was muted out of habit. - **Failed deliveries back off** 15 → 30 → 60 → 120, capped at the 240-minute reminder, resetting to 15 once a delivery succeeds. Before this existed, one dead destination produced a failed row every single run, forever, and made one outage look like dozens. - **Fingerprints exclude volatile counters and sub-threshold alerts.** Message text carries running values ("no successful upload for 33049 minutes") that change every run, and `silently_idle` flickers as machines cross the six-hour mark. An info-level alert appearing was observed to trigger an attempt while the overall status stayed `warning`. - **The panel is the channel, and that is a recorded outcome.** With no webhook configured the row lands as `result=panel`, `channel=panel`, `recipient=monitoring page (reports tab)` and counts as *told*, because the reports tab of `/monitoring` reads that same table. The earlier `no_channel` outcome — a state where the log admits nobody was told — is no longer reachable on the default configuration, only when a webhook is configured and then fails. Verified against a local receiver rather than by inspection: payload delivered with Persian device names and the dashboard link intact; second run silent; dead port recorded with the exact cURL error; delivery resumed 50 s after the outage cleared instead of waiting out the reminder; backoff ladder exercised through the real method (15/30/60/120/240/240, reset to 15 after a success) and its synthetic rows removed afterwards (0 left). **Reports section in the panel — the requested destination (2026-10-15).** `/monitoring` gained a **گزارش‌های سامانه** tab with two halves: - *Current verdict*, computed on demand from `ProductionMonitorService` when the tab is opened (not in `refresh()`, which the other four tabs share): status badge, service running, heartbeat age, the five device buckets (total / healthy / offline / silently idle / read stale), and every active alert with its severity. - *History*, read straight from `monitor_alert_notifications`: time, status, how it was recorded, alert count, summary, per-alert detail, and any error. **Evidence** - Component + Blade + real data path driven through `Livewire::test` with an actual `switchTab('alerts')` action: **12 of 12 assertions passed**. One of them is deliberately inverted — the empty-state row must be *absent* while history exists, because a silent empty loop would otherwise read as "nothing to report". - Live in a real browser as the `admin` account: HTTP 200, tab clicked, section showed `هشدار`, service `در حال اجرا`, heartbeat `0 دقیقه پیش`, `5 / 1 / 1 / 3` buckets, `هشدارهای فعال (5)` (including the Persian device names), and the history row `2026-10-15 20:39:56 → panel → 5`. - First real row recorded as `panel` with no error; a second run 53 min later correctly produced **no** new row (fingerprint unchanged, 240-min reminder). - History is bounded: `retention_days=90`, pruned inside `deliver()` on every announcement rather than by a separate schedule nobody would remember. Proven with a synthetic 120-day row — deleted, **0 real rows damaged**. The verification session used to open that browser was created without touching any password and was deleted afterwards (`sessions` back to its ordinary 9 rows). --- ## Field finding — 172.20.30.221 looks reachable, and that is the trap (2026-10-15) **Status: diagnosed — needs a power cycle; no code fix, and no setting change** Reported as "couldn't connect with the ZKTeco test tool using the same device IDs either". From the service side: ``` api=Connect_Net ok=False lastError=-2 elapsedMs=17885 LIVE_CONNECT_FAILED device=172.20.30.221 failures=385 ``` Probing from this host says something that *looks* healthy, which is exactly why it is worth recording: | | healthy `172.30.70.5` | failing `172.20.30.221` | |---|---|---| | ICMP ping | reply | no reply (ICMP blocked — normal) | | TCP :4370 | open in 14 ms | open in 0 ms, 5/5 sequential, 6/6 concurrent held | | HTTP :80 | **200 in 79 ms** | **no answer at all (timeout)** | Both devices accept TCP identically; only the healthy one ever *replies*. The device therefore accepts connections while its application layer never answers — which is why `Connect_Net` waits ~18 s and returns `-2`, and why the ZKTeco test tool failed too. **Do not read "port 4370 open" as "device fine"**; it is the misleading signal here. Remedy is a physical power cycle. --- ## Database self-audit (2026-10-15) Asked for explicitly: *"you wrote the databases, you manage them, and check that nothing spills anywhere."* - **Schemas on the server:** 12, of which only two belong to this project — `attendance_hub` (production, 71 tables) and `attendance_hub_test` (disposable, 72 tables, dropped and recreated per run). - **The test schema cannot be anything else:** `tests/bootstrap.php` defines `TEST_DATABASE`, asserts the `_test` suffix, and aborts *before* any DDL if it is ever absent. Production is not reachable from the test bootstrap. - **Production counts held:** `raw_attendance_logs` 260,062 · `devices` 67 · `personnel` 5,079 · `users` 1 · `monitor_alert_notifications` 1 · `sessions` 9. - **The alert table is bounded** (`retention_days=90`, pruned on every announcement): a synthetic 120-day row was inserted and deleted while all real rows survived. - **Nothing left behind by the browser check:** the temporary authenticated session was created without changing any password, deleted afterwards, and `sessions` returned to its ordinary rows. Correction worth remembering: the first run of this audit reported that prune had wiped the real row. It had not. `->where()` mutates a Laravel query builder, so the earlier filter leaked into every later count on that same variable. The numbers were wrong, not the product — the audit now starts a fresh builder for each measurement. --- ## PHP test suite — could not run at all (found 2026-10-15) **Status: runnable — `31e2e41`, 1 passed → 166 passed on MySQL** 237/240 died during schema bootstrap: three migrations issued `SHOW INDEX` and one issued `ALTER TABLE … MODIFY`, MySQL-only SQL, against the sqlite in-memory schema. Those migrations date from September; nothing committed earlier that day touched them or any test. - `SHOW INDEX` → `Schema::hasIndex()`, the cross-database API `down()` in those same files was already using. `2026_09_14` gained the sqlite guard `2026_08_24` already had for the identical `MODIFY`. - `tests/bootstrap.php` and `tests/TestCase.php` hardcoded `sqlite ':memory:'` and overrode `phpunit.xml` and `.env.testing` unconditionally: four layers, three of them disagreeing, which is why editing either config file alone silently changed nothing. All now name `attendance_hub_test` as a literal, with a `_test`-suffix assertion before any destructive DDL — a literal cannot be misconfigured by a missing or stale env file. - bootstrap drops and recreates the schema per run, because the suite has no `RefreshDatabase` and `TestCase` only migrates, which is a no-op on a database that already has tables. Proved not to be the deciding variable: identical output before and after. Production verified untouched by comparing seven table counts across a run. **Known red: 74.** The count rose from 53 because the engine became the real one. FOREIGN KEY failures 8 → 0 and NOT NULL failures 16 → 8 disappeared with the switch; in exchange 38 unique-key collisions appeared, because fixtures insert punches at `now()` while MySQL `TIMESTAMP` drops sub-second precision, collapsing them onto the `(device_id, personnel_code, punch_time)` key. Those tests were not controlling time and were passing on sqlite for the wrong reason. Follow-up, scoped and not started: per-test isolation, plus fixtures with fixed timestamps. Out of scope here deliberately — the four blockers outrank it. `database/migrations/2026_08_16_000002_add_unique_constraint_to_raw_logs.php` is no longer unstaged: `ac56a9a` committed it after fixing what the rewrite still got wrong. The derived-table DELETE was right about portability — proven, it runs on SQLite while MySQL's `DELETE t1 FROM … INNER JOIN` does not — but the migration was not idempotent (a second `up()` died on `Duplicate key name`), and it would have bolted a redundant third index onto production, which already enforces this constraint under the name `uq_device_personnel_time` (information_schema, 2026-10-15). `up()` now checks for an existing unique index over the same column set first; since all three columns are NOT NULL, skipping the delete when the constraint exists is provably equivalent to running it. Verified in `attendance_hub_test` with controlled duplicates: 12 checks of 12 — dedupe keeps the lowest id, no unrelated row is touched, a second run is a no-op, and both halves of the portability claim hold. Production was never executed against, and has zero duplicate groups anyway. --- ## Repository integrity — the working tree outran git (found 2026-10-15) **Status: closed — `58a7957`, `c64989f`, `f3f721a`, `3722ae8`, `54062e8`** One question was asked of every untracked PHP file: does committed code name this class? Ten answers came back yes, seven of them the Monitoring DTOs that `ProductionHealthCommand`, `MonitorNotifier`, the `Monitoring` component and `ProductionMonitorService` all import. A fresh clone fataled before it booted. What was wrong, in full: - **423 files staged and never committed** — 34,896 lines of the Laravel application sitting in the index, one careless `git checkout .` from being gone. - **210 files untracked** — 56 migrations, domain models, tests, the V1 C# source and its 25-file .NET test suite, `_deployment` scripts. - **216 build artifacts staged** by an earlier add-all, because the ignore rule read `publish_*_staging` while the directory is called `publish_staging`. - **`docs/ATLAS_DB/` unignored** — legacy-system exports that contain real personnel records. `/tools/` (device inventory), three backup folders (~330 MB) and `bin`/`obj` at any depth were equally exposed. Fixed as five commits split by what they are rather than by urgency: ignore rules first, then the Laravel application (314 files), then the C# source and test suite (62), then the deployment notebook (45), then the token below. After them `git status` reports **zero** untracked files — nothing is outside version control, and nothing ignored is a source file. Scratch that was mine and worthless was moved out rather than deleted, to `Temp/opencode/repo_scratch_20261015/`: the Hello-World `Program.cs`, `AttendanceHub.csproj` and its `obj/`, `SqliteDiag/`, `ZKTecoComForensics/`, `public/router-p5.php` and `public/p5-boot-test.php` (both web-accessible debug scripts), `tests/test_today_overview_sql.php`, and the PECL droppings `channel.xml`/`package.xml` — 4,754 lines of xdebug metadata. Every item was checked against committed history first; the two `Program.cs` hits were the service's own file, not the root one. ### The credential this cleanup itself exposed Committing the V1 source surfaced `ZKTecoSyncService/appsettings.json`, whose `LaravelApi.ApiToken` is **byte-identical to `tenants.api_token` for tenant 1** and to the secret in both copies of the V2 device config. A live credential, committed by the very commit that tidied the repository. The repository has no remote, so it never left this machine — but the last two commits were rewritten regardless (`f3f721a` and `3722ae8` replace `005e4d6` and `a3c30c5`), the file is now ignored, `git grep` over HEAD and `git log --all -S` find nothing, and after `reflog expire` plus `gc --prune=now` the old blob is physically gone (`git cat-file -e` fails). **Not rotated, deliberately.** The service running right now authenticates with that value, so rotating on reflex would take the sync path down. Rotation is a scheduled operation across three places at once — V1 `appsettings.json`, both V2 `phase1.device.json` copies, and the `tenants` row — with the service stopped in between. What ships in the repository instead is `appsettings.example.json` with a placeholder. ### Closed while answering: unauthenticated report export (F5) Questioning the token led straight into a live hole. `/api/reports/export/{pdf,excel,csv}` carried no middleware at all and `ReportExportController` validates input only, so an unauthenticated `GET .../export/csv?year=1405&month=7` returned HTTP 200 with a CSV holding every personnel's code, name and attendance summary. The architecture document had already logged the defect ("currently OPEN!") — it had simply never been executed. The fix is one line: the `reports` group in `routes/api.php` now carries `->middleware('auth')`, the session guard the panel itself uses and the one a `login` route exists for. Sanctum is not installed and no in-application code calls those endpoints, so nothing else moves. Verified against the running server: a JSON caller gets 401, a browser caller gets 302 to `/login`, a signed-in user still gets the CSV. `tests/Feature/ReportExportAuthTest.php` locks those three behaviours in (3 tests, 7 assertions, green) and the full suite stays at 243 tests with the same 74 red, so the addition broke nothing. ## Security & governance hardening — 2026-10-16 Mandate: fix what needs fixing (security and management topics) without breaking anything that works today. The evidence for "nothing broke" is the suite comparison at the end of this section. ### Closed 1. **Sync token hashed at rest** — migration `2026_10_16_000001_add_api_token_hash_to_tenants` (idempotent DDL + PHP backfill, applied to production) and a rewritten `SyncAuthMiddleware`: sha256 lookup against `api_token_hash` first, constant-time `hash_equals` on the plaintext column as fallback — both paths valid in every intermediate state, so ingest cannot break mid-deployment. Live proof through the *running* V2 service: real token 200, wrong token 401, `device_sync_states.last_read_success_at` moved for devices 1/2/14 within seconds of the migration. `SyncAuthMiddlewareTest` 7 tests. 2. **Login brute-force cost** — 5 attempts per username+IP per 60 s (`RateLimiter`, counter cleared on success, Persian message rendered on the component). `LoginThrottleTest` 4. 3. **Seeder gates** — `TestDataSeeder` now refuses production *and* any database that already holds a punch in `raw_attendance_logs` (`SEED_TEST_DATA=true` is the documented escape hatch, checked first so it works under cached config); roles/permissions extracted into an idempotent `PermissionSeeder` that carries no demo data. `SeederSafetyTest` 7 (production refusal, punch gate, opt-in, roleless-denied). 4. **Permission model installed on production** — it had 0 roles / 0 permissions while every sidebar entry and every create/approve button sits behind `auth()->user()->can(...)`: the admin had **no navigation at all** and `CorrectionRequestList` refused approvals outright (five `can()` probes on the live user all returned false). Seeded 3 roles + 30 permissions, assigned `system_admin` to the only account; roleless users still denied (asserted). Then the exact `PersonnelService::create` call the panel makes was replayed live inside a rolled-back transaction: personnel row + user + `personnel` role assigned + random 10-char temporary password (not 123456) — counts identical before/after, no residue left. The panel's create- personnel path is confirmed working end-to-end on the running installation. 5. **Default `123456` removed** — `PersonnelService::create()` mints a per-account random temporary password shown once in the create flash (no caller signature changed; `password` is hashed by the model cast). `PersonnelAccountPasswordTest` 3. 6. **Export throttle** — `throttle:60` per user on the reports group. `ExportThrottleTest` 2 (60 served then the 61st gets 429; one user's budget is not shared with another's). The sync group stays unthrottled on purpose: the ingest burst profile is unmeasured and a 429 there would drop punches — documented, not guessed. 7. **Cross-tenant IDOR sweep** — 153 fetch-by-id sites audited; the 33 browser-reachable ones re-filtered with the project's own `where('tenant_id', TenantContext::getTenantId())` across Leave/Mission/Shift/Calendar/Organization/Personnel/Device/Workflow/Attendance services plus `OrganizationTree::openEditModal` and the monitor's per-device verdict (Persian "not found" wording where the lookup raises). The 15 left unfiltered are deliberate and documented: `assertDeviceBelongsToTenant` guard, a filter on the very next line, inner per-device queries inside an already-scoped loop, the legacy sync endpoints authenticated by per-device `settings.api_key`, and installation-wide monitor aggregates (changing those would flip production verdicts). `CrossTenantIsolationTest` 3 — foreign tenant refused *with the row untouched*, same-tenant control still served, Livewire modal included. 8. **F4 closed with proof** — `php artisan backup:database` scheduled daily 02:30 (`--single-transaction` so it never blocks the punch path, gzip streamed in 1 MB chunks, keeps the newest 14 so the disk cannot fill). First real dump of `attendance_hub` ever taken: 131 MB → 7.5 MB in 10.6 s, then **restored into a scratch schema and compared row-for-row — all 71 tables identical** (260,079 raw punches / 5,079 personnel / 67 devices), scratch and intermediate dropped afterwards. `BackupDatabaseCommandTest` 3 (dump content, retention, clean failure). Offsite copy still open — no remote exists on this box. ### Token rotation — DONE 2026-10-16 23:06 The last F5 secret closed in one 26-second elevated window: service stopped, `tenant:rotate-token` minted the replacement (stores only its sha256, nulls `api_token`, prints the value once), all 15 discovered config copies patched byte-for-byte with encoding preserved, and the mid-window gate proved it over real HTTP — new token 200, old token 401 — before the service was started again. The window ended on `--check` exit 0 ("database holds only hashes and every config file verifies"), and the running V2 service resumed reading 25–62 s later on all four live devices (the fifth, `172.20.30.221`, is the wedged field case, unchanged). `verify_token_tenant.py` still reports MATCH against production, and tonight's 02:30 `backup:database` will be the first dump in this database's history taken with no plaintext token inside it. Operational notes worth remembering: the elevated half could not be driven remotely — the service runs as LocalSystem and its DACL grants interactive users no stop/start rights (`sc sdshow`), and two UAC consents launched by the agent were declined before the operator ran the window themselves; the flow is therefore written for a human-triggered elevated window. Config snapshots (the rollback path) live in `backups/rotation_20261016/` and hold the now-dead old token; the window transcript was deleted for containing the printed token; the window's helper scripts (get_old_token / patch_configs / api_test / restore_token) were archived out of the repository to `%TEMP%\opencode\rotation_helpers_20261016\`. Nothing rotates the token on a schedule, on purpose — it is a stop-services operation — and the runbook in `docs/SYNC_AND_CALC_ARCHITECTURE.md` §9 is the procedure for the next one. ### Tenant-ownership guard — DONE 2026-10-17 The last F5 leftover closed at the model layer instead of per form: `GuardsTenantOwnership` (a trait, on `BaseTenantModel` and on `User`) reverts any update that tries to dirty `tenant_id`, so a payload can no longer move a row into another tenant however it arrived — `update()`, `fill()+save()`, `forceFill`. Creation still assigns from context, unchanged. A legitimate ownership move opts in by overriding `allowsTenantChange()` — denied by default, allowed on purpose, never the other way around. `User` is the reason the guard is a trait and the tripwire test exists: it sits on `Authenticatable`, not `BaseTenantModel`, so its `tenant_id` was in `$fillable` with no ownership rule behind it — exactly the silent hole such a fix is supposed to prevent, found by the fix's own tripwire rather than by an attacker. The tripwire walks every `Domain/*/Models/*.php`, checks whether its table actually has a `tenant_id` column, and fails if such a model is neither under `BaseTenantModel` nor using the guard — a future model outside the family cannot go unnoticed. 5 tests: update payload blocked, fill+save blocked, creation still works, opt-in override works, tripwire green. ### Suite state (2026-10-18) 290 tests / 813 assertions: **2 failures, 0 errors, 0 risky** — down from the 74-red baseline (290/671/74). Name-level diff against that baseline: 0 newly failing. The 74 collapsed in three passes: * 65 fell to the per-test isolation itself (`purgeDomainTables` in `TestCase`): cross-test row accumulation had been failing whole classes — Organization, Shift, Personnel, AttendanceService, SyncReliability, DeviceSync, CorrectionPersistence, HolidayObserver, CalculateDailyAttendanceJob. * Fixture and contract repairs covered that family's remainder: Bearer/hash token fixtures (`Tenant::$fillable` silently dropped `api_token`), a real approver user for the `approved_by` FK, the `default_shift_id` spelling, the empty-batch ack (`'logs' => 'present|array'`), `Queue::fake()` wherever the sync queue executed jobs inline, `PRAGMA` → `SHOW INDEX` on MySQL. * The last 7 fell to the engine and harness review: `pairPunches` now sorts its input (a leading OUT of an unsorted collection was dropped silently); `collapseNearDuplicates` runs at both pipeline entries before positional type derivation — a fingerprint double-tap (08:00 + 08:01, same raw type) used to be flipped by `autoDetectPunchTypes` into a 1-minute phantom session after which the duplicate rule could never fire, turning a healthy 540-minute day into `incomplete`; `HolidayObserver` normalizes the date at the single dispatch point (the date cast stores `Y-m-d 00:00:00`, so `getRawOriginal()` bypassed the limiter in production too); `CalculateDailyAttendanceJob` restores the caller's tenant context instead of clearing it; the stale inline fast-path test was rewritten to the always-async contract (the feature was removed on purpose — nothing may block the ACK path); the pre-calculation persistence test fakes the queue. The 2 remaining red are `AttendanceEngineTest::test_32/33`, kept red on purpose: LeaveService and MissionService still write `daily_attendances` rows directly; the tests assert the architecture they should have. They are the review item, not noise. ### Open (unchanged) * `172.20.30.221` wedged 31+ h — needs a field power cycle; no code fix exists. * Blocker 2 partly open: SCM non-crash restart ladder + optional external prober (availability itself is measured since 2026-10-17, `uptime_samples`). * Migration ledger is partial (found 2026-10-17): `cache`, `jobs` and `monitor_alert_notifications` exist on production but are absent from the `migrations` table, so `migrate:status` reports them Pending and a full-directory `migrate` dies on "table already exists". Single-file `--path` is the only safe pattern here until the ledger rows are added. * F4 leftovers: offsite copy, disk-space watch, laravel.log rotation. * F5 leftovers: Livewire `can()` coverage (the permission model now exists — deciding which UI needs which gate is a product decision). The mass-assignment of `tenant_id` closed 2026-10-17 with the ownership guard (see below). * Deferred: `AttendanceEngineTest::test_32/33` review (the last 2 red — LeaveService and MissionService still write `daily_attendances` directly; the tests assert the architecture they should have), F6 perf, F7 product gaps (placeholder Livewire lists, workflow inbox, hardcoded fa strings), offsite-backup destination (needs a remote target from the operator), nightly-dump gap for 2026-10-17 (task `\AttendanceHub_LaravelSchedule` registered and verified producing the 2026-10-18 02:30 dump). ## Production data-loss incident and restore — 2026-10-18 At ~01:00 (local) the first iteration of the test-harness purge truncated every table of `attendance_hub` — and of five other schemas on the same shared MariaDB (`asset_management`, `cctv_monitor`, `documents_management`, `liateam_catalog`, `pakrah`). Root cause, fully ownable: `purgeDomainTables` v1 called `getTableListing()` without a schema argument, which returns every non-system schema with schema-qualified names; the keep-list held bare names, so nothing matched — not even `migrations` — and the qualified `TRUNCATE` statements ran across schemas in alphabetical order until `sarvand.ir`'s dotted schema name produced invalid SQL (1064) and stopped the loop. That schema is the only one that escaped. Evidence: `uptime_samples` restarts at id=1 / 2026-10-18 01:00:05 (the monitor's first post-wipe sample), the restored `migrations` ledger holds 43 rows again, and the failing run's own error text names `truncate table sarvand.ir.admins`. The C# sync service could not land heartbeats or punches from 01:00 until the restore (empty FK targets) — the first measured availability outage on the graph. Recovery, same night (02:26–02:39): restored from the only surviving dump, `backups/db/attendance_hub_2026-10-16_101724.sql.gz` (taken 2026-10-16 10:17). The first attempt piped the file through PowerShell, which replaced every non-ASCII byte with `?` (all Persian text corrupted); the restore was redone byte-safe via `cmd /c mysql < file` and verified by row counts (260,079 raw logs, 332,986 daily rows, 5,079 personnel, 67 devices) plus Persian spot-checks. Post-restore reconciliation: PermissionSeeder (roles/permissions had been seeded after the dump was taken), the `2026_10_16_000002` ledger row re-inserted, `tenants.api_token_hash` realigned to the rotated token the running service sends (sha256 only, plaintext stays NULL), admin password reset to the seeded dev credential, login throttle cleared. Verified live: rotated Bearer 200 / wrong token 401, heartbeats 4 devices fresh in <2 min, monitor "Service Running: YES", and the 02:30 nightly dump captured the restored database on schedule. Permanently lost: punches ingested between 2026-10-16 10:17 and the wipe (~39 h; the C# SQLite buffer had already flushed them, Pending: 0) and the availability history before 2026-10-18 01:00. The five other schemas were truncated too and no dumps for them exist in this project — their owners must restore from their own backups; that blast radius is on this project's account, not on those projects'. The guard that prevents a repeat is in `TestCase::purgeDomainTables()`: it names the current schema explicitly (`getTableListing($connection->getDatabaseName(), false)`, refuses to run unless `migrations` appears in that listing (tripwire), and only issues `DELETE FROM` against tables it just listed — no `TRUNCATE`, no cross-schema names, per-test cost ~6 ms/table. ## Pipeline assurance review and the wolf-crying alert — 2026-10-18 evening Asked to certify the device→database path and the ability to localize any failure, the review walked every hop with live evidence and found one signal that lied — the monitor's own `upload.no_success` alert. Live evidence at review time (production, 19:10–19:41): heartbeats landing every 60 s on all reachable devices; 82 punches ingested for 2026-10-18 of which 82 (100 %) already processed into 56 daily rows; zero duplicate `(device_id, personnel_code, punch_time)` triples across all 260 k raw rows (the ingestion dedup contract holds at rest); `failed_jobs` 0, queue 0; offline buffer Pending 0 / Sending 0 / Failed 0; measured availability climbing back post-restore (91.9 % → 92.2 % over the evening). The false alarm: `checkUploadHealth()` derived its "legacy path in use" heuristic from *any* recent `device_sync_logs` row — but that table is also written by the panel's manual refresh request, and that request is a dead end: `DeviceSyncService::manualSyncRequest()` inserts a `sync_type='manual'`, `status='running'` row and returns; nothing consumes it (no endpoint reads pending requests, the C# service has no poller for them), so the row stays `running` forever. One click at 19:03 therefore manufactured a permanent `[CRITICAL] No successful upload for 37384 minutes` on an otherwise healthy pipeline — a wolf-crying alarm, the exact failure mode the 2026-10-15 note in this file warns about. Fix (commit in this change): the heuristic now counts only rows from the two legacy *delivery* routes (`sync_type IN ('batch','realtime')`). A manual request can no longer escalate it. Verified live at 19:41: the alert fell back to `[INFO]` with its explanatory note, and Overall Status dropped CRITICAL→WARNING — the remaining WARNING is the real offline device `172.20.30.220` (device 14), whose heartbeat is fresh but whose ZKT connection the service cannot establish; `172.20.30.221` (device 4) is back online. Two tests pin both sides of the switch (`tests/Feature/UploadHealthAlertTest.php`): a recent manual row keeps the alert INFO-with-note; a recent legacy batch row restores CRITICAL. Suite after the change: 292 tests / 819 assertions / 2 failures — the same deliberately-red `test_32/33`, no new failures. Open, born here: the manual refresh button records a request that nothing acts on. Either give the C# service a poller for pending manual requests (real cross-stack feature) or remove the button and its route (it currently only manufactures stuck `running` rows and operator confusion). Decision belongs to the operator; until then, treat `sync_type='manual'` rows as inert. Also observed while walking the evidence and worth stating: 179,581 raw rows carry `is_processed=0` (the restored backlog — every day currently touched by new punches reaches 100 %, and the nightly backfill continues absorbing the rest), and there is no alert yet for a manual request stuck in `running` forever — the dead-end above. Both are candidates for the next hardening pass, not defects in the live path.