Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
RDS: replicated Aurora PostgreSQL readers survive Stop/Start and warm boot (#1440)
kiran01bme2c3dbf22ef6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 037c01ad..77c50cd4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **RDS — replicated Aurora PostgreSQL readers survive StopDBCluster / StartDBCluster and warm boot** — stopping a cluster with replicating readers was refused with `InvalidDBClusterStateFault` (the follow-up slice of #1325 the reader feature shipped without), and a MiniStack restart demoted a persisted reader to an alias of the writer's shared container. `StopDBCluster` now stops the writer's container and every reader-owned standby container — a stop that fails on any of them rolls back what it stopped and reports the failure instead of publishing `stopped` — and `StartDBCluster` restarts the writer, waits for it to accept authenticated connections, then revives each reader by re-cloning from the writer at its current address, keeping the member's identity, endpoint, and volume name (reader compute owns no durable state, as on Aurora, so revival recreates the container rather than restarting it). The same revival runs on warm boot. A revival that genuinely fails lands the cluster back on `stopped` for retry; only when compute deliberately cannot come back (control-plane-only restore, or the replication flag withdrawn between runs) does the member fall back to aliasing the writer, releasing its former container and volume, instead of advertising an endpoint nothing serves. Contributed by @kiran01bm.### Fixed- **RDS — global Aurora stop/start preserves topology and MySQL replication** — `StopDBCluster` and `StartDBCluster` allowed individual members of a multi-cluster Aurora global database to transition independently, and deleting a primary's last instance stopped shared compute that secondaries still needed. Starts and stops are now limited to sole-member global databases (`InvalidDBClusterStateFault`, 400), last-instance deletion preserves compute while other global members exist, and a successful recreate resets stale MySQL replica state before reconfiguring or deferring replication after readiness without overwriting a deliberate legacy-volume failure. Contributed by @kiran01bm.### Addeddiff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 81cd6e4d..944faeb5 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -366,12 +366,6 @@ def restore_state(data):account_id, region, instance_id = keyinst["_docker_container_id"] = Noneinst["DBInstanceStatus"] = "creating"- # Warm boot of per-instance reader containers is not implemented- # yet (#1325 slice 3). Demote a persisted replicating reader to a- # shared-container alias member so the restored cluster is fully- # usable instead of leaving a reader that points at a container- # the restart killed.- inst.pop("_pg_standby", None)if RDS_PERSIST:inst.setdefault("_docker_volume_name",@@ -532,6 +526,10 @@ def restore_state(data):member.get("_docker_volume_name")for member in membersif member.get("_docker_volume_name")+ # A replicating reader's volume is live compute state+ # (#1325), not a superseded pre-migration member volume; its+ # revival below remounts it.+ and not member.get("_pg_standby")}adopted_volume = cluster.get("_shared_volume_name")if not adopted_volume and writer is not None:@@ -688,10 +686,22 @@ def restore_state(data):if result.get("started"):status = "creating"for member in members:+ if (+ member.get("_pg_standby")+ and not result.get("started")+ and not result.get("failed")+ ):+ # Control-plane-only restore: no reader container is+ # coming back, so the member falls back to aliasing the+ # writer (#1325).+ _demote_pg_standby_to_alias(+ member, cluster, "no cluster compute on warm boot",+ )_attach_instance_to_shared_cluster(member, cluster)member["DBInstanceStatus"] = status_sync_cluster_endpoints(cluster)+ standbys_to_revive = []if result.get("started"):container_id = cluster.get("_shared_container_id")container_epoch = result.get("container_epoch")@@ -807,11 +817,27 @@ def restore_state(data):member = _instances.get(current_member.get("DBInstanceIdentifier"),)- if member is not None:- _attach_instance_to_shared_cluster(member, cluster)- member["DBInstanceStatus"] = status+ if member is None:+ continue+ if member.get("_pg_standby") and authenticated_ready:+ # A replicating reader's compute is revived+ # outside the lock below (#1325); the writer+ # becoming ready does not make a reader whose+ # container the host restart killed available.+ standbys_to_revive.append(member)+ continue+ _attach_instance_to_shared_cluster(member, cluster)+ member["DBInstanceStatus"] = status_sync_cluster_endpoints(cluster)_refresh_cluster_status(cluster_id)+ for member in standbys_to_revive:+ if not _revive_pg_reader(+ member["DBInstanceIdentifier"], member, cluster,+ ):+ # The failed revival landed the cluster back on+ # stopped; reviving further standbys would race+ # that transition.+ breakelse:cluster["_shared_container_ready"] = status == "available"@@ -1390,11 +1416,39 @@ def _bg_finalize_pg_reader(db_id, container_id, instance.get("_docker_volume_name"),)return+ if cluster.get("Status") == "stopped":+ # StopDBCluster stopped this standby's container along with the+ # writer's. That is a parked reader, not a dead one: its+ # container and volume are preserved, and StartDBCluster revives+ # it with a fresh worker.+ return+ if cluster.get("Status") == "stopping":+ # StopDBCluster is mid-flight. It either lands on ``stopped``+ # (handled above on the next pass) or fails, rolls this+ # container back to running, and restores ``available`` —+ # keep waiting rather than mistaking the stop for a death.+ time.sleep(1)+ continue+ if instance.get("DBInstanceStatus") == "stopped":+ # A failed StopDBCluster's rollback could not restart this+ # standby's container and parked the member instead. Preserved+ # compute, not a bootstrap failure: a StopDBCluster retry and+ # StartDBCluster bring it back.+ returnif not _container_alive():- instance["DBInstanceStatus"] = "failed"- _remove_failed_pg_reader_compute(- db_id, container_id, instance.get("_docker_volume_name"),- )+ with _shared_container_lock:+ # StopDBCluster stops containers while holding this lock and+ # publishes ``stopping`` before taking it; serialize with it+ # so a container it just stopped is not destroyed as dead.+ current = _clusters.get(cluster_id)+ if current is cluster and cluster.get("Status") in (+ "stopping", "stopped",+ ):+ continue+ instance["DBInstanceStatus"] = "failed"+ _remove_failed_pg_reader_compute(+ db_id, container_id, instance.get("_docker_volume_name"),+ )_refresh_cluster_status(cluster_id)returnif cluster.get(@@ -1412,14 +1466,26 @@ def _bg_finalize_pg_reader(if instance is None or _stale(instance):returnif not database_ready:- logger.warning(- "RDS: reader container for %s at %s:%s exited before becoming "- "reachable", db_id, ready_host, ready_port,- )- instance["DBInstanceStatus"] = "failed"- _remove_failed_pg_reader_compute(- db_id, container_id, instance.get("_docker_volume_name"),- )+ with _shared_container_lock:+ # A stop landing while this worker was inside the readiness wait+ # kills the container deliberately. Same park-don't-destroy rule+ # as the pre-wait loop: the stopped container and its volume are+ # exactly what StartDBCluster revives.+ stop_intervened = (+ cluster is not None+ and _clusters.get(cluster_id) is cluster+ and cluster.get("Status") in ("stopping", "stopped")+ )+ if stop_intervened or instance.get("DBInstanceStatus") == "stopped":+ return+ logger.warning(+ "RDS: reader container for %s at %s:%s exited before "+ "becoming reachable", db_id, ready_host, ready_port,+ )+ instance["DBInstanceStatus"] = "failed"+ _remove_failed_pg_reader_compute(+ db_id, container_id, instance.get("_docker_volume_name"),+ )_refresh_cluster_status(cluster_id)returninstance["DBInstanceStatus"] = "available"@@ -1432,6 +1498,206 @@ def _bg_finalize_pg_reader()+def _demote_pg_standby_to_alias(instance, cluster, reason):+ """Demote a replicating reader to a shared-container alias member.++ The fallback when a reader's per-instance compute cannot come (or come+ back): the member stays usable through the writer's shared container —+ the flag-off behavior — instead of advertising an endpoint no container+ serves.++ Demotion is also the last moment the member still references its owned+ compute: ``_attach_instance_to_shared_cluster`` overwrites the container+ id and nulls the volume name, so anything not removed here is orphaned —+ and a container left holding the reserved instance name would 409 a+ later CreateDBInstance under the same identifier. Removal is best-effort+ (no Docker means nothing can be removed, and the stale-name sweep on+ creation remains the backstop).+ """+ db_id = instance.get("DBInstanceIdentifier")+ docker_client = _get_docker()+ if docker_client:+ identifiers = []+ recorded = instance.get("_docker_container_id")+ if recorded and recorded != cluster.get("_shared_container_id"):+ identifiers.append(recorded)+ reserved_name = _rds_docker_name(db_id)+ if reserved_name not in identifiers:+ identifiers.append(reserved_name)+ for identifier in identifiers:+ try:+ stale = docker_client.containers.get(identifier)+ except Exception:+ continue+ try:+ stale.remove(force=True, v=False)+ except Exception as e:+ logger.warning(+ "RDS: failed to remove container %s of demoted reader "+ "%s: %s", identifier, db_id, e,+ )+ volume_name = instance.get("_docker_volume_name")+ if volume_name and volume_name != cluster.get("_shared_volume_name"):+ try:+ docker_client.volumes.get(volume_name).remove()+ except Exception as e:+ logger.warning(+ "RDS: failed to remove volume of demoted reader %s: %s",+ db_id, e,+ )+ instance.pop("_pg_standby", None)+ _attach_instance_to_shared_cluster(instance, cluster)+ logger.warning(+ "RDS: demoted replicating reader %s to a shared-container alias "+ "member: %s",+ instance.get("DBInstanceIdentifier"), reason,+ )+++def _revive_pg_reader(db_id, instance, cluster):+ """Recreate a replicating reader's compute after StopDBCluster →+ StartDBCluster or a warm boot (#1325 slice 3).++ Reader compute is stateless — as in real Aurora, where reader instances+ own no durable storage — so revival recreates the container and+ re-clones from the writer instead of restarting the stopped one. A+ restarted container would re-run its bootstrap with the writer address+ baked into its environment at creation, which the writer's own restart+ may have changed; recreation always targets the writer's current+ address. Falls back to shared-container aliasing when per-instance+ replication cannot run here, and lands the cluster back on ``stopped``+ when the launch genuinely failed, so the start can be retried.++ Returns False when the revival failed and the caller should stop+ reviving further standbys (the cluster has been returned to+ ``stopped``); True otherwise.+ """+ cluster_id = cluster["DBClusterIdentifier"]+ if not _pg_cluster_replication_enabled(cluster):+ # The opt-in can be withdrawn between runs; a persisted standby must+ # not outlive the flag that created it.+ _demote_pg_standby_to_alias(+ instance, cluster,+ "MINISTACK_RDS_PG_CLUSTER_REPLICATION is off",+ )+ instance["DBInstanceStatus"] = "available"+ _sync_cluster_endpoints(cluster)+ _refresh_cluster_status(cluster_id)+ return True+ docker_client = _get_docker()+ if docker_client:+ # Free the reserved container name (and the recorded container, if+ # different) before relaunching under the same identifier. The old+ # standby's data is at most a stale clone, so removal loses nothing.+ identifiers = []+ recorded = instance.get("_docker_container_id")+ if recorded and recorded != cluster.get("_shared_container_id"):+ identifiers.append(recorded)+ reserved_name = _rds_docker_name(db_id)+ if reserved_name not in identifiers:+ identifiers.append(reserved_name)+ for identifier in identifiers:+ try:+ stale = docker_client.containers.get(identifier)+ except Exception:+ continue+ try:+ stale.remove(force=True, v=False)+ except Exception as e:+ logger.warning(+ "RDS: failed to remove stale reader container %s for "+ "%s: %s", identifier, db_id, e,+ )+ revive_epoch = int(cluster.get("_shared_container_epoch", 0))+ launch = _start_pg_reader_container(db_id, cluster)+ if launch is None:+ _demote_pg_standby_to_alias(+ instance, cluster,+ "per-instance replication cannot run here",+ )+ instance["DBInstanceStatus"] = "available"+ _sync_cluster_endpoints(cluster)+ _refresh_cluster_status(cluster_id)+ return True+ if not launch.get("started"):+ # Real AWS lands a failed start back on ``stopped`` — never on a+ # transitional status (see _fail_start in _start_db_cluster). A+ # reader marked ``failed`` here would drive the cluster to+ # ``creating``, where StartDBCluster and StopDBCluster are both+ # rejected and the cluster is wedged until the instance is deleted.+ # Instead, park the cluster's compute again and land everything back+ # on ``stopped`` so StartDBCluster can simply be retried. The member+ # keeps its standby identity for that retry.+ logger.warning(+ "RDS: failed to revive replicating reader %s; returning cluster "+ "%s to stopped for retry", db_id, cluster_id,+ )+ if _stop_cluster_shared_container(cluster_id, cluster):+ cluster["Status"] = "stopped"+ for member in _cluster_member_instances(cluster):+ member["DBInstanceStatus"] = "stopped"+ else:+ # The fail-back stop itself failed: the writer (and any+ # already-revived reader) is still serving, so publishing+ # ``stopped`` would lie. Keep the cluster available, publish+ # only this member as stopped, and let the ReaderEndpoint fall+ # back to compute that exists.+ cluster["_shared_container_ready"] = True+ cluster["Status"] = "available"+ instance["DBInstanceStatus"] = "stopped"+ _sync_cluster_endpoints(cluster)+ return False+ with _shared_container_lock:+ # The Docker launch above is slow; re-verify this worker is still+ # acting on live records (mirrors the restore and start paths). A+ # concurrent DeleteDBInstance, cluster teardown, or Stop/Start+ # (epoch bump) supersedes this revival: remove the just-created+ # compute instead of publishing it onto a stale record.+ if (+ _instances.get(db_id) is not instance+ or _clusters.get(cluster_id) is not cluster+ or int(cluster.get("_shared_container_epoch", 0)) != revive_epoch+ ):+ _remove_failed_pg_reader_compute(+ db_id, launch.get("container_id"), launch.get("volume_name"),+ )+ return True+ instance.update({+ "Endpoint": {+ "Address": launch["endpoint_host"],+ "Port": int(launch["endpoint_port"]),+ "HostedZoneId": (instance.get("Endpoint") or {}).get(+ "HostedZoneId", "Z2R2ITUGPM61AM",+ ),+ },+ "_HostPort": launch.get("host_port"),+ "_docker_container_id": launch.get("container_id"),+ "_docker_volume_name": (+ launch.get("volume_name")+ or instance.get("_docker_volume_name")+ ),+ "_internal_address": launch.get("internal_host"),+ "_internal_port": launch.get("internal_port"),+ "DBInstanceStatus": "creating",+ })+ ctx = contextvars.copy_context()+ threading.Thread(+ target=ctx.run,+ args=(+ _bg_finalize_pg_reader, db_id, cluster_id,+ cluster.get("Engine", "aurora-postgresql"),+ cluster.get("MasterUsername", "admin"),+ cluster.get("_MasterUserPassword", "password"),+ cluster.get("DatabaseName") or "mydb",+ launch.get("readiness_host"),+ launch.get("readiness_port"),+ launch.get("container_id"),+ ),+ daemon=True,+ ).start()+ return True++def _stop_cluster_shared_container(cluster_id, cluster):"""Stop, but do not remove, an Aurora cluster's database compute.@@ -1443,8 +1709,15 @@ def _stop_cluster_shared_container(cluster_id, cluster):DeleteDBCluster (the container itself may be replaced if a laterStartDBCluster has to fall back to recreating compute).- Returns True when compute is stopped — including when there was nothing- to stop — and False when a running container could not be stopped.+ Returns True when all compute is stopped — including when there was+ nothing to stop — and False when a running container could not be+ stopped. A False return is all-or-nothing about the writer: reader+ containers stop first and the writer's shared container last, and any+ container this call already stopped is restarted before returning, so a+ failed stop never leaves the writer's published ``available`` pointing+ at exited compute. If that rollback restart itself fails, the affected+ standby member alone is published ``stopped`` and the ReaderEndpoint is+ re-synced away from it."""with _shared_container_lock:# Invalidate every readiness worker before the potentially slow Docker@@ -1458,8 +1731,11 @@ def _stop_cluster_shared_container(cluster_id, cluster):docker_client = _get_docker()if not docker_client or not container_ids:return True- all_stopped = True- for container_id in container_ids:+ stopped = []+ # _cluster_owned_container_ids lists the shared (writer) container+ # first; stop it last so a reader-stop failure leaves the writer+ # untouched and only reader containers ever need rolling back.+ for container_id in reversed(container_ids):try:container = docker_client.containers.get(container_id)except Exception:@@ -1470,6 +1746,7 @@ def _stop_cluster_shared_container(cluster_id, cluster):container.reload()if container.status not in ("created", "exited", "dead", "removing"):container.stop(timeout=5)+ stopped.append(container)logger.info("RDS: stopped container %s for cluster %s",container_id,@@ -1482,8 +1759,35 @@ def _stop_cluster_shared_container(cluster_id, cluster):cluster_id,e,)- all_stopped = False- return all_stopped+ # Partial stops must not survive a failed StopDBCluster:+ # the caller keeps the cluster ``available``, so every+ # container this call stopped is restarted to keep that+ # status honest.+ for prior in stopped:+ try:+ prior.start()+ except Exception as restart_error:+ logger.warning(+ "RDS: failed to restart container %s while "+ "rolling back a failed stop of cluster %s: %s",+ prior.id,+ cluster_id,+ restart_error,+ )+ # The writer stops last, so an unrestartable+ # container here is always a reader's. Publish that+ # one member as stopped and steer the+ # ReaderEndpoint away from its exited container.+ for member in _cluster_member_instances(cluster):+ if (+ member.get("_pg_standby")+ and member.get("_docker_container_id")+ == prior.id+ ):+ member["DBInstanceStatus"] = "stopped"+ _sync_cluster_endpoints(cluster)+ return False+ return Truedef _remove_cluster_shared_resources(@@ -2554,7 +2858,7 @@ def _refresh_cluster_status(cluster_id):cluster = _clusters.get(cluster_id)if not cluster:return- if cluster.get("Status") in ("stopped", "deleting"):+ if cluster.get("Status") in ("stopping", "stopped", "deleting"):returnmember_ids = {m.get("DBInstanceIdentifier")@@ -2563,7 +2867,12 @@ def _refresh_cluster_status(cluster_id):}if any(inst.get("DBInstanceIdentifier") in member_ids- and inst.get("DBInstanceStatus") != "available"+ # A member in ``stopped`` was parked deliberately (a failed+ # StopDBCluster's rollback could not restart its container); it is+ # not converging toward available, so it must not hold the cluster+ # in ``creating`` — that would reject the StopDBCluster retry that+ # repairs it.+ and inst.get("DBInstanceStatus") not in ("available", "stopped")for inst in _instances.values()):cluster["Status"] = "creating"@@ -5248,15 +5557,42 @@ def _start_db_cluster(p):member_instances = _cluster_member_instances(cluster)docker_client = _get_docker()had_compute = bool(cluster.get("_shared_container_id"))+ has_replicating_standbys = _pg_cluster_replication_enabled(cluster) and any(+ inst.get("_pg_standby") for inst in member_instances+ )if not docker_client or not (had_compute or cluster.get("_shared_storage_initialized")):+ if has_replicating_standbys and (+ had_compute or cluster.get("_shared_storage_initialized")+ ):+ # The cluster has real compute (a standby only exists because a+ # reader container launched) but Docker is unreachable right+ # now — often transiently, e.g. Docker Desktop restarting.+ # Demoting here would irreversibly discard the standby identity+ # on a condition that may clear in seconds; fail the start and+ # keep everything stopped so a retry can revive the reader.+ return _error(+ "InternalFailure",+ f"Failed to start compute for DB cluster {cluster_id}.",+ 500,+ )# Control-plane only, or the cluster never had real compute:# flipping the statuses is the entire start.cluster["_shared_container_ready"] = Truecluster["Status"] = "available"for inst in member_instances:+ if inst.get("_pg_standby"):+ # No compute is coming back — replication is switched off,+ # or the cluster never had real compute — so no standby+ # container will serve this member's endpoint (#1325).+ _demote_pg_standby_to_alias(+ inst, cluster, "no cluster compute on StartDBCluster",+ )inst["DBInstanceStatus"] = "available"+ # Demotion changes what the ReaderEndpoint should resolve to;+ # republish it so it does not keep advertising the former standby.+ _sync_cluster_endpoints(cluster)return _xml(200, "StartDBClusterResponse",f"<StartDBClusterResult><DBCluster>{_cluster_xml(cluster)}</DBCluster></StartDBClusterResult>")@@ -5296,11 +5632,29 @@ def _start_db_cluster(p):f"Failed to start compute for DB cluster {cluster_id}.",500,)+ if has_replicating_standbys:+ # Docker went away between the check above and the start+ # attempt. Same reasoning as the pre-check: a transient Docker+ # miss must not irreversibly demote a standby. Keep the cluster+ # stopped and let a retry revive the reader.+ cluster["Status"] = "stopped"+ for inst in member_instances:+ inst["DBInstanceStatus"] = "stopped"+ return _error(+ "InternalFailure",+ f"Failed to start compute for DB cluster {cluster_id}.",+ 500,+ )# Benign control-plane-only outcome: no Docker in this environment.cluster["_shared_container_ready"] = Truecluster["Status"] = "available"for inst in member_instances:+ if inst.get("_pg_standby"):+ _demote_pg_standby_to_alias(+ inst, cluster, "no cluster compute on StartDBCluster",+ )inst["DBInstanceStatus"] = "available"+ _sync_cluster_endpoints(cluster)return _xml(200, "StartDBClusterResponse",f"<StartDBClusterResult><DBCluster>{_cluster_xml(cluster)}</DBCluster></StartDBClusterResult>")@@ -5327,6 +5681,7 @@ def _start_db_cluster(p):cluster = _clusters.get(cluster_id)if not cluster:return+ standbys_to_revive = []def _container_alive():client = _get_docker()@@ -5451,6 +5806,13 @@ def _start_db_cluster(p):_refresh_cluster_status(cluster_id)returnfor inst in _cluster_member_instances(cluster):+ if inst.get("_pg_standby"):+ # A replicating reader's compute is revived outside+ # the lock below (#1325); the writer becoming ready+ # does not make a reader whose container is still+ # stopped available.+ standbys_to_revive.append(inst)+ continue_attach_instance_to_shared_cluster(inst, cluster)inst["DBInstanceStatus"] = "available"_sync_cluster_endpoints(cluster)@@ -5461,6 +5823,13 @@ def _start_db_cluster(p):cluster_id,)return+ for inst in standbys_to_revive:+ if not _revive_pg_reader(+ inst["DBInstanceIdentifier"], inst, cluster,+ ):+ # The failed revival landed the cluster back on stopped;+ # reviving further standbys would race that transition.+ returnlogger.info("RDS: cluster %s started and ready", cluster_id)threading.Thread(target=ctx.run, args=(_bg_start_ready,), daemon=True).start()@@ -5488,22 +5857,7 @@ def _stop_db_cluster(p):f"in {status} state but expected it to be one of available.",400,)- if any(- inst.get("_pg_standby") for inst in _cluster_member_instances(cluster)- ):- # Restarting per-instance reader containers after a stop is not- # implemented yet (#1325 slice 3). Refusing here beats the two bad- # alternatives: an ``available`` reader whose container is exited,- # or a cluster wedged in ``creating`` because a member never- # becomes available again.- return _error(- "InvalidDBClusterStateFault",- "StopDBCluster is not supported for clusters with replicating "- "reader instances yet; delete the reader instances first "- "(MINISTACK_RDS_PG_CLUSTER_REPLICATION, "- "https://github.com/ministackorg/ministack/issues/1325).",- 400,- )+global_cluster, _member = _global_cluster_member_for_cluster(cluster)if (global_cluster@@ -5517,14 +5871,20 @@ def _stop_db_cluster(p):"global database if it's the only cluster in the global database.",400,)+ # Publish the transitional status before touching compute so concurrent+ # reader bootstrap workers can tell a stop-in-progress from a genuinely+ # dead container and park instead of destroying preserved compute.+ cluster["Status"] = "stopping"if not _stop_cluster_shared_container(cluster.get("DBClusterIdentifier", cluster_id), cluster,):- # Compute is still running; publishing ``stopped`` here would be the+ # Compute is still running (a failed stop rolls back any container+ # it already stopped); publishing ``stopped`` here would be the# reachable-endpoint lie this state machine exists to prevent.# Restore readiness (the container is still serving) and surface the# failure so StopDBCluster can be retried.cluster["_shared_container_ready"] = True+ cluster["Status"] = "available"return _error("InternalFailure","Failed to stop compute for DB cluster "diff --git a/tests/test_rds.py b/tests/test_rds.pyindex 708acd6d..2d414d2b 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -10335,8 +10335,9 @@ def test_rds_pg_replicating_reader_lifecycle(monkeypatch):Fake-Docker walk of the control plane: the writer aliases the sharedcluster container, the reader launches its own, the cluster- ReaderEndpoint follows the reader once available, StopDBCluster is- refused while a replicating reader exists (slice 3), and deleting the+ ReaderEndpoint follows the reader once available, StopDBCluster stops+ the writer's and the reader's containers, StartDBCluster restarts the+ writer and revives the reader as a standby (slice 3), and deleting thereader removes only reader-owned compute and falls the ReaderEndpointback to the writer."""@@ -10364,6 +10365,9 @@ def test_rds_pg_replicating_reader_lifecycle(monkeypatch):def exec_run(self, _cmd):return 0, b""+ def start(self):+ self.status = "running"+def stop(self, timeout=5):self.status = "exited"@@ -10442,22 +10446,60 @@ def test_rds_pg_replicating_reader_lifecycle(monkeypatch):assert [w["DBInstanceIdentifier"] for w in writers] == ["pgrepl-writer"]assert _poll_until(lambda: cluster["Status"] == "available")- # Stop/start with a replicating reader is slice 3: refused, not- # published wrongly.- status, _, body = m._stop_db_cluster({+ # StopDBCluster stops the writer's shared container and the+ # reader's own container; nothing is removed.+ shared_container = FakeDocker.containers.get(+ cluster["_shared_container_id"],+ )+ reader_container = FakeDocker.containers.get(+ reader["_docker_container_id"],+ )+ status, _, _body = m._stop_db_cluster({"DBClusterIdentifier": "pgrepl-cluster",})- assert status == 400- assert "InvalidDBClusterStateFault" in str(body)+ assert status == 200+ assert cluster["Status"] == "stopped"+ assert shared_container.status == "exited"+ assert reader_container.status == "exited"+ assert writer["DBInstanceStatus"] == "stopped"+ assert reader["DBInstanceStatus"] == "stopped"+ assert reader["_pg_standby"] is True+ assert not removed++ # StartDBCluster restarts the writer first, then revives the+ # reader under its own identity: the member stays a standby with+ # a container of its own, and the ReaderEndpoint follows it again.+ status, _, _body = m._start_db_cluster({+ "DBClusterIdentifier": "pgrepl-cluster",+ })+ assert status == 200+ assert _poll_until(+ lambda: writer["DBInstanceStatus"] == "available",+ )+ assert shared_container.status == "running"+ assert _poll_until(+ lambda: reader["DBInstanceStatus"] == "available",+ )+ assert reader["_pg_standby"] is True+ assert m._instance_owns_container(reader)+ assert reader["_docker_container_id"] != cluster["_shared_container_id"]+ assert cluster["_shared_container_id"] not in removed+ assert _poll_until(lambda: cluster["Status"] == "available")+ assert cluster["ReaderEndpoint"] == "10.0.0.7"+ assert cluster["Endpoint"] == "10.0.0.5"# Deleting the reader removes only its own compute; the- # ReaderEndpoint falls back to the writer.+ # ReaderEndpoint falls back to the writer. The fake derives+ # container ids from names, so the revive step's stale-name sweep+ # already put this id in ``removed`` once — only removals that+ # happen after this point prove the delete did its own cleanup.reader_container_id = reader["_docker_container_id"]+ removed_before_delete = len(removed)m._delete_db_instance({"DBInstanceIdentifier": "pgrepl-reader","SkipFinalSnapshot": "true",})- assert reader_container_id in removed+ assert reader_container_id in removed[removed_before_delete:]assert cluster["_shared_container_id"] not in removedassert cluster["ReaderEndpoint"] == "10.0.0.5"finally:@@ -10473,8 +10515,14 @@ def _pg_repl_fake_docker(m, monkeypatch, member_ips, exec_calls, removed):shared container) get 10.0.0.5. ``exec_calls`` collects the names ofcontainers that received ``exec_run``; ``removed`` collects removedcontainer ids.++ Returns a handle dict with the live ``containers`` and ``volumes``+ registries and the ``removed_volumes`` list, for tests that assert on+ volume lifecycle."""containers = {}+ volumes = {}+ removed_volumes = []class FakeContainer:def __init__(self, name, kwargs):@@ -10496,6 +10544,9 @@ def _pg_repl_fake_docker(m, monkeypatch, member_ips, exec_calls, removed):exec_calls.append(self.name)return 0, b""+ def start(self):+ self.status = "running"+def stop(self, timeout=5):self.status = "exited"@@ -10507,6 +10558,8 @@ def _pg_repl_fake_docker(m, monkeypatch, member_ips, exec_calls, removed):def run(self, **kwargs):container = FakeContainer(kwargs["name"], kwargs)containers[kwargs["name"]] = container+ for volume_name in kwargs.get("volumes", {}):+ volumes.setdefault(volume_name, FakeVolume(volume_name))return containerdef get(self, identifier):@@ -10515,13 +10568,34 @@ def _pg_repl_fake_docker(m, monkeypatch, member_ips, exec_calls, removed):return containerraise Exception("not found")+ class FakeVolume:+ def __init__(self, name):+ self.name = name++ def remove(self):+ volumes.pop(self.name, None)+ removed_volumes.append(self.name)++ class FakeVolumes:+ def get(self, name):+ volume = volumes.get(name)+ if volume is None:+ raise Exception("not found")+ return volume+class FakeDocker:containers = FakeContainers()+ volumes = FakeVolumes()monkeypatch.setattr(m, "RDS_PG_CLUSTER_REPLICATION", True)monkeypatch.setattr(m, "_get_docker", lambda: FakeDocker())monkeypatch.setattr(m, "_get_ministack_network", lambda _client: "ms_net")monkeypatch.setattr(m, "_is_host_port_free", lambda _port: True)+ return {+ "containers": containers,+ "volumes": volumes,+ "removed_volumes": removed_volumes,+ }def test_rds_pg_two_replicating_readers_provision_source_once(monkeypatch):@@ -10689,13 +10763,15 @@ def test_rds_pg_stale_reader_worker_is_inert(monkeypatch):m._clusters.clear()-def test_rds_restore_state_demotes_pg_standby(monkeypatch):- """Warm boot demotes a persisted replicating reader to an alias member.+def test_rds_restore_state_without_docker_demotes_pg_standby(monkeypatch):+ """Control-plane-only warm boot demotes a persisted replicating reader.- Restarting reader containers across host restarts is #1325 slice 3;- until then a restored reader must not stay marked ``_pg_standby``- pointing at a container the restart killed, and the cluster must- re-verify replication provisioning against the respawned writer.+ With no Docker there is no reader container to revive, so the restored+ member must not stay marked ``_pg_standby`` pointing at compute that+ does not exist, and the cluster must re-verify replication provisioning+ against a future respawned writer. (With Docker, warm boot revives the+ reader instead — see+ test_rds_restore_state_revives_pg_standby.)"""from ministack.core.responses import (AccountRegionScopedDict,@@ -10736,15 +10812,16 @@ def test_rds_restore_state_demotes_pg_standby(monkeypatch):reader = m._instances.get("warm-pg-reader")assert reader is not None- assert "_pg_standby" not in readercluster = m._clusters.get("warm-pg")assert "_pg_replication_source_ready" not in cluster# The demoted reader re-attaches to the shared cluster endpoint like# any alias member (no Docker in this test: restore publishes the- # endpoint without real compute).+ # endpoint without real compute). Demotion happens on the cluster+ # restore daemon once it decides no compute is coming back.assert _poll_until(lambda: reader.get("DBInstanceStatus") == "available",)+ assert "_pg_standby" not in readerassert reader.get("_shared_cluster_id") == "warm-pg"assert m._cluster_reader_endpoint(cluster) == cluster["_shared_endpoint"]finally:@@ -10752,6 +10829,849 @@ def test_rds_restore_state_demotes_pg_standby(monkeypatch):m._clusters.clear()+def test_rds_restore_state_revives_pg_standby(monkeypatch):+ """Warm boot with Docker revives a persisted replicating reader.++ The writer's shared container respawns first; once it is ready the+ reader gets fresh compute under its own identity (#1325 slice 3): the+ member stays ``_pg_standby`` with a container of its own, its persisted+ volume name survives, replication provisioning is re-verified against+ the respawned writer, and the ReaderEndpoint follows the standby again.+ """+ from ministack.core.responses import (+ AccountRegionScopedDict,+ get_account_id,+ get_region,+ )+ from ministack.services import rds as m++ exec_calls = []+ removed = []+ _pg_repl_fake_docker(+ m, monkeypatch, {"warm-pgr-reader": "10.0.0.7"}, exec_calls, removed,+ )+ monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args: True)+ # Persistence on, so the revival genuinely remounts the reader's named+ # volume; without it the launch sets no volume name and the persisted+ # name would survive only through a fallback, proving nothing.+ monkeypatch.setattr(m, "RDS_PERSIST", True)+ reader_volume = m._rds_docker_volume_name("warm-pgr-reader")++ key_scope = (get_account_id(), get_region())+ m._instances.clear()+ m._clusters.clear()+ try:+ clusters = AccountRegionScopedDict()+ instances = AccountRegionScopedDict()+ clusters._data[(*key_scope, "warm-pgr")] = {+ "DBClusterIdentifier": "warm-pgr",+ "Engine": "aurora-postgresql",+ "Status": "available",+ "MasterUsername": "admin",+ "_MasterUserPassword": "password123",+ "_pg_replication_source_ready": True,+ "_shared_storage_initialized": True,+ "_shared_volume_name": "warm-pgr-volume",+ "DBClusterMembers": [+ {"DBInstanceIdentifier": "warm-pgr-writer", "IsClusterWriter": True},+ {"DBInstanceIdentifier": "warm-pgr-reader", "IsClusterWriter": False},+ ],+ }+ instances._data[(*key_scope, "warm-pgr-writer")] = {+ "DBInstanceIdentifier": "warm-pgr-writer",+ "DBClusterIdentifier": "warm-pgr",+ "_shared_cluster_id": "warm-pgr",+ }+ instances._data[(*key_scope, "warm-pgr-reader")] = {+ "DBInstanceIdentifier": "warm-pgr-reader",+ "DBClusterIdentifier": "warm-pgr",+ # No _shared_cluster_id: a replicating reader never aliases the+ # shared container, so a persisted standby does not carry it.+ "_pg_standby": True,+ "_docker_container_id": "dead-reader-container",+ "_docker_volume_name": reader_volume,+ }+ m.restore_state({"clusters": clusters, "instances": instances})++ reader = m._instances.get("warm-pgr-reader")+ writer = m._instances.get("warm-pgr-writer")+ cluster = m._clusters.get("warm-pgr")+ assert _poll_until(+ lambda: writer.get("DBInstanceStatus") == "available",+ )+ assert _poll_until(+ lambda: reader.get("DBInstanceStatus") == "available",+ )+ assert reader["_pg_standby"] is True+ assert m._instance_owns_container(reader)+ assert reader["_docker_container_id"] != cluster["_shared_container_id"]+ # The reader's persisted volume identity survives revival — the+ # relaunch genuinely remounted the derived named volume (RDS_PERSIST+ # is on, so this is not the persisted-name fallback) — and the+ # revived standby is not mistaken for a superseded legacy member+ # volume to reap.+ assert reader["_docker_volume_name"] == reader_volume+ reader_container = m._get_docker().containers.get(+ reader["_docker_container_id"],+ )+ assert reader_volume in reader_container.kwargs.get("volumes", {})+ # Replication provisioning was re-verified on the respawned writer+ # exactly once.+ assert cluster["_pg_replication_source_ready"] is True+ shared_execs = [+ name for name in exec_calls+ if name == m._rds_cluster_docker_name("warm-pgr")+ ]+ assert len(shared_execs) == 1+ assert _poll_until(lambda: cluster.get("Status") == "available")+ assert cluster["ReaderEndpoint"] == "10.0.0.7"+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_stop_db_cluster_reader_stop_failure_surfaces_error(monkeypatch):+ """A reader container that fails to stop must fail StopDBCluster.++ Publishing ``stopped`` while a standby container still serves its+ endpoint would be a reachable-endpoint lie; the stop surfaces+ InternalFailure instead and a retried stop succeeds. Readers stop+ before the writer, so a reader-stop failure must leave the writer's+ container untouched — no member's published status may point at an+ exited container while the cluster republishes ``available``.+ """+ from ministack.services import rds as m++ exec_calls = []+ removed = []+ _pg_repl_fake_docker(+ m, monkeypatch, {"stopfail-reader": "10.0.0.7"}, exec_calls, removed,+ )+ monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args: True)++ m._instances.clear()+ m._clusters.clear()+ try:+ m._create_db_cluster({+ "DBClusterIdentifier": "stopfail-cluster",+ "Engine": "aurora-postgresql",+ "MasterUsername": "admin",+ "MasterUserPassword": "password123",+ })+ for db_id in ("stopfail-writer", "stopfail-reader"):+ m._create_db_instance({+ "DBInstanceIdentifier": db_id,+ "DBClusterIdentifier": "stopfail-cluster",+ "DBInstanceClass": "db.r6g.large",+ "Engine": "aurora-postgresql",+ })+ cluster = m._clusters.get("stopfail-cluster")+ writer = m._instances.get("stopfail-writer")+ reader = m._instances.get("stopfail-reader")+ assert _poll_until(lambda: cluster["Status"] == "available")++ shared_container = m._get_docker().containers.get(+ cluster["_shared_container_id"],+ )+ reader_container = m._get_docker().containers.get(+ reader["_docker_container_id"],+ )++ def _fail_stop(timeout=5):+ raise Exception("cannot stop reader container")++ reader_container.stop = _fail_stop+ status, _, body = m._stop_db_cluster({+ "DBClusterIdentifier": "stopfail-cluster",+ })+ assert status == 500+ assert b"InternalFailure" in body+ assert cluster["Status"] == "available"+ assert reader["_pg_standby"] is True+ # Readers stop first: the failure happened before the writer's+ # container was touched, so ``available`` stays honest.+ assert shared_container.status == "running"+ assert writer["DBInstanceStatus"] == "available"++ # The failure is transient: a retried stop succeeds.+ del reader_container.stop+ status, _, _body = m._stop_db_cluster({+ "DBClusterIdentifier": "stopfail-cluster",+ })+ assert status == 200+ assert cluster["Status"] == "stopped"+ assert reader["DBInstanceStatus"] == "stopped"+ assert reader["_pg_standby"] is True+ assert reader_container.status == "exited"+ assert shared_container.status == "exited"+ assert not removed+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_stop_db_cluster_writer_stop_failure_rolls_back_readers(+ monkeypatch,+):+ """A writer-stop failure restarts the reader containers it stopped.++ Readers stop before the writer; if the writer's stop then fails, the+ already-exited reader containers must be rolled back to running before+ the cluster republishes ``available`` — otherwise the ReaderEndpoint+ advertises an exited standby.+ """+ from ministack.services import rds as m++ exec_calls = []+ removed = []+ _pg_repl_fake_docker(+ m, monkeypatch, {"wstopfail-reader": "10.0.0.7"}, exec_calls, removed,+ )+ monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args: True)++ m._instances.clear()+ m._clusters.clear()+ try:+ m._create_db_cluster({+ "DBClusterIdentifier": "wstopfail-cluster",+ "Engine": "aurora-postgresql",+ "MasterUsername": "admin",+ "MasterUserPassword": "password123",+ })+ for db_id in ("wstopfail-writer", "wstopfail-reader"):+ m._create_db_instance({+ "DBInstanceIdentifier": db_id,+ "DBClusterIdentifier": "wstopfail-cluster",+ "DBInstanceClass": "db.r6g.large",+ "Engine": "aurora-postgresql",+ })+ cluster = m._clusters.get("wstopfail-cluster")+ reader = m._instances.get("wstopfail-reader")+ assert _poll_until(lambda: cluster["Status"] == "available")++ shared_container = m._get_docker().containers.get(+ cluster["_shared_container_id"],+ )+ reader_container = m._get_docker().containers.get(+ reader["_docker_container_id"],+ )++ def _fail_stop(timeout=5):+ raise Exception("cannot stop writer container")++ shared_container.stop = _fail_stop+ status, _, body = m._stop_db_cluster({+ "DBClusterIdentifier": "wstopfail-cluster",+ })+ assert status == 500+ assert b"InternalFailure" in body+ assert cluster["Status"] == "available"+ # The reader container was stopped before the writer failure and+ # rolled back to running, so the ReaderEndpoint stays served.+ assert reader_container.status == "running"+ assert reader["_pg_standby"] is True+ assert cluster["ReaderEndpoint"] == "10.0.0.7"++ # The failure is transient: a retried stop succeeds.+ del shared_container.stop+ status, _, _body = m._stop_db_cluster({+ "DBClusterIdentifier": "wstopfail-cluster",+ })+ assert status == 200+ assert cluster["Status"] == "stopped"+ assert reader_container.status == "exited"+ assert shared_container.status == "exited"+ assert not removed+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_revive_pg_reader_flag_off_demotes(monkeypatch):+ """Reviving a persisted standby with the opt-in withdrawn demotes it.++ MINISTACK_RDS_PG_CLUSTER_REPLICATION can change between runs; a standby+ must not outlive the flag that created it.+ """+ from ministack.services import rds as m++ monkeypatch.setattr(m, "RDS_PG_CLUSTER_REPLICATION", False)+ m._instances.clear()+ m._clusters.clear()+ try:+ cluster = {+ "DBClusterIdentifier": "flagoff",+ "Engine": "aurora-postgresql",+ "Status": "available",+ "_shared_endpoint": {+ "Address": "10.0.0.5",+ "Port": 5432,+ "HostedZoneId": "Z2R2ITUGPM61AM",+ },+ "DBClusterMembers": [+ {"DBInstanceIdentifier": "flagoff-reader"},+ ],+ }+ m._clusters["flagoff"] = cluster+ instance = {+ "DBInstanceIdentifier": "flagoff-reader",+ "_pg_standby": True,+ "DBInstanceStatus": "stopped",+ }+ m._instances["flagoff-reader"] = instance++ m._revive_pg_reader("flagoff-reader", instance, cluster)++ assert "_pg_standby" not in instance+ assert instance["DBInstanceStatus"] == "available"+ assert instance["Endpoint"]["Address"] == "10.0.0.5"+ assert instance["_shared_cluster_id"] == "flagoff"+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_revive_pg_reader_launch_failure_lands_stopped_and_retryable(+ monkeypatch,+):+ """A failed reader revival returns the cluster to ``stopped``.++ Real AWS lands a failed start back on ``stopped`` — never on a+ transitional status — so StartDBCluster can simply be retried. A+ reader marked ``failed`` here would drive the cluster to ``creating``,+ where StartDBCluster and StopDBCluster are both rejected and the+ cluster is wedged until the instance is deleted. The launch failure is+ genuine: the fake's ``containers.run`` raises for the reader, driving+ ``_start_pg_reader_container``'s own failure branch.+ """+ from ministack.services import rds as m++ exec_calls = []+ removed = []+ _pg_repl_fake_docker(+ m, monkeypatch, {"revfail-reader": "10.0.0.7"}, exec_calls, removed,+ )+ monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args: True)++ m._instances.clear()+ m._clusters.clear()+ try:+ m._create_db_cluster({+ "DBClusterIdentifier": "revfail-cluster",+ "Engine": "aurora-postgresql",+ "MasterUsername": "admin",+ "MasterUserPassword": "password123",+ })+ for db_id in ("revfail-writer", "revfail-reader"):+ m._create_db_instance({+ "DBInstanceIdentifier": db_id,+ "DBClusterIdentifier": "revfail-cluster",+ "DBInstanceClass": "db.r6g.large",+ "Engine": "aurora-postgresql",+ })+ cluster = m._clusters.get("revfail-cluster")+ writer = m._instances.get("revfail-writer")+ reader = m._instances.get("revfail-reader")+ assert _poll_until(lambda: cluster["Status"] == "available")++ status, _, _body = m._stop_db_cluster({+ "DBClusterIdentifier": "revfail-cluster",+ })+ assert status == 200++ # The reader's relaunch fails (e.g. its host port was claimed while+ # the cluster was stopped); the writer's restart is untouched.+ fake_containers = m._get_docker().containers+ real_run = type(fake_containers).run+ fail = {"active": True}++ def _flaky_run(**kwargs):+ if (+ fail["active"]+ and kwargs.get("labels", {}).get("db_id") == "revfail-reader"+ ):+ raise Exception("port is already allocated")+ return real_run(fake_containers, **kwargs)++ fake_containers.run = _flaky_run+ status, _, _body = m._start_db_cluster({+ "DBClusterIdentifier": "revfail-cluster",+ })+ assert status == 200+ # The failed revival lands the whole cluster back on ``stopped`` —+ # not ``creating``, where every recovery API returns 400.+ assert _poll_until(lambda: cluster["Status"] == "stopped")+ assert writer["DBInstanceStatus"] == "stopped"+ assert reader["DBInstanceStatus"] == "stopped"+ assert reader["_pg_standby"] is True+ shared_container = m._get_docker().containers.get(+ cluster["_shared_container_id"],+ )+ assert shared_container.status == "exited"++ # ``stopped`` is retryable: the next StartDBCluster succeeds.+ fail["active"] = False+ status, _, _body = m._start_db_cluster({+ "DBClusterIdentifier": "revfail-cluster",+ })+ assert status == 200+ assert _poll_until(+ lambda: reader["DBInstanceStatus"] == "available",+ )+ assert reader["_pg_standby"] is True+ assert m._instance_owns_container(reader)+ assert _poll_until(lambda: cluster["Status"] == "available")+ assert cluster["ReaderEndpoint"] == "10.0.0.7"+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_start_db_cluster_transient_no_docker_preserves_standby(+ monkeypatch,+):+ """A transient Docker outage during StartDBCluster demotes nothing.++ A standby only exists because a reader container launched, so a+ ``_get_docker()`` miss on Start (Docker Desktop restarting) is+ transient, not proof the compute is gone. The start fails, everything+ stays ``stopped``, and a retry once Docker is back revives the reader+ with its standby identity intact.+ """+ from ministack.services import rds as m++ exec_calls = []+ removed = []+ _pg_repl_fake_docker(+ m, monkeypatch, {"nodock-reader": "10.0.0.7"}, exec_calls, removed,+ )+ monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args: True)++ m._instances.clear()+ m._clusters.clear()+ try:+ m._create_db_cluster({+ "DBClusterIdentifier": "nodock-cluster",+ "Engine": "aurora-postgresql",+ "MasterUsername": "admin",+ "MasterUserPassword": "password123",+ })+ for db_id in ("nodock-writer", "nodock-reader"):+ m._create_db_instance({+ "DBInstanceIdentifier": db_id,+ "DBClusterIdentifier": "nodock-cluster",+ "DBInstanceClass": "db.r6g.large",+ "Engine": "aurora-postgresql",+ })+ cluster = m._clusters.get("nodock-cluster")+ reader = m._instances.get("nodock-reader")+ assert _poll_until(lambda: cluster["Status"] == "available")++ status, _, _body = m._stop_db_cluster({+ "DBClusterIdentifier": "nodock-cluster",+ })+ assert status == 200++ fake_get_docker = m._get_docker+ monkeypatch.setattr(m, "_get_docker", lambda: None)+ status, _, body = m._start_db_cluster({+ "DBClusterIdentifier": "nodock-cluster",+ })+ assert status == 500+ assert b"InternalFailure" in body+ assert cluster["Status"] == "stopped"+ assert reader["DBInstanceStatus"] == "stopped"+ assert reader["_pg_standby"] is True+ # The member's own endpoint was not clobbered with the writer's,+ # and the cached ReaderEndpoint does not advertise the parked+ # standby (it is not available).+ assert m._cluster_reader_endpoint(cluster) == cluster["_shared_endpoint"]++ # Docker comes back: the retry revives the reader as a standby.+ monkeypatch.setattr(m, "_get_docker", fake_get_docker)+ status, _, _body = m._start_db_cluster({+ "DBClusterIdentifier": "nodock-cluster",+ })+ assert status == 200+ assert _poll_until(+ lambda: reader["DBInstanceStatus"] == "available",+ )+ assert reader["_pg_standby"] is True+ assert m._instance_owns_container(reader)+ assert _poll_until(lambda: cluster["Status"] == "available")+ assert cluster["ReaderEndpoint"] == "10.0.0.7"+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_demote_pg_standby_removes_owned_compute(monkeypatch):+ """Demotion removes the reader's own container and named volume.++ Demotion is the last moment the member still references its owned+ compute — ``_attach_instance_to_shared_cluster`` overwrites the+ container id and nulls the volume name — so anything not removed at+ that point is orphaned, and a container left holding the reserved+ instance name would 409 a later CreateDBInstance under the same+ identifier.+ """+ from ministack.services import rds as m++ exec_calls = []+ removed = []+ handles = _pg_repl_fake_docker(+ m, monkeypatch, {"demote-reader": "10.0.0.7"}, exec_calls, removed,+ )+ monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args: True)+ monkeypatch.setattr(m, "RDS_PERSIST", True)+ reader_volume = m._rds_docker_volume_name("demote-reader")++ m._instances.clear()+ m._clusters.clear()+ try:+ m._create_db_cluster({+ "DBClusterIdentifier": "demote-cluster",+ "Engine": "aurora-postgresql",+ "MasterUsername": "admin",+ "MasterUserPassword": "password123",+ })+ for db_id in ("demote-writer", "demote-reader"):+ m._create_db_instance({+ "DBInstanceIdentifier": db_id,+ "DBClusterIdentifier": "demote-cluster",+ "DBInstanceClass": "db.r6g.large",+ "Engine": "aurora-postgresql",+ })+ cluster = m._clusters.get("demote-cluster")+ reader = m._instances.get("demote-reader")+ assert _poll_until(lambda: cluster["Status"] == "available")+ assert reader["_docker_volume_name"] == reader_volume+ reader_container_id = reader["_docker_container_id"]++ status, _, _body = m._stop_db_cluster({+ "DBClusterIdentifier": "demote-cluster",+ })+ assert status == 200++ # The opt-in is withdrawn between runs: StartDBCluster demotes the+ # standby to a shared-container alias member.+ monkeypatch.setattr(m, "RDS_PG_CLUSTER_REPLICATION", False)+ status, _, _body = m._start_db_cluster({+ "DBClusterIdentifier": "demote-cluster",+ })+ assert status == 200+ assert _poll_until(+ lambda: reader["DBInstanceStatus"] == "available"+ and "_pg_standby" not in reader,+ )+ # The demoted member aliases the writer's compute...+ assert reader["_shared_cluster_id"] == "demote-cluster"+ assert reader["_docker_container_id"] == cluster["_shared_container_id"]+ assert cluster["ReaderEndpoint"] == "10.0.0.5"+ # ...and its owned container and named volume were removed, not+ # orphaned: the exited container would hold the reserved name and+ # the volume would never be reaped.+ assert reader_container_id in removed+ assert reader_volume in handles["removed_volumes"]+ assert reader_volume not in handles["volumes"]+ # The writer's cluster-owned volume is untouched.+ assert cluster["_shared_container_id"] not in removed+ shared_volume = cluster.get("_shared_volume_name")+ assert shared_volume not in handles["removed_volumes"]+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_pg_reader_worker_parks_when_cluster_stopped(monkeypatch):+ """A readiness worker seeing the cluster ``stopped`` parks, not fails.++ StopDBCluster deliberately stopped this standby's container along with+ the writer's. The worker must treat that as a parked reader — its+ container and volume are exactly what StartDBCluster revives — not a+ dead one to destroy.+ """+ from ministack.services import rds as m++ exec_calls = []+ removed = []+ _pg_repl_fake_docker(+ m, monkeypatch, {"park-reader": "10.0.0.7"}, exec_calls, removed,+ )+ monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args: True)++ m._instances.clear()+ m._clusters.clear()+ try:+ m._create_db_cluster({+ "DBClusterIdentifier": "park-cluster",+ "Engine": "aurora-postgresql",+ "MasterUsername": "admin",+ "MasterUserPassword": "password123",+ })+ for db_id in ("park-writer", "park-reader"):+ m._create_db_instance({+ "DBInstanceIdentifier": db_id,+ "DBClusterIdentifier": "park-cluster",+ "DBInstanceClass": "db.r6g.large",+ "Engine": "aurora-postgresql",+ })+ cluster = m._clusters.get("park-cluster")+ reader = m._instances.get("park-reader")+ assert _poll_until(lambda: cluster["Status"] == "available")+ status, _, _body = m._stop_db_cluster({+ "DBClusterIdentifier": "park-cluster",+ })+ assert status == 200++ # A straggling worker for the parked container wakes up after the+ # stop landed (its pre-readiness loop re-checks cluster status).+ removed_before = len(removed)+ m._bg_finalize_pg_reader(+ "park-reader", "park-cluster", "aurora-postgresql",+ "admin", "password123", "mydb", "10.0.0.7", 5432,+ reader["_docker_container_id"],+ )+ assert reader["DBInstanceStatus"] == "stopped"+ assert reader["_pg_standby"] is True+ assert removed[removed_before:] == []+ # The parked container still exists for StartDBCluster to revive.+ container = m._get_docker().containers.get(+ reader["_docker_container_id"],+ )+ assert container.status == "exited"+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_pg_reader_worker_parks_when_stop_lands_mid_wait(monkeypatch):+ """A stop landing inside the readiness wait parks the reader.++ StopDBCluster kills the container deliberately while the worker is+ blocked in ``_wait_for_database_ready``; the wait returns False. The+ worker must not mistake that for a bootstrap death: destroying the+ container and volume would delete exactly the compute the stop just+ promised to preserve.+ """+ from ministack.services import rds as m++ exec_calls = []+ removed = []+ _pg_repl_fake_docker(+ m, monkeypatch, {"midwait-reader": "10.0.0.7"}, exec_calls, removed,+ )+ monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args: True)++ m._instances.clear()+ m._clusters.clear()+ try:+ m._create_db_cluster({+ "DBClusterIdentifier": "midwait-cluster",+ "Engine": "aurora-postgresql",+ "MasterUsername": "admin",+ "MasterUserPassword": "password123",+ })+ for db_id in ("midwait-writer", "midwait-reader"):+ m._create_db_instance({+ "DBInstanceIdentifier": db_id,+ "DBClusterIdentifier": "midwait-cluster",+ "DBInstanceClass": "db.r6g.large",+ "Engine": "aurora-postgresql",+ })+ cluster = m._clusters.get("midwait-cluster")+ reader = m._instances.get("midwait-reader")+ assert _poll_until(lambda: cluster["Status"] == "available")++ # Re-run a readiness worker whose wait is interrupted by a stop:+ # while the worker is blocked, StopDBCluster lands, stops the+ # container, and publishes ``stopped``; the wait then reports the+ # database never became reachable.+ reader["DBInstanceStatus"] = "creating"+ cluster["Status"] = "creating"++ def _stop_lands_mid_wait(*_args):+ # Simulate StopDBCluster landing while the worker is blocked+ # here: containers stopped, statuses published as stopped.+ m._stop_cluster_shared_container("midwait-cluster", cluster)+ cluster["Status"] = "stopped"+ for inst in m._cluster_member_instances(cluster):+ inst["DBInstanceStatus"] = "stopped"+ return False++ monkeypatch.setattr(+ m, "_wait_for_database_ready", _stop_lands_mid_wait,+ )+ removed_before = len(removed)+ m._bg_finalize_pg_reader(+ "midwait-reader", "midwait-cluster", "aurora-postgresql",+ "admin", "password123", "mydb", "10.0.0.7", 5432,+ reader["_docker_container_id"],+ )+ # Parked, not destroyed: no failure published, no compute removed.+ assert reader["DBInstanceStatus"] == "stopped"+ assert reader["_pg_standby"] is True+ assert removed[removed_before:] == []+ container = m._get_docker().containers.get(+ reader["_docker_container_id"],+ )+ assert container.status == "exited"+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_pg_two_readers_survive_stop_start(monkeypatch):+ """Stop/Start with two standbys revives both under their own identity.++ The multi-container stop loop and the multi-element revival loop are+ exercised with N=2: both readers park with their compute preserved,+ both come back as standbys, member order still decides the+ ReaderEndpoint, and the writer is not re-provisioned for replication —+ the role and pg_hba rule live in the preserved cluster volume.+ """+ from ministack.services import rds as m++ exec_calls = []+ removed = []+ _pg_repl_fake_docker(+ m, monkeypatch,+ {"ss2-reader1": "10.0.0.7", "ss2-reader2": "10.0.0.8"},+ exec_calls, removed,+ )+ monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args: True)++ m._instances.clear()+ m._clusters.clear()+ try:+ m._create_db_cluster({+ "DBClusterIdentifier": "ss2-cluster",+ "Engine": "aurora-postgresql",+ "MasterUsername": "admin",+ "MasterUserPassword": "password123",+ })+ for db_id in ("ss2-writer", "ss2-reader1", "ss2-reader2"):+ m._create_db_instance({+ "DBInstanceIdentifier": db_id,+ "DBClusterIdentifier": "ss2-cluster",+ "DBInstanceClass": "db.r6g.large",+ "Engine": "aurora-postgresql",+ })+ cluster = m._clusters.get("ss2-cluster")+ reader1 = m._instances.get("ss2-reader1")+ reader2 = m._instances.get("ss2-reader2")+ assert _poll_until(lambda: cluster["Status"] == "available")++ status, _, _body = m._stop_db_cluster({+ "DBClusterIdentifier": "ss2-cluster",+ })+ assert status == 200+ assert cluster["Status"] == "stopped"+ for reader in (reader1, reader2):+ assert reader["DBInstanceStatus"] == "stopped"+ assert reader["_pg_standby"] is True+ container = m._get_docker().containers.get(+ reader["_docker_container_id"],+ )+ assert container.status == "exited"+ assert not removed++ status, _, _body = m._start_db_cluster({+ "DBClusterIdentifier": "ss2-cluster",+ })+ assert status == 200+ assert _poll_until(+ lambda: reader1["DBInstanceStatus"] == "available"+ and reader2["DBInstanceStatus"] == "available",+ )+ for reader in (reader1, reader2):+ assert reader["_pg_standby"] is True+ assert m._instance_owns_container(reader)+ assert (+ reader["_docker_container_id"]+ != cluster["_shared_container_id"]+ )+ assert _poll_until(lambda: cluster["Status"] == "available")+ # Member order (reader1 first) still decides the ReaderEndpoint.+ assert cluster["ReaderEndpoint"] == "10.0.0.7"+ assert cluster["Endpoint"] == "10.0.0.5"+ # The two racing revival workers did not re-provision the writer:+ # replication access was provisioned exactly once, at creation.+ shared_execs = [+ name for name in exec_calls+ if name == m._rds_cluster_docker_name("ss2-cluster")+ ]+ assert len(shared_execs) == 1+ assert cluster["_shared_container_id"] not in removed+ finally:+ m._instances.clear()+ m._clusters.clear()+++def test_rds_stale_revive_removes_its_own_compute(monkeypatch):+ """A superseded revival removes the compute it just created.++ The Docker launch inside ``_revive_pg_reader`` is slow; a concurrent+ DeleteDBInstance (or delete + recreate under the same identifier) can+ supersede the revival while it runs. The worker must notice its records+ are stale and remove the just-created container instead of publishing+ it onto a record it no longer owns — otherwise the container, its host+ port, and its volume leak with nothing owning them.+ """+ from ministack.services import rds as m++ exec_calls = []+ removed = []+ handles = _pg_repl_fake_docker(+ m, monkeypatch, {"stalerev-reader": "10.0.0.7"}, exec_calls, removed,+ )++ m._instances.clear()+ m._clusters.clear()+ try:+ cluster = {+ "DBClusterIdentifier": "stalerev",+ "Engine": "aurora-postgresql",+ "Status": "available",+ "MasterUsername": "admin",+ "_MasterUserPassword": "password123",+ "_shared_internal_address": "10.0.0.5",+ "_shared_internal_port": 5432,+ "_shared_container_epoch": 0,+ "DBClusterMembers": [+ {"DBInstanceIdentifier": "stalerev-reader"},+ ],+ }+ m._clusters["stalerev"] = cluster+ instance = {+ "DBInstanceIdentifier": "stalerev-reader",+ "_pg_standby": True,+ "DBInstanceStatus": "stopped",+ }+ # The instance record this worker holds was superseded: the live+ # registry has a different record under the same identifier.+ recreated = {+ "DBInstanceIdentifier": "stalerev-reader",+ "DBInstanceStatus": "creating",+ }+ m._instances["stalerev-reader"] = recreated++ assert m._revive_pg_reader("stalerev-reader", instance, cluster)++ # The launch happened and its container was removed again; neither+ # the stale record nor the recreated one was published onto.+ launched_name = m._rds_docker_name("stalerev-reader")+ assert launched_name not in handles["containers"]+ assert any(launched_name in container_id for container_id in removed)+ assert instance["DBInstanceStatus"] == "stopped"+ assert "Endpoint" not in instance+ assert recreated["DBInstanceStatus"] == "creating"+ assert "_docker_container_id" not in recreated+ finally:+ m._instances.clear()+ m._clusters.clear()++_PG_REPLICATION_LIVE = (os.environ.get("DOCKER_NETWORK")and os.environ.get(