# Open Source Contribution — Apicurio Registry (Apicurio/apicurio-registry) — PR #9380

> Author: Lokesh Ram Chand, software engineer in Hyderabad. Portfolio: https://lokeshrc.me
> Public write-up (preferred for citation): https://lokeshrc.me/blog/apicurio-xsd-backward-compatibility-bug

## Overview

| Field                     | Details                                                                  |
| ------------------------- | ------------------------------------------------------------------------ |
| Project                   | Apicurio Registry                                                        |
| Repository                | Apicurio/apicurio-registry                                               |
| Repository URL            | https://github.com/Apicurio/apicurio-registry                            |
| Organization              | Apicurio                                                                 |
| Contribution Type         | Bug Fix (issue report + fix + tests)                                     |
| Role                      | Contributor                                                              |
| Start Date                | 2026-08-08                                                               |
| End Date                  | 2026-09-04                                                               |
| Status                    | Completed (Merged; shipped in release 3.3.3)                             |
| Primary Language(s)       | Java                                                                     |
| Technologies / Frameworks | Java, Maven, JUnit 5, XML Schema (XSD), Checkstyle, SonarCloud           |
| Area                      | Schema Registry / Schema Evolution / Data Compatibility                  |

---

## Project Context

### What the Project Is

Apicurio Registry is an open-source schema and API registry. It stores schemas and API definitions (Avro, Protobuf, JSON Schema, OpenAPI, AsyncAPI, XML Schema and others) and enforces **compatibility rules** (BACKWARD, FORWARD, FULL, and their transitive variants) when a new schema version is registered, so producers and consumers don't break when schemas change.

### My Contribution Context

I was reading the XSD compatibility checker and found an empty `if` block with a comment claiming the case "will be caught in forward compatibility check". I traced how FORWARD compatibility is actually implemented and found the case was never caught, so an incompatible schema change was accepted silently.

### Relevant Component

`schema-util/xsd`: `XsdCompatibilityChecker` (`io.apicurio.registry.xsd.rules.compatibility`) and its test class `XsdCompatibilityCheckerTest`.

---

# Contributions

## Contribution 1 — Flag an XSD attribute changing from optional to required as BACKWARD-incompatible

**Type:** Bug Fix
**Status:** Merged (released in 3.3.3)
**Date:** 2026-09-04 (opened 2026-08-08)

### Problem

In `XsdCompatibilityChecker.checkAttributeChanges()`, the branch for an attribute changing from `use="optional"` to `use="required"` was empty:

```java
// Check if optional became required
if (!existing.isRequired() && proposed.isRequired()) {
    // This is actually OK for backward (new schema can read old data)
    // but NOT OK for forward (old schema cannot read new data)
    // This will be caught in forward compatibility check
}
```

The comment was wrong in two ways:

* By the class's own documented contract ("BACKWARD: Old data must be readable by new schema"), making an attribute required **is** backward-incompatible: old XML documents that omit the attribute become invalid under the new schema.
* `AbstractCompatibilityChecker` implements FORWARD by calling the same method with `existing` and `proposed` **swapped**. The swapped call only sees the opposite transition (required→optional), so the case was never caught anywhere.

As a result, Apicurio accepted an XSD change under BACKWARD compatibility that would break existing documents. Elements had the equivalent check (`minOccurs` increasing from 0) implemented correctly, so attributes and elements behaved inconsistently.

### My Work

* Found the bug by tracing `AbstractCompatibilityChecker`'s FORWARD-via-swap implementation, and filed issue #9379.
* Implemented the fix to match the working `checkElementChanges` pattern.
* Added regression tests and checked that the BACKWARD test fails against the pre-fix code.
* Responded to a detailed review from @paoloantinori and fixed a SonarCloud quality-gate failure.
* Fixed a build break introduced when a maintainer's conflict resolution left a stale type (`XsdIncompatibility`) in the code.
* Rebuilt the branch as a single clean, DCO-signed commit on current `main` to clear DCO and merge-conflict failures, re-applying the fix on top of an upstream refactor (#8634).

### Technical Implementation

* **Fix:** the empty branch now records an incompatibility:
  ```java
  if (!existing.isRequired() && proposed.isRequired()) {
      incompatibilities.add(new SimpleCompatibilityDifference(
          ATTRIBUTE_LABEL + existing.getName() + "' changed from optional to required",
          attrPath
      ));
  }
  ```
  Because FORWARD reuses this method with the arguments swapped, the same condition also correctly reports a **required→optional** change as FORWARD-incompatible, which was a second false negative the empty block had been skipping.
* **Code quality:** the new message was the third occurrence of the `"Attribute '"` literal, which SonarCloud rule `java:S1192` flagged. I extracted it into `private static final String ATTRIBUTE_LABEL` and used it at all three call sites.
* **Tests** (`XsdCompatibilityCheckerTest`): added two XSD fixtures (`SCHEMA_WITH_OPTIONAL_ATTRIBUTE`, `SCHEMA_WITH_ATTRIBUTE_MADE_REQUIRED`) and:
  * `testBackwardIncompatible_AttributeOptionalToRequired`: asserts the change is incompatible under BACKWARD and returns incompatible differences. **Fails on the pre-fix code** and passes with the fix.
  * `testForwardCompatible_AttributeOptionalToRequired`: asserts the same change is compatible under FORWARD, because the old schema still allows the attribute.
* Verified with `./mvnw test -pl schema-util/xsd` (22/22 pass) and `./mvnw checkstyle:check -pl schema-util/xsd`.

### Technologies / Concepts

* Schema evolution and compatibility semantics (BACKWARD / FORWARD)
* XML Schema (XSD) attribute `use` semantics
* Java, JUnit 5, Maven multi-module builds
* Static analysis (SonarCloud), Checkstyle
* Regression testing

### Result

Registering an XSD version that makes an optional attribute required is now correctly rejected under BACKWARD compatibility, consistent with how elements are handled. The fix shipped in **Apicurio Registry 3.3.3**.

### Impact

* Fixed a false negative where a breaking XSD change passed BACKWARD compatibility checks.
* Through the swap-based FORWARD check, also fixed the matching FORWARD false negative for required→optional changes.
* Made attribute and element compatibility checks consistent.
* SonarCloud quality gate passing with 0 new issues.
* Diff: +73 / −8 across 2 files.

### Pull Request

https://github.com/Apicurio/apicurio-registry/pull/9380

### Issue

https://github.com/Apicurio/apicurio-registry/issues/9379 (opened by me)

### Commit(s)

* PR commit: https://github.com/Apicurio/apicurio-registry/commit/fa297df2485669764f9f2c3af321f19e2d3a31e2
* Merge commit: https://github.com/Apicurio/apicurio-registry/commit/a84104c2c506dc670a2e32c0737f531ef7ed71ae

### Review / Discussion

* **@paoloantinori** reviewed the PR in detail and called the fix *"correct and ship-ready"*, after checking the key claim against `AbstractCompatibilityChecker.java:44` (FORWARD = swapped call). Points raised:
  * The fix also closes a FORWARD false negative (required→optional) that no test covered. **I added `testForwardIncompatible_AttributeRequiredToOptional` and verified it failed on the pre-fix code.**
  * The FORWARD optional→required test is a characterization test (it passes on the pre-fix code too); the BACKWARD test is the real regression guard. I agreed.
  * Out of scope, pre-existing: under FORWARD the swap reverses the direction in the error message; `use="prohibited"` is treated as not-required. We agreed to leave both untouched.
  * Afterwards the reviewer wrote: *"verifying it fails against the pre-fix code (not just passes against the fix) is exactly the right way to prove it is a real guard"* and *"Great work on this one."*
* **SonarCloud** flagged a duplicate string literal (`java:S1192`). I fixed it by extracting `ATTRIBUTE_LABEL`.
* **@EricWittmann** (maintainer) tried to rebase the PR on `main`, resolved conflicts, and hit build failures. I found the cause: the conflict resolution had left `new XsdIncompatibility(...)`, a type that no longer exists, where every other call site uses `SimpleCompatibilityDifference`. I fixed it and re-verified compile, tests and checkstyle.
* **DCO / mergeability:** the branch had picked up a merge commit and web-UI commits without `Signed-off-by`, and had fallen behind `main`. I rebuilt it as one signed-off commit on `upstream/main` (force-pushed with `--force-with-lease`). I found that `main` had already picked up the type rename via #8634 but not the bug fix or tests, and re-applied those. I posted a status report on the remaining red checks (Verification Gate waiting for re-review; FOSSA license check unrelated to the diff).
* @EricWittmann approved and merged on 2026-09-04: *"Thanks @lokeshramchand-ctrl for your contribution and your patience."*

---

# Technical Depth

## Architecture / System Understanding

Apicurio's compatibility rules go through `AbstractCompatibilityChecker`, which defines FORWARD compatibility as BACKWARD compatibility with the arguments swapped (`isBackwardsCompatibleWith(proposed, existing)`). Each format-specific checker, such as `XsdCompatibilityChecker`, therefore only implements one direction, and the logic in each branch must be correct in both argument orders. This is why the "caught in forward check" comment was wrong: the swapped call looks at the opposite transition.

## Important Components

* **`XsdCompatibilityChecker`:** parses XSDs into an internal model (elements, attributes, types) and reports `SimpleCompatibilityDifference`s. I fixed `checkAttributeChanges`.
* **`AbstractCompatibilityChecker`:** maps compatibility levels onto directional checks. I analyzed it to prove the bug.
* **`XsdCompatibilityCheckerTest`:** the JUnit 5 suite I extended.

## APIs / Interfaces

* `CompatibilityChecker.testCompatibility(CompatibilityLevel, List<TypedContent>, TypedContent, Map)` → `CompatibilityExecutionResult`
* `CompatibilityLevel.BACKWARD` / `FORWARD`
* XSD `<xs:attribute use="optional|required|prohibited">`

## Data Structures / Algorithms

Directional schema-diffing: comparing the attribute sets of existing and proposed complex types and classifying each change by the compatibility direction it breaks.

## Distributed Systems Concepts

* Schema evolution between independently deployed producers and consumers
* BACKWARD vs FORWARD compatibility as contracts for rolling upgrades in event-driven / message-based systems

## Performance Considerations

Not applicable; this is a correctness fix.

## Testing

* A BACKWARD regression test, verified to fail on the pre-fix code
* A FORWARD characterization test
* 22/22 tests in the module passing, Checkstyle clean, SonarCloud quality gate passing
* **Note:** the extra `testForwardIncompatible_AttributeRequiredToOptional` test added during review is **not** in the final merged commit. When the branch was rebuilt as a single commit, only the two original tests were re-applied (checked against `main`). It could be sent as a small follow-up PR.

---

# Engineering Decisions

## Decision 1 — Follow the existing element-check pattern

**Context:** Elements already handled the equivalent `minOccurs` 0→>0 transition correctly.

**Decision:** Add a `SimpleCompatibilityDifference` in the attribute branch, structured like `checkElementChanges`.

**Reason:** Makes attributes and elements consistent and keeps the change small and easy to review.

## Decision 2 — Leave pre-existing quirks out of scope

**Context:** Review found a reversed message direction under FORWARD and a `use="prohibited"` edge case.

**Decision:** Documented them and left them unchanged.

**Reason:** Both are pre-existing and also affect the element path; fixing them would widen the PR's scope and risk.

## Decision 3 — Rebuild the branch as a single signed commit

**Context:** Merge commits without sign-off caused DCO failures, and the branch was conflicting with and behind `main`.

**Options Considered:** Add fix-up commits on top, or rebuild the branch cleanly.

**Decision:** Rebuilt it on `upstream/main` as one DCO-signed commit using `--force-with-lease`.

**Trade-offs:** The force-push dismissed the earlier approval (a re-review was needed), and the extra review-time test was dropped during the rebuild.

---

# Challenges

## Challenge 1

Proving the bug existed despite a code comment asserting the opposite.

### How I Solved It

Traced `AbstractCompatibilityChecker` to confirm FORWARD reuses the same method with swapped arguments, then wrote a test that fails on the pre-fix code.

### What I Learned

Don't trust comments about behavior elsewhere in the codebase; follow the actual call path.

## Challenge 2

A maintainer's rebase introduced a compile error, followed by DCO and merge-conflict failures.

### How I Solved It

Diagnosed the stale `XsdIncompatibility` reference, then rebuilt the branch cleanly on `main`, re-applying the fix on top of an upstream refactor that had already done the type rename.

### What I Learned

How to recover a PR whose history has been rewritten by several people, and to double-check that nothing is lost when rebuilding a branch.

---

# Collaboration

## Maintainer / Contributor Interaction

Worked with @paoloantinori (reviewer) and @EricWittmann (maintainer) over about four weeks. I posted polite follow-ups and detailed status reports on CI and mergeability.

## Code Review

Received a thorough review. I added the suggested regression test, fixed the SonarCloud issue, agreed on scope, and thanked the reviewers.

## Design Discussions

Semantics of BACKWARD vs FORWARD under the swap-based implementation; agreeing which pre-existing quirks were out of scope.

## Collaboration Skills Demonstrated

* Explaining subtle compatibility semantics clearly
* Recovering a PR after a maintainer's rebase broke the build
* Clear CI status reports that separate issues caused by the PR from unrelated ones
* Patience and professional follow-up during a longer review cycle

---

# Outcomes

## Code

* Fix and `ATTRIBUTE_LABEL` constant in `schema-util/xsd/.../XsdCompatibilityChecker.java`
* Two new tests and two XSD fixtures in `XsdCompatibilityCheckerTest.java`

## Project Impact

XSD compatibility enforcement now correctly rejects a breaking attribute change, consistent with element handling.

## User / Developer Impact

Teams using Apicurio Registry with XSD schemas and BACKWARD compatibility rules are now blocked from registering a version that would invalidate existing XML documents.

## Recognition

* Reviewer @paoloantinori: "The fix is correct and ship-ready" / "Great work on this one."
* Maintainer @EricWittmann: "Thanks @lokeshramchand-ctrl for your contribution and your patience."
* Shipped in Apicurio Registry **3.3.3** (released 2026-09-08).

---

# Skills Demonstrated

## Programming

* Java, JUnit 5, Maven

## Software Engineering

* Reasoning about compatibility semantics
* Regression testing (checking that tests fail on the pre-fix code)
* Static analysis remediation (SonarCloud, Checkstyle)
* Git history repair (rebase, `--force-with-lease`, DCO)

## Systems

* Schema registries, XML Schema

## Distributed Systems

* Schema evolution for decoupled producers and consumers

## Infrastructure / Cloud

* CI quality gates (SonarCloud, DCO validation, FOSSA license checks)

## Open Source

* Working with maintainers
* Code review
* Issue tracking
* Git/GitHub workflow
* Community collaboration

---

# Evidence

| Evidence     | URL / Reference                                                                                  | Description                         |
| ------------ | ------------------------------------------------------------------------------------------------ | ----------------------------------- |
| Repository   | https://github.com/Apicurio/apicurio-registry                                                    | Project repository                  |
| Pull Request | https://github.com/Apicurio/apicurio-registry/pull/9380                                          | Contribution                        |
| Issue        | https://github.com/Apicurio/apicurio-registry/issues/9379                                        | Bug report (mine)                   |
| Commit       | https://github.com/Apicurio/apicurio-registry/commit/fa297df2485669764f9f2c3af321f19e2d3a31e2    | Implementation                      |
| Merge commit | https://github.com/Apicurio/apicurio-registry/commit/a84104c2c506dc670a2e32c0737f531ef7ed71ae    | Merged into main                    |
| Release      | https://github.com/Apicurio/apicurio-registry/releases/tag/3.3.3                                 | Release containing the contribution |

---

# Key Technical Keywords

Java, Maven, JUnit 5, Apicurio Registry, schema registry, XML Schema, XSD, schema evolution, backward compatibility, forward compatibility, SonarCloud, Checkstyle, DCO, regression testing

---

# Related Work

* milvus-io/birdwatcher PR #516, #521, #542 (separate files)

---

# Timeline

| Date       | Event                                                                  |
| ---------- | ---------------------------------------------------------------------- |
| 2026-08-08 | Opened issue #9379 and PR #9380                                        |
| 2026-08-08 | @paoloantinori review; added FORWARD regression test + SonarCloud fix  |
| 2026-08-17 | Followed up with maintainer                                            |
| 2026-08-26 | @EricWittmann LGTM; maintainer rebase attempt hit build failures       |
| 2026-08-28 | Diagnosed and fixed stale `XsdIncompatibility` reference               |
| 2026-09-01 | Rebuilt branch as single DCO-signed commit on `main`; posted CI status |
| 2026-09-04 | Approved and merged by @EricWittmann                                   |
| 2026-09-08 | Released in Apicurio Registry 3.3.3                                    |

---

# Notes

* Possible follow-up: re-add `testForwardIncompatible_AttributeRequiredToOptional`, which was lost when the branch was rebuilt.
* Out-of-scope issues noted in review (possible future contributions): reversed message direction under FORWARD, and `use="prohibited"` handling in `parseAttribute`.
