Skip to content

[BEAM-19331] Add namespace support for PipelineOptions - #41742

Open
Tarun4201 wants to merge 1 commit into
apache:masterfrom
Tarun4201:fix/19331-pipeline-options-namespace
Open

Tarun4201 wants to merge 1 commit into
apache:masterfrom
Tarun4201:fix/19331-pipeline-options-namespace

Conversation

@Tarun4201

Copy link
Copy Markdown

Description

Closes #19331

This PR introduces namespace support for PipelineOptions across the Java and Python SDKs, allowing options with identical names to be distinguished through qualified names.

Motivation

PipelineOptions with identical property names across different option interfaces or groups can create naming conflicts, especially when their types differ.

This change introduces qualified option names while preserving existing unqualified option behaviour.

Java SDK

  • Added qualified command-line option parsing (supporting --<Group>.<option>, decapitalized --<group>.<option>, and FQCN --<pkg>.<Group>.<option>).
  • Improved getter/setter pairing across interfaces via Multimap in PipelineOptionsFactory to allow disjoint interfaces to define identical property names without false type collisions.
  • Added ambiguity detection for conflicting unqualified options with informative error messages guiding the user to qualify the option.
  • Implemented group-aware candidate key resolution in ProxyInvocationHandler.
  • Preserved qualified names through Runner API translation and Jackson serialization/deserialization.

Python SDK

  • Added qualified command-line argument registration (--<Group>.<option> and snake_case --<group_name>.<option>) in _BeamArgumentParser.
  • Implemented MRO-aware qualified option lookup in PipelineOptions.__getattr__.
  • Added group-aware setter handling in PipelineOptions.__setattr__.
  • Preserved qualified options through Runner API translation (to_runner_api / from_runner_api).

Backward Compatibility

  • Existing unqualified options: Fully preserved. Unqualified command-line flags and programmatic access work unchanged.
  • Same-name options with compatible types: Fully preserved. Sibling interfaces continue to share values (testDisjointSiblingsShareValues passes).
  • Same-name options with incompatible types: Coexist cleanly when qualified. Independent values can be set and accessed per group.
  • Qualified and unqualified options supplied together: Unqualified options act as fallbacks; explicit qualified options override unqualified values without being overwritten by sibling setters.

Tests

  • Java SDK (:sdks:java:core:test):
    ./gradlew :sdks:java:core:test --tests "org.apache.beam.sdk.options.*" --tests "org.apache.beam.sdk.util.construction.PipelineOptionsTranslationTest*"
    Result: 257 passed, 0 failed, 0 skipped.
  • Java DirectRunner (:runners:direct-java:test):
    ./gradlew :runners:direct-java:test --tests "org.apache.beam.runners.direct.DirectRunnerTest*"
    Result: 22 passed, 0 failed, 0 skipped.
  • Python SDK (pytest):
    pytest sdks/python/apache_beam/options/pipeline_options_test.py
    Result: 162 passed, 2 skipped, 0 failed.
  • Code formatting & checkstyle:
    ./gradlew :sdks:java:core:spotlessCheck (BUILD SUCCESSFUL).

Discussion

Initial design discussion was started on the Apache Beam developer mailing list. Feedback on compatibility, option resolution and runner integration is welcome.

Issue: #19331

@github-actions github-actions Bot added python java core size/l L: 250-999 lines changed labels Nov 29, 2026

@github-actions github-actions 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.

📋 Review Summary

This PR introduces namespace-qualified pipeline option resolution across the Java, Python, and Go SDKs, enabling cross-language and multi-interface pipelines to disambiguate colliding option names (including incompatible types in Java). Overall, the approach is well-structured and backed by comprehensive unit tests across all three SDKs, though there are several bugs around default value caching, setter consistency, display data lookup, and Runner API URN case-conversion that should be addressed.

🔍 General Feedback

  • Java (ProxyInvocationHandler & PipelineOptionsFactory): Lazy default binding currently writes to the unqualified propertyName key without checking if a conflicting value or colliding getter already exists, which causes getters with incompatible return types or different @Default annotations to overwrite or break each other. Additionally, PipelineOptionsTranslation converts option keys using Guava's CaseFormat, which corrupts uppercase class names and package dots during Runner API translation.
  • Python (pipeline_options.py): Setting an attribute on a PipelineOptions view unconditionally overwrites the unqualified key in _all_options while reading prioritizes the class-qualified key, creating inconsistent state across views that share option names.
  • Go (pipeline_options.go): Struct tag names and qualified snake_case/camelCase keys should be handled consistently during LoadOptionsFromFlags.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.

💬 Inline Findings

  • sdks/java/core/src/main/java/org/apache/beam/sdk/options/ProxyInvocationHandler.java (line 274): 🔴 Critical: When lazily binding a default value, options.put(propertyName, BoundValue.fromDefault(value)) unconditionally writes to the unqualified propertyName key. This causes two bugs when two interfaces define the same option name:
  1. If options already holds an explicitly set value for propertyName of an incompatible type (e.g., String from FirstOptions, and now SecondOptions.getFoo() is called expecting Integer with no qualified override set), this overwrites the explicit String value in options with SecondOptions's default Integer!
  2. If two interfaces have the same option name with the same return type but different @Default annotations (or neither is set yet), the first getter called binds its default to the shared propertyName, and the second getter will return the first interface's default instead of its own.

Lazy defaults should either be bound to a qualified candidate key (e.g., candidates.get(0)) when not declared on PipelineOptions, or at minimum not overwrite an existing entry in options.

      String keyToBind = candidates.get(0);
  • sdks/java/core/src/main/java/org/apache/beam/sdk/options/ProxyInvocationHandler.java (line 292): 🟠 High: In the setter branch, targetKey only falls back to candidates.get(0) when an existing unqualified value has an incompatible runtime type. If two interfaces share a property name with the same type (e.g., DbOptions.setTimeout(100) followed by NetOptions.setTimeout(200)), both writes go to the unqualified "timeout" key and overwrite each other. Furthermore, if DbOptions.setTimeout(null) is called when propertyName holds a String, args[0] != null is false so it overwrites the unqualified key with null. Consider checking whether the property is defined on multiple known interfaces or if a qualified key is appropriate when disambiguating.

  • sdks/java/core/src/main/java/org/apache/beam/sdk/options/ProxyInvocationHandler.java (line 317): 🟠 High: getCandidateKeys iterates over proxy.getClass().getInterfaces() BEFORE checking method.getDeclaringClass(). When multiple interfaces are registered/proxied together (or when a sub-interface extends multiple option interfaces), proxy.getClass().getInterfaces() may list another interface before method.getDeclaringClass(). If both interfaces have a qualified entry in options, the getter/setter for InterfaceB will match InterfaceA.foo first! method.getDeclaringClass() (or the sub-interface in proxy.getClass().getInterfaces() to which declaringClass is assignable, i.e., declaringClass.isAssignableFrom(iface)) should be prioritized over unrelated interfaces on the proxy.

        if (PipelineOptions.class.isAssignableFrom(iface) && iface != PipelineOptions.class && declaringClass.isAssignableFrom(iface)) {
  • sdks/java/core/src/main/java/org/apache/beam/sdk/options/ProxyInvocationHandler.java (line 500): 🟡 Medium: In PipelineOptionsDisplayData.populateDisplayData, optionsMap is keyed only by the unqualified prop.getName() (see buildOptionNameToSpecMap). When an option is stored in options or jsonOptions under a qualified key (e.g., "FirstOptions.foo" or "firstOptions.foo"), optionsMap.get(option.getKey()) returns an empty collection. As a result, qualified options in copiedOptions are silently dropped from DisplayData, and qualified options in jsonOptions are added under UnknownPipelineOptions instead of their defining interface.

  • sdks/java/core/src/main/java/org/apache/beam/sdk/options/PipelineOptionsFactory.java (line 1762): 🟠 High: PipelineOptionsTranslation.toProto and fromProto convert option keys between LOWER_CAMEL and LOWER_UNDERSCORE using Guava's CaseFormat. For qualified keys:

  • In toProto: "MyOptions.fooBar" becomes "beam:option:my_options.foo_bar:v1".

  • In fromProto: CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "my_options.foo_bar") produces "myOptions.fooBar", and for a snake_case class prefix from Python like "beam:option:test_db_options.timeout:v1" it produces "testDbOptions.timeout" (which works via decap), except when the class name has consecutive uppercase letters (e.g. MyDBOptions -> Python _camel_to_snake produces my_db_options -> Java LOWER_UNDERSCORE.to(LOWER_CAMEL) produces myDbOptions, whereas Java Introspector.decapitalize("MyDBOptions") is "MyDBOptions" because the first two characters are uppercase!).

  • Worse, if a fully-qualified class name is used (org.example.MyOptions.fooBar), LOWER_UNDERSCORE.to(LOWER_CAMEL) turns org.example.my_options.foo_bar into org.example.myOptions.fooBar, which will not match full (org.example.MyOptions.fooBar), simple, or decap.

  • sdks/python/apache_beam/options/pipeline_options.py (line 225): 🟠 High: When _add_argparse_args is called with conflicting unqualified flags across subclasses (in get_all_options), has_conflict skips super().add_argument(*args, **kwargs). However, for the qualified flags added below (--Cls.flag, --cls_snake.flag), q_kwargs['default'] = None is used. If the second conflicting class defines a different default for --flag, the unqualified dest in get_all_options() will only have the first class's default, and if a user instantiates view = options.view_as(SecondClass), view._visible_options has SecondClass.flag = None, while _all_options['flag'] was already populated by the first class's default, so view.flag will return the first class's default instead of SecondClass's default.

  • sdks/python/apache_beam/options/pipeline_options.py (line 569): 🟠 High: In __setattr__, setting an option on a subclass view writes to both self._all_options[f"{cls_name}.{name}"] = value AND self._all_options[name] = value, whereas __getattr__ checks self._all_options[f"{cls_name}.{name}"] before self._all_options[name]. This causes two issues:

  1. If --TestDbOptions.timeout=100 is passed on the CLI and the user later sets options.view_as(TestDbOptions).timeout = None, __getattr__ will ignore None (because of and self._all_options[qualified_key] is not None on line 555) or fall back to _all_options['timeout'].
  2. If two views share a valid option (e.g. a base class and subclass, or two views sharing a standard option), setting view1.opt = 'a' sets View1.opt = 'a' and opt = 'a'. If view2.opt = 'b' is then set on another view, opt becomes 'b', but view1.opt is stuck returning 'a' forever because View1.opt in _all_options is never updated when modified via PipelineOptions or another view! As documented in view_as(), modifications in any view object are supposed to be reflected across views unless explicitly disambiguated.
  • sdks/go/pkg/beam/options/gcpopts/options_test.go (line 1): 🟢 Low: In sdks/go/pkg/beam/core/runtime/pipelinex/replace.go / sdks/go/container/tools/pipeline_options.go (or options.go), LoadOptionsFromFlags matches struct fields by json tag name (tag := strings.Split(f.Tag.Get("json"), ",")[0]), which is often snake_case or differs from f.Name. However, the qualified name candidates <structName>.<fieldName> only use f.Name (and strings.ToLower(f.Name[:1]) + f.Name[1:]), not tag (if tag != "" and tag != f.Name). Supporting <prefix>.<tag> as well would ensure struct fields with custom JSON tags work with qualified flags.

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @chamikaramj for label java.
Backup reviewer: Abacn (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

This pull request likely touches a core component ("core" label). Please review with scrutiny.

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Namespace for pipeline options

1 participant