Skip to content

feat(api): count days and missing_by deadlines in an IANA time zone - #34

Merged
angela-helios merged 41 commits into
HeliosSoftware:mainfrom
Gordex2014:feat/time-zones
Nov 24, 2026
Merged

angela-helios merged 41 commits into
HeliosSoftware:mainfrom
Gordex2014:feat/time-zones

Conversation

@Gordex2014

Copy link
Copy Markdown
Contributor

Stacked on #33. This branch has #33 (which contains #32 and the PRs below it) merged into it, so until those land the diff against main also shows their work. This PR's own change is git diff e22d0fa (#33's head): src/zone.rs, Cargo.toml (jiff), the day windows, /stats, /failures and monitoring counts in src/api.rs, missing_by in src/alerts.rs and src/pipeline.rs, the rule's tz in src/db.rs, tests/alerts.rs, tests/events.rs, tests/rule_alerts.rs, RELEASING.md and the matching parts of docs/.

What changes

Daily figures and missing_by deadlines can be counted in an IANA time zone instead of UTC.

  • tz on the daily answers.
    • GET /api/sources/{id}/stats?tz=Europe/Madrid and GET /api/sources/{id}/failures?tz=... count their days in that zone. A day runs from local midnight to the next local midnight. UTC is the default.
    • The answer's tz names the zone used, as the database spells it (europe/madrid echoes Europe/Madrid), and every day row names its day, today included. /stats gains today.day.
    • A name that is not a zone answers 400 {"error": "tz must be an IANA time zone name, such as Europe/Madrid or UTC", "code": "invalid_query", "field": "tz"}. The query is read before the source is looked up, on both routes. /failures now does that for days too, so a bad days on an unknown source answers 400 rather than 404.
    • The rolling 24 hours (last_24h on /failures, and the monitoring status) take no zone.
  • Daylight saving time and other offset changes.
    • A local time that a change skips stands for the first valid instant after it, the change itself. A time that happens twice stands for its first occurrence.
    • A day with a change keeps its length on the clock (23 or 25 hours in most zones), and a date a zone skipped is an empty day.
    • Days are computed in the store's SQL from boundaries the engine works out, exact to the millisecond on SQLite and PostgreSQL.
  • missing_by rules take an optional tz.
    • Both the time and "today" are the zone's. A rule without one, or with "tz": null, stays in UTC. A tz on any other condition, or an unknown zone, answers 400.
    • When a skipped time pushes a deadline onto the next local midnight, the rule checks it as that day begins, against the day it belongs to, once. A file of the new day does not hide that the day before had none. A rule made after that midnight does not judge the day before.
    • Changing a rule's tz ends its open alert, as feat(monitoring): report the FHIR server's reachability, with an idle probe #33 does for a change of threshold. An alert is written only while the rule still has the zone the pass read.
  • Zone rules come from the IANA database built into the engine (jiff with jiff-tzdb, 2026f today), never the host's, so every instance counts the same days. RELEASING.md adds cargo update -p jiff-tzdb before a release.
  • Failing beside rejected. failing counts rejected rows except those a transform filtered out on purpose (rejected as filtered).
    • It is on /stats (today.failing, by_day[].failing) and on the monitoring status (last_24h.failing, each source's failing_last_24h). Each pair is counted in one statement, so failing never exceeds rejected.
    • A source is listed under needs_you for failing rows only. The reason keeps its sentence, "N records rejected in the last 24 hours", with N counting failing rows.
  • Docs: docs/api.md (the rows, "Days and time zones", the failures section, invalid_query), docs/sources.md (missing_by with tz), docs/decisions.md (decision 44; decision 22 amended in place; a dated note on decision 43).

In plain words

A team that works in Madrid or New York can now ask for its numbers by its own days, and the answer says which zone it used and which day each row is. A deadline such as "the file is in by 06:00" can be set in local time, so it stays at 06:00 when the clocks change. Rows that a transform drops on purpose no longer make a source look broken.

Side effects checked

  • Without tz the answers are unchanged apart from the new fields (tz, today.day, failing, failing_last_24h). One exception: on /stats, today's figures now stop at the end of today, so a row with a time after the end of the day (another instance's clock) no longer counts as today.
  • needs_you no longer lists a source whose only rejected rows in the last 24 hours were filtered on purpose.
  • Store. One new column, alert_rules.tz, added on start to older stores. It is in the table definition too, so feat(events): event log of record attempts and outcomes, with retention #28's SQLite rebuild of alert_rules keeps it. An older engine on a store with zoned rules evaluates them in UTC, and an older engine that edits such a rule leaves its zone in place.
  • Library types. Rule gains tz, which breaks struct literals outside the crate. Db::day is removed. Alerter::check_missing_by, Db::received_between, Db::rule_alert_alive_since and the zone module are new.
  • Dependencies. jiff 1.0.1 without default features (std, tzdb-bundle-always). It carries its own copy of the zone database in the binary.

How to verify

The CI commands, with CI=true and default parallelism, on this tree (Linux):

$ helios-ci-gate      # fmt, clippy (both feature sets), Python tests, cargo test, the no-backend tests
test: passed (520 tests, 0 failures; Python transform tests OK)

The changed suites ran again on SQLite with no failure. Against a throwaway PostgreSQL 17 (HIE_TEST_DATABASE_URL=postgres://...), run twice:

$ cargo test --no-fail-fast --lib --test alerts --test api --test events --test rule_alerts --test destination
every listed integration suite passed
lib 174 passed, 2 failed: secrets::key::tests::a_key_file_removed_after_start_asks_for_a_restart and
a_socket_at_the_key_path_is_refused, the same two that fail on PostgreSQL before this change.
  • Zones (src/zone.rs): New York's 23- and 25-hour days in 2026, with 02:00, 02:30 and 03:00 on the spring day all at 07:00Z and 01:30 on the autumn day at its first occurrence. Santiago and Havana, whose changes fall at midnight. St. John's in 2009, Monrovia's 1972 offset, Apia's skipped 2011-12-30, and Vancouver from 2026-11. Kolkata, Kathmandu and UTC. The SQL day index is checked against every boundary of a 250-day window in the store.
  • API (src/api.rs, tests/alerts.rs, tests/events.rs): local days on both DST changes, today ending at the next local midnight, a zone without DST, the UTC default, the echo, case, an Etc/GMT%2B5 zone, unknown zones on known and unknown sources, and filtered rows that are not failing.
  • Rules (src/alerts.rs, tests/alerts.rs, tests/rule_alerts.rs): a rule firing and clearing in UTC and in a zone, a deadline pushed onto the next midnight (Nuuk, 2026-03-28 23:30), a next-day file that does not hide a missed day, a rule made after the pushed deadline, a change of zone ending the alert and a stale pass raising nothing, and an older store's rules reading back as UTC.

Links

Closes #25

GET /api/alerts takes since (alerts created at or after an RFC 3339
instant) and cursor (the previous page's next_cursor), keeping source,
open and limit. Pages are a keyset on the alert id, newest first, and
next_cursor is null exactly when nothing more matches. A malformed query
answers 400 invalid_query. Decision 39.
… query checked

limit=0 no longer reads the store; a row without an id is an error rather
than a silent end of the walk; /api/alert-rules checks limit and open as
before. The docs say a late or cleared alert is found by a new walk and
that a page after a cursor can be empty.
The cursor is a1.<id>, so a client cannot take an alert id for one and a
later form can be told apart. The docs state the limit=0 exception and
when an error names its field; tests cover an empty page after a cursor
and the rules list's type checks.
POST /api/sources/{id}/check-now now records a check and answers its
check_id; GET /api/checks/{id} answers pending, found (with the loads),
nothing_new or failed (with a fixed reason), with requested/finished
times. A check is answered by the first scan that starts after it, with
the source's loads since it was asked for. Decision 41.
Every change of an alert, fired and cleared, is now an event with a
random event_id, written with its exact body in the same transaction as
the alert (table alert_webhooks). A sender task per instance posts
waiting events oldest first, signs them with HMAC-SHA256 over the raw
body when alerts.webhook_secret (or HIE_ALERT_WEBHOOK_SECRET) is set,
and retries a failed attempt up to five times with exponential backoff
(alerts.webhook_backoff_ms, 10 s by default). Attempts are claimed with
one conditional update and their outcome is fenced by the attempt
number, so several instances on one store never send one attempt twice.
Redirects are not followed. An event belongs to the URL configured when
it was written and waits for it.

GET /api/alerts shows each alert's latest delivery (event, state,
attempts, last_error, last_status, delivered_at) and whether this
instance has a webhook configured and signed.

The webhook body changes: {event_id, event, alert, source, text}
replaces {text, feed, kind, alert_id, notify, cleared}. A clear is now
posted only when the alert's rule asked for the webhook. alerts: refuses
unknown keys, and its errors never quote the URL or the secret.

Decision 40.
The baseline is taken in the check's own INSERT; a delete fails the
source's waiting checks first, in one statement guarded by the lease,
and answers store_busy rather than strand them; a pause lifted while a
pass reads the checks leaves them to the next pass. Index files by
(feed_id, id) for the baseline and range reads.
- hie check no longer echoes values from a malformed alerts: block:
  YAML errors pointing into it are reported without the parser's words,
  and an unknown key is named only when it looks like a key.
- A blank webhook secret is refused on the library path too.
- A failed COMMIT of an alert and its event is rolled back.
- Tests: the PostgreSQL schema outlives the engines a test drops; the
  fence is tested while the newer attempt runs; timeout category; the
  API's pending and parked states; no URL, secret or fingerprint in the
  API answer; two more hie check canaries.
- Docs: ordering holds per URL; last_error, last_status, pending and
  failed spelled out; backoff bounds.
A runner stopped while it read the waiting checks drops them, so a
check asked for after a replace is answered with the new definition.
Docs: when a pass reads its checks, and the delete and index costs.
Tests wait for the live check's answer and release the delete case's
lease instead of letting it lapse.
An append-only events table, written in the same transaction as the change
it reports, through one insert path (on PostgreSQL under an advisory lock
keyed by schema, so ids commit in order). Every outcome is a guarded update
on the status it leaves and the record's revision, bumped when a person puts
a record back, so an outcome for a superseded revision changes nothing.
Admission, finishing a load, Retry and reprocess, REST batch outcomes, bulk
opening, settling and refusal each run in one transaction with their events.

GET /api/events lists the log oldest first by id, with source, kind, since,
cursor and limit; every unreadable parameter is a 400 invalid_query naming
its field.

retention.history (30d by default) purges events and stored alerts at start
and hourly; open alerts the engine tracks and the newest alert are kept, and
purged alerts still count in hie_alerts_total. safe_reason now keeps
brackets and parentheses inside a URL, and bulk texts replace the
submission token by value.
- hie.yaml parse errors leave out every quoted value while the file
  holds the webhook URL or secret: YAML can carry a value into an error
  from anywhere (quoted or explicit keys, aliases). The runtime check no
  longer reports a parse error of its own.
- HIE_ALERT_WEBHOOK_URL is refused under its own name.
- PostgreSQL schema set-up runs in one transaction under an advisory
  lock, so instances upgrading one store together all start.
- The webhook client speaks HTTP/1.1 only.
- A claimed attempt clears last_status until it is answered.
- Tests: concurrent claims on two connections, last_status while an
  attempt runs, five more hie check canaries.
- Docs: which clears are posted (the channels recorded when the alert
  fired; rules turned off or deleted leave their alert open).
- A hie.yaml that is not valid YAML is refused again (a repeated
  runtime: key no longer slips past the check), with quoted values left
  out of the error.
- Quoted values are left out of a typed parse error when the decoded
  file gives alerts: any value, rather than when the text names a key:
  escaped keys are caught, and a blank template keeps full errors.
- PostgreSQL: added columns are altered one at a time and only when
  missing, outside the locked schema transaction, so start-up cannot
  deadlock with a query joining those tables.
- The concurrent-claim test cannot hang when its set-up fails.
Failure reasons name a request target only by its origin, or <URL> for a
relative one, and cleanup errors replace the submission token by value.
Settling locks the open submission first, as a refusal does. A source-object
submission opens only if each file claims exactly what its manifest counted,
and REST outcomes are also guarded by the attempt count selected. Admission
takes a per-source lock on PostgreSQL and looks the content up again. The
alert purge checks its predicate again on the row it deletes. Large set
writes keep only ids and write their events a chunk at a time. A transform
that cannot finish now is logged once per record and reason per runner.
GET /api/events refuses unknown parameters and signed limits.
… probe

GET /api/monitoring/status gains destination: {reachable, since,
last_error, consecutive_failures, observed_at}, from every request a
delivery sends under the base URL and from an anonymous GET /metadata
once nothing has reached the server for destination.probe_seconds (60 by
default, 0 off). last_error is one of a few fixed sentences, never a URL.

Recovery now clears every open delivery alert of the source, with a rule
or without, instead of raising a delivery_recovered alert next to an
outage alert that never cleared; start-up closes the ones earlier
versions left open. REST delivery errors name the FHIR server instead of
its URL.

Closes HeliosSoftware#24
… cannot be reached

A request's start instant is taken while the destination's lock is held,
so a probe always gives way to a delivery that registered after it. Each
change of state logs the failure with its whole error chain, and REST
transient reasons carry that chain too. Every server-error status gets
its own sentence. Start-up also closes an old rule-less outage alert when
a record of its source was delivered after it. Tests cover a connection
closed before the answer, the status request and a status page on the
server's own origin, and the webhook around a recovery.
Set updates page by id and check their guard again on each row, so a record
changed meanwhile is left alone and each chunk is a seek, on two new indexes
made after the added columns. A relative target echoed with a query keeps
its path only. A transform-phase failure is remembered as logged only once
its event is stored. A since finer than a millisecond starts at the next
one. A zip entry found taken after it was staged does not reuse its name.
`GET /api/sources/{id}/stats` takes `tz` and counts its days from local
midnight to the next, echoing the zone it used (`UTC` without one). A
`missing_by` rule takes an optional `tz` for its time of day and its
"today"; rules without one stay in UTC.

A local time skipped by a DST change stands for the change itself, a
repeated one for its first occurrence, and 23- and 25-hour days keep
their length. Zone rules come from the IANA database built into the
engine (jiff-tzdb), never the host's. An unknown zone answers 400 with
a fixed sentence (`invalid_query`, `field: tz`, on the stats query).

"Received today" for a rule and the `today` figures are bounded on both
sides, and a deadline pushed onto the next midnight by a DST gap is
checked as that day begins. Amends decision 22; adds decision 44.

Closes HeliosSoftware#25
…nd logs

A REST delivery that cannot reach the server stores the destination's
fixed sentence as its reason; the log gets the errors under the request
error, never the request error's own text, which carries the URL. A
request is built before it counts as one sent to the server, so one that
cannot be built does not hold back the probe. Start-up compares an old
outage alert with the source's newest record only, found through the
index. Tests keep their seeding store open, so they also run on
PostgreSQL, and check the webhook's alert ids and the probe's query.
GET /api/loads lists the loads of every source, newest first, with the
fields of the per-source list, narrowed by source and by status or to the
loads failing now (unreadable, or with a rejected row, also while in
progress). A page of up to 200 loads, its counts and whether more follow
come from one statement, behind an opaque cursor on the load id.

Every load answer gains failed and source_name, the name the source had
when the load was recorded, so a deleted source's loads stay identifiable.
New indexes let each page be chosen through an index, with one seek per
failed load on a partial index of rejected rows.
…y, once

A file of the next day no longer hides that the day before's never came, and an alert of the rule open at that deadline covers it. A date a zone skipped misses no deadline. An unknown tz is refused before the source is looked up. Tests tie the echoed zone to the dates the route returns; the docs give day lengths as the clock's.
A source name with a NUL, which a PostgreSQL text value cannot hold, is no
longer kept with its loads instead of failing every load of that source;
a source query with a control character is refused as invalid_query.
The docs now say what a source created again under a deleted id takes
over exactly (pending rows keep the earlier transform's resources, the
silence rule counts from the earlier loads, read-only sources skip by
name and size, zip entries), which empty parameters count as absent, and
what a failed scan raises. Tests walk failed pages one load at a time
across unreadable loads and loads with many rejected rows.
A new source on a deleted source's id sends waiting rows as they are by
REST or transformed bulk, but hands over the load's file on the
source-object path. The docs also list every alert a failed scan may be
followed by, qualify the read-only skip by name and size to non-empty
files, and require a UTF8 PostgreSQL store.
… send before clearing

The deadline pushed onto midnight is computed apart from today's, so a pass after today's deadline still checks the day before; an alert raised for it is cleared on the next pass, never in the one that sent it. Stats echo today's day beside the zone. Wording: a change of offset, such as daylight saving time; day lengths as on the clock.
safe_reason cuts any word with a ? followed later by = (a query), and
leaves questions alone. A submission's progress and failure writes hold only
at the attempt count read before the request, and the outage alert follows
only a write that changed it. Each file is finished in its own transaction
and its alerts weighed right after. An open alert is kept by an enabled rule
only if the rule is older than it. A since is rounded up from the digits of
its text. PostgreSQL builds the schema under a session lock, and SQLite gets
no index that its rowid already gives.
A row its transform turns into no resources is rejected as filtered and
still counts in rejected, but a load whose only rejected rows are
filtered is not failed: failed now means unreadable, or a row rejected
for any other reason. The partial indexes hold only those failing rows.
GET /api/sources/{id}/failures counts the distinct records a source
rejected over the last 24 hours and each of the last days (UTC, from one
day_windows function), filtered rows apart, with each window's coverage:
from when this store began recording events (store_meta.events_since, set
once) and within the retention. An index on events(source_id, kind, at)
serves it.

A SQLite alert_rules made before is rebuilt once with AUTOINCREMENT, with the
same rows and ids and its sequence past every rule id in use, so no rule id
is given again; every rule answer carries created_at, never taken from a
request body.
reject_submission, settle_page and settle_submission take the attempt count
read before the poll and require it, with the open status, on the
submission row they lock first. An answer to an older poll (a newer one
failed meanwhile) changes nothing: no record, no event, no archive. A
settlement that finds the count moved stops after the pages it applied.
…ince-cursor

# Conflicts:
#	docs/api.md
#	docs/decisions.md
#	docs/development.md
#	src/api.rs
#	tests/alerts.rs
failing counts the rejected rows that make a load fail, every rejected
row but the filtered ones, beside rejected, so a list's failure count
agrees with failed: a load whose only rejections are filtered shows
failing 0.
…t/alert-webhook-delivery

# Conflicts:
#	docs/api.md
#	docs/decisions.md
#	docs/development.md
#	src/api.rs
#	src/config.rs
#	src/db.rs
#	src/lib.rs
#	tests/alerts.rs
Checks join the retention purge (retention.history) with events and
alerts, and GET /api/checks/{id} reads its parameters as /api/events
does: an opaque cursor, and 400 invalid_query naming the field.
…se nothing

Rows a transform filters out on purpose are rejected as filtered and are not failures. Stats (per local day and today) and the monitoring status (last_24h and each source's failing_last_24h) gain failing beside rejected, which keeps its meaning, and needs_you lists a source for its failing rows only, with the same sentence.
…ate pause

purge_checks locks the rows it chooses, so on PostgreSQL a purge that
waited for another moves on to the next old checks instead of stopping
with some left. A pause that lands while a pass loads its credential
fails the checks it read and ends the pass. Docs name /api/checks among
the invalid_query routes and the duplicates a read-only source skips.
Loads record the source's name through the store calls that now take
files in (admit_file, insert_duplicate, insert_container), the paging
module is the landed one, /api/loads joins the routes that answer
invalid_query, and decision 42 follows 38 to 41.
The four indexes the loads list reads are built each in a transaction of
its own after the schema, so a long build over records never holds files
while another instance's Retry waits on both. The docs add the events,
failure figures and pending checks a reused id takes over, count the
four indexes in the upgrade note, and say how /api/loads refuses a
query. The test of a name a store cannot hold covers every way a file
is taken in.
Conflicts resolved: the alert clear keeps the webhook's `cleared` event
and clears by id, so recovery clears every open delivery alert of a
source through it; the bulk submitter keeps the origin-only base in its
reasons; the store keeps both sides' functions; the outage test checks
the cleared alert and the event log together; the docs keep both
sections. The destination tests follow the store's new signatures and
the webhook's new body.
A start ran the schema's indexes, and the two added with the event log,
each batch in one transaction. CREATE INDEX IF NOT EXISTS takes a SHARE
lock on its table even when the index exists, so a start that waited
for a running instance's write to one table held the others meanwhile,
and could deadlock with that write during a rolling start. The tables
and their added columns now come first, then every index on its own, as
the loads indexes already were. A PostgreSQL test holds each indexed
table in an open write, starts a second handle, then takes every other
table: it deadlocked before and passes now.
Turning a rule off, deleting it, or changing its condition, threshold
or source clears the rule's open alerts when the API makes the change,
through the same clear as every other, so each writes its cleared event
for the channels recorded when it fired. A changed rule that still
finds the condition raises a new alert with its own id. A change of
recipients or channels alone clears nothing. Each source's pass also
clears an open alert whose rule is gone, off, or watches another
condition or source, which catches one raised by a pass that read the
rule just before the change.
Review round 3. A rule turned off, deleted or changed through the API
clears its open alerts in the transaction that changes it, so a failed
clear cannot leave them behind a committed change, and an alert raised
under the changed rule is not cleared by it. An alert of a rule is
written only while the rule is on and has the condition, threshold and
source the pass read; on PostgreSQL the rule's row stays locked to the
alert's commit. The per-pass sweep goes: a start clears what earlier
versions left, a rule whose id was given again included.

The reconciliation of delivery alerts left by earlier versions runs
once per store, so a rolling start cannot close an outage alert this
version raised without its cleared event, and it counts any record of
the source delivered after the alert. Retention keeps an open outage
alert without a rule. The PostgreSQL start test checks which lock the
start waits for. Docs say when a changed rule raises again, what a
start still locks, and that bulk reasons keep the server's origin.
Brings the event log, the alert webhook, loads across sources and the
destination's reachability under the time zone work:

- /api/sources/{id}/failures takes tz: its days are local days of the
  zone, each named, and the answer echoes the zone. An unknown zone is
  refused as on /stats, before the source is looked up.
- A change of a rule's tz ends its open alert, and an alert is written
  only while the rule still has the zone the pass read.
- tz is in the rules table's schema, so the SQLite rebuild that stops
  rule ids being reused keeps it.
…failing with rejected

- An alert that a change, turning off or deletion of its rule ended no
  longer stands for the day it was raised for: the rule as changed judges
  that day itself. A rule made after a pushed deadline does not judge the
  day before it.
- The monitoring status counts rejected and failing rows in one statement,
  so failing never exceeds rejected.
- The failures test keeps clear of a midnight; the failures example and
  decisions 43 and 44 say what the code does.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Accept a time zone for daily aggregates and missing_by rules

2 participants