Repository navigation
fix(replay): reset plugin-held mutable state, not just the StateManager (#886) - #906
Merged
Merged
Conversation
…er (#886) ReplayEngine.resetState reset the StateManager and nothing else, while three plugins mint identifiers from state on their own struct: S3Plugin.versionSeq, SESv2Plugin.msgSeq and OmicsPlugin.rng. Nothing could reach them, so a second replay of one recorded stream continued the first replay's counter and produced different identifiers from byte-identical events. Adds ResettablePlugin, an optional capability discovered by type assertion in the same way SnapshotableStateManager already is, and PluginRegistry.ResetPlugins to drive it. Both reset paths call it — the replay engine and POST /v1/state/reset — clearing the state manager first so a plugin's ResetForRun can write its start-of-run state without being wiped. The HealthOmics source is rewound to its original seed rather than re-seeded, so a replay draws the values the recording drew, and its *rand.Rand picks up the mutex it always needed. Closes #886.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
# Conflicts: # CHANGELOG.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What was broken
ReplayEngine.resetStatereset theStateManagerand nothing else, and its doc comment said so — it existed so a replay begins from the recorded run's starting point, and it did that for state only. Three plugins mint identifiers from mutable state on their own struct, which no reset could reach:S3Plugin.versionSeq— everyx-amz-version-idand every delete-marker ID (emulator/s3_plugin.go:927,:1200);SESv2Plugin.msgSeq— everyMessageId(emulator/sesv2_plugin.go:243);OmicsPlugin.rng— every HealthOmics run ID (emulator/omics_plugin.go:215).So replaying one recorded stream twice in a single process minted different identifiers the second time from byte-identical events, and — since the CLI now runs a real registry (#855) — from
substrate replay, not only from a hand-built engine in a test. A replay whose output depends on how many replays preceded it is the one property the event log exists to rule out.POST /v1/state/resetis fixed with it, because it is the same defect through a different door: it is documented as wiping emulator state and is whatTestServer.ResetStatecalls between test cases, so a surviving counter made the identifiers one test case observes depend on how many test cases ran before it in the process.Two details in the issue body had drifted and are worth recording:
S3Plugin.versionSeqis a plainint64mutated withatomic.AddInt64, not anatomic.Int64, and the SES type isSESv2Plugin, notSESV2Plugin. The registry andresetStatewere otherwise exactly as described.The interface-design decision
ResettablePluginis an optional capability, discovered by type assertion:Optional, not a method on
Plugin, for three reasons:SnapshotableStateManageris exactly this shape — an optional interface over a mandatory one, asserted at the call site, with the absent case a documented skip — andresetStatewas already written against it, so the new half reads like the existing half.Pluginwould mean 64 no-op implementations whose only function is to satisfy the compiler, and the next plugin author would copy one without asking whether it should do something.Pluginis public API. Adding a method breaks every third-party plugin at compile time, which is a disproportionate price for reaching three counters.The method name is
ResetForRunrather thanReset: a single-method interface namedResetis the kind a type satisfies by accident, and both callers mean specifically "return to a run's starting point", which is what the name says.Two supporting decisions:
PluginRegistry.ResetPluginsvisits every resettable plugin even after one fails, joining the errors (errors.Join, each wrappedfmt.Errorf("reset plugin %s: %w", name, err)). Stopping at the first failure would leave the remaining plugins holding the previous run's counters — the exact condition the method exists to remove — while reporting that a reset had been attempted. Visiting order is sorted by name so a multi-plugin failure reports identically on every run, and the registry lock is released before any plugin is called, because a plugin's reset may re-enter the registry.StateManageris cleared first, the plugins second, in both call sites, with the reason in a comment.ResetForRunis allowed to write a plugin's start-of-run state into the state manager (a seed, an index); clearing the store afterwards would erase precisely what the plugin had just re-established. The reverse order would make a plugin's reset silently dependent on whether it wrote anything.PluginRegistry.Plugin(name) (Plugin, bool)is new so a caller can ask what a registered plugin implements without routing a request to it. The audit test below uses it; it is a plain registry accessor otherwise.HealthOmics gets one further change. Its source is rewound to the seed it was built from rather than re-seeded, so a replay draws the same values the recording drew — the recording drew from position 0 of that seed, and so must the replay. The seed itself is still per-process wall clock; making it reproducible across processes is #856's question and is deliberately not answered here. Its
*rand.Randalso picks up the mutex it always needed: a reset can now replace it under a concurrent request, and two concurrentStartRuncalls were already racing on it unguarded.Inventory of plugin-held mutable state
Every one of the 67 registered plugin structs was read field by field. 60 hold nothing but injected dependencies (
state,logger,tc).Fixed here — mutable state feeding a minted identifier:
S3PluginversionSeq(s3_plugin.go:54)int64+atomic.AddInt64SESv2PluginmsgSeq(sesv2_plugin.go:20)atomic.Int64MessageIdOmicsPluginrng(omics_plugin.go)*rand.RandFound, deliberately not fixed here, filed instead:
S3Pluginfs afero.FsPutObjectoverwrites them — but it is unbounded growth and a read-through waiting for a future fast path. The plugin does not own an injectedafero.Fs, so "wipe it" is not obviously correct; that needs its own decision.LambdaPluginesmStop map[string]chan struct{}LambdaPluginexecutor.poolRDSPluginexecutor.activeRedshiftDataPluginresults map[string]*RedshiftDataResultThe #903 three are lifecycle rather than determinism: stopping a poller or tearing down a container is not reversible the way rewinding a counter is, and per
CLAUDE.md's scope boundary the executors run the workload rather than answer an API observation, so "reset" for them is a different question (what should a mid-run reset do to work in flight?).Not plugin-held mutable state, for the record: every
seedMu/keyLocksmutex on a plugin struct guards a value that lives in theStateManager, not on the plugin (S3Plugin.seedMu,EC2Plugin.seedMu,SQSPlugin.seedMu,S3Plugin.keyLocks) — a state reset already clears what they guard.TimeController,PluginRegistry,EventStore,CostControllerandAuthControllerreferences are server-owned shared dependencies.managedPolicyMap(iam_managed.go) and the CRC table (s3_checksum.go) are build-once lookup tables. The fault controller's PRNGs are controller-held and already cleared on reset.Two things found that are neither, and are not fixed here:
organizations_plugin.go:286,296,306mints IDs from the globalmath/rand. Not a struct field, so no hook can reach it; it is#856's subject matter exactly.Options["time_controller"], so those plugins fall back to a private real-time clock and run on wall-clock time inside a controlled-clock emulator — filed as 15 of 67 default plugin registrations omit time_controller, so those plugins run on wall-clock time #904. This is whySESv2Plugin.msgSeq's fix is only half of a reproducibleMessageId: the identifier ismsg-<clock>-<counter>, and the clock half is not the server's clock. The test wires SES v2 to the server clock itself and says to delete that workaround when 15 of 67 default plugin registrations omit time_controller, so those plugins run on wall-clock time #904 lands.Relationship to #856
This discharges #856's prerequisite and nothing else. #856 wants ~66 minters made deterministic; a counter or a PRNG is only reproducible if something rewinds it between runs, so the lifecycle hook had to exist first — that is why #886 was filed separately. What remains of #856 after this: where a mint's value comes from (
crypto/randin most minters, the globalmath/randin Organizations, wall-clock nanoseconds in the S3/SES composite IDs), and whether a seed is reproducible across processes rather than only within one. Nothing here decides any of that. #904 is now a second prerequisite: an identifier composed fromtc.Now()cannot be reproducible while the plugin's clock is not the server's.Files
emulator/types.go—ResettablePlugin,PluginRegistry.ResetPlugins,PluginRegistry.Plugin.emulator/replay.go—resetStatecalls the hook; doc comment no longer implies theStateManageris the whole of a plugin's mutable state, and states the ordering and its reason.emulator/server.go—handleStateResetcalls the hook, same ordering, same reason.emulator/s3_plugin.go,emulator/sesv2_plugin.go,emulator/omics_plugin.go— implementations; Omics also gainsrngSeedandrngMu.emulator/replay_plugin_reset_test.go— new.docs/contributing.md,emulator/doc_plugins.go— plugin-author guidance on state kept outside theStateManager.CHANGELOG.md—Added(the capability) andFixed(the defect).docs/services.mdis unchanged: it is generated, and nothing here changes a service's surface.Tests
emulator/replay_plugin_reset_test.go,package emulator_test, table-driven, no network and no wall-clock dependence:TestPluginReset_ReplayingTwiceMintsTheSameIdentifiers— the behavioral test. Three rows (S3 version IDs, SES v2MessageIds, HealthOmics run IDs). Each records its workload over the wire through aTestServer, then replays that stream twice in one process through the same registry the server serves from, and asserts the two replays produce identical identifiers and that they reproduce the ones the recording minted — the stronger claim, since two replays could agree on the wrong values. Each replay also assertsSkippedEvents == 0andSuccessEvents == TotalEvents, so the comparison cannot be satisfied by a replay that executed nothing (Replay bypasses authorization, quota, consistency and fault injection #833).Two deliberate choices, both explained in the file: the simulated clock is frozen (
SetScale(0)) before recording, because the minted values are<clock>-<counter>pairs and with the clock running the time half varies on wall-clock elapsed time — freezing leaves the counter as the only thing that can differ, which is the defect. And the S3/Omics rows read the resulting identifiers from the state manager rather than throughListObjectVersions/ListRuns, because an AWS call over the wire is recorded, which would make the second replay replay a longer stream than the first and the two runs incomparable. The SES v2 row reads back over the wire throughGET /v1/emails, which is control-plane and records nothing.TestPluginReset_StateResetRewindsAMintingCounter— entirely over the wire: two versioned writes,POST /v1/state/reset, the same two writes again, and the version IDs must be identical.TestPluginRegistry_ResetPlugins— the registry hook itself: resettable plugins are called exactly once, a non-implementer is skipped, a failure is wrapped with the plugin's name, and one or two failures do not stop the others.TestPluginRegistry_ResetPluginsIsSafeOnAFreshRegistry— an empty registry, and a plugin that has minted nothing.TestPluginReset_DefaultPluginsImplementingTheHook— the audit as an assertion: the implementer set is exactly{omics, s3, sesv2}, so a plugin gaining or losing the hook cannot pass unnoticed.Mutation test
Production change reverted by copying the file aside (not
git stash), re-run, restored.Reverting the
ResetPluginscall inemulator/replay.go— all three rows fail:with, for example, the SES v2 row reporting
expected: ["msg-…-4","msg-…-5","msg-…-6"]againstactual: ["msg-…-7","msg-…-8","msg-…-9"]— the recording having minted 1–3, the first replay 4–6 and the second 7–9 from identical events, which is the defect verbatim.TestPluginReset_StateResetRewindsAMintingCounterstill passed, correctly: that half lives inserver.go.Reverting the
ResetPluginscall inemulator/server.go:Both files restored; the suite is green.
Verification
Coverage baseline held exactly: 83.9% emulator / 83.4% total.
Compatibility
For a consumer: no API shape, error code or response changes. Two observable behaviour changes, both of them the point of the PR. A replay now mints the same identifiers every time it runs in a process, where before the second and later replays diverged — code asserting the old divergent values would have been asserting a bug. And
POST /v1/state/reset(soTestServer.ResetState) now rewinds the S3 version-ID counter, the SES v2 message counter and the HealthOmics random source, so a test case's minted identifiers no longer depend on how many test cases preceded it; a test asserting a literalmsg-…-7that only held because six earlier sends had run will need updating, and was pinning process history rather than behaviour. Object payloads in the S3 plugin's filesystem still survive a reset (#902), and 15 plugins still run on a private wall-clock (#904).For a plugin author:
Pluginis unchanged — no existing plugin needs to do anything. If your plugin keeps mutable state on its own struct rather than in theStateManager, implementResetForRun(ctx) errorand both reset paths will call it;docs/contributing.mdandemulator/doc_plugins.gosay so with an example.ResetForRunmust be safe on a plugin that has never handled a request and safe to call while requests are in flight (Omics needed a mutex for exactly this). New exported symbols are additive:ResettablePlugin,PluginRegistry.ResetPlugins,PluginRegistry.Plugin.Sub-task of #856, which stays open — see the section above for what remains of it. Follow-ups filed: #902, #903, #904.
Closes #886.