Repository navigation
Description
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 therunningstate. An instance enters thependingstate when it is launched or when it is started after being in thestoppedstate.
When you stop your instance, it enters the
stoppingstate, and then thestoppedstate.
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.
- Advance on the next observation. The first
DescribeInstancesafter a terminate reportsshutting-down; the second reportsterminated. 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. - 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-118comparesc.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 forshutting-down. - 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 invocationPending → 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:
previousStatein the operation's own response.TerminateInstanceson arunninginstance reportspreviousState: running, currentState: shutting-down. Substrate reportsrunning → terminated. Whatever advances the state, the immediate response must report the transient one.- What is legal from a transient state. Real EC2 refuses
StartInstanceson an instance that isstopping(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 —StopInstanceson apendinginstance, for instance, currently just writesstopped.
Acceptance criteria
- A decision recorded on this issue for what advances the state, with the argument for it — not just the implementation.
-
TerminateInstancesreports32shutting-downascurrentStateand the instance's prior state aspreviousState. -
DescribeInstancesobservesshutting-downbeforeterminated, and the sequence is reproducible across a replay of the same event log. - The same for
pendingonRunInstancesandStartInstances, andstoppingonStopInstances. - An operation that is illegal from a transient state is refused with
IncorrectInstanceStaterather than silently applied; terminating an already-terminated instance stays idempotent. - No test depends on wall-clock time.
-
docs/services.mdreplaces 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
scttfrdmn commentedon Aug 9, 2026
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()issimBaseline + (wall_now − wall_baseline) × scale, so simulated time advances withreal wall time.
emulator/sqs_control.go:20-27already draws the conclusion — aduration-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 → runningwindow 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.gousesand 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
RunInstancesstill returns an instance alreadyrunning.This issue stands on its own merits, with the clock question answered and the pattern to
follow now in-repo.
scttfrdmn commentedon Aug 9, 2026
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.
CreateAccountbecomes asynchronous there: it returnsIN_PROGRESSwith a persistedcar-request ID, andDescribeCreateAccountStatusreports 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
DescribeCreateAccountStatusflipsIN_PROGRESStoSUCCEEDED(or to the seededFAILED) and stampsCompletedTimestampfrom the simulated clock. Not clock-driven, on purpose:So treat it as a placeholder, not a design input. When this issue lands a general mechanism,
DescribeCreateAccountStatusis a natural early consumer: the observable contract (IN_PROGRESS→SUCCEEDED/FAILED, withCompletedTimestamp) stays the same, and only what triggers the transition changes. The choice is recorded in theOrganizationsPlugindoc comment for the same reason.feat(organizations): make account vending asynchronous (#578) (#607)
scttfrdmn commentedon Sep 19, 2026
Premise corrections and provenance, verified at
57fdf31before 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."sqsConsistencySeedrecords 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:and its prose publishes the orderings: "When you stop your instance, it enters the
stoppingstate, and then thestoppedstate", "When you start your instance, it enters thependingstate", "When you launch an instance, it enters thependingstate", "As soon as the status of an instance changes toshutting-downorterminated…".Separately, both operation pages' sample responses publish the transient state in the immediate response:
API_StartInstancesshowscurrentState0/pendingagainstpreviousState80/stopped, andAPI_StopInstancesshowscurrentState64/stoppingagainstpreviousState16/running. Substrate currently reports the settled state ascurrentStatein 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 nostate/finalStatemembers — 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
StartInstanceson an instance that isstopping(IncorrectInstanceState)".API_StartInstancesandAPI_StopInstancesboth 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.htmldoes 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:
startInstancesandstopInstancescurrently resurrect aterminatedinstance, 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) anddescribeInstanceStatus(: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 makesinstance-state-namefiltering, the renderedinstanceState, andDescribeInstanceStatusall 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 hazardec2SnapObservedKeyrecords.No test in the tree asserts
currentState,previousState, or any transient state name, so the unconditional response fix breaks nothing.scttfrdmn commentedon Sep 19, 2026
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), andServerrecords an event only in the AWS-request path — so the seed never enters the stream.ReplayEngine.Replaythen callsresetState, which doesss.Reset(ctx)on the wholeStateManager, 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 — anddocs/services.mdcurrently 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:
stopping, stopping, stopping, stopped, stoppedboth 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.pendingtwice under a seed while its record holdsrunning; the replay, seedless, re-derivesrunning. Had either observation been written back, the recording's record would have heldpendingand 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
RunInstancesmints a new random ID and a recordedStopInstancesnaming the recording's ID answersInvalidInstanceID.NotFoundon replay. That is #856's second debt, neither introduced nor fixed here; the assertion reads whichever single instance the replay minted instead.refactor: one shared seeded-progression helper, with EC2 snapshots an…