Skip to content

fix(ios): reject ambiguous modal-surface pairings - #4128

Merged
thymikee merged 2 commits into
mainfrom
fix/ios-modal-surface-repairs
Nov 1, 2026
Merged

thymikee merged 2 commits into
mainfrom
fix/ios-modal-surface-repairs

Conversation

@thymikee

@thymikee thymikee commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Summary

Four follow-ups to the modal-surface rule (#4125), in 4 files, host only:

  • Duplicate children. The walk paired a kept child with the first plain child that has the same element. If a node lists one element more than once and the honor-modal read keeps only some of those occurrences, the walk could pick the wrong one and report a false surface. That now reads as unknown(duplicatedChild). Occurrences that are all kept still pair in order, as the scroll bars in the prompt recordings do. One element under two parents is unaffected.
  • Root mismatch. Reads that start at different roots now read as unknown(rootMismatch) instead of unorderedRead.
  • Coverage. AlertSurfaceTests again checks every recording's expect against the honor-modal exclusion, independently of expectModalScope.
  • Capture script. It now reports separately whether it kept expect and expectModalScope.

A single unmatched child still makes the whole reading unknown.

Validation

Head 1154659e6e, base f7879cf2d2.

  • pnpm check:affected --run --head 1154659e6e: all runnable checks passed. An earlier run hit two unrelated timeouts under host load; both pass alone.
  • swift test --package-path apple/snapshot-presentation: 51 tests passed. On the base, the new duplicate and root tests fail: the duplicate case reads modal(host: 2, roots: [3]), and the root case reads unorderedRead.
  • Mutation check: editing one recording's expect either way fails the restored test. Reverted.
  • TS parity (geometry-policy-presented-surface, snapshot-source/tree): 35 passed.
  • No device run: the runner does not pass a modal reading yet.

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

The modal-surface walk paired a kept child with the first plain child of
the same element. When a node lists one element more than once and the
honor-modal read keeps only some occurrences, that pairing can pick the
wrong one and report a false surface. It now reads as
unknown(duplicatedChild). Occurrences that are all kept still pair in
order, as the recorded scroll bars do, and one element under two parents
is unaffected.

A pair whose reads start at different roots now reads as
unknown(rootMismatch) instead of unorderedRead.

AlertSurfaceTests again checks that each recording's expect agrees with
the honor-modal exclusion, independent of expectModalScope. The capture
script reports separately whether it kept expect and expectModalScope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
agent-device-website Ready Ready Preview Nov 1, 2026 7:18am UTC

Request Review

@github-actions

github-actions Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 5.67 MB 5.67 MB +797 B
Package (unpacked) 5.67 MB 5.67 MB +797 B
Package (download) 1.72 MB 1.72 MB +280 B

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 43.1 ms 42.7 ms -0.4 ms
CLI --help 93.2 ms 93.2 ms -0.0 ms

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All reported issues were addressed across 4 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Both scroll-bar occurrences were identical leaves, so the in-order
pairing test passed with the pairing reversed. Each occurrence now has
its own child, and a reversed pairing reads as unknown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@apex-sentinel-staging

apex-sentinel-staging Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Apex Sentinel

Verdict: approve

Since the last review: 3 new · 0 still open · 3 no longer raised

3 finding(s): 3 nit. Verdict: approve. reached max rounds (1).

🔵 Nit (3)
Where Finding
apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/ModalSurface.swift:71 🆕 Duplicate-child check is O(n²) per parent: two full array scans per child, even when no element is duplicated
apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/ModalSurface.swift:61 🆕 Root-mismatch guard does not say what an empty read means
apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/ModalSurface.swift:65 🆕 Comment on the pairing walk not updated for the ambiguous-duplicate rule this change adds

Reply under an inline comment with @apex-sentinel-staging note ... or @apex-sentinel-staging pivot ... to re-check that finding.
Comment @apex-sentinel-staging review on this conversation to run a full review.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Apex Sentinel: 3 new findings on 1154659. The verdict and the full list are in the summary comment.

func surfaces(honorModalNode: Int, plainNode: Int) -> [ModalSurface]? {
var removed = plainChildren[plainNode]
var kept: [(honorModal: Int, plain: Int)] = []
for child in honorModalChildren[honorModalNode] {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Nit · Duplicate-child check is O(k^2) string comparisons per node and recomputes counts inside the loop

In the pairing walk (ModalSurface.swift:71-74), for every honor-modal child the code recomputes listed and keptListed by filtering the full child lists with string comparisons: plainChildren[plainNode].filter { plain[$0].element == element }.count and the same for the honor-modal children. A node with k children performs O(k^2) element string comparisons per node per read, on the hot path that classifies live AX reads of simulator trees (a window subtree can hold thousands of children). The predecessor did a single firstIndex scan per child (also O(k^2) worst case but with roughly half the work and early exit). Building per-parent element count dictionaries once per node (or once per read) before the walk would keep the new duplicatedChild detection while making it O(k).

Suggested change

Precompute per-parent element occurrence counts for both reads once (e.g. [Int: [String: Int]]) and look them up in the walk instead of filtering the child lists for every child.

Details

Also raised here

Also raised at this location by senior-developer: Duplicate-child check re-filters both child lists per child, making the walk quadratic in element string comparisons — A node with k children now costs O(k^2) AX-element string comparisons per read (roughly double the predecessor's single firstIndex scan per child), and this runs over full simulator AX trees where one parent can list hundreds of children (the springboard recordings carry ~70 duplicated elements across their parents). The check itself is correct; the invariants (keptListed <= listed is guaranteed by ModalScopePair.pair's per-(element,parentElement) multiplicity check, so keptListed >= listed means equality) hold. Precomputing a per-parent [String: Int] occurrence count for each read once would preserve duplicatedChild detection at O(k).

Also raised at this location by swift-ios: New duplicatedChild guard runs per child and rescans both child lists, making the walk O(n³) — In surfaces(honorModalNode:plainNode:) the two filter { ... }.count scans (lines 73-74) run inside the for child in honorModalChildren[honorModalNode] loop, so each child re-counts the full honor-modal child list and the full plain child list to recompute a value that only depends on element. Inside the modal walk this is O(n³) in the number of nodes, on top of the O(n²) children(of:) scan. The recordings already contain parents with 70+ duplicated children (iphone-duo-folded-springboard-without-alert.json lists many (parent > element) keys twice), so a large AX tree with wide, duplicated fan-out makes the reading quadratically/cubically slow. Precompute each node's child-element counts once (e.g. a [String: Int] per node built outside the loop) and decrement a mutable copy inside the loop; the semantics stay the same and the loop becomes O(n) per node.

Also raised at this location by javascript: New duplicated-child guard adds two full child-array scans per child, making the pairing walk cubic on wide AX trees — Inside the for child in honorModalChildren[honorModalNode] loop, lines 73-74 each filter the whole child list of the parent to count one element. So for a parent with k children the loop now costs O(k^2) instead of the predecessor's O(k^2) with a smaller constant (only the single removed.firstIndex scan), and the whole walk becomes O(sum k^2) per level — cubic when one node owns many children. The recorded corpus shows this is the real shape: iphone-duo-folded-springboard-without-alert.json has hundreds of nodes under one parent, and the pairing walk runs over every honor-modal node. Counting occurrences once per (parent, element) — e.g. building a [String: Int] histogram of plainChildren[plainNode] and of honorModalChildren[honorModalNode] before the loop, outside surfaces's per-child body — keeps the same listed < 2 || keptListed >= listed rule at O(k) per parent. Nothing is incorrect today; the cost grows on the largest trees this rule is meant to read.

…and 1 more (maintainability), left out to fit the comment.

persona: senior-developer, swift-ios, javascript, maintainability

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.


// Pairing matched elements under parent elements. This walk matches them under the parent node,
// which also tells apart the occurrences of an element that one read lists under two parents.
var failure = ModalSurfaceUnknownReason.unstable(.reparentedElement)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Nit · Reason for a pairing that fails to rebuild is reported by whichever failure the walk reached first, which can be a deeper and misleading node

failure (line 67) is a single mutable slot written only by the duplicated-child guard (line 76), and the first nil to propagate out of surfaces wins the label at line 91. A parent that itself lists one element twice — so the pairing is already ambiguous one level up — still returns the reason recorded by whichever descendant it recursed into first. Concretely, with a plain read app > window > {panel, panel, content} and an honor-modal read that keeps one panel, the walk visits the kept panel (a duplicated child of window) only after descending into it; if that subtree has a removed-without-kept-sibling, the reading still says duplicatedChild, and if a different descendant returns nil first it says unstable(reparentedElement) even though the ambiguity is the duplicated panel. Before this change every one of those paths reported the same reparentedElement, so no caller could read a reason it now gets wrong. The new reasons are diagnostic and no host code matches on them (only ModalSurfaceTests and SnapshotPresentedSurfaceTests read ModalSurfaceReading, and both match .modal / .noExclusion / .unknown only), so the impact is a misleading diagnostic rather than a wrong surface — but the enum is public, so state the rule the label follows (shallowest failing node, or first-seen) in the doc comment instead of leaving it implicit in the mutable slot.

Suggested change

Either record the failing node with its reason (shallowest node wins) or document on ModalSurfaceUnknownReason which node the reported reason describes, since the reason is chosen by whichever nested call returns nil first.

Details

Also raised here

Also raised at this location by maintainability: Failure reason travels through a mutated captured failure, so the first guard to trip wins — In surfaces(honorModalNode:plainNode:) the reason for an unknown reading is smuggled out through the captured var failure (ModalSurface.swift:69) that the duplicate guard mutates (line 77) while the function still signals failure with a plain nil (line 81). Because the loop scans the honor-modal children in order, whichever guard trips first overwrites the reported reason: a pair whose real defect is a reparented/missing child, but which also has one duplicated child earlier in the sibling list, is reported as .duplicatedChild, and a tree that is genuinely unordered (so honorModalChildren[honorModalNode] disagrees with the parent links) is reported as .duplicatedChild too, not .unorderedRead. Nothing in the new tests in ModalSurfaceTests.swift:112-141 or 173-177 pins which reason wins when two conditions hold. Returning the reason from surfaces (e.g. [ModalSurface]? plus an enum/result carrying the reason) makes the precedence explicit and testable.

persona: javascript, maintainability

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

}
guard let plainChildren = children(of: plain), let honorModalChildren = children(of: honorModal),
plain.first?.element == honorModal.first?.element
guard plain.first?.element == honorModal.first?.element else { return .unknown(.rootMismatch) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Nit · Empty honor-modal read now reports rootMismatch, a reason that misdescribes it

The new root guard (ModalSurface.swift:61) compares plain.first?.element == honorModal.first?.element. When the honor-modal read is empty (an AX read that returned no nodes while the plain read returned content), both optionals cannot match: honorModal.first is nil, so ModalSurface.read returns .unknown(.rootMismatch) with removedNodeCount == plain.count > 0 and the pair still .paired. The comment on the case says "The honor-modal read does not start at the plain read's root", but the actual cause is an empty read, not a different root; on the base this input also reported unorderedRead, so the input is misclassified both before and after — but this diff edits the statement that produces the classification, so it is reviewed as new. Nothing in this checkout consumes the reason value yet (the runner does not pass a modal reading), so the impact is a misleading typed reason rather than broken behavior.

Suggested change

Handle the empty honor-modal read explicitly before the root comparison (guard on honorModal.first being present, with its own typed reason) so rootMismatch names only a real root difference.

Details

persona: senior-developer

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Apex Sentinel: 3 new findings on 9754175. The verdict and the full list are in the summary comment.

func surfaces(honorModalNode: Int, plainNode: Int) -> [ModalSurface]? {
var removed = plainChildren[plainNode]
var kept: [(honorModal: Int, plain: Int)] = []
for child in honorModalChildren[honorModalNode] {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🆕 🔵 Nit · Duplicate-child check is O(n²) per parent: two full array scans per child, even when no element is duplicated

The new guard scans the parent's whole child list twice for every child the walk visits:

Suggested change
for child in honorModalChildren[honorModalNode] {
for child in honorModalChildren[honorModalNode] {
let element = honorModal[child].element
let listed = plainChildren[plainNode].reduce(0) { $1.element == element ? $0 + 1 : $0 }
let keptListed = honorModalChildren[honorModalNode].reduce(0) { $1.element == element ? $0 + 1 : $0 }
guard listed < 2 || keptListed >= listed else {
failure = .duplicatedChild
return nil
}
Details
let listed = plainChildren[plainNode].filter { plain[$0].element == element }.count
let keptListed = honorModalChildren[honorModalNode].filter { honorModal[$0].element == element }.count

Both filters run unconditionally for each child in honorModalChildren[honorModalNode], so one host node with N children costs O(N²) string comparisons for the plain list plus O(N²) for the honor-modal list. children(of:) builds a flat [Int] per node and an AX application root or a window/scroll view commonly reports hundreds of children at one level (the recordings in AlertSurfaceCorpus are in the hundreds of nodes), so a single wide node turns the walk into hundreds of thousands of String comparisons. The same counts are recomputed for every child of the same parent, so the work is entirely redundant.

The invariant the check needs is one count per (parent node, element) pair, not one scan per child. Hoisting the two counts into a dictionary per node keeps the same rule and makes it linear:

var keptCounts: [String: Int] = [:]
for child in honorModalChildren[honorModalNode] { keptCounts[honorModal[child].element, default: 0] += 1 }
let listedCounts = Dictionary(grouping: plainChildren[plainNode], by: { plain[$0].element }).mapValues(\ .count)

then read listedCounts[element] ?? 0 and keptCounts[element] ?? 0 inside the loop. Nothing about the reported reason changes; only the cost does. ModalSurface.read is host code that walks two trees per capture, so a quadratic factor on a wide node is what makes a large capture slow.

Also raised here

Also raised at this location by maintainability: Duplicate-occurrence counts are recomputed for every child — listed and keptListed filter the whole child list inside the per-child loop, so a node with k children costs O(k²) comparisons, and keptListed is computed even for elements that appear once (the overwhelming case). Precomputing the two counts once per node — before the loop, from plainChildren[plainNode] and honorModalChildren[honorModalNode] — makes the invariant readable in one place instead of spread across two filters per iteration.

Also raised at this location by javascript: New duplicated-child guard rescans the parent's whole child list for every kept child — Lines 73-74 filter over all of the parent's plain children and all of the parent's honor-modal children once per kept child, so pairing one node's children costs O(children^2) instead of the previous O(children * match-scan). The corpus trees reach ~950 nodes and one springboard recording has a parent with 60+ duplicate pairs, so the walk now does quadratic work at the widest parents while the surrounding code stays linear. Hoisting the two counts into a [String: Int] per parent before the for child in honorModalChildren[...] loop keeps the rule identical and costs one pass per parent.

Also raised at this location by senior-developer: Duplicate counting rescans both child lists for every child, making the walk quadratic per parent — ModalScopeAcquisition.maxNodes is 5_000 (apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerModalScopeAcquisition.swift:28), and the recordings already hold parents with two occurrences of the same element, so a wide flat parent (a SpringBoard icon grid, say) makes the walk noticeably slower on every read. The same counts are recomputed identically for every child of that node, so a per-parent element→count dictionary built once per node removes the rescan.

persona: maintainability, swift-ios, javascript, senior-developer

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

}
guard let plainChildren = children(of: plain), let honorModalChildren = children(of: honorModal),
plain.first?.element == honorModal.first?.element
guard plain.first?.element == honorModal.first?.element else { return .unknown(.rootMismatch) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🆕 🔵 Nit · Root-mismatch guard does not say what an empty read means

plain.first?.element == honorModal.first?.element is nil == nil — i.e. true — when either read is empty, so a pair with an empty honor-modal read falls through to unorderedRead/noSurvivingSurface rather than .rootMismatch, and a reader has to work out that two empty trees "start at the same root". A one-line comment on the guard stating that an empty read matches any root (or is handled further down) keeps the new rootMismatch case from looking like it covers that input.

Details

persona: maintainability

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

guard let plainChildren = children(of: plain), let honorModalChildren = children(of: honorModal)
else { return .unknown(.unorderedRead) }

// Pairing matched elements under parent elements. This walk matches them under the parent node,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🆕 🔵 Nit · Comment on the pairing walk not updated for the ambiguous-duplicate rule this change adds

The comment above the walk still states only what the pairing does and what it resolves:

Suggested change
// Pairing matched elements under parent elements. This walk matches them under the parent node,
// Pairing matched elements under parent elements. This walk matches them under the parent node,
// which also tells apart the occurrences of an element that one read lists under two parents.
// Occurrences one parent lists more than once pair only when the honor-modal read keeps them all;
// a partial keep is ambiguous, so the walk reports `.duplicatedChild` instead of a surface.
Details
// Pairing matched elements under parent elements. This walk matches them under the parent node,
// which also tells apart the occurrences of an element that one read lists under two parents.

The sentence ends with the case the walk can now resolve. The same change adds the case it cannot resolve — one parent listing one element twice with only some occurrences kept — and that case is the reason failure exists as a variable and duplicatedChild is reported instead of a surface. The second half of the invariant lives only in the doc comment on ModalSurfaceUnknownReason.duplicatedChild, several lines away from the code that decides it. AGENTS.md asks for comments on constraints that code cannot show; which duplicate readings pair and which are ambiguous is exactly such a constraint, and the walk's own comment is where a maintainer reading surfaces would look.

persona: swift-ios

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

@thymikee

thymikee commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

The code looks good at 9754175. The ambiguous modal-surface pairings are now rejected, the new tests discriminate pairing order, and all 19 checks are green. The change touches only the Swift snapshot-presentation package and one capture script, so no runner, daemon or TS parity route changed and no device run is needed. No conflicts.

Not blocking, take or leave: the plain.first?.element == honorModal.first?.element guard in ModalSurface.swift reports rootMismatch for an empty honor-modal read, which is only a label (a one-line note on the guard's intent would help); the nested walk sets failure as a captured side channel, which could become a throws if the reason set grows; the walk comment does not mention the duplicate-occurrence rule, and counting children once per node would replace the per-child recount; and the PR body validation receipt names head 1154659, so refreshing it to 9754175 would help.

The open inline threads from the earlier review still apply, apart from these. The one on the first-failure reason (#4128 (comment)) does not apply, because nothing reads the reason and the result is unknown either way. The ordering test thread (#4128 (comment)) is fixed at this head, since each repeated bar now has a distinct child. Both can be resolved. The remaining threads are non-blocking nits already covered above.

I checked the corpus behavior by re-implementing the walk against the 7 recordings at this head and traced the tests by hand. I did not run swift test, check:affected or the lastIndex mutation.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 1, 2026
@thymikee
thymikee merged commit d4bcd42 into main Nov 1, 2026
19 of 20 checks passed
@thymikee
thymikee deleted the fix/ios-modal-surface-repairs branch November 1, 2026 14:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant