Skip to content

EC2: every instance state transition is instantaneous, so pending, stopping and shutting-down are never observable #514

Closed

Description

@scttfrdmn

Found while implementing #489 (termination protection), and deliberately left out of scope there: widening that PR into a lifecycle change would have put its own gate at risk. #489 documented the divergence in docs/services.md and pointed here.

What substrate does

Every instance state transition is instantaneous. The transient state is never written, so it is never observable:

Operation Substrate writes Real EC2 passes through
RunInstances 16 running (ec2_plugin.go:537) 0 pending → 16 running
StartInstances 16 running (ec2_plugin.go:1071) 0 pending → 16 running
StopInstances 80 stopped (ec2_plugin.go:1025) 64 stopping → 80 stopped
TerminateInstances 48 terminated (ec2_plugin.go:963) 32 shutting-down → 48 terminated

EC2InstanceState's own doc comment (ec2_types.go:16) already enumerates all six codes — 0=pending, 16=running, 32=shutting-down, 48=terminated, 64=stopping, 80=stopped — so the type models states three of which no code path can ever produce.

Why it matters

The lifecycle is confirmed against Amazon EC2 instance state changes:

pending — The instance is preparing to enter the running state. An instance enters the pending state when it is launched or when it is started after being in the stopped state.

When you stop your instance, it enters the stopping state, and then the stopped state.

shutting-down — The instance is preparing to be terminated.

This is the tracker's recurring defect shape, in its second form. It is not "substrate returns success where AWS refuses" — it is substrate reaches the terminal state where AWS is still in transit, so a consumer's waiter never observes the state it exists to wait through.

Concretely, a consumer whose teardown does this:

ec2.terminate_instances(InstanceIds=[iid])
waiter = ec2.get_waiter("instance_terminated")
waiter.wait(InstanceIds=[iid])

passes against substrate on the first poll, having never exercised the loop. Worse, a consumer who polls for the transient state — while state == "shutting-down": sleep(5) or an assertion that a stop was acknowledged before it completed — has a branch that is unreachable against substrate and cannot be tested. Substrate's whole value proposition is that a poll/retry/wait loop can be exercised instantly and reproducibly; here the loop is skipped instead of accelerated.

ec2_fleet_test.go:646 already accommodates the gap defensively (if d.State != "terminated" && d.State != "shutting-down"), which is a hint that the shape was expected at some point.

In scope by the CLAUDE.md test

Is this observable through an API call, or is it resource-internal? Purely observable: DescribeInstances reports the state, and TerminateInstances/StopInstances/StartInstances each report currentState and previousState in their own response. Nothing here requires modeling what the instance is doing while it shuts down — only that the API says so, in order, over the simulated clock. TerminateInstances's own reference response shows code 32 as the currentState.

What a fix needs to decide

The design question is what advances the state, and there are three candidate shapes with an established precedent each. The answer must not introduce wall-clock dependence — no test may depend on real time (CLAUDE.md), so "settle after 30 real seconds" is not available.

  1. Advance on the next observation. The first DescribeInstances after a terminate reports shutting-down; the second reports terminated. Cheap, needs no clock, and every waiter converges. But the state then depends on how many times it was read, which is a strange property to hold and could surprise a consumer who describes twice for unrelated reasons.
  2. Advance over the simulated clock. Store a transition deadline; report the transient state until tc.Now() passes it. This is the shape substrate already uses for read-after-write consistency (consistency.go:81-118 compares c.tc.Now() against a stored expiry and refuses until it passes), and it is the most faithful: the state is a function of simulated time, not of read count. It needs a durable answer to how a test advances the clock, and a default duration that is documented as substrate's own rather than observed — the reference gives no duration for shutting-down.
  3. Seeded, defaulting to instantaneous. Keep today's behaviour as the default and let a test seed a transition duration or a fixed number of transient observations per instance, via POST /v1/ec2/instance-state/... keyed by instance ID or "*". This is the plugin-seeding pattern the repo uses everywhere (SSM command invocation Pending → InProgress → Success, Bedrock/SageMaker job status), and it is the only option that cannot regress an existing fixture.

My instinct is 3 layered over 2: the transient state is a function of the simulated clock, and the duration is a seedable value that defaults to zero, so existing tests are byte-identical and a consumer opts in to exercising their waiter. But that trades fidelity-by-default for compatibility, which is the opposite of how #489 and #490 were decided, so it deserves an argument rather than an assumption.

Two further questions a fix must answer:

  • previousState in the operation's own response. TerminateInstances on a running instance reports previousState: running, currentState: shutting-down. Substrate reports running → terminated. Whatever advances the state, the immediate response must report the transient one.
  • What is legal from a transient state. Real EC2 refuses StartInstances on an instance that is stopping (IncorrectInstanceState), and terminating an already-terminated instance is idempotent (Termination protection is recorded and reported but TerminateInstances does not honour it #489's suite pins that and it must stay pinned). Introducing transient states introduces states from which today's unconditional handlers would do the wrong thing — StopInstances on a pending instance, for instance, currently just writes stopped.

Acceptance criteria

  • A decision recorded on this issue for what advances the state, with the argument for it — not just the implementation.
  • TerminateInstances reports 32 shutting-down as currentState and the instance's prior state as previousState.
  • DescribeInstances observes shutting-down before terminated, and the sequence is reproducible across a replay of the same event log.
  • The same for pending on RunInstances and StartInstances, and stopping on StopInstances.
  • An operation that is illegal from a transient state is refused with IncorrectInstanceState rather than silently applied; terminating an already-terminated instance stays idempotent.
  • No test depends on wall-clock time.
  • docs/services.md replaces Termination protection is recorded and reported but TerminateInstances does not honour it #489's "one divergence remains" paragraph with the modelled lifecycle, and states plainly which durations are substrate's own rather than observed.
  • The existing EC2 and fleet suites pass unchanged, or every changed expectation is justified as a fidelity fix rather than an accommodation.

Activity

  1. added
    type: bug
    priority: medium
    status: needs-design
    on Aug 2, 2026
  2. scttfrdmn commented on Aug 9, 2026

    @scttfrdmn
    OwnerAuthor

    The shared clock question is settled — it no longer blocks anything

    This issue's design section waited on whether a simulated transient window is
    representable, the same question #501 was deferred on. It is settled, and settled
    against the assumption both issues were filed under: TimeController.Now() is
    simBaseline + (wall_now − wall_baseline) × scale, so simulated time advances with
    real wall time. emulator/sqs_control.go:20-27 already draws the conclusion — a
    duration-based window "would make 'still missing' assertions wall-clock dependent —
    which no test here may be", and a counted-observation seed "is exactly reproducible".

    The consequence for a transient-state model is concrete: a duration-based
    pending → running window is not available
    , because a test asserting "still pending"
    would pass or fail depending on how long the machine took to get there. The established
    substitute is a counted one — N observations in the transient state before the
    transition, seeded and exactly reproducible — which is the shape sqs_control.go uses
    and the shape #501 applied (position-based ordering rather than manufactured intervals).

    That is a constraint on the design here, not a reason to close: EC2 instance transient
    states remain unmodelled, and RunInstances still returns an instance already running.
    This issue stands on its own merits, with the clock question answered and the pattern to
    follow now in-repo.

  3. scttfrdmn commented on Aug 9, 2026

    @scttfrdmn
    OwnerAuthor

    Flagging a deliberate decision made in v0.97.0's Organizations work (#578) so it does not get read as a precedent this issue has to live with.

    CreateAccount becomes asynchronous there: it returns IN_PROGRESS with a persisted car- request ID, and DescribeCreateAccountStatus reports the terminal outcome. That needed a rule for when the status resolves, which is exactly the question this issue is open to design.

    It resolves on the first observation — the initial DescribeCreateAccountStatus flips IN_PROGRESS to SUCCEEDED (or to the seeded FAILED) and stamps CompletedTimestamp from the simulated clock. Not clock-driven, on purpose:

    • A waiter converges in one poll with no dependence on wall-clock time or on the test having advanced the clock, so the async shape is testable today.
    • It commits nothing about the transition-over-simulated-time model. Picking a duration, a schedule, or an advance-the-clock trigger here would have front-run this issue's design with a shape chosen for one operation's convenience.

    So treat it as a placeholder, not a design input. When this issue lands a general mechanism, DescribeCreateAccountStatus is a natural early consumer: the observable contract (IN_PROGRESS → SUCCEEDED/FAILED, with CompletedTimestamp) stays the same, and only what triggers the transition changes. The choice is recorded in the OrganizationsPlugin doc comment for the same reason.

  4. added this to the v0.120.0 milestone on Sep 19, 2026
  5. scttfrdmn commented on Sep 19, 2026

    @scttfrdmn
    OwnerAuthor

    Premise corrections and provenance, verified at 57fdf31 before implementation.

    1. All four cited lines have drifted. The write sites are now ec2_plugin.go:681 (RunInstances → running), :1298 (terminated), :1366 (stopped) and :1412 (StartInstances → running) — not :537/:963/:1025/:1071. All four still reach a terminal state directly, so the defect is real and unfixed. EC2InstanceState's doc comment (ec2_types.go:14-22) enumerates all six codes, three of which no code path can produce.

    2. The recommended shape is the one the in-tree precedent explicitly rejects. This issue recommends "option 3 layered over option 2" — a seedable duration over the simulated clock. ec2_snapshot_control.go (#715) is the precedent in this same plugin and argues against exactly that: "[TimeController.Now] advances with wall time from its baseline, so a duration seed would expire partway through a test and make every 'still pending' assertion depend on how long the rest of the test took — which no test here may be. A count of observations is exactly reproducible." sqsConsistencySeed records the same choice for the same reason. So this ships as a seeded count of observations defaulting to zero, which keeps every existing fixture byte-identical.

    3. AC2 and AC4 are stronger than the issue claims — the whole progression is published, and in two independent places.

    ec2-instance-lifecycle.html's state table publishes each transient state directly:

    pending — "The instance is preparing to enter the running state. An instance enters the pending state when it is launched or when it is started after being in the stopped state."
    stopping — "The instance is preparing to be stopped."
    shutting-down — "The instance is preparing to be terminated."

    and its prose publishes the orderings: "When you stop your instance, it enters the stopping state, and then the stopped state", "When you start your instance, it enters the pending state", "When you launch an instance, it enters the pending state", "As soon as the status of an instance changes to shutting-down or terminated…".

    Separately, both operation pages' sample responses publish the transient state in the immediate response: API_StartInstances shows currentState 0/pending against previousState 80/stopped, and API_StopInstances shows currentState 64/stopping against previousState 16/running. Substrate currently reports the settled state as currentState in both, so that is a published-response divergence independent of any seed, and it is fixed unconditionally rather than behind the seed. Note this also means the transient state is derived from the target by the published lifecycle, so the progression carries no state/finalState members — unlike a snapshot, whose state is a free choice from a five-value enumeration.

    4. AC5's supporting claim is published nowhere, and the precedent's own rule makes it unreachable. The issue says "Real EC2 refuses StartInstances on an instance that is stopping (IncorrectInstanceState)". API_StartInstances and API_StopInstances both publish empty Errors sections — only "For information about the errors that are common to all actions, see Common Error Types" — and neither states any state precondition beyond the instance-store-root rule. errors-overview.html does publish the code, in the client-errors-for-specific-actions table, but with a generic description ("The instance is in an incorrect state for the requested action") and two worked examples, neither of them a start.

    More decisively: under the precedent's rule that a seed governs what an observation reports and never rewrites the record, the stored state is always the settled one, so no operation ever sees a transient state. AC5's first half is vacuous by construction rather than declined — which is the right outcome, because it is also what keeps the feature from breaking a caller whose start follows a stop.

    What AC5's second half points at is a real and published defect, which this PR does fix: startInstances and stopInstances currently resurrect a terminated instance, where the lifecycle table publishes "The instance has been permanently deleted and cannot be started." The start refusal rests on that sentence directly; the stop refusal rests on "permanently deleted" alone, since no page found states a stop precondition, and the doc comment records that difference. ec2IncorrectInstanceState (ec2_instanceattribute.go:235) already exists but its message is attribute-specific, so this adds a sibling constructor rather than reusing it.

    5. The observation point. describeInstances (:1146) and describeInstanceStatus (:1455) have byte-identical loop shapes — unmarshal, ID filter, ec2InstanceMatchesFilters, render — so the observed state is substituted after the ID filter and before the filters, in one line each. That makes instance-state-name filtering, the rendered instanceState, and DescribeInstanceStatus all agree, rather than leaving a filter matching the settled state while the body reports the transient one. Advancing only for ID-matched instances is what keeps a describe of one instance from burning another's countdown, which is the hazard ec2SnapObservedKey records.

    No test in the tree asserts currentState, previousState, or any transient state name, so the unconditional response fix breaks nothing.

  6. scttfrdmn commented on Sep 19, 2026

    @scttfrdmn
    OwnerAuthor

    One further correction, found while implementing and worth recording before the PR opens: the replay half of AC6 cannot hold, and not because of anything specific to this feature.

    AC6 asks for "replay the event log to prove the sequence reproduces". A seed is written through the control plane (POST /v1/ec2/instance-state), and Server records an event only in the AWS-request path — so the seed never enters the stream. ReplayEngine.Replay then calls resetState, which does ss.Reset(ctx) on the whole StateManager, clearing the seed along with the resource state. A replay of a seeded stream therefore answers the unseeded sequence, and no event fails, so nothing surfaces. This is true of every seed in substrate — Bedrock and SageMaker job status, the Athena/RedshiftData/Timestream results, the snapshot progression this feature is modelled on, the SQS consistency seed — and docs/services.md currently states the opposite ("Seeds live in the state manager, so they replay like any other state"). Filed as #1140, with the three candidate fixes; the false sentence is corrected in this PR.

    So AC6 ships as two assertions that can hold, and which say more between them than the literal one would have:

    1. Determinism by repetition. The stop-then-poll sequence runs twice over two servers sharing nothing, asserting stopping, stopping, stopping, stopped, stopped both times. That is the property the seed exists for — a poll loop sees the same states in the same order on every run, so a red test is a real signal and not timing noise.
    2. A replay proving the record was never rewritten. The recording observes pending twice under a seed while its record holds running; the replay, seedless, re-derives running. Had either observation been written back, the recording's record would have held pending and the two would disagree. This is the sharp test of the rule the whole design rests on, and it is also what makes AC5's first half vacuous by construction, as the earlier comment set out.

    One incidental constraint on the second: its recorded stream contains no instance ID at all, because a replayed RunInstances mints a new random ID and a recorded StopInstances naming the recording's ID answers InvalidInstanceID.NotFound on replay. That is #856's second debt, neither introduced nor fixed here; the assertion reads whichever single instance the replay minted instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: ec2priority: mediumstatus: needs-designtype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions