wycliffRotich-dev/aethergrid
حول
Open-source distributed AI workload orchestration. Schedule jobs across distributed workers, coordinate execution through time-bound leases, enforce tenant isolation, and recover reliably from worker failures and stale state.
الأنظمة والبنية التحتيةالنمو المقاس للنجوم
- خلال 24 ساعة
- ٠
- خلال 7 أيام
- ٠
- خلال 15 يومًا
- جارٍ جمع السجل
- خلال شهر
- جارٍ جمع السجل
تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.
README.md
الأصل
AetherGrid is the control plane for AI workloads. It places work on the compute you already own, and it keeps one rule under failure: a job has one owner at a time, held through a time-bound lease.
AetherGrid takes workloads, matches them against available compute nodes by resource requirements and constraints, and manages the full lifecycle: queued, scheduled, running, completed, failed, retried and cancelled. It is built for teams that run AI under audit, where a job that runs twice, a tenant that reads another tenant's data, or an upgrade that loses a row is an incident and not a bug.
- Exclusive ownership. A job runs under a time-bound lease. A release or an outcome report is checked against the identity of the lease the caller holds, so a stale owner cannot end a job it no longer owns (ADR 0034, ADR 0036).
- Tenant isolation. Every tenant-owned record carries a tenant. On Postgres, the database refuses a row without one, and reads of keys, nodes, jobs, workers and events are scoped to the caller's tenant (ADR 0064, ADR 0075).
- Least privilege. Every route except the root and the two health probes requires an API key, including the one that issues keys. Powers that widen reach, such as setting a job command, need an explicit scope (ADR 0054).
- Upgrades that are rehearsed. The upgrade rehearsal seeds the previous release, upgrades it to the new one, and compares the rows, the schema, the API start and the stored job command (ADR 0085 to ADR 0089).
- A decision record you can audit. Every non-obvious decision is an ADR that states what was decided, why, and what is not claimed.
Click the diagram to open it full-size.
Live demo: a public, read-only demo is being built and is not online yet (ADR 0094). Follow progress at .
Why AetherGrid
AI workloads are expensive, long-running and shared. When a node drops, a network splits or a worker restarts, the questions are always the same: who owns this job, did it run twice, and can the next release be trusted with production data.
AetherGrid answers them with rules the system enforces, not habits teams have to remember. A job has one owner at a time. A tenant sees only its own work. A key carries only the powers it was issued with. An upgrade is rehearsed on seeded data from the previous release before it ships.
For platform and infrastructure teams, one cluster serves several teams or customers, each inside its own tenant, and the cluster recovers from node and worker failures on its own. For the people who sign off on risk, every guarantee is written down, tied to the decision that created it, and checked by tests that run in CI.
Engineering Decision Records
ADR index (click to open)
Few ADRs Worth Skimming
Every non-obvious decision in this codebase, why a domain rule lives where it does, why an obvious-looking shortcut was rejected, what broke and how it got fixed, is written down at the moment it was made, not reconstructed afterward for a portfolio. The ADRs live in . A few worth reading directly if you want to see the reasoning, not just the conclusion:
- ADR 0007 - Reconciliation Loop: how the system detects and repairs state left inconsistent by dead workers and expired leases, instead of assuming the happy path is the only path.
- ADR 0011 - Job Reclaim and Reconciliation Repair: closing a real race condition where a dying worker's lease renewal could land after reconciliation had already started reassigning its work.
- ADR 0012 - Real Job Execution: building genuine subprocess execution with enforced timeouts, then deliberately keeping it unreachable from the public API until the system had authentication, and proving that absence with a test rather than a comment.
- ADR 0014 - Continuous Lease Renewal: why a lease is renewed continuously for a job's entire runtime instead of once at acquisition.
- ADR 0015 - API Key Authentication: opaque server-issued tokens were chosen over JWTs because the system needs instant revocation. ADR 0020 limits reading a job's command to the worker assigned that job.
- ADR 0018 - Domain Owns Scheduling Policy: why
list_available()moved out of the repository entirely, since deciding which nodes are eligible for scheduling is a business rule, not a persistence concern, and letting infrastructure decide that would have made scheduling behavior dependent on which database backend was running. - ADR 0019 - Standalone Worker Agent Process: replacing in-process job execution with a real out-of-process agent that confirms its own execution start over the network, and why pull-based polling was chosen over push delivery, since it reuses reconciliation this codebase already trusts instead of introducing new failure and delivery-guarantee logic.
- ADR 0029 - Cancel a Running Job by Reusing Lease Renewal: extending an existing, already-trusted channel (lease renewal) to deliver cancellation to a running job's subprocess, instead of adding a second polling mechanism, and introducing an explicit CANCELLING status so a job caught mid-cancellation is a visible, real state rather than indistinguishable from one still running.
- ADR 0030 - Idempotent Worker Registration Per Node: keying worker identity to node identity so an agent restarting reclaims its existing worker instead of leaving a permanently dead row behind, using the same recovery path reconciliation already trusts, closing a gap before fleet-scale restart churn could ever expose it.
- ADR 0031 - Reclaim a Job Abandoned Mid-Cancellation: finalizing a job as CANCELLED, with no retry consumed, when its worker dies before confirming a cancellation already in progress, instead of leaving it stranded in CANCELLING forever or silently retrying a stop nobody asked to undo.
- ADR 0032 - Move Cluster Tick Execution Off the Event Loop: running the cluster tick on a worker thread via asyncio.to_thread once real, caller-controlled commands could run for an unbounded duration, so one long-running job can no longer stall every other request the server would otherwise serve.
- ADR 0033 - Persist a Job's RUNNING Transition Immediately After worker.start(): closing a gap independently rediscovered twice, WorkerRepository.save() only ever writes the workers table, so a job's own row silently stayed SCHEDULED for its entire real execution unless something separately persisted it, extracting a single shared function instead of patching the second occurrence in isolation.
- ADR 0034 - Fence Lease Release by Lease Identity, Not Just Worker Identity: closing a gap one level upstream of what ADR 0014 had already named and deferred, releasing a lease checked only that a worker held some lease, not that it was the same one the caller had been renewing, letting a stale caller delete a different, legitimately-held lease out from under whoever actually owned it, verified with a test that proved the unsafe delete happening before any fix landed.
- ADR 0035 - Delete a Job's Lease Before Reclaiming It in RecoverOfflineNodeService: the third independent occurrence of the same shape in one session, a sibling service (RecoverExpiredLeaseService) already had the correct pattern, and this one hadn't inherited it, silently stranding every job recovered from an offline node since its stale lease was never deleted, verified with a test that proved the strand before any fix landed.
- ADR 0036 - Fence Standalone-Agent Outcome Reports by Lease Identity: closing the one limitation ADR 0034 named rather than claimed to cover, the external HTTP contract a standalone agent uses to report a job's outcome carried no lease identity at all, so a stale report could never be distinguished from a current one.
lease_idis now a required field, captured by the agent at poll time before execution starts and checked against whatever lease is actually current for the worker, not looked up internally where it could never disagree with itself. - ADR 0037 - Verify Lease Fencing Against a Real, Reconstructing Repository: ADR 0034 and ADR 0036's lease-fencing logic had only ever been proven against
InMemoryLeaseRepository, which shares object references on read, the same class of gap that produced a false-negative repro attempt during ADR 0033's own development before that bug was proven against SQLite instead. Adds a test reproducing the full lease-theft scenario, acquire, reconcile-reclaim, legitimate reassignment, stale release attempt, againstPostgresLeaseRepository, with each step run through its own independently constructed repository instance so a shared in-memory reference can't mask the behavior under test. - ADR 0038 - Fence Lease Renewal by Lease Identity, Not Just Worker Identity: the third and final lease-mutating operation to close this gap, after release (ADR 0034) and outcome reporting (ADR 0036).
RenewLeaseServiceresolved the current lease by worker_id alone and renewed whatever it found, with no check that the caller's belief about which lease it held still matched reality. Unlike release, a mismatch here is silent rather than destructive: a stale caller renews the wrong lease with no error, potentially masking a real reconciliation failure. Closes both the internal WorkerExecutionLoop path and the externalPOST /workers/{worker_id}/lease/renewcontract in the same change, since renewal is the standalone agent's repeated heartbeat mechanism, not a one-time terminal call like release. - ADR 0039 - Fully Reclaim an Abandoned Job on Worker Re-registration: ADR 0030 accepted, at the time, that reclaiming a worker on agent restart would silently discard its abandoned job, calling that a mirror of reconciliation's own recovery behavior. That mirror stopped being accurate the moment reconciliation was fixed to always release a node's resources and delete a stale lease before recovering a worker, a pairing worker re-registration never inherited. Left alone, this wasn't only a resource leak: since lease acquisition fences by job identity, not worker identity, and a recovered worker goes idle immediately, it could be reassigned a new job before the old one's lease expired, and that old lease's eventual expiry would then corrupt the new job's tracking instead. Fixed by reusing reconciliation's exact reclaim sequence, lease deletion, resource release, job reclaim, before recovering the worker, verified the same way as the gap it closed: a test proving the corruption before any fix landed.
- ADR 0040 - Shared useAsyncResource Hook Closes a Stale-Response Race Present in Seven Hooks: seven frontend hooks each independently reimplemented fetch, error, and loading handling, none of them guarding against a response resolving after a newer fetch had already started, a real race for any hook whose fetch depends on an id or that polls. Closed by extracting one shared hook where refresh() and the automatic fetch share the exact same guarded effect run, rather than two implementations that could quietly drift apart.
- ADR 0041 - Recover a Worker from OFFLINE on Heartbeat, Only When It Holds No Job: an idle worker whose heartbeat lapsed had no path back to IDLE at all, every existing recovery route was triggered exclusively by job-recovery services that never fire for a worker with no job to reclaim, observed live when a dashboard tab's heartbeat keeper went idle overnight. Fixed narrowly: heartbeat recovers status only when the worker holds no running job, since an OFFLINE worker still holding one may already be mid-reassignment by reconciliation, the same shape of race ADR 0034, ADR 0036, and ADR 0038 closed for lease identity, one layer up here at the worker level.
- ADR 0042 - Heartbeat OFFLINE Workers Too, So ADR 0041's Recovery Path Is Actually Reachable: ADR 0041's OFFLINE-to-IDLE recovery was unreachable from the dashboard's own heartbeat keeper, which filtered OFFLINE workers out of every heartbeat cycle on reasoning that predated ADR 0041 and was never revisited once it landed. Observed live: a worker went OFFLINE from ordinary job-cancellation activity rather than a stale timeout, and was then permanently excluded from recovery until the page was reloaded. Fixed by heartbeating every worker regardless of status; this is safe by construction, since ADR 0041 already restricts recovery to workers holding no running job, so heartbeating an OFFLINE worker that still holds one has no effect.
- ADR 0043 - Multi-Dimensional Best-Fit Scheduling, Not CPU-Only:
select_node()broke ties among sufficient nodes using CPU remainder alone, with memory and VRAM playing no role once a node passed the sufficiency check, the wrong dimension to optimize in isolation for a scheduler built around AI workloads where VRAM is frequently the actual binding constraint. The existing best-fit test scaled all three resource dimensions proportionally, so it could never have caught this. Fixed by scoring each candidate on normalized tightness, summed across only the dimensions a job actually requests a nonzero amount of, so a job needing no VRAM is never steered by VRAM it will never touch, and a CPU-only job reduces to the exact comparison that existed before. - ADR 0044 - Agent Retries Transient Failures With Capped Backoff and Jitter: the standalone agent was meant to run unattended but treated most failures as fatal, so one 429, 5xx, or timeout during registration, polling, or outcome reporting killed it, and after a control plane restart every agent failed and came back in lockstep. Worse, lease renewal treated any error as a lost lease, discarding the result of a job that had finished successfully. Fixed by classifying failures: transient ones retry without limit under capped exponential backoff with full jitter that honors Retry-After, a 404 on the poll re-registers, and renewal retries inside a trust window measured from the last confirmed renewal, keeping its only-409-means-lost contract. Verified by stopping the real API, starting an agent, and restarting the API: the agent retried through seven failures and registered on its own.
- ADR 0045 - Fleet Agents Use One API Key Per Agent, Not a Shared Key: ADR 0044 fixed the agent's own failure handling but named a problem retries cannot fix: rate limiting is per API key, and a shared key across a fleet of agents caps out at roughly 14 concurrent agents before throttling begins. The mechanism to fix this already existed and required no code changes: issue one API key per agent instead of one shared key, since the rate limiter already buckets independently per key. Fixed by documenting per-agent key issuance as the intended pattern in scripts/issue_api_key.py's usage and run_agent.py's docstring, removing the ceiling by using what was already there correctly.
- ADR 0046 - Health Endpoint Bypasses the Repository Pattern for a Fast, Explicit Timeout: routing
/healththroughNodeRepository.list()meant a health check inherited the shared pool's 30-second default connection timeout, since neitherdatabase.pynordependencies.pyoverrides it, defeating the purpose of a signal meant to report bad news fast. Fixed by giving/healthits own accessor to the rawConnectionPooland an explicit 2-second timeout onpool.connection(), a deliberate, narrow exception to the repository boundary rather than a precedent. A ~28.86s anomaly observed once during testing was later confirmed, not just observed: the official Postgres image's two-phase startup letspg_isreadyreport healthy against a temporaryinitdbinstance before the real instance is up, and the pool's first connection attempts landed in that gap, triggeringpsycopg_pool's own retry/backoff. Fixed by blockinglifespan()onpool.wait(timeout=30.0)before the app reports itself started, so no request, including Docker's own healthcheck, can reach the app before its dependency is confirmed reachable. Verified by reproducing the same cold-start gap under debug-level pool logging:Application startup completenow logs only after Postgres's real instance is ready. - ADR 0047 - Resilient Client Architecture for Government API Integration: AetherGrid is expected to integrate with a government-operated API for an upcoming pilot, but its endpoint, auth mechanism, and rate limits are not yet known, and government infrastructure is known for unpredictable downtime with no on-call engineer to reach on the other side. Fixed by building
GovAPIClientwith exponential backoff and jitter on transient failures, a circuit breaker (closed, open, half-open) that fails fast during sustained downtime instead of retrying indefinitely, and auth-agnostic configuration supporting mTLS and OAuth2 client-credentials so real credentials can be dropped in later without a code change. Verified by a 7-test suite using respx to mock every failure mode in isolation: transient recovery, retry exhaustion, non-retryable client errors, all three circuit breaker transitions, and OAuth2 token acquisition and caching, since no real sandbox exists yet to test against directly. - ADR 0048 - Generalize GovAPIClient into ResilientAPIClient for Reuse Beyond One Integration: ADR 0047 built a retry, circuit breaker, and auth-agnostic client for a possible pilot integration, but nothing about its actual design was specific to that one counterparty, only its name and folder were. Fixed by renaming GovAPIClient to ResilientAPIClient before any other integration came to depend on it, while the rename was still a pure rename with no call sites to migrate, and rewording its docstrings to describe the general problem rather than one specific third party. ADR 0047 is left unchanged as the historical record of what was actually known and decided at the time; this entry is the follow-up explaining what changed and why, the same pattern ADR 0042 used for ADR 0041.
- ADR 0049 - Resilient Client Replays Only Requests That Are Safe to Replay: the resilient client retried every HTTP method, so when a response was lost after the server had already acted, a retried POST repeated its side effect and the caller saw a clean success. A characterization test made this concrete: a payment applied twice with no error anywhere. Fixed by deciding per request whether a replay can repeat a side effect: idempotent methods and requests that provably never reached the server are retried as before, a 429 is always retried since the server declined it, and a POST or PATCH that hit a 5xx or a read timeout is not replayed unless the caller supplies an idempotency key. Failures that leave the outcome unknown say so through an
outcome_unknownflag, so callers reconcile instead of guessing. Verified over real HTTP against a mock partner that applies its side effect before losing the response: a POST without a key charges exactly once, a POST with a key is retried and still charges exactly once, and re-introducing the old behavior fails five tests. - ADR 0050 - Split Liveness From Readiness, and Move Reconciliation Off the Event Loop: ADR 0032 left
ReconciliationLoop.execute()running directly on the event loop, reasoning that its work was bounded and fast by construction. That held only while the database was reachable. A stopped database sent it into the connection pool's 30 second default timeout, freezing every request the server handled, including ones with no database dependency at all, once per tick for the duration of any outage. It also meant the container healthcheck saw the app as unhealthy during an outage, turning a database blip into a restart loop under any orchestrator that acts on that. Fixed by moving reconciliation to a worker thread, the same pattern ADR 0032 already used for the cluster tick, and by adding/livez, a dependency free liveness probe the healthcheck now polls instead of the database aware/health. Verified against a stopped Postgres container over a 130 second window: worst case latency on an unrelated endpoint dropped from ~29s to 0.124s, and the container stayed reported healthy throughout. - ADR 0051 - Bound the Shared Connection Pool's Timeout: every Postgres repository in the application shared one
ConnectionPoolconstructed with no explicittimeout, silently inheritingpsycopg_pool's 30 second default. ADR 0046 had already special-cased/healtharound this, and ADR 0050 threaded reconciliation off the event loop, but neither addressed the pool's own default, so any call during an outage, reconciliation included, still blocked a worker thread for up to 30 seconds, the concrete mechanism behind the thread-pool exhaustion risk flagged as a follow-up to ADR 0050. Fixed by passingtimeout=5.0explicitly at construction, an order of magnitude below the library default while giving real traffic more patience than/health's 2 second, fail-fast value. Verified in isolation against a non-routable address (30.36s unbounded versus 5.0s bounded) and against a real outage, where a reconciliation failure that previously logged "after 30.00 sec" now logs "after 5.00 sec", reproduced twice in one outage window. Narrows but does not eliminate thread-pool exhaustion under sustained outages; closed as issue #261. - ADR 0052 - Fence Reconciliation's Lease Delete by Expiry at Delete Time: RecoverExpiredLeaseService reclaimed a job based on a stale snapshot read: it checked whether a lease was expired once, against a list() call taken at the top of its loop, then deleted that lease unconditionally later in the same pass. A worker's background renewal thread renewing the lease in between meant a legitimately-owned, no-longer-expired lease could still be deleted and its job reclaimed out from under its current owner, the same class of bug ADR 0034 fenced for ReleaseLeaseService, but never covered for reconciliation's own delete. Fixed by adding LeaseRepository.delete_if_expired(), a conditional delete that re-checks expiry atomically at the moment of deletion rather than trusting an earlier read, on both backends, and wiring RecoverExpiredLeaseService to skip reclaiming a job entirely when the lease survives that check. Verified with new contract tests on both the in-memory and Postgres repositories, plus a service-level test that simulates the exact race by renewing a lease between construction and execute(). RecoverOfflineNodeService was not touched and is explicitly flagged as an open question, not assumed safe.
- ADR 0053 - Fence Offline-Node Lease Delete by Lease Validity: node heartbeat and lease renewal turned out to be structurally independent signals, confirmed by tracing both WorkerExecutionLoop (lease renewal on its own dedicated thread, no heartbeat call at all) and the standalone agent (heartbeat and renewal on two separate threads, a heartbeat failure never propagated to the renewal thread). RecoverOfflineNodeService never looked up a job's lease at all, reclaiming any job on an offline node's worker unconditionally, so a node could go offline on one missed heartbeat while that worker's lease kept renewing successfully, and its job would still be reclaimed out from under it, the same class of race ADR 0052 fixed elsewhere but explicitly left open here pending evidence. Fixed by checking the job's lease before reclaiming: no lease or an actually expired one proceeds as before, using the same delete_if_expired() from ADR 0052; a still valid lease is left entirely untouched. Verified with a test that constructs exactly that scenario, an offline node with a worker holding a still-valid lease, and asserts the job survives unreclaimed. Closes issue #267.
- ADR 0054 - Scope API Keys, and Require jobs:execute to Set Job.command:
ApiKeycarries ascopesset drawn from a closed vocabulary, empty by default, and settingcommandrequiresjobs:execute. The check usesis Noneand not truthiness, so an empty list cannot pass as unset. Scopes are granted only throughscripts/issue_api_key.py, never over HTTP, andPOST /jobsis the only path that can set a command. Verified by mutation: removing the check, switching to a truthiness gate, dropping scopes in the service, and dropping them in the Postgressave()each fail the tests written to catch them. - ADR 0055 - Scope API Key Issuance and Revocation:
POST /api-keysandPOST /api-keys/{id}/revokerequire thekeys:managescope, and a key without it receives a 403 that names the missing scope. A pureauthorize_key_managementfunction makes the check, mirroring thejobs:executegate, and no unscoped path is left, since issuing and revoking are the whole surface of that router.scripts/issue_api_key.pyneeded no change, because its--scopeflag already validates against the shared scope registry. Which keys a caller may revoke is decided in ADR 0056. - ADR 0056 - Allow a Key to Revoke Keys It Issued, Without keys:manage: ADR 0055 closed the path where any key could issue or revoke any other key, but left
keys:manageas a flat, all-or-nothing scope: a key that only needs to clean up sub-keys it issued itself had no narrower option than the same broad scope an operator uses to administer the whole fleet, a gap ADR 0055 named directly in its own Follow-ups.ApiKeynow carriesissued_by, set once at issuance to the authenticated caller that requested it,Nonefor every key issued before this column existed or issued byscripts/issue_api_key.py's bootstrap path. A key may now revoke a key it issued without holdingkeys:manage, whilekeys:manageremains a full override reaching any key regardless of ownership. The authorization decision for revocation moved from the route intoRevokeApiKeyService, the one deliberate departure from this codebase's convention that the gate lives at the route, because deciding ownership requires the target'sissued_by, a fact that does not exist until the target is loaded, and no route in this codebase holds its own repository access. The decision itself stays a pure domain function,authorize_key_revocation; only which layer calls it changed. - ADR 0057 - List the Keys a Key Has Issued: ADR 0056 let a key revoke the keys it issued without holding
keys:manage, but gave no way to see which keys that was. The ownership relationship was enforceable but not visible: an operator or an owning key could not ask what a given key had created short of a direct database query, a gap ADR 0056 named in its own Follow-ups.GET /api-keys/{id}/issuednow returns every key whoseissued_byequals the id in the path, revoked keys included so the list is the full issuance history. Authorization mirrors ADR 0056's revocation shape: a caller holdingkeys:managemay list any key's issued keys, and a caller may list its own with no scope at all, since viewing is a strictly smaller right than revoking. The decision is a pure domain function,authorize_key_view, and the service loads the requested issuer before authorizing, the same not-found-before-authorization orderingRevokeApiKeyServiceuses, so a caller without rights over an id learns only whether it exists. The response never includeskey_hashorissued_by. The repository gainedlist_issued_by, backed by a newidx_api_keys_issued_byindex. Results are capped at 100 rather than paginated, with no truncation indicator in the response, a limit the ADR records as acceptable for now and lists as a follow-up. - ADR 0058 - Harden the Container Defaults and Keep Credentials Out of the Repository: the image ran as root, compose hardcoded the Postgres password and published both ports on every host interface, and a shell-form
CMDleft/bin/shas PID 1, sodocker stopsent SIGTERM to a shell that never forwarded it, waited out the full 10 second grace period, and SIGKILLed the app before its lifespan teardown could close the database pool. Fixed by running as a numeric non-root user, requiringPOSTGRES_PASSWORDfrom a gitignored.envand refusing to start without it, binding both ports to 127.0.0.1, pinning the Postgres image by digest, and usingexecso uvicorn is PID 1. The test suite gained a guard that refuses any database whose name does not end in_test, since the presentation fixtures runTRUNCATE ... CASCADE. Verified by measurement:docker stopwent from 10.5s to 0.9s with the full shutdown sequence in the logs, compose fails with a message naming the missing variable, and the Postgres tests fail immediately and readably when the test URL is unset. A read-only root filesystem, dropped capabilities and secrets files are recorded as follow-ups, not applied. - ADR 0059 - Run the App Container Read-Only With No Capabilities: ADR 0058 moved the app to a non-root user but left its filesystem writable and Docker's default capability set available to anything that gained privileges, and listed the tighter settings as a follow-up it had not tested. The
neuromeshservice now runs withread_only: true,cap_drop: [ALL]andno-new-privileges. No tmpfs was added, becausedocker diffon the running container listed no written paths after startup and after exercising the API, so there was nothing to give a writable mount. Verified by measurement:docker inspectreports all three settings, a write under/appfails with "Read-only file system", PID 1's effective and permitted capabilities are all zeros, node, job and worker creation, reads and key revocation succeeded, and the logs held no filesystem errors. The SQLite default backend started under the same restrictions with its database file owned by uid 10001. A row insert through the API on SQLite, a root-owned bind mount, and the same restrictions on Postgres are recorded as follow-ups, not claimed. - ADR 0060 - Enforce Container Hardening in CI and Keep Pins Fresh: ADR 0058 and ADR 0059 hardened the container, but every property was verified by hand, so a later change could undo one unnoticed, and the pinned digests and action versions would go stale silently. A separate workflow now starts the compose stack with a generated password on every push and pull request and fails if the app stops running as uid 10001 with no effective capabilities, loses its read-only root,
CapDrop=[ALL]orno-new-privileges, writes to its own filesystem, or stops shutting down gracefully within 3 seconds. Runners are pinned toubuntu-24.04, and Dependabot covers the docker, docker-compose, github-actions, pip and npm ecosystems, with Python and Postgres majors ignored on purpose. Two frontend majors are held back after they broke the build:typescript7 failsnpm ciagainsttypescript-eslint's peer range, andtailwindcss4 failsvite buildbecause its PostCSS plugin moved to a separate package. Verified by failure, not only by passing: a throwaway branch that removedexecmade the job fail on the stop-timing step withdocker stop took 10207 ms, after every earlier step passed. Only that one of the six assertions has been shown to fail so far, and the e2e job is skipped on Dependabot pull requests by design, both recorded as follow-ups. - ADR 0061 - Prove the Hardening Checks Can Fail: ADR 0060 added a workflow that asserts the container hardening properties, but a check that has only ever passed has not been shown to catch anything, and only the shutdown timing had been seen to fail. Each property was removed on its own throwaway branch, one per branch because the job stops at the first failing step, and the workflow was dispatched on it: dropping
execfailed the stop-timing step at 10207 ms, droppingUSERfailed the uid step withapp runs as uid 0, and removingread_only,cap_droporno-new-privilegeseach failed the inspect step with its own message. MakingPOSTGRES_PASSWORDoptional failed the first custom step in under a second. One observation worth keeping: withcap_dropremoved the uid and capability check still passed, because a non-root process holds no effective capabilities regardless, so the inspect check is what catches it. Six of the seven checked properties have now been shown to fail on a deliberate break. The seventh, thedocker diffwrite check, was verified only at the level of the command it runs, not as a red workflow step, and that gap is recorded as a follow-up. - ADR 0062 - Status of the Hardening Follow-ups: ADR 0058 to ADR 0061 each ended with follow-ups, and later ADRs restated earlier ones, so the same item could read as open in one place and done in practice. This ADR is the single record of which is which, and it opens nothing of its own. Resolved, with the pull request or run that resolved each: the read-only root and dropped capabilities (#282), the CI job asserting them (#283), a refresh process for the pinned digests through Dependabot (#285), Python 3.12 in the test matrix (#302), a SQLite write and a root-owned bind mount for
/data(#301), and the Node.js 20 notice onactions/checkout(#289). All seven hardening checks have now failed the real workflow on a deliberate break, and the gate also goes red on thepull_requesttrigger, which supersedes the "six of seven" count in ADR 0061. Three items remain open and stay in the ADR that names them, linked and not re-listed: the secrets file for the database password, the same restrictions on Postgres, and running the e2e job on frontend dependency updates. - ADR 0063 - Close the Remaining Hardening Follow-ups: ADR 0062 left three items open, and all three are now done. The e2e job runs on pull requests that touch
frontend/orci.yml, with both directions shown on real pull requests: it ran on the pull request that editedci.ymland was skipped on one that touched onlydocker-compose.yml(#304). The Postgres service runs read-only with every capability dropped except the four its entrypoint needs, measured against the pinned image, one error at a time (#305). One result worth keeping:DAC_READ_SEARCHlooked removable on a fresh volume and was not on a copy of real data, so a fresh-volume test alone would have shipped a service that failed on an existing database. The database password is a Docker secret and no longer an environment variable or part of any URL: Postgres readsPOSTGRES_PASSWORD_FILE, the application readsNEUROMESH_DATABASE_PASSWORD_FILE, and a password in both places is a startup error (#306). Checked on the running stack: no password in either container's environment or indocker compose config, and the suite passed with the password only in the file. A clean clone following only the README also found a real fault, a restrictive umask makingschema.sqlunreadable to the container, fixed in #308. It opens no follow-ups of its own. - ADR 0064 - Isolate Resources by Tenant: Accepted. Every tenant-owned record carries a tenant: keys, nodes, jobs, workers, leases and events. The tenant comes from the credential and never from the request, repository methods either take a required tenant or are named
_across_tenantsfor system actors such as the scheduler, another tenant's resource answers exactly like a missing one, the scheduler never places a job on another tenant's node, and composite foreign keys make Postgres refuse cross-tenant links. The enforcement test of its point 10 is on main: a registry test classifies every route as tenant-scoped or exempt, two-tenant tests cover the scoped routes, and migration tests start from a pre-tenancy database. A rule test holds the key, event, job, lease, node and worker repositories to the tenant rule. No release carries migration 0005 yet, so a database on the released v0.6.0 can still hold a worker or lease with no tenant (see ADR 0075). The SQLite backends keep workers and leases in memory, so the composite keys exist on Postgres only. The boundary is application and database enforcement inside one shared database, not separate infrastructure, and it does not defend against compromised database credentials. - ADR 0065 - Scope the API Key Repository by Tenant: the first tenancy change gave every key a tenant, but the key routes still looked keys up across tenants, so a caller in one tenant could revoke or list a key in another. Revoke, list-issued and authentication now go through a repository whose methods either take a required tenant or are named
_across_tenants, and a key in another tenant answers exactly like a missing one. The tenant filter runs before any scope check, so a caller never gets a 403 for a key that exists. Review of the first change found two real gaps: the Postgres upsert and the in-memory save both matched on id alone, so saving an object with another tenant's key id could change that key. Both are fixed, and a save that would touch another tenant's key now raises instead of being ignored. The unusedlist_activewas removed instead of renamed, since a fleet-wide read with no caller is what the_across_tenantsname is meant to rule out. A test reads the parameter types of the repository and fails on any method that is neither scoped nor named_across_tenants. Verified by removing the Postgres upsert guard, the in-memory lookup filter and the_across_tenantsname on the credential lookup in turn, each failing the tests written for it. Only the API key repository was scoped when this change merged, and ADR 0064 was still Proposed. That was true when this change merged. ADR 0064 is now Accepted, and AetherGrid on main is multi-tenant as it defines it. - ADR 0066 - Give Nodes a Tenant: the second tenancy change after keys. Nodes now carry a required tenant taken from the authenticated key, the nodes table gains a tenant column that assigns existing rows to the default tenant on upgrade, and saving a node never moves it or changes another tenant's node. Reading nodes by tenant followed in ADR 0067 and giving jobs a tenant in ADR 0068, and AetherGrid was still not multi-tenant at that point. That was true when this change merged. ADR 0064 is now Accepted, and AetherGrid on main is multi-tenant as it defines it.
- ADR 0067 - Scope Node Reads by Tenant: the third tenancy change. Node get, list and delete require a tenant and apply it inside the query, system actors use named across-tenants reads that a test allowlists by caller, the node and cluster routes pass the authenticated key's tenant, and registering a worker on another tenant's node answers 404. Workers, leases and events are not scoped yet, and jobs followed in ADR 0068, so AetherGrid was still not multi-tenant at that point. That was true when this change merged. ADR 0064 is now Accepted, and AetherGrid on main is multi-tenant as it defines it.
- ADR 0068 - Give Jobs a Tenant and Scope Job Reads: the fourth tenancy change. Jobs carry a required tenant taken from the authenticated key, the jobs table gains a tenant column that assigns existing rows to the default tenant on upgrade, a save never moves a job or changes another tenant's job, and job reads, cancel, retry and history are scoped by tenant, with another tenant's job answering like a missing one. Keeping a job on its own tenant's nodes followed in ADR 0069, and workers, leases and events are not scoped yet, so AetherGrid was still not multi-tenant at that point. That was true when this change merged. ADR 0064 is now Accepted, and AetherGrid on main is multi-tenant as it defines it.
- ADR 0069 - Keep a Job on Its Own Tenant's Nodes: the fifth tenancy change. The domain Scheduler only considers nodes in the job's tenant, checked before fit, and a composite foreign key makes the database refuse a job assigned to another tenant's node. Both are covered by tests, including through the scheduler loop. Workers, leases and events are not scoped yet, so AetherGrid was still not multi-tenant at that point. That was true when this change merged. ADR 0064 is now Accepted, and AetherGrid on main is multi-tenant as it defines it.
- ADR 0070 - Persist a Job's Execution Timeout: a job's execution timeout drives the real subprocess timeout, but no repository stored it, so a job loaded from storage always got the one hour default. The jobs table gains a nullable column of float seconds in Postgres and SQLite, NULL means the domain default, and the worker repository's own copy of the job mapper reads it too, since the worker API serves a running job through it. No test read a running job back through the worker repository before this. Nothing sets a non-default timeout yet: the create job request has no such field, so every job created through the API still gets one hour.
- ADR 0071 - Apply Schema Changes with Versioned Migrations:
schema.sqlreached a Postgres database only when the compose init mount ran on a new data volume, so a database that already existed never received a schema change. Schema changes are now numbered SQL migrations applied by a small runner on psycopg, with aschema_migrationstable that keeps a checksum per file, an advisory lock so two runners cannot overlap, and a one-shotmigrateservice in compose that the application waits for. The compose init mount is gone, CI and the README use the runner, and migration 0001 is the no-transaction marker followed byschema.sql, byte for byte, which a test enforces. Run against a real volume built by the old init script, which held rows and was behind the code, the baseline brought it up to date in place with every row count unchanged, and a second run applied nothing. The runner first refused a database that was ahead of the image, which would have blocked a rollback of the code; it now accepts it and applies nothing. SQLite is unchanged. The ADR adds before it removes by convention, and nothing enforces that, so a migration that removes or renames something can still break a rolled-back image. The startup check is ADR 0072. - ADR 0072 - Check the Schema Version When the Application Starts: the only protection against a database that is behind the code was the start order in compose, which does not cover a database restored from an older backup or a deployment that does not use the compose file. The application now checks the schema after the pool is ready and before the cluster loop starts. It only reads and never creates
schema_migrations. A database that is behind, a missing table, a hole in the history, a missing file below the highest version and a changed checksum each stop startup with a message that names what is wrong, and a database that is ahead of the image starts and logs one warning. Nothing runs under SQLite or memory. Verified through compose on the real image: a database with its history emptied stopped the container with exit code 3, a cold start came up healthy, and a database with an extra recorded version started and logged the warning. The first version read rows by position and failed 26 tests with KeyError, because the Postgres repositories setdict_rowon pooled connections and nothing resets it. The check now asks for tuple rows on its own cursor. A reset callback on the pool was tried and removed after it failed 16 tests, and the cause was not found, so the fix went into the repositories instead: all 25 assignments across 7 files are gone, each repository asks for dict rows on its own cursor, and a test fails if code underapp/infrastructuresets the row factory on a pooled connection again. - ADR 0073 - Scope Worker Routes by the Tenant of the Worker's Node: Accepted. ADR 0064 says a resource in another tenant must look like one that does not exist, but the worker routes took no caller, and a test showed
GET /workers/{id}returning another tenant's job command to a key from a different tenant. A worker has no tenant of its own, so it belongs to the tenant of its node, and the worker services take a required tenant and answer the same 404 as for a missing id. The read routes, lease renewal,startand the three outcome routes (complete,fail,cancel) are scoped, each with a two-tenant test that failed first.heartbeatis scoped too, with a two-tenant test that failed first, so all nine routes take the caller. The lease renewal test also proves that a foreign call leaves the lease unchanged.GET /eventsis scoped by ADR 0074. The ADR holds a threat model, four properties every route must satisfy and a status table for all nine routes. AetherGrid was not multi-tenant when this change merged. That was true when this change merged. ADR 0064 is now Accepted, and AetherGrid on main is multi-tenant as it defines it. - ADR 0074 - Give Events a Tenant and Scope the Event Feed: Accepted, with all three slices merged.
GET /eventstook no caller, so a key from any tenant could list the events of every tenant: job ids, event types and times. The payload is empty, so no commands or resources were exposed. Events now carry the tenant of their job, read from the job when the event is recorded, and the database refuses an event in another tenant's job through a composite key.GET /eventsreads only the caller's tenant, proven by a two-tenant test that failed before the fix, and the job history reads by tenant in one query. The third slice is a migration that makes the columns required, so Postgres now refuses an event with no tenant. AetherGrid was not multi-tenant when this change merged. That was true when this change merged. ADR 0064 is now Accepted, and AetherGrid on main is multi-tenant as it defines it. - ADR 0075 - Give Workers and Leases a Tenant: Accepted, with all three slices merged.
workersandleasescarry a tenant, and four composite keys make the database refuse a worker in another tenant than its node, a worker that runs another tenant's job, and a lease whose worker or job is in another tenant. Slice 1 is migration 0004, which adds the nullable columns, backfills through the owner and adds the composite keys while keeping the old keys, so an older image keeps working. Slice 2 is migration 0005, which makes the tenant required and stops with a count if a row has none or crosses tenants. Slice 3 is repository scoping. It is Accepted because v0.7.0, a release that carries 0005, was run against a database upgraded from v0.6.0 by the upgrade rehearsal. - ADR 0076 - Run the README Setup Blocks in CI: Accepted. Three faults on the documented path,
pythonmissing before a venv exists andNEUROMESH_STORAGE_BACKENDunset in both the key block and the test block, went unseen because the README was only ever run in a shell that already had the right environment. ADR 0063's manual clean clone test found one fault and nothing repeated it. A workflow now executes the README's setup blocks on a clean runner. The blocks are read fromREADME.mdbyscripts/readme_blocks.py, not copied into the workflow, so the two cannot drift. Everybashfence carries aci:readmecomment that either gives it a step number or records why it is skipped, an unmarked fence fails the job, and so does a README with fewer than three run blocks, so deleting markers cannot make it pass by running nothing. Blocks run in step order, each in its ownbashprocess. The key step captures the issued key, masks it, and requires an authenticatedGET /nodesto return 200. The job passed on a pull request and onmain(927 tests), and it was shown to fail on two deliberate breaks: removing the backend export from the key block turned step 2 red, and removing it from the test block turned step 3 red. Not claimed: other operating systems, shells or Python 3.11, or that the prose is clear. It proves the commands run. - ADR 0077 - Serve the API Docs Only When Enabled: Accepted. The README and ADR 0015 said every route requires an API key. A runtime check showed that
/docs,/redoc,/openapi.jsonand/docs/oauth2-redirectreturned 200 with no key, because FastAPI adds them itself, and the route registry of ADR 0064 never saw them since it reads the OpenAPI schema and the router modules. The exposure was reconnaissance, not a breach: route names, request schemas and scope names, no data and no action. The docs are now off unlessNEUROMESH_ENABLE_API_DOCSis set, a test asserts each path returns 404 by default, and a guard test fails if the app holds any plainRoute, so the registry and the app cannot disagree about which routes exist. The only unauthenticated routes remainGET /,GET /healthandGET /livez. Shown to fail: with the flag set, five of the eleven new tests go red. The full suite passes (938). Not claimed: that every other route was swept at runtime for a 401, or that the probes reveal nothing, since/healthreturns the exception class name on failure. - ADR 0078 - Elect One Scheduler With an Advisory Lock: Accepted. The cluster tick ran in every API process, and nothing stopped a second process on the same database, such as a second replica or the overlap during a rolling deploy, from scheduling against the same nodes. The unique constraints on leases stop a double lease but not two ticks allocating against the same node. The tick now runs only in the process that holds a Postgres advisory lock on a dedicated connection, a follower waits and asks again on the next tick, and a clean shutdown hands the lock over at once. This narrows the risk to a failover window and does not close it. The gap was found by review and never reproduced, and rate limiting and error tracking still keep their state in each process, so running several replicas needs its own decision.
- ADR 0079 - Kill What a Job Command Leaves Running: Accepted. A job's command runs as a subprocess, and since #424 it runs in its own process group, so a timeout, a cancel or a lost lease stops the command's children as well as the command. Two cases were left. A command that started a child with its output detached and then exited closed its pipes at once, so the wait ended, the command was reaped and nothing signalled the group afterwards. A command that died on SIGTERM while a detached descendant ignored it ended the wait early, so the SIGKILL that follows the grace period was never sent. In both, a process kept running after its job had ended, on a node whose resources the scheduler already counted as free, and after a lost lease it was work done by a worker that no longer owned the job. SIGKILL now goes to the whole group whenever the wait ends, so a command can no longer leave work running after it exits, and a signal the kernel refuses is logged and never discards the job's result. Two tests written first failed against the old code on the assertion that the child is gone, and a third failed on the refused signal. The full suite passes (995). Not claimed: that a descendant that starts its own session or process group is stopped, since only a cgroup or a PID namespace contains it, or that the group id cannot be reissued between reaping the command and the last signal, which was not tested under heavy process churn. An agent or API process that is killed outright still runs no cleanup, and that is the next change.
- ADR 0080 - Stop a Job's Processes When Their Owner Dies: Accepted. ADR 0079 stops a job's processes from code in the process that runs them, and a process that is killed outright runs none of that code. The command ran in its own session, so nothing signalled it when its owner died, and for the standalone agent the lease could expire and the job start on another worker while the first run was still going. The command now starts through a small supervisor in its own process group, which holds the read end of a pipe whose write end only the owner holds. When the owner dies by any means, the kernel closes the pipe and the supervisor kills the group. The supervisor ends the way the command did, so the owner still reads the command's own exit code or signal, and a command that cannot start is reported on a second pipe, so the failed result of ADR 0081 does not change. A test written first failed against the old code on the assertion that the child outlives its killed owner. A probe in a container whose first process stayed alive showed the supervisor ending the job while a job started the old way survived. The full suite passes (1048). Not claimed: that a descendant in its own session is stopped, that the kill lands before the lease expires, that a supervisor killed on its own ends the job before its timeout, or that an owner that is stopped or frozen is handled.
- ADR 0081 - Fail a Job Whose Command Cannot Start: Accepted. A job's command is started with Popen, which raises when the program does not exist, is not executable, or has a file where a directory should be. JobExecutionService let the exception out and neither caller caught it. By the code, the standalone agent ends and leaves the job leased to a process that is gone, and the in-process loop skips marking the worker failed, releasing the lease, freeing the node and recording the event. The service now returns a failed result with no exit code and the reason in stderr, and both callers already send that down the failed path. Only these three launch errors are converted, because any other error from starting a command is a fault of the host and still raises. Seven tests written first failed against the old code, and the full suite passes (1009). Not claimed: that the agent was run end to end, whether a failed job is retried and onto which node, or that an operator can see the reason, which is not sent to the server.
- ADR 0082 - Enforce the Layer Dependencies With a Test: Accepted. The rule that dependencies point inward was written down and not checked, and the document for it was empty. A test now parses every module in
app/and fails on an import that crosses a layer the rules do not allow, a relative import that leaves its package, a third-party package outside its layer, or a dynamic import. The composition root and the scheduler leadership port are the two named exceptions, and there is no list of tolerated imports. The two places that broke the rules,get_job_service.pyandapi.pyimporting the connection pool, are fixed in the same change, andGET /healthnow has tests. - ADR 0083 - End a Job When Its Supervisor Ends: Accepted. execute() waits for a job with communicate(), which returns when the output pipes close, so anything in the process group that still holds stdout or stderr keeps the wait going after the supervisor has ended. A command that exited 0 and left a child holding its output was reported as timed out, which a probe on the code before ADR 0080 showed, and a supervisor killed on its own left the job to run to its timeout. When the supervisor has ended, execute() now kills the group, collects the output and returns the supervisor's own result with no timeout flag, so a command that succeeded stays succeeded. Two tests written first failed against the old code because each job ran to its 10 second timeout, and the full suite passes (1073). Not claimed: that a descendant in its own session holding the pipes is stopped, or the time between the supervisor ending and the return, which the tests bound at five seconds.
- ADR 0084 - Enforce the Architecture Index With a Test: Accepted. The architecture index listed seven documents and five of them had been empty since the commit that added them, with no check that the index and the directory agree. A test now fails on a listed document with no text, a row for a missing file and a document with no row, and the five empty documents and their rows are removed.
- ADR 0085 - Finish the Upgrade Rehearsal With Migrate and Compare: Accepted. The rehearsal script seeded a database with the old release, exported every table and ended, so a run exited 0 having migrated and compared nothing. It now builds the new release, runs only its migrate service against the same database with the new API never started, exports again and fails on any difference. Five tests written first failed for the expected reasons, two mutations each failed the tests, and one real run from v0.6.0 to main at 0655914 changed nothing in 7 tables. Not claimed: that migration 0005 was applied, because the export leaves schema_migrations out and the script does not print what migrate applied, that a run from a commit closes condition 5 of ADR 0075, which needs a tag that carries 0005, or that the constraint changes are checked.
- ADR 0086 - Show Which Migrations the Upgrade Rehearsal Applied: Accepted. The rehearsal compared every table except schema_migrations, so a run in which migrate applied nothing printed the same result as one that applied 0005 and kept every row. It now reads schema_migrations before and after the migrate run, prints the versions the upgrade added, and fails when none was added, an applied version is missing or a recorded name or checksum changed. Fourteen new tests failed first, four mutations each fail them, a real run from v0.6.0 printed
applied migration 5 0005_require_a_tenant_on_workers_and_leases.sql, and the full suite passes (1218). Not claimed: that a migration changed the schema as intended, or condition 5 of ADR 0075. - ADR 0087 - Compare the Upgraded Schema With a Fresh One: Accepted. The rehearsal compared the rows of every table, so a constraint, an index or a default that a migration changed could not be seen in a CSV export. It now builds a second database with the new release's migrate service, dumps the schema of both with pg_dump --schema-only, and fails on any difference other than the two lines that carry a random key, naming each one. Nineteen new tests failed first, six mutations each fail them, a real run from v0.6.0 reported
the upgraded schema matches a fresh one (452 lines), and the full suite passes (1237). Not claimed: that a defect in the migration SQL itself is caught, since both builds run the same files, or condition 5 of ADR 0075. - ADR 0088 - Start the New API on the Upgraded Database: Accepted. The rehearsal shows that an upgraded database holds the right rows and the right schema, and not that the release that upgraded it can start on it. It starts the new release's API on that database with
up --no-deps --no-build --wait, read back the seeded node, worker and job with the key the old release issued, and fails when the API does not start, a read is not a 200 or a body carries a different id. Not claimed: that any state is preserved, since the new API may reclaim a lease on startup, or condition 5 of ADR 0075. - ADR 0089 - Read the Job Command After the Upgrade: Accepted. The rehearsal checked the status and the id of the seeded node, worker and job, and the seeded job had no command, so a migration that lost or changed a stored command would have passed. It now issues the key with the
jobs:executescope inside the old release, seeds the job with a command, and fails when the worker route returns no running job or a different command. Fourteen new tests were written first, five mutations each fail them, and a real run from v0.6.0 to main at 304177f read the command back from the new API. Not claimed: that the command runs, that any other command survives, or that the lease survives startup in any run other than that one. - ADR 0090 - Issue API Keys for a Named Tenant: Accepted. A key belongs to one tenant, and the application could issue one for any existing tenant, but the script that issues keys only reached the default tenant, so a deployment had one tenant unless someone edited the database. The script now issues a key for a named tenant with
--tenant, creates the tenant only with--create-tenant, and prints its usage without a database. The test database guard runs before any tenant is resolved or created. Two tests pin the failure paths, a lost race on the tenant name and the guard order, and each fails against a deliberately broken script. One real run on Postgres 16 from e3304e2 showed three keys in three tenants, and through the running API the acme key created a job and read it back while the globex key got the same status and body for that job as for a random id. Not claimed: that two operators creating one new name at the same moment fail cleanly on Postgres, that response headers or timing hide a foreign job, or that isolation holds beyond jobs, which ADR 0064 and ADR 0075 decide. - ADR 0092 - Release a Node Only After the Job Is Saved: Accepted.
reclaim_jobreleased and saved the node before it calledJob.reclaim(), so a job that had completed or failed in the meantime still credited its node. It now callsJob.reclaim()first, saves the job, and releases and saves the node after that save. Whenreclaim()raisesInvalidJobTransitionit returns False and does not credit the node, with one exception that the ADR names for a cancelled job. - ADR 0093 - Record a Heartbeat Without Writing Capacity: Accepted.
HeartbeatNodeServiceread the node and saved the whole row, available CPU, memory and VRAM included, so a heartbeat could write older figures over an allocation the scheduler had made between the read and the save.NodeRepository.record_heartbeat(node_id, tenant_id, seen_at)now writeslast_seen_atand nothing else, and returns False for a node in another tenant or for no node, without changing the stored row. A race test on real Postgres covers it. - ADR 0094 - Serve the Public Demo from a Separate Read-Only App: Proposed. A public demo needs a URL that anyone can open, and the existing app cannot also serve an anonymous surface. The public surface is a separate FastAPI app in
app/presentation/public/, with its own app object, entry point and process, servingGETroutes only from an explicit list. The dashboard keeps asking for an API key. - ADR 0095 - Start a Job with an Allowlisted Environment and Close the Executor to It: Accepted. A job's command is a real subprocess, and it received the whole environment of the process that ran it, credentials included. The supervisor now builds the environment from an allowlist (
HOME,LANG,LC_ALL,PATH,TMPDIR,TZ), andNEUROMESH_JOB_ENV_PASSTHROUGHlists any further names an operator chose to pass. - ADR 0097 - Create a Public Read Role That Can Do Nothing: Accepted. Migration 0006 creates the role
aethergrid_public_readas NOLOGIN, NOSUPERUSER, NOCREATEDB, NOCREATEROLE, NOREPLICATION and NOBYPASSRLS, and grants it nothing: no privilege on any table and no USAGE or CREATE on any schema. It has no members and is a member of no role, so every later grant is visible in the history. - ADR 0098 - Expose the Public Demo Through Views Only: Accepted. A grant on a base table would let the public role read every column, every column added later and every tenant, including job commands, free-form event payloads, node labels and API key hashes. Migration 0007 creates five views instead,
public_nodes,public_jobs,public_workers,public_leasesandpublic_events, each naming its columns, and nothing is created for tenants or API keys. ADR 0109 later amends decision 1 on purpose. - ADR 0099 - Give the Public App a Login Role of Its Own: Accepted. The public app logs in as its own role,
aethergrid_public_app, which is not a member ofaethergrid_public_readand has no member. A script,scripts/create_public_app_role.sql, creates it on the demo database, run by an operator and never placed among the migrations, because a migration cannot carry a password and would create the role in every database that migrates. The password comes from the file named byAETHERGRID_PUBLIC_APP_PASSWORD_FILE. ADR 0109 later amends decision 6 on purpose. - ADR 0100 - Install Only from Hashed Locks and Test the Rule: Accepted.
pyproject.tomlgave the runtime dependencies a lower bound and there was no lock file, so every image build and CI run resolved the whole tree again. Three lock files now hold exact versions and SHA-256 hashes, installs use only them, and a test enforces the rule. - ADR 0101 - Give Every Workflow Job a Timeout and Test the Rule: Accepted. A workflow job with no
timeout-minutesruns for up to six hours, and one test job took 23 minutes 36 seconds on Python 3.11 against 2 minutes 23 seconds on 3.12, with nothing to stop it. Every job in every workflow now setstimeout-minutesat the job level, with values taken from observed run times, andtests/supply_chain/test_job_timeouts.pyfails any job that lacks one. - ADR 0102 - Read the Public Demo Through a Port of Its Own: Proposed. The public app cannot read through the existing services, because the repositories select from base tables and scope by a tenant argument, and the public role has no privilege on any base table. One port,
app/application/public_read_port.py, holds a read-only protocol with one method per public view and one frozen record type per view with exactly its columns. No method takes a tenant, every method takes a limit that the reader clamps to a fixed maximum, and every read has a fixed order, events newest first. - ADR 0103 - Limit Anonymous Requests With a Bounded Limiter of Its Own: Accepted. An anonymous caller has no API key, so the limiter of ADR 0021 cannot be reused.
AnonymousRateLimiter, inapp/application/public_rate_limiter.pyand standard library only, passes a request only when both a per-client bucket and one global bucket hold a token, checks and consumes both under one lock, and consumes nothing on a refusal. The counted address, the proxy hops setting and the middleware that applies the limiter to every request of the public app are implemented and tested, and four deliberate breaks of the wiring each turned tests red. Nothing is deployed. - ADR 0104 - Open the Public Database Pool From a Checked URL: Accepted.
open_public_pool, inapp/infrastructure/public_read/public_pool.py, takes plain values and parses the URL with libpq through psycopg'sconninfo_to_dict. Reading the URL the way libpq reads it showed a flaw in the check the public settings already made: a password written after a question mark passed it. The URL check, the password file, the pool values and options, and the wait for the first connection are implemented and tested, including against a real database. Nothing is deployed. - ADR 0106 - Build the Demo Page From a Real Run of One Scenario: Proposed. The list of what is built for the demo page, so that none of it is forgotten, with the page built from a real run of one scenario. Each item that changes the architecture gets its own ADR before any code.
- ADR 0107 - Record the Lease That Reclaim Deletes: Proposed. A lease row is gone after reclaim, so a record keeps what the row held. Migration 0008 adds
lease_reclaims, one row for each lease that a recovery path deleted while it reclaimed a job, withrecovered_byone ofexpired_lease,offline_nodeandworker_registered. The storage is built, and the three recovery paths keep the record. - ADR 0108 - Record the Renew and Release Calls That Lease Fencing Refuses: Proposed. Nothing recorded a renew or a release that lease fencing refused. Migration 0009 adds
lease_refusals, one row for the first refusal of each kind of a lease that reclaim removed, withoperationrenew or release andreasonno_active_leaseorlease_not_current. The database refuses a refusal whose reclaim record is missing or is in another tenant, and one whose job is in another tenant. The storage is built. - ADR 0109 - Show Reclaimed and Refused Leases Through Two More Views: Proposed. The records of ADR 0107 and ADR 0108 reach the public demo through two more views,
public_lease_reclaimsandpublic_lease_refusals, created by migration 0010. No other table gets a view. It amends ADR 0098, decision 1, and ADR 0099, decision 6, on purpose. - ADR 0110 - Accept the Tables the Upgrade Creates in the Rehearsal: Accepted. The upgrade rehearsal named a table that exists only after the upgrade as a difference, which would have ended every rehearsal across a release that adds tables. It now accepts such a table when it is empty and prints its name, and it still fails on a created table that arrives with rows, on a dropped table and on every change it named before. The first real rehearsal, from v0.7.0 to efaf3d6, passed in 95 seconds and accepted three created tables.
- ADR 0111 - Accept a Reclaimed Lease in the Upgrade Rehearsal: Accepted. The first real rehearsal from v0.7.0 to efaf3d6 ended at the read back of the seeded worker, because a 30 second lease expired in the 99 seconds between the seed and the read and reconciliation reclaimed the job. The rehearsal now accepts a worker that holds nothing when the database holds a reclaim record for the seeded job and worker, waited for up to 10 seconds, and it still fails on every other worker body.
- ADR 0112 - Let a Caller Set a Bounded Retry Budget on a New Job: Accepted. A reclaim returns a job to the queue only while it has retries left, and every job made through
POST /jobshadmax_retries0.POST /jobsnow takes an optionalmax_retries, a JSON integer from 0 to 3 that defaults to 0. A value above 3, below 0 or not a JSON integer is refused with 422 before any service runs. Merged as PR 568. - ADR 0113 - Run the Lease Scenario Through the API with Its Own Key: Accepted. The driver of the lease scenario is
scripts/lease_scenario.py. It uses only routes of the API, with a key of the demo tenant that holds no scope, and the job it makes has no command. It sends the key only tohttp://127.0.0.1:<port>until a deployment ADR names another address, reads it from a file, and never prints or logs it. The command line of the driver is merged as PR 574. - ADR 0114 - Record Each Scenario Run and Show It Through a View: Proposed. One run of the lease scenario is recorded as an immutable
ScenarioRunwith every time taken from a row and never from the caller, and is shown through a view. Slice 1, the entity, the port, the in-memory and PostgreSQL repositories and migration 0011, is built and merged as PR 582.
The index above is the fastest way to see how each part of the system was decided.
Capabilities
One owner for every job. A job runs under a time-bound lease that the worker renews for as long as the job runs. Retries, reconnects, network failures and long runs cannot produce two workers executing the same job. A worker confirms that execution has begun before the job counts as running, and a worker managed by a standalone agent is never raced by the in-process scheduler (ADR 0019, ADR 0034, ADR 0036).
Recovery without an operator. Heartbeats detect offline nodes and dead workers. Their jobs return to the queue within a retry budget and fail outright once it is spent, so one unhealthy node cannot bounce a job forever. A restarted agent reclaims its own worker identity, and the job it abandoned is cleaned up first (ADR 0030, ADR 0039). A node can be drained for maintenance while its running work finishes.
Placement that fits the workload. The scheduler matches resource requirements and labels, skips nodes that are draining or offline, and picks the tightest sufficient fit across CPU, memory and VRAM together (ADR 0043). Jobs carry priorities and retry policies, and a running job can be cancelled.
A complete record of every job. Every lifecycle step is stored as an immutable event at the moment it happens, from creation to completion, failure or reclaim. Each job has its own timeline, and a live feed shows the same events across the caller's tenant.
Access that is controlled. Every route except the root and the two health probes requires an API key, including the route that issues keys, and the first key is minted by a script run locally with database access, never over HTTP. Keys carry scopes: setting a job command needs one (ADR 0054), and so does issuing or revoking keys (ADR 0055). Each agent in a fleet holds its own key (ADR 0045), and every key is rate limited, with a 429 and a Retry-After header when a caller exceeds its share (ADR 0021).
Execution with a bound. A job with a command runs as a subprocess with an enforced timeout: a graceful stop first, then a forced kill after a grace period.
One console. Nodes, jobs, workers and the activity feed sit in a multi-page dashboard, with a command palette for moving between views from the keyboard.
Architecture
AetherGrid is built in four layers, and dependencies point inward. A test enforces the layer rules, so they hold as the code changes (ADR 0082).
Domain. Jobs, nodes, workers, leases, events and API keys enforce their own rules. The scheduling algorithm and the job lifecycle live here as plain Python, with no web or database imports. Remove the infrastructure layer and the domain tests still pass.
Application. Services coordinate the domain and the repositories without holding business rules. A worker execution loop runs an assigned job as a subprocess, renews the lease for the job's whole runtime, records the outcome and releases the lease. If a renewal fails, the lease has been reclaimed elsewhere, and the loop discards its result instead of writing it against another worker's work. A reconciliation loop covers what the normal path cannot: crashed workers, expired leases and state left inconsistent by infrastructure failures.
Infrastructure. Every repository has a PostgreSQL implementation, written with psycopg and no ORM, so query behavior and transaction boundaries stay explicit. A shared contract suite runs against each backend a repository supports, so identical behavior is tested, not assumed.
Presentation. FastAPI endpoints validate input, call an application service and return a response, and hold no business logic. The dashboard follows the same split: typed API calls, data hooks and components.
Every non-obvious decision is documented as an ADR in /docs/adr.
Test Coverage
The suite spans domain, application, infrastructure, and API layers (see badge above for current count), all passing:
- Full domain logic coverage: job lifecycle, retry policy, constraint matching, node and worker liveness, lease semantics, node draining and the scheduler's exclusion of draining nodes, and API key issuance, revocation, and usage tracking
- Contract tests proving every repository's in-memory, SQLite (where implemented), and PostgreSQL implementations behave identically, including foreign-key-enforced aggregates such as
WorkerandLease, and specifically that lease renewal fails rather than resurrects a lease already reclaimed by reconciliation - Application service tests for every use case, including lease acquisition, renewal, release, reconciliation repair (both the requeue-with-retries-remaining path and the fail-outright-once-exhausted path), real subprocess execution (including tests that genuinely kill a process that ignores
SIGTERM, forcingSIGKILL, on both the timeout path and the cancellation path), and the full API key lifecycle from issuance through revocation - Event recording tests proving every lifecycle event fires at the correct point, in the correct order, across the full job lifecycle, scheduling, assignment, lease acquisition and release, completion, failure, and reconciliation reclaim
- API-level tests against real FastAPI endpoints, including the event feed, per-job history, and every route's auth requirement, verified through a real end-to-end request, not mocked
Separately, a Playwright end-to-end test drives the real dashboard against the real API and Postgres, not mocked, reproducing the ADR 0041/0042 worker-recovery incident through an actual browser (frontend/e2e). It is verified locally and in this PR's own CI run, not yet part of the standing CI workflow on every push, that wiring is a deliberate, separate follow-up.
These commands assume the setup in Running It is done first: the secret file, the virtualenv and the hashed installs. The Postgres-backed tests need a separate neuromesh_test database. The suite refuses to run against any database whose name does not end in _test, because some fixtures truncate tables. With the compose Postgres running:
docker compose up -d postgres
docker compose exec -T postgres psql -U neuromesh -d neuromesh -c 'CREATE DATABASE neuromesh_test'
export NEUROMESH_TEST_DATABASE_URL="postgresql://[email protected]:5433/neuromesh_test"
export NEUROMESH_STORAGE_BACKEND=postgres
export NEUROMESH_DATABASE_PASSWORD_FILE=./secrets/postgres_password.local
NEUROMESH_DATABASE_URL="$NEUROMESH_TEST_DATABASE_URL" python -m app.infrastructure.migrations
pytest
Running It
git clone https://github.com/wycliffRotich-dev/aethergrid.git
cd aethergrid
mkdir -p secrets
openssl rand -hex 24 | tr -d '\n' > secrets/postgres_password
cp secrets/postgres_password secrets/postgres_password.local
chmod 600 secrets/postgres_password secrets/postgres_password.local
sudo chown 10001:10001 secrets/postgres_password && docker compose up -d --build --wait --wait-timeout 180
This starts Postgres, applies the database migrations in a one-shot migrate container, and then starts the API. Postgres and the API are reachable from the host only (127.0.0.1). The last line asks for your sudo password once, because the container user must own the secret file, and then waits until the migrations have finished and both services are healthy. migrate exits when it is done, and docker compose ps -a shows it as exited with code 0. If a migration fails, the API does not start, docker compose up stops with service "migrate" didn't complete successfully, and docker compose logs migrate shows the reason (ADR 0071). The .local copy is for tools you run on the host, which cannot read the original. Follow the logs with docker compose logs -f. docker compose up fails if secrets/postgres_password is missing, and the application reads the same file through NEUROMESH_DATABASE_PASSWORD_FILE, so the password is in neither the connection URL nor the container environment. A Postgres volume created by an earlier version keeps its old password: reset it with docker compose down -v (ADR 0058). Issue yourself a key before calling anything, every route requires one. Grant both scopes so nothing is gated during local development (ADR 0054, ADR 0055):
python3 -m venv .venv && . .venv/bin/activate
pip install --require-hashes --only-binary=:all: -r requirements-build.lock
pip install --require-hashes --only-binary=:all: -r requirements-dev.lock
pip install --no-deps --no-build-isolation -e .
export NEUROMESH_DATABASE_URL="postgresql://[email protected]:5433/neuromesh"
export NEUROMESH_DATABASE_PASSWORD_FILE=./secrets/postgres_password.local
export NEUROMESH_STORAGE_BACKEND=postgres
python scripts/issue_api_key.py "local-dev" --scope jobs:execute --scope keys:manage
The image defaults to SQLite and stores its database in /data, owned by uid 10001. A named volume works as is. If you bind-mount a host directory at /data instead, give it to that user first (sudo chown 10001:10001 <dir>). A root-owned directory fails at startup with sqlite3.OperationalError: unable to open database file.
Run the frontend separately. It needs Node 22.x, the version CI uses, pinned in frontend/.nvmrc. Match the pin with nvm use (or your version manager): several frontend dependencies declare an engines range of ^22.22.2 || ^24.15.0 || >=26.0.0, so a Node outside it (for example 23 or 25) installs with an EBADENGINE warning and is not what CI runs:
cd frontend
npm install
npm run dev
CI runs the full test suite against a live Postgres service on every push. See .github/workflows.
Contributing
Fork the repository, create a branch, and open a pull request against main. Setup, the checks every change must pass, and the rules for ADRs are in CONTRIBUTING.md. For anything larger than a small fix, open an issue first.
What AetherGrid covers
AetherGrid decides where a job runs, who owns it, and what happens when a node or a worker fails, and it keeps the record of every step. The machines, the network and the identity systems around it stay yours. It runs on compute you operate.
Evaluating AetherGrid for your organization? Get in touch.
استكشف مشاريع مشابهة ومرتبطة
جارٍ التحميل…