ENGINEERING NOTE / 17 POSTGRESQLARCHITECTURE
Inspect and Change Are Different Verbs
The monitoring half of the portal is built to retry: a check that fails runs again. The half that changes production is built the other way round. One executor claims each job once, a unique index keeps changes to the same target from overlapping, a silent executor makes a job lost rather than retried, and stopping a job is not the same as undoing it. This is how those rules work in the SQL and the code.
TABLE OF CONTENTS
- Two queues, two sets of logins
- A job is a row with a lock key
- The other half of the lock: topology changes
- Claimed once
- Heartbeats, and what “lost” means
- Why a restart of the executor does not lose the job
- Nothing retries itself
- Confirmation, stored with the job
- Schedules run as their owner
- Closing the loop: re-check what the job touched
- Stopping a running job
- Audit rows, and one permissions matrix
- Takeaway
The command center note ends with the second queue in a list of bullet points: claimed once, nothing retries itself, one change per target, typed confirmation, schedules that run as their owner. Each bullet is a sentence there. This note covers how each one is built, and the edge cases each one had to handle.
The monitoring side is built to be retried. A check that fails is retried up to three times. A worker that dies mid-check loses its claim after a timeout, and another worker picks the check up. Running a read-only check twice costs nothing. Running a replication rebuild twice could do real damage, and so could failing a cluster over to a site that is already being rebuilt. So the queue for changes keeps the shape of the monitoring queue but flips most of its defaults.
Two queues, two sets of logins§
The rule behind everything below is that inspect and change are different verbs. The separation is in the logins, not in comments in the code.
Every stored credential is keyed by what it is for. A database or Windows
login is either a monitor login or an admin one, with separate
replication and backup logins for the replication tooling. The checks only
ever ask for monitor logins, and on the target those logins hold read-only
grants: a SQL Server monitor login has VIEW SERVER STATE and nothing more.
The admin, replication and backup logins never fall back to environment
variables, and the checks never ask for them. They reach a job through one
route only: the action executor’s start-up, which writes them for its own
handlers.
The executor is one container, and it learns about work through the portal’s REST API, using a service account whose role holds exactly one permission: act as a job executor. That role sits below the viewer role, has no directory group, and so is never given to a person who signs in. The portal does not run changes itself. It records the request and waits for the executor to report back.
A job is a row with a lock key§
A request becomes one row. The columns that matter here are the target, the
lock key, the requester and how they asked, the confirmation text, the
status and the executor’s timestamps. The statuses are queued, claimed,
running, lost, and then one final state: done,
completed_with_warnings, skipped, failed or cancelled.
Every action kind is registered in code, and the registry enforces two
rules when the module is imported. A kind that changes things must name a
confirmation level other than “none”, and it must resolve a lock key for its
target. A kind that breaks either rule cannot be registered, so the portal
fails at start-up rather than at request time. Lock keys look like
host:<id> for work on one host and geo:<id> for work on a geo-cluster.
A rebuild, a rebalance and max server memory lock the whole geo-cluster,
because they touch several of its members. Read-only kinds take no lock.
The lock itself is not a lock table. It is a partial unique index:
CREATE UNIQUE INDEX uq_job_lock
ON action_job (lock_key)
WHERE status IN ('queued', 'claimed', 'running', 'lost')
AND lock_key IS NOT NULL;
Two changes to the same target cannot both be active, because the second
INSERT fails with a unique violation. The portal catches that violation,
looks up which job holds the key and returns a 409 that names the job and
its status. There is no check-then-insert window, because the check is the
insert.
The detail that matters most is 'lost' in that list. A lost job is one
whose executor has stopped sending heartbeats. That does not mean the
command has stopped. The process may still be running on the executor host,
so the lock holds until a person settles the job.
The other half of the lock: topology changes§
The unique index covers job against job. It does not cover a job against something that is not a job, such as a geo failover, which swaps the live and DR roles in the portal’s topology, or disabling or deleting a host. Those changes would leave a queued rebuild holding a topology that no longer exists.
These are serialised with transaction-scoped advisory locks, one per geo-cluster and one per host, taken in sorted order so that two holders cannot deadlock:
keys = sorted({(GEO, g) for g in geo_ids} | {(HOST, h) for h in host_ids})
for key in keys:
cur.execute("SELECT pg_advisory_xact_lock(%s, %s)", key)
Requesting a changing job resolves its target once to find out which locks to take. It then takes them and resolves the target again under the lock before it inserts the row, so an inventory edit cannot land between the resolution and the insert. A failover holds the same geo lock from its “is any job active here?” check to the end of the role swap. A host’s lock covers the geo-clusters it belongs to. Neither side can slip in between the other’s check and its write.
The two interlocks are not quite symmetrical, and the difference is deliberate:
- A geo failover is refused while any active job is on the geo-cluster. That includes read-only ones, because a running diagnosis would report a half-swapped topology. The only exceptions are offline kinds, which work only on what the portal handed them.
- Disabling or deleting a host is refused only while a changing job touches it. That covers jobs on the host itself and jobs on any geo-cluster it is a member of.
“Refused” here means refused, not queued behind. The failover page says which job is in the way and points to the Jobs page. Nothing waits in the background to fire later.
Claimed once§
The executor polls for queued jobs it may take: the right kinds, the right
environment, oldest first. It then claims each job with one conditional
UPDATE:
UPDATE action_job
SET status = 'claimed', executor_id = :me,
claimed_at = now(), heartbeat_at = now()
WHERE id = :job AND status = 'queued'
AND kind = ANY(:my_kinds) AND environment = ANY(:my_envs)
AND EXISTS (SELECT 1 FROM executor x
WHERE x.id = :me AND x.enabled AND NOT x.claims_paused
FOR SHARE)
RETURNING id;
status = 'queued' makes the claim exclusive. If two claims race, one
updates the row and the other updates nothing and gets a 409, which the
executor treats as “someone else has it” and moves on. The FOR SHARE on
the executor’s own row is there for deploys. Pausing an executor’s claims is
an UPDATE of that row, so the pause waits for any claim in flight to
commit, and any claim queued behind the pause sees it. Once the pause has
committed, the executor’s active jobs really are all of them. The deploy
script relies on that when it counts them and decides whether recreating the
container is safe. Recreating the container would kill every job in it.
The portal also refuses to register two enabled executors for the same kind and environment. Each kind of change has exactly one place it can run.
Everything the executor does after the claim repeats the ownership check instead of trusting an earlier read:
UPDATE action_job SET ...
WHERE id = :job AND executor_id = :me
AND status IN ('claimed', 'running', 'lost')
RETURNING id;
An operator may cancel or settle the job between the executor’s read and its
write. If they do, the UPDATE matches nothing, the executor gets a 409,
drops the run locally and overwrites nothing.
A job’s input files (a reviewed fix script, for example) are inserted in the same statement as the job, as a CTE. There is never a moment when an executor could claim a job whose inputs are not there yet.
Heartbeats, and what “lost” means§
While a job runs, the executor sends a heartbeat every 30 seconds by
default. Shipping log lines and uploading artifacts also count as
heartbeats. Each one sets heartbeat_at = now() under the ownership guard
above.
No background timer marks jobs lost. The rule is applied lazily, whenever jobs are listed, requested or polled:
UPDATE action_job SET status = 'lost'
WHERE status IN ('claimed', 'running')
AND heartbeat_at < now() - :lost_after * interval '1 second';
The worker’s leader runs the same statement, so a job lost while nobody has the page open is still marked and emailed. The threshold is a setting, defaulting to ten minutes, with a floor of one minute.
- HEARTBEAT
- 30 s
- LOST AFTER
- 10 min
- STOP GRACE
- 60 s
- SCHEDULE MISSED AFTER
- 15 min
Lost is not final. If the executor turns out to be alive after all, its next
heartbeat brings the job back to claimed or running, depending on
whether it had started, and clears the alert mark. The loss was reported,
so how the job finally ends is reported again. A job goes lost because of
silence, not because anyone decided it had failed. It never goes back to
queued.
Why a restart of the executor does not lose the job§
The executor launches each job through a small wrapper in a new session. The wrapper starts the real command, sends its output to a log file, and writes the exit code to a file atomically, as the last thing it does. Every claimed job has its own work directory holding the claimed job, its inputs, its output, its exit code and a progress file. The progress file records how many bytes of output have been read, the next log sequence number and the lines the portal has not yet accepted, and it is also written atomically.
Because of that layout, the executor process can crash or restart without
killing anything. On start it re-attaches to every work directory that has
not been reported, picks up the output where the progress file says, and
carries on. Log batches carry sequence numbers, and the portal ignores a
(job, seq) pair it already has, so a batch re-sent after a crash is
neither duplicated nor lost.
There were two edge cases in deciding whether a job is still running:
- A pid is not proof. A zombie still answers
kill -0, and after a restart a saved pid can belong to some other process. Where/procexists, the wrapper only counts as alive if its command line names the job’s work directory, and a zombie’s command line is empty. The executor also runs with an init process, which reaps orphans. - A wrapper that vanishes without an exit code, after a host reboot for example, is reported as failed with “process disappeared”. Otherwise it would keep sending heartbeats for a job that no longer exists.
Nothing retries itself§
The monitoring queue retries. This one never does, at any layer:
- A failed job stays failed. The fix is a new request, which goes through permissions, confirmation and the lock again.
- A lost job waits for a person to settle it.
- A scheduled run that cannot take the lock is skipped, not queued behind the job that holds it. The next run tries again.
- A scheduled run that is due while the portal is down, and is more than 15 minutes late when the portal comes back, is recorded as missed, not fired late. A 02:00 rebuild must not start at 09:00.
- A due schedule is claimed by an
UPDATEthat movesnext_run_atforwardWHERE next_run_at = <the due time>. The scheduler loop runs in every web worker, so this makes each run fire at most once, and a claimed run is never retried.
Network errors are the exception, and they are about delivering reports, not about actions. If the executor cannot reach the portal, it retries the call on the next tick, because a heartbeat or a log batch is safe to send again. Running a command again is not.
Confirmation, stored with the job§
Every changing kind has a confirmation level, and the text the requester gave is stored on the job row:
- confirm: an OK dialog in the browser, or any non-empty confirmation over the API. Rebuilds, replication fixes, cluster rebalancing, role moves and max server memory use this.
- typed_target: the target’s name, typed back. Script fixes and high-risk analysis fixes use this. The level can depend on the request’s parameters, so the same fix kind asks for a typed name only when its risk is high.
- typed_word: a fixed word, which the registry supports for kinds that want one.
A geo failover is not a job, but it is gated the same way: the operator has
to type failover.
The levels were not always like this. The rebuild, the replication fixes and the cluster moves used to ask for the target’s name. They later moved to a plain confirmation. The disruptive ones kept their red buttons, and the typed name stayed where it adds something.
Schedules run as their owner§
A schedule is a saved request: the kind, the target reference, the
parameters and the confirmation its owner gave. The owner is whoever saved
the schedule last. When a run is due, the scheduler loads the owner’s
account, sets it as the acting user with the permissions of the owner’s
role as it is now, and calls the same request_job that the browser and
the API use. That gives a run several ways to be refused that a stored
grant would not:
- If the owner can no longer sign in, the run is refused, and the message says to save the schedule again as someone who can.
- If the owner has lost the schedule action jobs permission or the kind’s own permission, the run is refused.
- The stored confirmation is checked again against the target as it is now, so a renamed geo-cluster refuses a typed confirmation.
- A changing run only acts on the target that was confirmed. If the target
reference now resolves to a different localised cluster or environment,
for example after a failover that swapped live and DR, the run is refused
as
target_changeduntil someone looks at it and saves the schedule again. - A kind can refuse some combinations outright. A repeating rebuild cannot be forced to rebuild healthy replication. Only a one-off can, as a single decision made for one day.
Renaming a schedule or switching it off changes nothing it does. Switching it on, or changing when it runs, is a new decision to run the job, so it is checked as a new request from the editor, with the confirmation given again, and the editor becomes the owner. Every due run writes a row saying what happened, with one of five outcomes: queued, skipped, refused, missed or error.
-
01 DUE
One web worker wins the UPDATE that moves next_run_at forward. The others see nothing to do.
-
02 LATE? RULED OUT
More than the grace period late: recorded as missed, not fired.
-
03 AS OWNER
Owner loaded with their current role. Permission, confirmation and target identity checked again.
-
04 LOCK OBSERVED
The INSERT hits the partial unique index: skipped, not queued behind the other job.
-
05 QUEUED CONFIRMED
An ordinary job, requested via schedule, linked to its schedule.
Closing the loop: re-check what the job touched§
When a changing job ends as done, completed with warnings or failed (or a lost job is settled), the hosts it may have touched go to the front of the monitoring queue. That is its own host plus every member of its geo-cluster, or of its localised cluster if it has no geo-cluster, which is the same set the lock covered. Skipped and cancelled jobs changed nothing, so they do not trigger this.
This does not back-date anything. It sets a separate mark, and the check queue’s claim orders by it first:
ORDER BY recheck_requested_at IS NULL, next_run_at
next_run_at keeps its meaning, so the stuck-check alert is not fooled.
The awkward case is a host that is being checked at the moment the job
ends. That check may have read the old state. So the mark is left on a
locked row, and when that check completes, the mark is compared with the
moment the row was locked:
next_run_at = CASE WHEN recheck_requested_at > locked_at
THEN now() ELSE now() + :interval END
A check that started before the change is followed straight away by one that started after it.
Stopping a running job§
Originally only a queued job could be cancelled. A running job ran to its end, and if a replication rebuild was stuck in a copy that would take most of a day, the only way out was to open a shell in the executor container and find its processes by hand. Stopping a job is now a button and an API call, and the request travels back on the heartbeat:
-
01 ASK
stop_requested_at and stop_requested_by are set with COALESCE, so asking twice changes nothing and is audited once. A queued job gets 409, cancel it instead.
-
02 HEARTBEAT
The heartbeat's answer carries stop: true. A lost job is stopped as soon as its executor is heard from again.
-
03 SIGTERM
The executor writes a stop marker, then signals every process in the job's session except the session leader, which is the wrapper.
-
04 SIGKILL
Whatever is still alive after the grace period (60 s by default). Each step goes to the job log.
-
05 REPORTED CONFIRMED
The wrapper records the exit code. The job ends failed, result.stopped: true, "Stopped by <who>".
The executor finds the job’s processes by reading /proc/<pid>/stat for
every process and keeping those whose session id is the wrapper’s pid. The
wrapper started the job with a new session, so its pid is the session id.
The process name in that file can itself contain spaces and ), so the
fields are parsed from the last closing parenthesis.
Leaving the wrapper alone is the point of the design. If the wrapper were killed, nothing would write the exit code, and the job would look exactly like a vanished process. Because it survives, a stopped job is reported through the normal path. The stop marker on disk preserves the stopped outcome across an executor restart. A job that exited 0 before the signal reached it keeps its own outcome, because a stop only rewrites the result of a non-zero exit.
One deployment note followed from this. An older executor ignores the
stop field, so the portal and the executor had to ship together, or the
button would do nothing.
Audit rows, and one permissions matrix§
Every step a person takes on a job writes an audit row: requesting, cancelling, stopping and settling it. So does the executor reporting completion. Each row records the action, the host, the before and after values as JSON, the username (kept as text, so history survives the account being deleted), the client address, and the route the action came in by: the browser, the API with the token it used, a schedule, or a watcher acting automatically. A scheduled run is audited as its owner.
There is one trade-off here, and I made it on purpose. If writing the audit row fails, the failure is logged and the action goes ahead. Auditing never blocks the change it describes. The job row keeps its own record either way: who requested it, how they asked, what they confirmed and how it ended.
Permissions are declared in code, next to the feature that needs them, and stored in one matrix that admins edit. When the portal starts, it adds new permission keys, gives each new key its default roles only the first time it sees that key, so later edits are never overwritten, and deletes keys the code no longer has. Every action kind names its permission, and the portal refuses to start if a kind names a permission nobody registered.
The browser and the API read the same matrix. An API call is allowed only if the token owner’s role holds the endpoint’s permission, and the token’s scope caps that: a read-scope token can only call GET endpoints, whatever its owner may do. A script therefore has exactly the rights its owner would have in the browser, or fewer. Deleting an account, or revoking a token, that an executor is using mid-job is refused, because it would cut the executor off while its commands carry on.
Takeaway§
The rules in the command center note read like policy. Each one turned out to be a specific mechanism:
- one-change-per-target is a partial unique index that counts
lostas active; - claimed-once is a conditional
UPDATEwith a share lock on the executor’s own row; - every later write repeats the ownership predicate;
- a topology change and a job request serialise on the same advisory lock;
- a stop is a field on the heartbeat’s answer, and the process tree is signalled in a way that keeps the reporter alive.
Most of the work went into failure cases, not the normal path: a silent executor, a pid that has been reused, a check that started before the change, a schedule whose owner left, a failover under a queued rebuild. None of these is resolved by trying again. Each one has a defined outcome: lost, failed, skipped, refused or missed. A person makes the next decision.