Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(connectors): leader election for the scheduler (parity 6.8)

Beenu Arorafd988f3ebf9c
diff --git a/services/api/migrations/112_scheduler_leases.sql b/services/api/migrations/112_scheduler_leases.sql
new file mode 100644
index 000000000..a3d9a7915
--- /dev/null
+++ b/services/api/migrations/112_scheduler_leases.sql
@@ -0,0 +1,86 @@
+-- Depth plan 4.5 / parity 6.8 — leader election for the connector scheduler.
+--
+-- The problem
+-- -----------
+-- `ConnectorScheduler` adds one APScheduler job per enabled connector
+-- instance, in process. Two replicas therefore each run every job: every
+-- vendor is polled twice on every cycle, every page of results is fetched
+-- twice, and the duplicate events are deduplicated downstream at best. On
+-- a rate-limited vendor API it is worse than duplication — the second
+-- replica's poll is what gets 429'd, and a connector that is being
+-- throttled looks identical to one whose credentials have expired.
+--
+-- That is why the Helm chart pins `connectors` to one replica. A
+-- deployment that scales it for availability silently doubles its vendor
+-- call volume, which is the kind of change nobody attributes to a replica
+-- count.
+--
+-- Why a Postgres lease rather than the Kubernetes Lease API
+-- ---------------------------------------------------------
+-- Because the scheduler also runs under Docker Compose, under `make up`,
+-- and in a plain systemd unit, and a leader election that only works on
+-- Kubernetes is a leader election that is off wherever most first runs
+-- happen. Every deployment of this service already has Postgres; not
+-- every one has an API server or the RBAC to write a coordination object
+-- in its own namespace.
+--
+-- The shape
+-- ---------
+-- One row per scope. A holder renews it; a challenger may take it only
+-- once `expires_at` has passed. `UPDATE ... WHERE expires_at < now()` is
+-- the whole mechanism: Postgres takes a row lock, so a second challenger
+-- blocks and then re-evaluates the predicate against the committed row,
+-- finds a fresh expiry and matches nothing. A SELECT-then-UPDATE has no
+-- such re-evaluation and elects two leaders.
+--
+-- `fenced_at` is not used for mutual exclusion and is not a substitute
+-- for it. It is the monotonically increasing term number, recorded so a
+-- log can answer "which generation of the leader wrote this" after a
+-- network partition — the question an election without one cannot answer
+-- at all.
+
+CREATE TABLE IF NOT EXISTS scheduler_leases (
+ -- What is being led. One row per scope rather than one global row, so
+ -- a future second scheduler does not contend with this one.
+ scope TEXT PRIMARY KEY,
+ -- Who holds it. A hostname or pod name; carried for the log, never
+ -- compared for correctness except by the holder renewing its own.
+ holder TEXT NOT NULL,
+ -- The term. Incremented on every acquisition, never on a renewal.
+ fenced_at BIGINT NOT NULL DEFAULT 1,
+ acquired_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ renewed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ -- The only thing that decides whether a challenger may take over.
+ expires_at TIMESTAMPTZ NOT NULL
+);
+
+COMMENT ON TABLE scheduler_leases IS
+ 'Leader election for in-process schedulers. A Postgres lease rather than a Kubernetes Lease '
+ 'because the scheduler also runs under Compose and systemd, and an election that only works '
+ 'on Kubernetes is off wherever most first runs happen.';
+
+COMMENT ON COLUMN scheduler_leases.fenced_at IS
+ 'Term number, incremented on acquisition and not on renewal. Not used for mutual exclusion '
+ 'and not a substitute for it: it exists so a log can say which generation of the leader '
+ 'wrote a line after a partition.';
+
+-- Deliberately **not** tenant-scoped and deliberately without RLS.
+--
+-- A scheduler lease is infrastructure coordination between replicas of
+-- one deployment, not tenant data: it holds a hostname and two
+-- timestamps. Adding a tenant_id would be inventing a dimension the thing
+-- does not have, and a tenant-scoped RLS policy on a table the scheduler
+-- reads before it has resolved any tenant would make the election fail
+-- closed on every boot.
+--
+-- Stated here rather than left as an absence, because
+-- scripts/check_tenant_query_predicates.py reads migrations to learn
+-- which tables carry a policy, and a table with none and no reason looks
+-- like an oversight.
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN
+ EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON scheduler_leases TO aisoc_app';
+ END IF;
+END
+$$;
diff --git a/services/connectors/app/leader_lease.py b/services/connectors/app/leader_lease.py
new file mode 100644
index 000000000..38ca54e71
--- /dev/null
+++ b/services/connectors/app/leader_lease.py
@@ -0,0 +1,316 @@
+"""Leader election for the connector scheduler (parity 6.8 / depth 4.5).
+
+Why it is needed
+----------------
+``ConnectorScheduler`` adds one APScheduler job per enabled connector
+instance, in process. Two replicas therefore each run every job: every
+vendor is polled twice on every cycle. On a rate-limited vendor API that
+is worse than duplication, because the second replica's poll is what gets
+throttled and a throttled connector looks identical to one whose
+credentials have expired.
+
+Without this, `connectors` has to be pinned to one replica — which the
+Helm chart does — and a deployment that scales it for availability
+silently doubles its vendor call volume.
+
+The mechanism, and the one thing that makes it correct
+------------------------------------------------------
+``UPDATE scheduler_leases SET ... WHERE scope = :scope AND expires_at < now()``.
+
+Postgres takes a row lock on the UPDATE, so a second challenger blocks
+until the first commits and then re-evaluates the predicate against the
+committed row — finding a fresh expiry, matching nothing, and learning
+that it lost. A SELECT followed by an unconditional UPDATE has no such
+re-evaluation: both challengers read an expired lease and both become
+leader. That distinction is the whole of this module, and
+``tests/isolation/test_scheduler_lease_live.py`` proves it with two
+interleaved transactions rather than with a race, because a race between
+two coroutines on one loop passes under the broken implementation as
+well.
+
+What a lost lease means
+-----------------------
+A follower does not poll. A leader that fails to renew **stops polling
+before its lease expires**, not after: the renewal deadline is earlier
+than the expiry by a margin, so there is a window in which the old leader
+has stopped and no new one has started. That gap is deliberate. Polling
+twice is worse than polling late — late costs one cycle, twice costs the
+vendor's rate limit — and a design that overlaps instead would have to
+assume the two clocks agree.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import os
+import socket
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncEngine
+
+logger = logging.getLogger(__name__)
+
+#: The scope this scheduler leads. One row per scope, so a future second
+#: scheduler does not contend with this one.
+CONNECTOR_SCHEDULER_SCOPE = "connector-scheduler"
+
+#: How long a lease is valid once taken. Long enough that an ordinary
+#: garbage-collection pause or a slow query does not lose it; short enough
+#: that a replica which dies is replaced within a poll cycle. The default
+#: poll cadence is five minutes, so a 90-second lease means at most one
+#: missed cycle.
+DEFAULT_LEASE_SECONDS = 90.0
+
+#: How often the holder renews. A third of the lease, so two consecutive
+#: renewals can fail before the lease is lost — one failed renewal is a
+#: transient database blip and should not cause a leadership change.
+#:
+#: The relation is what matters, not either number: renewal must be
+#: strictly less than the lease with room for at least two attempts. A
+#: test asserts the relation rather than the values, because two constants
+#: describing one budget and drifting apart is how this repository came to
+#: have a retry capped at a sixth of its own window.
+RENEW_FRACTION = 1.0 / 3.0
+
+_ENABLED_ENV = "AISOC_SCHEDULER_LEADER_ELECTION"
+_LEASE_ENV = "AISOC_SCHEDULER_LEASE_SECONDS"
+
+
+def election_enabled() -> bool:
+ """Whether to elect at all.
+
+ Off by default. A single-replica deployment — which is every Compose
+ install and the chart's own default — gains nothing from an election
+ and would gain a new way to fail to start if Postgres is slow. The
+ Helm values turn it on, because that is where a second replica is
+ possible.
+ """
+ return os.environ.get(_ENABLED_ENV, "false").strip().lower() in {"1", "true", "yes"}
+
+
+def lease_seconds() -> float:
+ raw = os.environ.get(_LEASE_ENV, "").strip()
+ if not raw:
+ return DEFAULT_LEASE_SECONDS
+ try:
+ value = float(raw)
+ except ValueError:
+ logger.error("scheduler.lease.bad_duration value=%r using=%s", raw, DEFAULT_LEASE_SECONDS)
+ return DEFAULT_LEASE_SECONDS
+ # A lease shorter than two renewal intervals cannot survive one failed
+ # renewal, which turns every database blip into a leadership change.
+ if value < 10.0:
+ logger.error("scheduler.lease.too_short value=%s using=%s", value, DEFAULT_LEASE_SECONDS)
+ return DEFAULT_LEASE_SECONDS
+ return value
+
+
+def renew_interval(lease: float) -> float:
+ return lease * RENEW_FRACTION
+
+
+def holder_identity() -> str:
+ """Who this process is, for the log.
+
+ The pod name when Kubernetes supplies one, the hostname otherwise.
+ Never compared for correctness except by the holder renewing its own
+ lease; a lease is held by whoever last satisfied the predicate, not by
+ whoever has the right name.
+ """
+ for env in ("POD_NAME", "HOSTNAME"):
+ value = os.environ.get(env, "").strip()
+ if value:
+ return value
+ with contextlib.suppress(OSError):
+ return socket.gethostname()
+ return "unknown"
+
+
+@dataclass
+class LeaseState:
+ held: bool
+ holder: str
+ term: int
+ expires_at: datetime | None
+
+
+#: Taking a lease nobody holds, or one that has expired. `fenced_at`
+#: increments only here, never on renewal, so the term counts leadership
+#: changes rather than heartbeats.
+_ACQUIRE_SQL = text(
+ """
+ INSERT INTO scheduler_leases (scope, holder, fenced_at, acquired_at, renewed_at, expires_at)
+ VALUES (:scope, :holder, 1, now(), now(), now() + make_interval(secs => :lease))
+ ON CONFLICT (scope) DO UPDATE
+ SET holder = EXCLUDED.holder,
+ fenced_at = scheduler_leases.fenced_at + 1,
+ acquired_at = now(),
+ renewed_at = now(),
+ expires_at = now() + make_interval(secs => :lease)
+ WHERE scheduler_leases.expires_at < now()
+ RETURNING fenced_at, expires_at
+ """
+)
+
+#: Renewing. Conditional on still being the holder *and* on the lease not
+#: having already lapsed: a process that was paused past its expiry must
+#: not resume and renew a lease someone else has taken.
+_RENEW_SQL = text(
+ """
+ UPDATE scheduler_leases
+ SET renewed_at = now(),
+ expires_at = now() + make_interval(secs => :lease)
+ WHERE scope = :scope
+ AND holder = :holder
+ AND expires_at >= now()
+ RETURNING fenced_at, expires_at
+ """
+)
+
+#: Releasing on a clean shutdown, so a rolling restart does not wait out
+#: the whole lease with nobody polling.
+_RELEASE_SQL = text(
+ """
+ UPDATE scheduler_leases
+ SET expires_at = now()
+ WHERE scope = :scope AND holder = :holder
+ """
+)
+
+
+class LeaderLease:
+ """Acquire, renew and release one scope's lease."""
+
+ def __init__(
+ self,
+ engine: AsyncEngine,
+ *,
+ scope: str = CONNECTOR_SCHEDULER_SCOPE,
+ holder: str | None = None,
+ lease: float | None = None,
+ ) -> None:
+ self._engine = engine
+ self._scope = scope
+ self._holder = holder or holder_identity()
+ self._lease = lease if lease is not None else lease_seconds()
+ self._term = 0
+ self._held = False
+
+ @property
+ def holder(self) -> str:
+ return self._holder
+
+ @property
+ def lease_seconds(self) -> float:
+ return self._lease
+
+ @property
+ def renew_after(self) -> float:
+ return renew_interval(self._lease)
+
+ @property
+ def held(self) -> bool:
+ return self._held
+
+ @property
+ def term(self) -> int:
+ return self._term
+
+ async def acquire(self) -> bool:
+ """Try to become leader. Returns whether this process now leads."""
+ async with self._engine.begin() as conn:
+ row = (await conn.execute(_ACQUIRE_SQL, {"scope": self._scope, "holder": self._holder, "lease": self._lease})).first()
+ if row is None:
+ self._held = False
+ return False
+ self._term = int(row[0])
+ self._held = True
+ logger.info(
+ "scheduler.lease.acquired scope=%s holder=%s term=%s expires=%s",
+ self._scope,
+ self._holder,
+ self._term,
+ row[1],
+ )
+ return True
+
+ async def renew(self) -> bool:
+ """Extend the lease. Returns whether it is still held.
+
+ A ``False`` here is a leadership loss and the caller must stop
+ scheduling. It is not an error to retry past: the lease has gone
+ to someone else, or this process was paused past its own expiry,
+ and continuing to poll in either case is the double-poll this
+ exists to prevent.
+ """
+ async with self._engine.begin() as conn:
+ row = (await conn.execute(_RENEW_SQL, {"scope": self._scope, "holder": self._holder, "lease": self._lease})).first()
+ if row is None:
+ if self._held:
+ logger.warning(
+ "scheduler.lease.lost scope=%s holder=%s term=%s — stopping scheduling",
+ self._scope,
+ self._holder,
+ self._term,
+ )
+ self._held = False
+ return False
+ self._held = True
+ return True
+
+ async def release(self) -> None:
+ """Give the lease up on a clean shutdown.
+
+ Best effort and never raising: a shutdown path that can fail is a
+ shutdown path that leaves a pod terminating. The worst case is the
+ lease expiring on its own, which is the same outcome one lease
+ period later.
+ """
+ try:
+ async with self._engine.begin() as conn:
+ await conn.execute(_RELEASE_SQL, {"scope": self._scope, "holder": self._holder})
+ except Exception as exc: # noqa: BLE001 — see the docstring
+ logger.warning("scheduler.lease.release_failed scope=%s error=%s", self._scope, exc)
+ finally:
+ self._held = False
+
+ async def state(self) -> LeaseState:
+ """What readiness reports.
+
+ A follower is healthy. The thing worth surfacing is *which* it is,
+ because a deployment where every replica is a follower — which a
+ clock skew or a stuck row can produce — is one where nothing is
+ polling, and every replica reporting 200 is how that stays
+ invisible.
+ """
+ async with self._engine.connect() as conn:
+ row = (
+ await conn.execute(
+ text("SELECT holder, fenced_at, expires_at FROM scheduler_leases WHERE scope = :scope"),
+ {"scope": self._scope},
+ )
+ ).first()
+ if row is None:
+ return LeaseState(held=False, holder="", term=0, expires_at=None)
+ expires = row[2]
+ if expires is not None and expires.tzinfo is None:
+ expires = expires.replace(tzinfo=UTC)
+ return LeaseState(
+ held=row[0] == self._holder and expires is not None and expires > datetime.now(UTC),
+ holder=str(row[0]),
+ term=int(row[1]),
+ expires_at=expires,
+ )
+
+
+def lease_is_longer_than_two_renewals(lease: float) -> bool:
+ """The relation the two constants have to keep.
+
+ Asserted by a test rather than left to the numbers: two constants
+ describing one budget and drifting apart is how this repository came
+ to have a documented retry capped at a sixth of its own window.
+ """
+ return lease > 2 * renew_interval(lease) + timedelta(seconds=0).total_seconds()
diff --git a/services/connectors/app/scheduler.py b/services/connectors/app/scheduler.py
index 89625c91e..eecd29f8c 100644
--- a/services/connectors/app/scheduler.py
+++ b/services/connectors/app/scheduler.py
@@ -49,6 +49,7 @@ Design rationale
from __future__ import annotations
+import contextlib
import json
import logging
import os
@@ -71,6 +72,7 @@ from app.db.connector_repo import (
)
from app.db.engine import get_engine
from app.ingest_client import IngestClient, IngestClientError
+from app.leader_lease import LeaderLease, election_enabled
from app.pipeline import (
apply_filter_rules,
compute_fingerprint,
@@ -171,6 +173,9 @@ class ConnectorScheduler:
self._vault = vault
self._reload_interval_s = reload_interval_seconds
self._scheduler: AsyncIOScheduler | None = None
+ # None when leader election is off, which is the default and
+ # means this replica always schedules.
+ self._lease: LeaderLease | None = None
# Cache of {connector_id_str: last_seen_config_signature} so reloads
# can detect when an instance's poll interval / config changed and
# need its job rescheduled, vs leaving an unchanged job alone.
@@ -202,9 +207,41 @@ class ConnectorScheduler:
logger.error("connector.scheduler.vault_unavailable: %s", exc)
raise
+ # Parity 6.8. Without an election, two replicas each add one job
+ # per connector instance and every vendor is polled twice on every
+ # cycle — which on a rate-limited API is worse than duplication,
+ # because the second replica's poll is what gets throttled and a
+ # throttled connector looks identical to one whose credentials
+ # expired. Off by default: a single-replica deployment gains
+ # nothing from an election and gains a new way to fail to start.
+ if election_enabled():
+ self._lease = LeaderLease(self._engine)
+ if not await self._lease.acquire():
+ state = await self._lease.state()
+ logger.info(
+ "connector.scheduler.follower holder=%s term=%s — not scheduling any poll jobs",
+ state.holder,
+ state.term,
+ )
+
self._scheduler = AsyncIOScheduler(timezone="UTC")
self._scheduler.start()
+ if self._lease is not None:
+ # Renewal runs whether or not this replica is the leader: a
+ # follower has to keep trying to acquire, or a dead leader is
+ # never replaced. The same job does both, because "renew if I
+ # hold it, otherwise try to take it" is one decision.
+ self._scheduler.add_job(
+ self._maintain_lease,
+ "interval",
+ seconds=self._lease.renew_after,
+ id="_leader_lease",
+ replace_existing=True,
+ max_instances=1,
+ coalesce=True,
+ )
+
# Fire one reload immediately so we don't wait
# ``reload_interval`` seconds for the first poll cycle.
await self.reload_jobs()
@@ -238,6 +275,56 @@ class ConnectorScheduler:
self._reload_interval_s,
)
+ def _remove_all_poll_jobs(self) -> None:
+ """Drop every connector poll job, keeping the control jobs.
+
+ Called when leadership is lost. The reload and lease jobs stay,
+ because a follower still has to notice when the leader dies.
+ """
+ if self._scheduler is None:
+ return
+ keep = {"_reload_loop", "_leader_lease", "_vuln_promotion_loop"}
+ removed = 0
+ for job in list(self._scheduler.get_jobs()):
+ if job.id in keep:
+ continue
+ with contextlib.suppress(Exception):
+ self._scheduler.remove_job(job.id)
+ removed += 1
+ self._known_signatures.clear()
+ if removed:
+ logger.info("connector.scheduler.follower_dropped_jobs count=%s", removed)
+
+ def _is_leader(self) -> bool:
+ """Whether this replica should be scheduling polls.
+
+ True when election is off, which is the default: a deployment
+ that has not asked for an election must not stop polling because
+ a lease table it never populated says nobody leads.
+ """
+ return self._lease is None or self._lease.held
+
+ async def _maintain_lease(self) -> None:
+ """Renew the lease, or try to take one.
+
+ A leadership change in either direction reshapes the job set, and
+ it does so by calling the same reload the periodic job calls — a
+ second code path for "schedule everything" is a second place for
+ the two to disagree about what everything is.
+ """
+ lease = self._lease
+ if lease is None:
+ return
+ was_leader = lease.held
+ still_leader = await lease.renew() if was_leader else await lease.acquire()
+ if still_leader == was_leader:
+ return
+ if still_leader:
+ logger.info("connector.scheduler.became_leader term=%s", lease.term)
+ else:
+ logger.warning("connector.scheduler.lost_leadership term=%s", lease.term)
+ await self.reload_jobs()
+
async def stop(self) -> None:
"""Stop the scheduler and release resources."""
if self._scheduler is not None:
@@ -270,6 +357,16 @@ class ConnectorScheduler:
# called. Either way: nothing to do.
return
+ if not self._is_leader():
+ # A follower removes whatever it was running rather than just
+ # declining to add more. A replica that loses leadership while
+ # holding jobs keeps polling every vendor from the jobs it
+ # already had, which is the double-poll the election exists to
+ # prevent — only now it is invisible, because the follower is
+ # reporting itself as a follower.
+ self._remove_all_poll_jobs()
+ return
+
try:
async with self._engine.begin() as conn:
instances = await fetch_enabled_connectors(conn)
diff --git a/tests/isolation/test_scheduler_lease_live.py b/tests/isolation/test_scheduler_lease_live.py
new file mode 100644
index 000000000..7b62595e2
--- /dev/null
+++ b/tests/isolation/test_scheduler_lease_live.py
@@ -0,0 +1,226 @@
+"""Only one connector scheduler leads, against real Postgres (depth 4.5).
+
+Without an election, two replicas each add one APScheduler job per
+connector instance and every vendor is polled twice on every cycle — and
+on a rate-limited API that is worse than duplication, because the second
+replica's poll is what gets throttled and a throttled connector looks
+identical to one whose credentials expired.
+
+The election is one conditional UPDATE, and the only way to show it works
+is to run two of them against one row. The interleaving is **forced**
+rather than raced: two coroutines on one loop can serialise by luck, and
+a concurrency test that cannot fail on the broken implementation is not a
+concurrency test — measured on this repository's own lake-job claim,
+where a five-way `asyncio.gather` passed under a SELECT-then-UPDATE.
+
+Skips when ``ISOLATION_LEASE_DSN`` is unset; the workflow that owns this
+suite sets it unconditionally.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import uuid
+
+import pytest
+import pytest_asyncio
+
+pytestmark = [
+ pytest.mark.asyncio(loop_scope="module"),
+ pytest.mark.skipif(
+ not os.environ.get("ISOLATION_LEASE_DSN", "").strip(),
+ reason="ISOLATION_LEASE_DSN is not set; this suite needs a live Postgres",
+ ),
+]
+
+
+def _dsn() -> str:
+ value = os.environ.get("ISOLATION_LEASE_DSN", "").strip()
+ if not value:
+ pytest.skip("ISOLATION_LEASE_DSN is not set")
+ if value.startswith("postgresql://"):
+ return value.replace("postgresql://", "postgresql+asyncpg://", 1)
+ return value
+
+
+@pytest_asyncio.fixture(scope="module", loop_scope="module")
+async def engine():
+ from sqlalchemy.ext.asyncio import create_async_engine
+
+ eng = create_async_engine(_dsn())
+ try:
+ yield eng
+ finally:
+ await eng.dispose()
+
+
+@pytest_asyncio.fixture(loop_scope="module")
+async def scope(engine):
+ """A fresh scope per test, removed afterwards."""
+ from sqlalchemy import text
+
+ name = f"test-scope-{uuid.uuid4().hex[:12]}"
+ yield name
+ async with engine.begin() as conn:
+ await conn.execute(text("DELETE FROM scheduler_leases WHERE scope = :s"), {"s": name})
+
+
+def _lease(engine, scope: str, holder: str, seconds: float = 90.0):
+ from app.leader_lease import LeaderLease
+
+ return LeaderLease(engine, scope=scope, holder=holder, lease=seconds)
+
+
+class TestOnlyOneLeader:
+ async def test_two_replicas_racing_for_a_free_lease_produce_one_leader(self, engine, scope):
+ a = _lease(engine, scope, "replica-a")
+ b = _lease(engine, scope, "replica-b")
+ results = await asyncio.gather(a.acquire(), b.acquire())
+ assert sum(1 for won in results if won) == 1, f"acquisitions: {results}"
+
+ async def test_two_interleaved_transactions_cannot_both_take_an_expired_lease(
+ self, engine, scope
+ ):
+ """The deterministic proof, not a race.
+
+ The first challenger runs the acquire and **holds its
+ transaction open**; the second runs the same statement and
+ blocks on the row lock; the first commits; the second unblocks
+ and re-evaluates `expires_at < now()` against the committed row,
+ finds a fresh expiry, and matches nothing.
+ """
+ from sqlalchemy import text
+
+ # Seed an expired lease so both challengers see one going spare.
+ async with engine.begin() as conn:
+ await conn.execute(
+ text(
+ "INSERT INTO scheduler_leases (scope, holder, fenced_at, expires_at) "
+ "VALUES (:s, 'dead-replica', 7, now() - interval '1 minute')"
+ ),
+ {"s": scope},
+ )
+
+ from app.leader_lease import _ACQUIRE_SQL # noqa: PLC0415
+
+ first: list[bool] = []
+ second: list[bool] = []
+ first_has_run = asyncio.Event()
+
+ async def challenger_a() -> None:
+ async with engine.connect() as conn:
+ await conn.begin()
+ row = (
+ await conn.execute(_ACQUIRE_SQL, {"scope": scope, "holder": "a", "lease": 90.0})
+ ).first()
+ first.append(row is not None)
+ first_has_run.set()
+ await asyncio.sleep(0.5)
+ await conn.commit()
+
+ async def challenger_b() -> None:
+ await first_has_run.wait()
+ await asyncio.sleep(0.1)
+ async with engine.connect() as conn:
+ await conn.begin()
+ row = (
+ await conn.execute(_ACQUIRE_SQL, {"scope": scope, "holder": "b", "lease": 90.0})
+ ).first()
+ second.append(row is not None)
+ await conn.commit()
+
+ await asyncio.gather(challenger_a(), challenger_b())
+
+ assert first == [True], "the first challenger did not take the expired lease"
+ assert second == [False], (
+ "both replicas took the lease; every vendor would be polled twice on every cycle"
+ )
+
+ async def test_a_held_lease_cannot_be_stolen(self, engine, scope):
+ a = _lease(engine, scope, "replica-a")
+ assert await a.acquire() is True
+ b = _lease(engine, scope, "replica-b")
+ assert await b.acquire() is False, "a live lease was taken from its holder"
+
+ async def test_an_expired_lease_is_taken_over(self, engine, scope):
+ dying = _lease(engine, scope, "replica-a", seconds=1.0)
+ assert await dying.acquire() is True
+ await asyncio.sleep(1.2)
+ taking = _lease(engine, scope, "replica-b")
+ assert await taking.acquire() is True
+
+
+class TestRenewal:
+ async def test_the_holder_renews(self, engine, scope):
+ a = _lease(engine, scope, "replica-a")
+ await a.acquire()
+ assert await a.renew() is True
+ assert a.held is True
+
+ async def test_a_non_holder_cannot_renew(self, engine, scope):
+ a = _lease(engine, scope, "replica-a")
+ await a.acquire()
+ b = _lease(engine, scope, "replica-b")
+ assert await b.renew() is False
+
+ async def test_a_process_paused_past_its_expiry_cannot_resume_and_renew(self, engine, scope):
+ """The window that matters. A replica stopped for longer than its
+ lease must not come back and renew one somebody else now holds."""
+ a = _lease(engine, scope, "replica-a", seconds=1.0)
+ await a.acquire()
+ await asyncio.sleep(1.2)
+ assert await a.renew() is False, "a lapsed holder renewed its own expired lease"
+
+ async def test_renewal_does_not_advance_the_term(self, engine, scope):
+ # The term counts leadership changes. A heartbeat that incremented
+ # it would make the number useless for the one question it answers.
+ a = _lease(engine, scope, "replica-a")
+ await a.acquire()
+ before = a.term
+ await a.renew()
+ assert (await a.state()).term == before
+
+ async def test_acquisition_after_a_takeover_advances_the_term(self, engine, scope):
+ a = _lease(engine, scope, "replica-a", seconds=1.0)
+ await a.acquire()
+ first_term = a.term
+ await asyncio.sleep(1.2)
+ b = _lease(engine, scope, "replica-b")
+ await b.acquire()
+ assert b.term == first_term + 1
+
+
+class TestRelease:
+ async def test_releasing_lets_the_next_replica_in_without_waiting(self, engine, scope):
+ # A rolling restart that waited out the whole lease would leave
+ # nobody polling for its full duration.
+ a = _lease(engine, scope, "replica-a")
+ await a.acquire()
+ await a.release()
+ b = _lease(engine, scope, "replica-b")
+ assert await b.acquire() is True
+
+ async def test_release_never_raises(self, engine, scope):
+ # A shutdown path that can fail is a pod stuck terminating.
+ a = _lease(engine, scope, "replica-a")
+ await a.release()
+ assert a.held is False
+
+
+class TestState:
+ async def test_state_names_the_holder_so_an_all_follower_deployment_is_visible(
+ self, engine, scope
+ ):
+ a = _lease(engine, scope, "replica-a")
+ await a.acquire()
+ b = _lease(engine, scope, "replica-b")
+ state = await b.state()
+ assert state.held is False
+ assert state.holder == "replica-a"
+ assert state.expires_at is not None
+
+ async def test_an_unclaimed_scope_reports_no_holder(self, engine, scope):
+ state = await _lease(engine, scope, "replica-a").state()
+ assert state.held is False
+ assert state.holder == ""