# API and reporting contract

All data endpoints require workspace authorization. Read/control bearer tokens
are distinct from ingest-only service credentials. Cookie writes require the
exact public Origin; sessions are revocable, HttpOnly, Secure on HTTPS and
expire after twelve hours. Password login requires TOTP, rejects reuse of an
accepted step, and locks an account for fifteen minutes after ten failures.
The edge also limits login attempts by client address.

## Acceptance

`POST /api/v1/ingest/batches`, with `Authorization: Bearer <service token>`:

```json
{
  "batch_id": "019ee1a0-0000-7000-8000-000000000001",
  "service_id": "019ee1a0-0000-7000-8000-000000000002",
  "events": [{
    "occurrence_id": "019ee1a0-0000-7000-8000-000000000003",
    "timestamp": "2026-09-07T00:00:00Z",
    "environment": "production",
    "severity": "error",
    "message": "Database operation failed",
    "code": "APP.PERSIST.FAILED",
    "cause_discriminator": "connection",
    "outcome": "failed",
    "operation": "invoice.persist",
    "exception_chain": [{"kind": "database", "message": "connection unavailable"}],
    "correlation_ids": ["request-123"],
    "attributes": {"region": "east"}
  }]
}
```

Success returns `receipt_id`, `new_events` and `duplicates`, after synchronous
PostgreSQL commit. Identical batch retries return the original receipt/counts.
Rebatching uses new batch IDs and original occurrence IDs. The global identity
ledger guarantees deduplication for ninety days from first acceptance. A
different canonical event or batch under an existing identity is a `409`.
Retry uncertain responses with unchanged identities and content.

The wire crate defines the complete DTO. Severity is `debug`, `info`, `warning`,
`error` or `fatal`; outcomes are `rejected`, `retrying`, `recovered` and `failed`.
Error/fatal events qualify for attention except the first three
outcomes. Optional code, fingerprint, stack, release, causal chain, breadcrumbs,
attributes and correlation IDs enrich evidence without becoming required.

Limits: 100 events, 1 MiB JSON request on both the wire and after decoding,
64 KiB per event, 32 attributes, depth four and 32 breadcrumbs. Plain JSON and
`Content-Encoding: gzip` are supported; discover support in the public catalog.
Unsupported encodings return `415 UNSUPPORTED_ENCODING`. Decode concurrency,
body-read time, and expanded bytes are bounded; a request is admitted only
after authentication and after its workspace has a free share, so one
workspace cannot hold the decoders or the database pool against the others. Credentials are checked before the body is validated: a missing or
revoked credential is `401`, a credential for another service is `403`.
Invalid batches fail atomically with `422 INVALID_BATCH` and field errors;
request overflow returns `413`; the per-second rate, or more than two
concurrent collection requests from one workspace, returns `429 RATE_LIMITED`
with `Retry-After: 1`; the daily allowance returns `429 QUOTA_REACHED` with
`Retry-After: 60`; unavailable storage returns `503` with `Retry-After: 5`.
The workspace default is one million events/2 GiB per UTC day, 200
events/second and 100/service/second. Identity conflicts and duplicates do not
consume accepted-event allowances.

Configured field-name redaction is case insensitive and happens before payload,
title, grouping rationale or policy selection is persisted. Configure safe
attribute names; structural wire fields cannot be selected for redaction.
Producers must still exclude credentials and unsafe provider diagnostics.

Grouping applies producer fingerprint, a matching server rule, code plus cause,
normalized exception/stack, then conservative message normalization. The final
pilot algorithm is version 2 and uses length-prefixed identity components to
avoid delimiter collisions. Existing version-1 groups and accepted decisions
remain explainable; new acceptance uses version 2. Each occurrence retains the
method, basis and applicable rule version. Rule edits affect future acceptance.

## Investigation

Every endpoint answers with the same error shape, including malformed JSON or
query strings (`422 INVALID_BATCH`, field `body` or `query`). A missing,
expired or revoked session/token is `401 AUTH_REQUIRED`; an authenticated
principal without the required role is `403 PERMISSION_DENIED`. A request that
references a record outside its workspace, an unknown project or an
out-of-range value is `422 INVALID_REQUEST` and must not be retried.

- `GET /api/v1/workspaces`: authorized workspaces and role.
- `GET /api/v1/workspaces/{workspace}/investigation`: portfolio, groups,
  navigation, hourly histogram, evidence, attention, usage and replay health.
- `/groups` and `/occurrences` under the workspace expose the same paginated
  filters. Parameters: `project`, `service`, `group`, `occurrence`, `environment`,
  `code` (prefix), `severity`, `release` (exact), `correlation`, `text`, `since`, `until`, `page`,
  `view=all|attention`. Pages contain up to fifty displayed items plus one
  lookahead row; page numbers are bounded at 200.
- `GET /api/v1/workspaces/{workspace}/services/{service}/occurrences/{id}`:
  one retained occurrence or explicit expired/unknown evidence state.
- `GET /api/v1/workspaces/{workspace}/policies`: policy and delivery state.
- `GET /api/v1/workspaces/{workspace}/receipts/{receipt}`: retained receipt,
  processing, suppression, and notification stages. `sent` means SMTP accepted.
- `GET /api/v1/workspaces/{workspace}/checks` and `/checks/{check}`: expected
  signals and retained history. See the [checks contract](https://www.logmast.com/docs/checks/).

Evidence expires according to the workspace's retained coverage on reads,
independently of cleanup; the trial defaults to fourteen days. Increasing
retention never restores evidence that previously expired. Minimal
group identities remain so old links are explainable. Counts combine complete
hour rollups and exact partial-hour evidence, including pending historical
receipts. Viewing does not acknowledge anything. Group details include a
`representative_occurrence`, defined as
the first still-retained occurrence independently of the displayed page, and
the group's first/last receipt times. The UI exposes latest, representative and
individually selected evidence. Query execution is bounded at
five seconds, with five simultaneous evidence reads and 8 MiB work_mem per
PostgreSQL query operation. Text search is literal substring matching.
Exact correlation lookup uses a workspace-scoped identity index. A query that
exceeds its time budget returns `422 QUERY_LIMIT` with a request to narrow the
time range or service. Broad substring searches can reach that limit on a full
retention window; the supported common-query target is not an unbounded search
guarantee.

## Control

`POST /api/v1/workspaces/{workspace}/control` accepts the closed tagged commands
in `crates/logmast/src/policy.rs`. Members manage projects/services, credentials,
grouping/notification rules, mutes and attention. Owners additionally manage
membership and collection limits; viewers cannot mutate. The `check` action
configures service/environment heartbeats, job completions, and application-owned
verification results. Update, pause/resume, and archive require a current revision.
Control tokens can be
read-only and have explicit expiry/revocation.

Rule scope can select project, service, group (mutes), environment, code prefix,
severity, producer fingerprint and up to eight exact scalar attribute values.
First submit `{"action":"preview","scope":{...}}`, then pass its `id` as
`preview_id` with a matching scope. Previews belong to their actor and expire
after fifteen minutes; they read evidence without holding the workspace
acceptance lock. Group mutes can be applied directly. Disabling a rule or
ending a mute that is already inactive is `409`. Rule decisions are captured
at acceptance; later changes affect future events.

First qualifying occurrence and ten occurrences in five minutes are the pilot
alert conditions. Rearming requires five continuous minutes below threshold;
cooldown is fifteen minutes per group. Nineteen regular emails plus one overflow
summary fit the twenty-email workspace/hour budget. Mutes advance alert state
and record suppression without releasing a backlog at expiry. Acknowledgment
affects one attention item; later conditions can create new items.
Creation and SMTP dispatch both enforce the current UTC-hour budget, including
retries and old queued notifications. Nineteen regular attempts reserve the
twentieth for overflow; blocked deliveries wait until the next hour. SMTP
failure retries retain the same Message-ID (`<notification id>@<sender
domain>`) and stop after eight attempts or twenty-four hours. A stored
recipient that cannot form an address exhausts only that notification.
Automatic email contains condition metadata and protected links, without copied
event messages, codes, stacks, or attributes. Checks share this notification
budget and existing broad service/environment rules. Their accepted check-ins
use a separate included allowance; error-event exhaustion does not consume it.

## Rust producer

Depend on `logmast-reporting` and install its layer in each executable alongside
the normal tracing subscriber. `Config::from_env()` is opt-in. The endpoint is
the full ingestion URL; token, service ID and environment are required when it
is set. HTTPS is required except for loopback demonstrations.

`report_error` walks a typed error's safe Display/source chain;
`report_safe_failure` records a selected classification and safe cause instead
of traversing raw provider text. Only `logmast::report` tracing events export.
Ordinary logs, panic-hook output and exporter diagnostics remain local.

`supervise_task` owns one safe report for an unexpected Tokio JoinError and
does not export the panic payload. Do not report its returned error again.
Await intentional shutdown aborts directly, outside that failure boundary.

The in-memory queue holds at most 1,024 events/16 MiB, including in-flight work.
Flushes occur at 100 events, 512 KiB or one second. Retries use jitter, bounded
backoff and a fifteen-minute lifetime. Permanent rejects are isolated and valid
events rebatch with their original occurrence IDs. Counters distinguish
delivered, invalid, overflow, retry-expired and shutdown-dropped events.
The SDK discovers gzip support once, compresses bodies of at least 1 KiB when
smaller, and prepares the transport body once per batch. Unsupported or unknown
servers use plain JSON; a `415` response falls back with unchanged identities.
Delivery requires a successful HTTP status and a valid acceptance body with
a non-nil receipt ID and `new_events + duplicates` matching the batch size.
Acceptance and validation-error response reads are capped at 16 KiB, including
chunked responses. Invalid acknowledgments retry the unchanged batch under the
same bounded policy; an HTTP success status alone does not establish delivery.
Await the guard's shutdown for a ten-second drain. Abrupt process termination
can lose queued evidence; the producer does not promise disk durability.

Check-ins are not queued. `CheckIns::new(&config)` derives the check-in URL
from the same ingest endpoint and credential. `send(&CheckInReport)` returns the
receipt, or a typed error once its 30-second budget is spent:

- `Rejected` carries the stable code of a permanent 4xx rejection.
- `Unacknowledged` covers exhausted retries on transport errors, 408, 429 and
  5xx responses, and acknowledgments without a valid receipt.

Each report is built once and resent byte-for-byte, so a retry after a committed
write deduplicates instead of conflicting. `stable_run_id(check_id, key)`
derives a deterministic run ID from the application's own durable run key, so
a report retried after a restart keeps its identity. `applied = false` stores
the result without advancing the check's state, and never establishes liveness.
