Repository navigation
fix(physics2d): stop spurious TriggerEnd for sustained sensor overlaps after rebuild - #1191
Conversation
smsunarto
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · Argus PR review / Argus-Labs/world-engine
🔁 Want another pass? Push your changes, then comment
@slopcopon 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.
| // 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). |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
| 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) { |
There was a problem hiding this comment.
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.
| // 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 |
There was a problem hiding this comment.
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.
| // Sensor pairs never appear in liveContacts, so the End loop must check persisted sensor | ||
| // pairs against this re-derived set instead. |
There was a problem hiding this comment.
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.
| // 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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
| // 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 |
There was a problem hiding this comment.
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.
|
Re: #1191 (review) On whether all three paths should use the live sensor set:
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 |
0ed3acd to
0ddd0a2
Compare
Detail bug report: View on Detail
Closes PER-556
Premise
TriggerBegin, cleared onTriggerEnd) silently desynchronizes after every snapshot restore /Plugin.Resetperformed while a player stands in a trigger volume: the overlap's end transition is consumed while the entity is still inside, and no compensatingTriggerBeginfires until the entity physically leaves and re-enters the sensor.diffActiveContactsAfterRebuildinpkg/plugin/physics2d/internal/contact_flush.go, introduced in commit ae574a1 (PR feat: add Box2D physics2d plugin with CGO #880).createContactassert), so persisted sensor pairs are structurally absent from that list and were always spuriously ended. The fix re-derives the live sensor overlap set fromWorld.ShapeSensorDataand checks sensor pairs against that set, so a sustained overlap produces no event while a genuinely ended one still emitsTriggerEnd.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 persistedActiveContactsbaseline 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 spuriousTriggerEndand deleted from the baseline.diffActiveContactsAfterRebuildnow gathers the live sensor overlap set separately from each sensor shape's overlap list (World.ShapeSensorCapacity/ShapeSensorData) and routes the End check forIsSensorpairs through that set:TriggerEndstill emitted, pair removed (no over-correction)Two reused scratch fields were added to
Runtimeand are dropped byReset(), matching the existing scratch convention.How did you verify?
contact_flush_internal_test.go): drive the realStep+FlushBufferedContactspipeline 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 oneTriggerEnd; a third test pins that new (unsuppressed-baseline) sensor overlaps still do not emit aTriggerBegin; two solid-path tests confirm no regression. All pass. As a negative control, reverting only theIsSensorbranch back to the oldliveContacts-only lookup makes the sustained test fail with a spuriousTriggerEnd (A=1,B=2)while the other four stay green, confirming the test pins the exact bug.TestRestoreIsDeterministicAcrossRepeatedRuns.pkg/plugin/physics2d/test/) passes, includingTestPhysics2D_CardinalIntegration(crash1/crash2 syntheticTriggerEndassertions — still correct since the ball is genuinely moved out of the sensor) andTestGoldenTrace(incl.sensor_trigger).pkg/plugin/physics2d/test/e2e/) passes, includingTestScenarios/reset("the rebuild invents no TriggerEnd"),TestRestore,TestExhaustiveBodyMatrix,TestDigestIsWorkerInvariant, andTestRandomScenes.gofmtclean,go vetclean,go build ./pkg/...andclibuild 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
TriggerEndevents afterPlugin.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 emitTriggerEndinstead of resolving to a freed slot.TriggerEnd.IsSensorflag.Written for commit 0ddd0a2. Summary will update on new commits.