Skip to content

fix(replay): reset plugin-held mutable state, not just the StateManager (#886) - #906

Merged
scttfrdmn merged 2 commits into
mainfrom
feat/plugin-reset-hook
Sep 15, 2026
Merged

scttfrdmn merged 2 commits into
mainfrom
feat/plugin-reset-hook

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

What was broken

ReplayEngine.resetState reset the StateManager and 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 — every x-amz-version-id and every delete-marker ID (emulator/s3_plugin.go:927, :1200);
  • SESv2Plugin.msgSeq — every MessageId (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/reset is fixed with it, because it is the same defect through a different door: it is documented as wiping emulator state and is what TestServer.ResetState calls 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.versionSeq is a plain int64 mutated with atomic.AddInt64, not an atomic.Int64, and the SES type is SESv2Plugin, not SESV2Plugin. The registry and resetState were otherwise exactly as described.

The interface-design decision

ResettablePlugin is an optional capability, discovered by type assertion:

type ResettablePlugin interface {
	ResetForRun(ctx context.Context) error
}

Optional, not a method on Plugin, for three reasons:

  1. It is the house pattern already. SnapshotableStateManager is exactly this shape — an optional interface over a mandatory one, asserted at the call site, with the absent case a documented skip — and resetState was already written against it, so the new half reads like the existing half.
  2. 64 of the 67 registered plugins need no reset of their own. A method on Plugin would 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.
  3. Plugin is 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 ResetForRun rather than Reset: a single-method interface named Reset is 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.ResetPlugins visits every resettable plugin even after one fails, joining the errors (errors.Join, each wrapped fmt.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.
  • Ordering: the StateManager is cleared first, the plugins second, in both call sites, with the reason in a comment. ResetForRun is 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.Rand also picks up the mutex it always needed: a reset can now replace it under a concurrent request, and two concurrent StartRun calls 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:

plugin field type why it must be reset
S3Plugin versionSeq (s3_plugin.go:54) int64 + atomic.AddInt64 version IDs, delete-marker IDs
SESv2Plugin msgSeq (sesv2_plugin.go:20) atomic.Int64 MessageId
OmicsPlugin rng (omics_plugin.go) *rand.Rand run IDs; also unguarded against concurrent use

Found, deliberately not fixed here, filed instead:

plugin field what it holds disposition
S3Plugin fs afero.Fs every object payload; metadata is in the state manager, bytes are not, so both reset paths leave them #902. Cannot change a minted identifier — the metadata is gone so nothing can read the bytes, and a replayed PutObject overwrites them — but it is unbounded growth and a read-through waiting for a future fast path. The plugin does not own an injected afero.Fs, so "wipe it" is not obviously correct; that needs its own decision.
LambdaPlugin esmStop map[string]chan struct{} one stop channel per event-source mapping, each with a live poller goroutine #903
LambdaPlugin executor.pool warm containers #903
RDSPlugin executor.active live Postgres containers #903
RedshiftDataPlugin results map[string]*RedshiftDataResult caller-seeded result sets, survives a reset Left deliberately, and the reasoning is the point: a seeded result set is installed through a control-plane call, which streams do not record. Wiping it at replay would make the replay diverge from the recording it is reproducing — the recorded query returned seeded rows and the replay would return defaults. Not resetting it is the correct behaviour, not an oversight.

The #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/keyLocks mutex on a plugin struct guards a value that lives in the StateManager, not on the plugin (S3Plugin.seedMu, EC2Plugin.seedMu, SQSPlugin.seedMu, S3Plugin.keyLocks) — a state reset already clears what they guard. TimeController, PluginRegistry, EventStore, CostController and AuthController references 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:

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/rand in most minters, the global math/rand in 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 from tc.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 — resetState calls the hook; doc comment no longer implies the StateManager is the whole of a plugin's mutable state, and states the ordering and its reason.
  • emulator/server.go — handleStateReset calls the hook, same ordering, same reason.
  • emulator/s3_plugin.go, emulator/sesv2_plugin.go, emulator/omics_plugin.go — implementations; Omics also gains rngSeed and rngMu.
  • emulator/replay_plugin_reset_test.go — new.
  • docs/contributing.md, emulator/doc_plugins.go — plugin-author guidance on state kept outside the StateManager.
  • CHANGELOG.md — Added (the capability) and Fixed (the defect).

docs/services.md is 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 v2 MessageIds, HealthOmics run IDs). Each records its workload over the wire through a TestServer, 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 asserts SkippedEvents == 0 and SuccessEvents == 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 through ListObjectVersions/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 through GET /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 ResetPlugins call in emulator/replay.go — all three rows fail:

--- FAIL: TestPluginReset_ReplayingTwiceMintsTheSameIdentifiers/s3_object_version_IDs_come_from_S3Plugin.versionSeq
--- FAIL: TestPluginReset_ReplayingTwiceMintsTheSameIdentifiers/sesv2_MessageIds_come_from_SESv2Plugin.msgSeq
--- FAIL: TestPluginReset_ReplayingTwiceMintsTheSameIdentifiers/omics_run_IDs_come_from_OmicsPlugin.rng

with, for example, the SES v2 row reporting expected: ["msg-…-4","msg-…-5","msg-…-6"] against actual: ["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_StateResetRewindsAMintingCounter still passed, correctly: that half lives in server.go.

Reverting the ResetPlugins call in emulator/server.go:

--- FAIL: TestPluginReset_StateResetRewindsAMintingCounter

Both files restored; the suite is green.

Verification

$ gofmt -l . && go build ./... && go vet ./...
(no output, exit 0)

$ golangci-lint run ./...
0 issues.

$ make test
ok  github.com/scttfrdmn/substrate/cmd/gen-authz-reference     2.089s
ok  github.com/scttfrdmn/substrate/cmd/gen-service-reference   1.462s
ok  github.com/scttfrdmn/substrate/cmd/substrate               1.869s
ok  github.com/scttfrdmn/substrate/emulator                    18.634s

$ GOTOOLCHAIN=go1.26.6 make test
(exit 0, all four packages ok)

$ GOTOOLCHAIN=go1.26.6 make coverage
ok  github.com/scttfrdmn/substrate/emulator  13.516s  coverage: 83.9% of statements
total: (statements) 83.4%

$ make docs-reference docs-reference-check docs-versions authz-reference-check
docs/services.md already up to date (67 plugins)
(exit 0)

$ go vet -C test/e2e ./... && go test -C test/e2e ./...
ok  github.com/scttfrdmn/substrate/test/e2e  0.796s

$ npm --prefix docs run build
build complete in 1.79s.

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 (so TestServer.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 literal msg-…-7 that 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: Plugin is unchanged — no existing plugin needs to do anything. If your plugin keeps mutable state on its own struct rather than in the StateManager, implement ResetForRun(ctx) error and both reset paths will call it; docs/contributing.md and emulator/doc_plugins.go say so with an example. ResetForRun must 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.

…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

codecov Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.48936% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
emulator/replay.go 71.42% 2 Missing ⚠️
emulator/server.go 50.00% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn
scttfrdmn merged commit 4c4a23a into main Sep 15, 2026
17 checks passed
@scttfrdmn
scttfrdmn deleted the feat/plugin-reset-hook branch September 15, 2026 23:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

replay: PluginRegistry has no reset hook, so plugin-held counters survive resetState

1 participant