new: scheduled work as CronJobs of the hAPI image (ADR-0012)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
BobbyandClaude Opus 5.5 committed 2026-11-27 14:52:19 -05:00
1 parent 349a68b8b7
commit 7dd9c947fd
4 files changed
+30 -3

No files matched your search

+1 -1
View File
@@ -28,6 +28,6 @@ hAPI uses a **Linode Managed PostgreSQL 18** cluster (Shared 2 GB, 1 node) attac
- **Cross-Person work runs per Person.** Purging a removed Person's data, or a job such as reminders, sets `hapi.principal_id` to each Person in turn.
- **Data repairs** normally ship as reviewed Alembic data migrations run as `hapi_migrator`, targeting rows by id or condition without printing them.
- **Break-glass goes through `hapi db breakglass --reason "…"`.** It opens `psql` as `hapi_migrator` from a pod and emits structured audit events to hAPI's centralized logs: start, end, reason, and every statement. Query results are never logged. The platform offers no statement logging or pgaudit, so this is the only audit trail.
- **Connection budget:** the plan allows 50 connections. That leaves about 46 usable after 3 reserved superuser slots and one platform backend. Each app pod holds at most 10 (`pool_size=5`, `max_overflow=5`), and the admin CLI holds 1–2. The rule is: (maximum concurrent app pods, including rollout surge) × 10, plus about 6 for migrate, CLI, break-glass and bootstrap, must be ≤ 46. That caps app pods at 4. Any future worker process counts against the same budget.
- **Connection budget:** the plan allows 50 connections. That leaves about 46 usable after 3 reserved superuser slots and one platform backend. Each app pod holds at most 10 (`pool_size=5`, `max_overflow=5`), and the admin CLI holds 1–2. The rule is: (maximum concurrent app pods, including rollout surge) × 10, plus about 6 for migrate, CLI, break-glass and bootstrap, must be ≤ 46. That caps app pods at 4. Any future worker process counts against the same budget. **Amended by ADR-0012:** housekeeping CronJobs use a pool of 1, so the rule is app pods (with surge) × 10 + concurrently runnable CronJobs × 1 + ~6 ≤ 46.
- **Plan changes are restores.** An in-place resize stalled during verification. Changing size or node count is done as a restore-to-new-cluster, with the same runbook as disaster recovery: fork, wait for DNS, `hapi db bootstrap`, repoint the app. Single-node maintenance windows (pinned to a quiet slot) cause short downtime, covered by 14-day point-in-time recovery.
- Passwords are rotated manually with a runbook. `password_encryption` is set explicitly to `scram-sha-256`.
+1 -1
View File
@@ -14,7 +14,7 @@ hAPI needs Home Assistant to carry out actions in the house: things queued while
- **The bridge needs no new infrastructure or credentials.** HA is the `home-assistant` Bot with a Household grant of `smart_home:write`, and its Token lives in HA's `secrets.yaml`. There's no `jobs` Scope: `smart_home:write` both creates Jobs and consumes them, and ADR-0005 allows splitting the Scope later.
- **Delivery is at-least-once, FIFO by `not_before` (or creation time).** `next` hands out the oldest eligible Job and hides it for a 2-minute lease. After 3 deliveries with no result, the Job becomes `failed` (`no_result`), so one broken Job can't stall the queue. HA scripts must be idempotent: set states, don't toggle. After each result, HA calls `homeassistant.update_entity` on the sensor so a backlog drains without waiting for the next poll.
- **Job lifecycle:** `pending → succeeded | failed | expired | cancelled`. A Job may carry an optional `not_before`. `expires_at` defaults to 1 h after `not_before` (or after creation), and an expired Job is never delivered. A result is `{status, error?, response?}`, where `response` holds the script's response variables. The first result wins, and a later one gets `409`. Any Household member, or any Bot with `smart_home:write`, can cancel a `pending` Job. Finished Jobs are immutable and are kept for 90 days. Until scheduling exists, `hapi jobs purge` removes them.
- **Job lifecycle:** `pending → succeeded | failed | expired | cancelled`. A Job may carry an optional `not_before`. `expires_at` defaults to 1 h after `not_before` (or after creation), and an expired Job is never delivered. A result is `{status, error?, response?}`, where `response` holds the script's response variables. The first result wins, and a later one gets `409`. Any Household member, or any Bot with `smart_home:write`, can cancel a `pending` Job. Finished Jobs are immutable and are kept for 90 days. `hapi jobs sweep`, a CronJob every 15 min (ADR-0012), removes them and marks pending Jobs past `expires_at` as `expired`; until it does, reads derive `expired` from `expires_at`.
- **hAPI checks only the shape of a Job, not what it does.** Script names must match `hapi_[a-z0-9_]+`, and variables are capped at 16 KB. hAPI keeps no catalogue of HA scripts. HA rejects unknown scripts, which comes back as a failed result.
- **HA-side configuration** is a reference package in this repo (`integrations/home-assistant/hapi_jobs.yaml`: rest sensor, automation, rest_command), copied into HA by hand. The `hapi_*` scripts themselves live in a separate HA configuration repo.
- **hAPI records HA's last poll**, so a stalled bridge can be detected. Turning that into an alert is part of observability.
+21
View File
@@ -0,0 +1,21 @@
# Scheduled work runs as CronJobs of the hAPI image, as a tokenless `scheduler` Bot
hAPI's recurring work is a small set of **Kubernetes CronJobs that run `hapi <subcommand>`** from the same digest-pinned image as the app, delivered the same way as the migrate Job (ADR-0007). There is no worker Deployment, no in-process scheduler and no task queue. Most domain logic is computed on read (Finance summaries, Maintenance due dates, Fitness bests), so little has to run on a timer. A CronJob keeps nothing running between runs, gets retries and `concurrencyPolicy: Forbid` from Kubernetes, and is a CLI command the Owner can also run by hand.
## Considered Options
- **A worker Deployment with an in-process scheduler** (APScheduler, arq). Rejected: it runs all the time, holds its own pool of up to 10 connections from ADR-0004's budget, and needs leader election before it can have more than one replica.
- **Scheduling inside the API pods.** Rejected: with 2 replicas every task needs an advisory lock, and the work competes with requests for the event loop.
- **A transactional outbox of domain events** (e.g. "Reading recorded"), drained by a CronJob. Rejected for v1. The state already in the database is the event: a scheduled check compares it with what has already been notified, at the cost of up to one interval of latency. A generic event model can arrive once something needs sub-minute reactions.
- **FastAPI `BackgroundTasks` after commit.** Rejected: the work is lost if the pod dies.
- **Running as `hapi_migrator`**, which bypasses RLS as the table owner. Rejected: it would put migrator credentials in a recurring pod.
- **Giving the scheduler Bindings to Personal data.** Rejected: every Person would have to consent, and v1's per-Person work is read-only anyway.
## Consequences
- **v1 inventory:** `hapi jobs sweep` every 15 min marks pending Jobs past `expires_at` as `expired` and deletes finished Jobs older than 90 days (replacing ADR-0006's `hapi jobs purge`). Reads derive `expired` from `expires_at` until the sweep catches up, so correctness never depends on how often it runs. The notification checks are CronJobs running `hapi notify <check>`; what they check is decided with ntfy delivery. Purging a removed Person's data stays an on-demand Owner CLI command, and Finance month rollover, Banked carry-forward and `date_review` need no schedule.
- **Principal:** work on Household data runs as a built-in **`scheduler` Bot**. A migration creates it, it can never hold a Token (so it can't be reached from the API), and the Owner gives it Household grants like any other Bot. Recorded by shows `scheduler`. Work on Personal data runs once per Person with `hapi.principal_id` set to that Person (ADR-0004), and is **read-only**: a scheduled write to Personal data needs a new decision.
- **Event-triggered work** (e.g. a new Reading making a Task due) is picked up by the next scheduled check. Checks write **durable Notifications**, which double as the record of what was already notified. A Notification not yet delivered stays pending and is retried on the next run, so an ntfy outage loses nothing, and a future frontend inbox reads the same records.
- **Connection budget (amends ADR-0004):** each housekeeping CronJob uses a pool of 1 with no overflow and `concurrencyPolicy: Forbid`. The rule becomes: app pods including surge × 10 + concurrently runnable CronJobs × 1 + ~6 ≤ 46.
- **Monitoring:** one generic vmalert rule fires when any CronJob hasn't succeeded within twice its interval (kube-state-metrics' `kube_cronjob_status_last_successful_time`). ADR-0009's Watchdog covers vmalert itself. Kuma push monitors are kept for jobs whose silence must be caught even when the whole cluster is down: the importer (ADR-0011) and backups.
- **Time:** the Household timezone is one setting in `deploy/`, fed both to the app config and to `spec.timeZone` on calendar-based CronJobs (daily checks, month-end). Interval jobs like the sweep ignore it.