Skip to content

fix(physics2d): stop spurious TriggerEnd for sustained sensor overlaps after rebuild - #1191

Open
detail-app[bot] wants to merge 1 commit into
mainfrom
detail/bug-fix/fix-physics2d-stop-spurious-triggerend-for-sustain-31a3cc
Open

detail-app[bot] wants to merge 1 commit into
mainfrom
detail/bug-fix/fix-physics2d-stop-spurious-triggerend-for-sustain-31a3cc

Conversation

@detail-app

@detail-app detail-app Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Detail bug report: View on Detail

Closes PER-556

Premise

  • Problem: Game code that latches trigger state (e.g. an "in the zone" flag set on TriggerBegin, cleared on TriggerEnd) silently desynchronizes after every snapshot restore / Plugin.Reset performed while a player stands in a trigger volume: the overlap's end transition is consumed while the entity is still inside, and no compensating TriggerBegin fires until the entity physically leaves and re-enters the sensor.
  • Source: Bug report (autonomous run). Root cause traced to diffActiveContactsAfterRebuild in pkg/plugin/physics2d/internal/contact_flush.go, introduced in commit ae574a1 (PR feat: add Box2D physics2d plugin with CGO #880).
  • Why this fix: The post-rebuild diff's "gone overlaps" End loop treated any persisted pair absent from the live solid contact list as ended. Box2D sensors never create contacts (broad-phase short-circuit + createContact assert), so persisted sensor pairs are structurally absent from that list and were always spuriously ended. The fix re-derives the live sensor overlap set from World.ShapeSensorData and checks sensor pairs against that set, so a sustained overlap produces no event while a genuinely ended one still emits TriggerEnd.
  • Alternatives considered: A minimal mitigation (skip sensor pairs in the End loop, keep them in the map) was noted in the report. It fixes the spurious End but misses legitimate ends while the world is torn down. The implemented query-based variant handles both cases and uses an API that already exists.
  • Product sign-off: Not a product decision.
  • Interview: Skipped — autonomous run.

Screenshot / Recordings

No visual behavior to capture. This is a physics event-correctness fix with no UI. Verification is via unit and integration tests (see below).

What changed

After a world rebuild (Plugin.Reset / snapshot restore), the physics plugin diffs the persisted ActiveContacts baseline against the live Box2D contact list to synthesize the Begin/End events that were suppressed during the rebuild step. That diff assumed every persisted pair appears in the live contact list — true for solid contacts, false for sensors (Box2D sensors never create contacts), so every still-overlapping sensor pair was emitted as a spurious TriggerEnd and deleted from the baseline.

diffActiveContactsAfterRebuild now gathers the live sensor overlap set separately from each sensor shape's overlap list (World.ShapeSensorCapacity / ShapeSensorData) and routes the End check for IsSensor pairs through that set:

  • Sustained sensor overlap → no event, pair retained (the bug, fixed)
  • Genuinely ended sensor overlap → TriggerEnd still emitted, pair removed (no over-correction)
  • New sensor overlaps during the suppressed step → still not emitted as Begins (existing one-shot suppression preserved)
  • Solid contact path → unchanged

Two reused scratch fields were added to Runtime and are dropped by Reset(), matching the existing scratch convention.

diffActiveContactsAfterRebuild(em):
  liveContacts = gatherLiveContactsInto()        // solid pairs only
  liveSensorOverlaps = gatherLiveSensorOverlapsInto()  // NEW: sensor pairs from ShapeSensorData
  FOR key, info IN ActiveContacts:
    live = info.IsSensor ? liveSensorOverlaps : liveContacts   // FIX
    IF key NOT IN live: emit End, delete

How did you verify?

  • New unit tests (5 tests in contact_flush_internal_test.go): drive the real Step + FlushBufferedContacts pipeline with a co-located zero-gravity sensor/visitor pair and a persisted baseline. The sustained-overlap test asserts zero events, pair retention, and 5 follow-up ticks stay silent; the gone-overlap test asserts exactly one TriggerEnd; a third test pins that new (unsuppressed-baseline) sensor overlaps still do not emit a TriggerBegin; two solid-path tests confirm no regression. All pass. As a negative control, reverting only the IsSensor branch back to the old liveContacts-only lookup makes the sustained test fail with a spurious TriggerEnd (A=1,B=2) while the other four stay green, confirming the test pins the exact bug.
  • Internal package suite passes, including TestRestoreIsDeterministicAcrossRepeatedRuns.
  • Plugin integration suite (pkg/plugin/physics2d/test/) passes, including TestPhysics2D_CardinalIntegration (crash1/crash2 synthetic TriggerEnd assertions — still correct since the ball is genuinely moved out of the sensor) and TestGoldenTrace (incl. sensor_trigger).
  • E2e scenario suite (pkg/plugin/physics2d/test/e2e/) passes, including TestScenarios/reset ("the rebuild invents no TriggerEnd"), TestRestore, TestExhaustiveBodyMatrix, TestDigestIsWorkerInvariant, and TestRandomScenes.
  • E2e CLI (407 checks), the crash-restore check (10 checks), and the worker-invariance digest (407 checks at 8 workers) all pass.
  • Lint, format, and build pass: gofmt clean, go vet clean, go build ./pkg/... and cli build clean, golangci-lint run ./pkg/plugin/physics2d/... reports 0 issues (golangci-lint 2.15.0, the pinned version).

Caveats

None known. The fix only adds a sensor-specific path to the post-rebuild End check; the solid contact path and the one-shot suppression of build-time overlaps are unchanged.

AI Usage

Created with Detail in opencode. Fully autonomous — the human supplied the bug report; implementation, test design, and verification were performed autonomously.


Automatic Fixes PRs can be configured here.


Summary by cubic

Fixes spurious TriggerEnd events after Plugin.Reset / snapshot restore for sensor overlaps that are still active, so game code latching trigger state stays in sync.

The post-rebuild diff treated any persisted pair absent from the live solid contact list as ended. Box2D sensors never create contacts, so every still-overlapping sensor pair was wrongly ended and dropped from the baseline. The diff now also derives the live sensor overlap set from each sensor shape's overlap list (World.ShapeSensorData) and ends a persisted pair only when it appears in neither live set; destroyed visitor shapes are skipped so their pairs emit TriggerEnd instead of resolving to a freed slot.

  • Sustained sensor overlaps stay silent; genuinely ended ones still emit exactly one TriggerEnd.
  • A pair persisted as sensor but rebuilt solid is retained so the next refresh flips its IsSensor flag.
  • Solid contact path unchanged; added unit tests covering sustained and gone sensor overlaps after rebuild.

Written for commit 0ddd0a2. Summary will update on new commits.

View guided diff Turn on auto-fix

@smsunarto smsunarto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine

🔁 Want another pass? Push your changes, then comment @slopcop on this PR. SlopCop only re-reviews when asked, and the follow-up checks the new commits and your replies to these comments.

The root cause holds up. Sensors never get contacts, so the old End loop always treated a persisted trigger pair as gone, and ShapeSensorData is the right source to check against.

My main concern is that this fixes only one way the trigger latch desyncs on restore. New sensor overlaps from the suppressed step still get no Begin and aren't adopted. adoptLiveContactsWithoutEmit and refreshActiveContactsFromLive also read only the solid gather. So a trigger pair missing from the baseline at restore still gets an unpaired TriggerEnd later.

This PR already builds the live sensor set. I'd rather decide here whether all three paths should use it, or write down why they shouldn't.

Comment on lines +102 to +104
// TriggerEnd. New sensor overlaps that began during the suppressed step are intentionally not
// emitted as Begins, matching the build-time suppression of co-located overlaps (see
// adoptLiveContactsWithoutEmit and the suppressed step in bufferContactEventsFromWorld).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 H · field choice

A sensor overlap that starts during the suppressed step gets no TriggerBegin and never enters ActiveContacts. When the visitor leaves, the game gets a TriggerEnd it never saw begin, which is the same latch desync this PR fixes.

With a baseline present, the solid loop above does emit ContactBegin for new pairs. adoptLiveContactsWithoutEmit only runs on the missing-singleton path, so it doesn't fit as the precedent here.

Could we emit Begin and adopt any liveSensorOverlaps key missing from ActiveContacts, the same way the solid loop does? A test with a non-empty baseline would pin it either way.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR deliberately preserves the one-shot suppression of build-time sensor overlaps: TestDiffAfterRebuildDoesNotEmitBeginForNewSensorOverlap pins that a sensor overlap absent from the baseline gets no TriggerBegin, and the PR body documents "New sensor overlaps during the suppressed step → still not emitted as Begins." Emitting Begins + adopting new sensor overlaps would invert that pinned behavior, which is a design change beyond this PR's scope (it targets the sustained-overlap spurious End).

I checked diffActiveContactsAfterRebuild (contact_flush.go:105): the End loop only iterates ActiveContacts, so a pair that never enters the map is not ended by the diff. The unpaired TriggerEnd on a later leave runs through bufferContactEventsFromWorld (contact_listener.go:93) on a normal tick — the same pre-existing suppression tradeoff adoptLiveContactsWithoutEmit already makes. Extending the fix to also pair those Ends with Begins is a separate change; flagged for a follow-up rather than inverted here.

for key, info := range rt.ActiveContacts {
if _, exists := liveContacts[key]; !exists {
live := liveContacts
if info.IsSensor {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 H · field choice

Narrow edge case: routing on the persisted IsSensor breaks a pair persisted as sensor but rebuilt solid (collider toggled after the physics pass, then snapshotted). That pair now gets a TriggerEnd and is deleted while the solid contact still touches, and the Begin loop already skipped it.

Base kept it and let the refresh flip the flag. Treating a pair as gone only when it's in neither live set keeps that behavior.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 0ed3acd.

Comment on lines +261 to +269
info := ContactPairInfo{IsSensor: true}
if sensorEntity == key.EntityA && sensorShapeIndex == key.ShapeIndexA {
info.FilterA = toFixtureFilterBits(sensorFilter)
info.FilterB = toFixtureFilterBits(visitorFilter)
} else {
info.FilterA = toFixtureFilterBits(visitorFilter)
info.FilterB = toFixtureFilterBits(sensorFilter)
}
dst[key] = info

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 B · dead code

nit: nothing reads these values. The End loop only checks whether the key exists, and the event uses the persisted info.

A map[ContactPairKey]struct{} lets us drop both ShapeFilter calls and the orientation branch.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 0ed3acd.

for _, slots := range rt.Shapes {
for _, sensorID := range slots {
// Chain slots hold a null ShapeID; IsShapeSensor would assert on it.
if sensorID == (box2d.ShapeID{}) || !w.IsShapeSensor(sensorID) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 C · constants & shape

nit: sensorID.IsNull() is what reconcile.go uses for chain slots. IsShapeSensor is redundant too, because ShapeSensorCapacity already returns 0 for non-sensors.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 0ed3acd.

Comment on lines +165 to +175
// liveSensorOverlapsScratch is reused by gatherLiveSensorOverlapsInto, which runs once
// per post-rebuild diff (see diffActiveContactsAfterRebuild). Sensor pairs never appear
// in the solid contact list (Box2D sensors never create contacts), so the diff gathers
// the live sensor overlap set separately to decide whether a persisted sensor pair is
// sustained rather than ended.
liveSensorOverlapsScratch map[ContactPairKey]ContactPairInfo

// sensorVisitorScratch backs the per-sensor ShapeSensorData gather in
// gatherLiveSensorOverlapsInto, reused across rebuilds so the visitor ShapeID list does
// not reallocate per sensor.
sensorVisitorScratch []box2d.ShapeID

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 G · perf & concurrency

These never get reused in production. The diff only runs on the first step after FullRebuildFromECS, and that only happens after Reset(), which nils both fields.

The "reused across rebuilds" comment only holds in tests. I'd make them locals in the diff and drop the fields and the Reset lines.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 0ed3acd.

Comment on lines +113 to +114
// Sensor pairs never appear in liveContacts, so the End loop must check persisted sensor
// pairs against this re-derived set instead.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 I · user-visible

nit: "sensors never create contacts, so check the sensor set" is now written five times: the function doc, here, the End loop comment, the gather doc, and the runtime field. Let's keep it once, on gatherLiveSensorOverlapsInto.

The FlushBufferedContacts doc still says "map but not in live -> emit End" against the live contact list. That needs the sensor caveat.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 0ed3acd.

// every persisted sensor pair as "gone" (sensor pairs are structurally absent from the live
// solid contact list) and emitted a TriggerEnd while the overlap persisted, desynchronizing any
// game code that latches trigger state on Begin/End.
func TestDiffAfterRebuildSustainedSensorOverlapEmitsNoEvents(t *testing.T) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 D · claims & tests

scenario/reset.go already asserts "the rebuild invents no TriggerEnd". It can't fail on this bug, though: it checks at afterTick, the rebuild tick, which returns without stepping. The diff runs a tick later, and lateTick only rechecks ContactBegin.

The visitor also has no GravityScale = 0, so by tick 450 it has probably fallen out of the gate.

Could we make that visitor hover and assert the TriggerEnd count at lateTick? That gives us an end-to-end test that fails on main, instead of relying only on this in-package fixture.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The requested change targets scenario/reset.go, which is outside this PR's diff — this PR only touches pkg/plugin/physics2d/internal/{contact_flush.go, contact_flush_internal_test.go, runtime.go}, and I'm constrained to changes within that diff. The sustained-overlap no-End behavior is already pinned in-package by TestDiffAfterRebuildSustainedSensorOverlapEmitsNoEvents (including across 5 follow-up normal ticks), and TestDiffAfterRebuildSensorPairToggledSolidIsRetained pins the toggle edge case. Extending the e2e reset scenario to hover + assert the TriggerEnd count at lateTick is a separate change against reset.go.

// (World.ShapeSensorData). This is the API the fix re-derives state from, so it is also the API
// the assertions check.
//
//nolint:unparam // every suite uses entities 1 and 2; params stay generic for future multi-sensor suites.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 C · constants & shape

nit: every caller passes entities 1 and 2 with slot 0, so the unparam excuse covers speculative generality. The same goes for the swap branch in sensorVisitorPair, which never runs.

I'd hardcode those, or take the real shape indices. The two solid tests also copy the same floor, box, and baseline literals, and a shared helper or a table test would fold them together.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 0ed3acd.

// TestDiffAfterRebuildSustainedSensorOverlapEmitsNoEvents is the direct regression test for the
// spurious-TriggerEnd-after-rebuild bug. A sensor pair that is persisted in the ActiveContacts
// baseline and still overlapping after the rebuild must produce no events on the post-rebuild
// diff tick, and the pair must stay in the baseline. Before the fix, the diff's End loop treated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 I · user-visible

nit: "before the fix" comments describe history and go stale once this merges. Let's say what each test pins instead.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 0ed3acd.

@detail-app

detail-app Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

Re: #1191 (review)

On whether all three paths should use the live sensor set:

  1. diff Begin loop — emitting Begins for new sensor overlaps would invert the one-shot suppression this PR deliberately preserves; TestDiffAfterRebuildDoesNotEmitBeginForNewSensorOverlap pins the opposite (no TriggerBegin for a baseline-absent sensor overlap). See the inline reply on thread 1.

  2. adoptLiveContactsWithoutEmit — this is the missing-singleton (no-baseline) path, which is explicitly one-shot-suppressed. Adopting sensor overlaps into the map without a Begin would not fix the unpaired-TriggerEnd-on-leave desync anyway: that End is emitted by bufferContactEventsFromWorld on a later normal tick regardless of map membership.

  3. refreshActiveContactsFromLive (contact_flush.go:390) — a sensor→solid toggle is handled: the toggled pair re-enters the live solid contact list, so the next refresh overwrites IsSensor to false. The solid→sensor direction (pair leaves the solid list) is not refreshed, which is a separate edge case from the sustained-overlap spurious End this PR targets.

This commit additionally handles the sensor→solid toggle in the diff End loop: a persisted pair is now treated as gone only when it is in neither live set (contact_flush.go:132), so a sensor-persisted pair rebuilt solid is retained and the refresh flips its flag — pinned by the new TestDiffAfterRebuildSensorPairToggledSolidIsRetained. The dead liveSensorOverlaps value path is dropped (set, not map), the sensor scratch fields are inlined as locals, and the IsNull/IsShapeSensor nits are addressed (0ed3acd).

@detail-app
detail-app Bot force-pushed the detail/bug-fix/fix-physics2d-stop-spurious-triggerend-for-sustain-31a3cc branch from 0ed3acd to 0ddd0a2 Compare November 29, 2026 23:35

This branch has not been deployed

No deployments
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.

2 participants