15 Complete the application lifecycle
In a fresh example directory, generate and source .env, then run: Revision0001 creates the original jobs table. Revision0002 adds operation and creation-time columns, persistent credentials, users, counters and budget reservations.
Files: advanced.py, operator_cli.py, migrations/, tests/test_v3.py, tests/test_extended.py. These additions turn several earlier design exercises into executable examples. They remain a teaching service with deliberately bounded scope.
Initialize through migrations
In a fresh example directory, generate and source .env, then run:
Revision0001 creates the original jobs table. Revision0002 adds operation and creation-time columns, persistent credentials, users, counters and budget reservations. The migration registers every model before comparing metadata. A fresh-process regression test catches missing registration that an already-imported test process could hide.
For an existing v2 database, first take and restore a backup and compare its actual schema to revision0001. Stop API writers and workers during this teaching migration. Only if the schema really matches, mark that existing schema with alembic stamp 0001, then upgrade. Stamping does not create or repair tables. The new fingerprint includes operation type, so the migration recomputes existing fingerprints in bounded batches. Existing rows receive the migration timestamp because their original creation times were not stored; their age before migration is unknown. New jobs use their real enqueue time.
The migration is not a zero-downtime promise. On large tables, measure locks and runtime in staging and design a separate expand/backfill/contract release. Destructive downgrade is disabled. Roll forward when possible; restore into a separate database when necessary. Reverting application code does not reverse a schema change.
Separate schema ownership from runtime privileges
Compose runs migrations as lab_owner. The API and worker use lab_app, which receives SELECT, INSERT, UPDATE and DELETE on application tables, plus schema usage. It does not receive schema creation. Default privileges cover newly created tables owned by the migration identity. The native PostgreSQL drill verifies a runtime CREATE TABLE is rejected.
This is database-role separation, not row-level security. The application enforces tenant ownership in queries. A stolen runtime database credential can access application rows directly; protect it as a high-value secret and use network isolation. Stronger separation may require per-service roles, RLS and dedicated tenant databases, each with migration and pool behavior tests.
Human login and service credentials
Create a lab user through a local operator terminal:
The password prompt avoids placing the password in command history. Passwords must be at least16 characters; a random salt and scrypt-derived hash are stored. POST /auth/login accepts username/password and issues a15-minute bearer session with jobs:read and jobs:write. Login attempts have a database-backed per-source-IP rate limit. Disable a user with operator_cli.py disable-user learner; every later session request checks that the account is enabled. Existing sessions then fail immediately.
This is a worked API login, not a complete consumer identity product. There is no email verification, self-service recovery, MFA, account federation or browser cookie flow. Use a managed identity provider for those requirements and test issuer, audience, expiry, scopes, logout and account disable. Never retrofit a browser by putting long-lived admin tokens in local storage.
The initial generated machine token lasts30 days and has admin scope within one tenant. Admin may POST /credentials with a subset of scopes and a60–86400 second lifetime, then DELETE /credentials/{id} to revoke it. Only a SHA-256 digest of the high-entropy token is stored. Copy a newly issued secret directly into a protected store; it is returned only at issuance. SHA-256 is appropriate here because tokens are random, not human-chosen passwords.
Rotation means issue, install, verify, revoke old, and verify denial. Revocation persists in the database; restarting the API does not restore access. Seeding the same token does not extend its life or un-revoke it. Use an explicitly authorized recovery procedure if every admin credential expires.
Shared quotas, schedules and webhooks
Each authenticated tenant gets120 requests per minute by default, coordinated in the database across API instances. Each tenant may admit1000 distinct jobs per UTC day. A duplicate with identical input returns the original job without consuming another admission. Fixed windows allow bursts near boundaries; this is not a sophisticated fair scheduler or edge DDoS defense.
operator_cli.py tick learner hourly --period 3600 computes an integer time slot and uses a deterministic schedule key. Two scheduler processes submitting the same slot produce one job. This example skips missed slots; it does not silently backfill hours of work after an outage. Document catch-up, timezone, daylight-saving and overlap policy before scheduling real business work. Use UTC for stored event times.
The demo webhook signs the exact body bytes using HMAC-SHA256 over timestamp, a full stop, then body. It accepts timestamps within five minutes and uses event_id for duplicate detection. WEBHOOK_SECRET and WEBHOOK_TENANT are fixed server configuration. A valid signature cannot choose another tenant. Provider integrations must follow that provider's signature format, key rotation and timestamp rules; this custom format is a teaching protocol.
The job row is the durable inbox for this narrow webhook: verification and persistence complete before 202. There is no separate downstream delivery step to lose. If you add external event publication, use a transactional outbox and a separate dispatcher. Never mark a webhook processed before the durable work is committed.
Cancellation, retries and retention
POST /jobs/{id}/cancel changes an owned queued job to cancelled. It does not interrupt a running handler. A claim token fences database completion, and an expired lease permits recovery. The worker tries at most three times. The default pure analyzer is safe to repeat; remote side effects need their own deduplication protocol.
The model adapter has a10-second total call deadline inside the30-second lease. Every attempt reserves one model-call unit. No generic arbitrary command executor is exposed. A third-party response that exceeds32768 bytes or fails the summary schema is rejected. Transport cancellation can stop local waiting but cannot prove a remote provider stopped processing.
Run operator_cli.py maintain --days 90 as a scheduled, reviewed operation only after agreeing retention. It deletes old terminal jobs and expired counters/credentials. Active jobs are preserved. Job retention also defines how long an idempotency key remains remembered; clients must not replay older events as if deduplication were permanent. Backups may retain older data under a separate policy. Purging records is a data operation, not a harmless health check.
Acceptance criteria
Tests cover weak-token rejection, expired/disabled identity behavior, cross-tenant access, scope escalation denial, shared quotas, webhook modification and replay, queued cancellation, concurrent budget reservation and migration data preservation. Add real load, password-recovery, account lifecycle and incident drills for your target before serving customers. Document the identities that can access the database, backup keys, CI secrets and production host.