Skip to content

[bidi] Add tuple types for map entries to the schema - #18362

Open
pujagani wants to merge 6 commits into
SeleniumHQ:trunkfrom
pujagani:js-bidi-map-entry-tuples
Open

pujagani wants to merge 6 commits into
SeleniumHQ:trunkfrom
pujagani:js-bidi-map-entry-tuples

Conversation

@pujagani

Copy link
Copy Markdown
Contributor

🔗 Related Issues

BiDi sends a JavaScript Map or object as a list of [key, value] pairs. The spec defines each entry as a fixed pair: script.MappingLocalValue and script.MappingRemoteValue are

[*[(LocalValue / text), LocalValue]]
;   ^ key: a value or plain text   ^ value: always a full value object

so every entry has exactly two elements, and only the key may be plain text. The binding-neutral schema loses that, so no generator can enforce it.

💥 What does this PR do?

Where this shows up: script.callFunction

script.callFunction passes arguments to a function in the page and returns its result:

  • Outbound: script.CallFunctionParameters.arguments → script.LocalValue → script.MapLocalValue.value → script.MappingLocalValue
  • Inbound: script.CallFunctionResult → script.RemoteValue → script.MapRemoteValue.value → script.MappingRemoteValue

For example, calling (prefs) => prefs.get('theme') with a Map of theme → "dark" must send:

{ "type": "map", "value": [ ["theme", { "type": "string", "value": "dark" }] ] }

What is lost today

The schema on trunk (script.MappingLocalValue, script.MappingRemoteValue) projects the entry as:

"list": {
  "list": { "union": [{ "ref": "script.LocalValue" }, { "primitive": "string" }] }
}

That reads as "a list of any number of elements, each a value or a string". It drops two facts from the spec:

Spec says Schema today says
Exactly 2 elements Any number
Position 1 (the value) is a full value object only Any element may be a plain string

So the schema treats all of these as valid script.callFunction arguments, although only the first one is:

["theme", { "type": "string", "value": "dark" }]   // valid
["theme", "dark"]                                  // value is plain text
["theme"]                                          // no value
["theme", { ... }, { ... }]                        // three elements

What each binding does today:

  • JS and Java generate straight from the schema, so they send all of these unchecked and accept them unchecked in responses.
    • JS types an entry as Array<Array<LocalValue | string>>.
    • Java types it as List<List<Object>>, with only null checks.
  • Python and Ruby reject them, but only because their hand-written serializers assume that a list allowing plain strings must be a map of pairs. Nothing in the schema says so.

The changes fix this.

🔧 Implementation Notes

This PR covers only the schema, so the shared format change can be reviewed on its own.

🤖 AI assistance

  • No substantial AI assistance used
  • AI assisted (complete below)
    • Tool(s): Claude Code
    • What was generated: projection change, tests, regenerated schema
    • I reviewed all AI output and can explain the change

🔄 Types of changes

  • New feature (non-breaking change which adds functionality and tests!)

@selenium-ci

Copy link
Copy Markdown
Member

/agentic_describe

@selenium-ci selenium-ci added C-nodejs JavaScript Bindings B-devtools Includes everything BiDi or Chrome DevTools related labels Nov 20, 2026
@qodo-code-review

qodo-code-review Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Preserve fixed key-value tuple types in the BiDi schema

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Preserve two-position map entries in the shared BiDi schema, including distinct key and value
 types.
• Keep the existing list projection for bindings that do not yet consume tuples.
• Validate tuple contents during schema checks and test projection from fixed-length CDDL arrays.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The projector, generated common schema, type declaration, and binding generator participate in one bounded BiDi schema-to-client type-model integration.
  • The tuple field is an artifact-level contract addition rather than an independent runtime feature; the Java generator is a consumer of the same schema artifact.
  • The follow-up changes occurrence classification within that same projection behavior and does not establish another end-to-end outcome.
Sources

common/bidi/schema.json[10285-10301]

          },
          "tuple": [
            {
              "union": [
                {
                  "ref": "script.LocalValue"
                },
                {
                  "primitive": "string"
                }
              ],
              "scalar": "string"
            },
            {
              "ref": "script.LocalValue"
            }
          ]

javascript/selenium-webdriver/bidi/serialization/record.d.ts[29-30]

  // Not consumed by validateValue yet; declared so embedding a real schema node type-checks.
  tuple?: TypeNode[]
Behavioral complexity 🟡 Medium 🧩 Data transformation

  • Before: a multi-member array was projected only through its first member as a generic list element type.
  • After: the same list representation is retained while each positional member is recursively projected into tuple metadata; positions that are not exactly one occurrence are represented as unknown, now including one-or-more forms whose unbounded upper bound is null or Infinity.
  • New correctness condition: tuple positions must represent exact fixed arity and types, and all tuple members must participate in reference, unknown-type, empty-record, and bound validation.
  • The follow-up specifically adds the invariant that JSON-round-tripped Infinity remains classified as unbounded.
  • The transformation must also preserve the old list view for consumers that do not read tuple, so this remains a compatibility-preserving schema transformation rather than a direct field copy.
Sources

javascript/selenium-webdriver/project_bidi_schema.mjs[925-933]

  const nestedTypes = (node) => [
    node.list,
    ...(node.tuple ?? []),
    node.map,
    ...(node.union ?? []),
    ...(node.record ?? []).map((f) => f.type),
  ]
  const hasMisplacedBound = (node) =>
    !!node && ((BOUND_KEYS.some((k) => k in node) && !isNumeric(node)) || nestedTypes(node).some(hasMisplacedBound))

common/bidi/schema.json[10285-10301]

          },
          "tuple": [
            {
              "union": [
                {
                  "ref": "script.LocalValue"
                },
                {
                  "primitive": "string"
                }
              ],
              "scalar": "string"
            },
            {
              "ref": "script.LocalValue"
            }
          ]
Potential damage 🟡 Medium 🩹 Recoverable

  • Conditionally, an incorrect tuple projection or an unintended unknown marker could cause schema validation or downstream binding generation to reject an otherwise usable schema, or could give a tuple-aware consumer an incorrect positional type.
  • The follow-up reduces the risk of incorrectly treating unbounded one-or-more positions as fixed by failing closed for null and Infinity upper bounds, but the affected outcome remains BiDi client schema/type generation rather than stored user data or an external side effect.
  • Recovery consists of correcting the projector/schema and regenerating affected binding artifacts; reverting code alone would not repair already published generated artifacts, but no runtime state repair or external compensation is required.
  • Recoverable by correcting the schema projector and regenerating/redeploying affected binding artifacts.
  • Existing consumers that ignore tuple remain compatible, and the JavaScript runtime validator does not begin enforcing tuple arity in this change.
Sources

common/bidi/schema.json[10285-10301]

          },
          "tuple": [
            {
              "union": [
                {
                  "ref": "script.LocalValue"
                },
                {
                  "primitive": "string"
                }
              ],
              "scalar": "string"
            },
            {
              "ref": "script.LocalValue"
            }
          ]

javascript/selenium-webdriver/bidi/serialization/record.d.ts[29-30]

  // Not consumed by validateValue yet; declared so embedding a real schema node type-checks.
  tuple?: TypeNode[]
Assessed commit ce78f36
Diagram

graph TD
  AST["Normalized CDDL"] --> Projector["Schema projector"] --> Schema["Shared schema"] --> Bindings["Binding generators"]
  Schema --> Checks["Schema checks"]
  Tests["Projection tests"] --> Projector
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Enforce pairs directly in each binding
  • ➕ Could provide immediate runtime or generated-type enforcement.
  • ➖ Duplicates spec rules across bindings.
  • ➖ Leaves the binding-neutral schema unable to express the distinction.

Recommendation: Keep the tuple metadata in the shared schema: it fixes the information loss at its source without changing existing list consumers. Binding-level enforcement can follow; this PR does not make current serializers reject malformed pairs.

Files changed (4) +89 / -7

Enhancement (1) +2 / -0
record.d.tsDeclare tuple metadata on schema type nodes +2/-0

Declare tuple metadata on schema type nodes

• Adds an optional 'tuple' property so embedded schema nodes type-check. The declaration does not change runtime value validation.

javascript/selenium-webdriver/bidi/serialization/record.d.ts

Bug fix (2) +59 / -7
schema.jsonAdd positional types to local and remote map entries +34/-2

Add positional types to local and remote map entries

• Adds two-element tuples to 'script.MappingLocalValue' and 'script.MappingRemoteValue'. Each tuple permits a string or value object as its key but requires a value object in its second position; the existing list type remains.

common/bidi/schema.json

project_bidi_schema.mjsProject fixed array positions and validate tuple contents +25/-5

Project fixed array positions and validate tuple contents

• Projects multi-member arrays into positional tuples alongside their existing list type, marking variable-occurrence positions unknown rather than asserting a fixed arity. Reference collection and schema checks now traverse tuple positions.

javascript/selenium-webdriver/project_bidi_schema.mjs

Tests (1) +28 / -0
project_bidi_schema_test.mjsTest tuple projection and variable-occurrence rejection +28/-0

Test tuple projection and variable-occurrence rejection

• Adds a map-entry fixture verifying distinct key and value positions while preserving the list projection. A second test confirms that a repeating position triggers the schema's unknown-primitive check.

javascript/selenium-webdriver/project_bidi_schema_test.mjs

@qodo-code-review

qodo-code-review Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Repeated array positions get false arity ✓ Resolved

Resolving commit: ce78f36

Resolution reason
The once predicate now treats any unbounded occurrence (null or Infinity maximum, or n not 1) as
non-fixed, so such members project to { primitive: 'unknown' } instead of a fixed tuple position;
tests were extended to cover n:1 with m:null and m:Infinity.
Description
arrayNode defaults a null upper occurrence bound to 1, so an unbounded + member is treated as
a fixed tuple position. When a multi-member array contains such a member, checkSchema accepts the
projected tuple rather than rejecting its incorrect fixed arity; the current schema has no such
array, but a later projection would carry the wrong shape.

Grey Divider

Context sources
Review mode: Auto: ⚖️ Balanced: Changes schema projection and generated binding contracts; standard review warranted.
✅ Fix-loop round: fix loop

Grey Divider

Tip of the day
💡 Did you know, you can show, collapse, or hide each part of a finding: code, evidence, and all

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit ce78f36 ⚖️ Balanced

Results up to commit 3a07046 ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Repeated array positions get false arity ✓ Resolved

Resolving commit: ce78f36

Resolution reason
The once predicate now treats any unbounded occurrence (null or Infinity maximum, or n not 1) as
non-fixed, so such members project to { primitive: 'unknown' } instead of a fixed tuple position;
tests were extended to cover n:1 with m:null and m:Infinity.
Description
arrayNode defaults a null upper occurrence bound to 1, so an unbounded + member is treated as
a fixed tuple position. When a multi-member array contains such a member, checkSchema accepts the
projected tuple rather than rejecting its incorrect fixed arity; the current schema has no such
array, but a later projection would carry the wrong shape.

Grey Divider

Qodo Logo

@selenium-ci

Copy link
Copy Markdown
Member

/agentic_review

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit ce78f36

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

B-devtools Includes everything BiDi or Chrome DevTools related C-nodejs JavaScript Bindings

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants