Skip to content

feat(spec): let null remove keys in spec patches - #763

Merged
uniqueg merged 5 commits into
devfrom
feat/762-null-removes-key
Nov 11, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/762-null-removes-key

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Spec patches can now remove keys: null in a patch removes the key, at any depth, as in a JSON Merge Patch (RFC 7396). Merged spec files (path with several files) can opt in to the same with the new SpecConfig.merge_null_removes (off by default).

This covers the two cases from trs-filer#128 (TRS 2.0.2):

  • turning the BEARER API key scheme into an HTTP bearer scheme (type: http, scheme: bearer, name: null, in: null); without removing name and in, Connexion rejects the merged scheme;
  • replacing the remote $ref of /service-info by a local path item ($ref: null next to get); Connexion otherwise fetches the referenced file on every start.

Changes:

  • deep_merge() gets a keyword-only null_removes option (RFC 7396: null removes keys, removing unset keys is a no-op, null in mappings that replace non-mappings is dropped, lists are kept as they are). Config files keep the current behaviour (null_removes=False).
  • _apply_patches() merges with null_removes=True. _warn_weakened() is unchanged and still warns: removing a scheme's fields changes the schemes, and a path item that replaces a reference counts as a new operation, which is listed if it is public; removing security with null is listed like security: [].
  • ConfigParser.merge_yaml() now merges with deep_merge() only (the Addict loop behaved the same; checked by the round-2 reviewer on 2,955 file combinations). With merge_null_removes, register_openapi() merges the files of path through the same function as patches (_merge_layers()), so both get the guard below.
  • The existing guard against fields next to a $ref in path items now also covers removals: a patch (or, with merge_null_removes, a later file) that removes (null) a field of a path item that keeps its $ref would have no effect, as Connexion uses the referenced object (e.g. delete: null to drop an operation), so FOCA refuses to start, as it does for fields set next to a $ref. Removing the reference itself ($ref: null) is fine; a later layer that removes the path item or all paths, or gives it another $ref, clears it; restating the same $ref doesn't (_track_removals()). Removing a stray field that was set next to a $ref is rejected too, as the referenced object may have it: such fields are ignored by Connexion anyway.
  • Docs: new section "Merging specification files" and updated "Patching specifications" in docs/configuration/api.md, new docs/migration-0.23.md (linked from the changelog, index, README and nav), docstrings of SpecConfig.

Merged spec files: opt-in

The issue asked whether merged spec files should get the same semantics as an opt-in or not at all. I made it an opt-in (merge_null_removes, off by default):

  • Off by default, because null is a legitimate value in specifications (default: null, example: null), and additions files would otherwise silently lose it.
  • But needed at all, because apps adapt vendored specs with merged files, not with patches: patches is meant for operators, and an operator's overlay that sets patches for a named spec replaces the whole list, so removals that an app put in its own patches would be lost without notice. With the option, an app like trs-filer puts name: null, in: null and $ref: null into its additions.openapi.yaml and sets merge_null_removes: true.

Behaviour change

Patches that set a value to null now remove the key instead. This is noted in docs/migration-0.23.md, with the way out (set such values in a file of path). Patches that set a whole path item to null to replace it in a later patch keep working (existing test test_reference_after_removed_fields). Curated release notes (docs/releases/0.23.0.md) are added by the release-prep PR, as the contributing guide says; the item for them: "Patches of API specifications remove keys with null (JSON Merge Patch), and merged specification files can opt in via merge_null_removes (#762, #PR)".

Verification

Tests written first; the new end-to-end tests failed before the change ($ref next to fields rejected, merge_yaml() without null_removes) and pass after it.

  • End to end, through FOCA's spec loading (SpecConfig, files on disk) and Connexion's validation, without mocking add_api() (tests/api/test_register_openapi.py::TestRemovingKeys): a minimal spec with an API key scheme and a /service-info path item referring to a URL;
    • unpatched, Connexion fetches the URL (recorded via a stub of requests.get);
    • patched to HTTP bearer without removing name/in, Connexion rejects it (ValueError "invalid after applying patches");
    • patched with null, nothing is fetched, GET /service-info returns 200, GET /pets returns 401 (the bearer scheme validates tokens; Connexion ignores API key schemes without x-apikeyInfoFunc), and both warnings are logged (new public operation, changed schemes);
    • the same via merged files with merge_null_removes: true works; without the option Connexion rejects $ref: null.
  • Unit tests: test_deep_merge_null_removes (9 cases), test_merge_yaml_null, a new case of test_weakened_warned (security: null), the merge_null_removes default in tests/models/test_config.py, and tests for removals next to $ref (rejected when ineffective, also with the $ref restated or added in the same patch or in a later one, and in merged files; accepted after the reference, the path item or all paths are removed or replaced).
  • Local checks, as in CI: ruff format --check, ruff check, mypy, ast-grep scan (only the 2 existing warnings in examples/), semgrep scan --config .semgrep --error, mkdocs build --strict, coverage run -m pytest with MongoDB 7.0 on port 12345: 5006 passed, 2 skipped, coverage 100% (run before the last commit, which only touches _apply_patches and its tests; after it, tests/api tests/config tests/models: 701 passed, the new helper fully covered).
  • After the Sourcery fixes (f495870): ruff, mypy, mkdocs build --strict, tests/api tests/config tests/models (702 passed; the changed modules covered except lines that other test directories cover).
  • CI: all checks passed on the first run (lint, tests on all matrix entries incl. lowest dependencies, integration, docs, Codecov patch and project, Read the Docs; image push/publish jobs skipped on PRs as intended).

Declined review findings

Sourcery (5 medium findings on the removal guard and a test assertion): all fixed in f495870, threads answered.

Two rounds: adversarial + quality, then adversarial. Fixed: removals next to $ref silently ineffective (round 1, medium) and its gaps (round 2, two mediums and a low); single merge loop in merge_yaml(), model test of the default, grep hint in the migration guide, docs rewrapped (quality).

  • Rename operationId: showPetById of the test's /service-info operation (quality, not raised as a finding): kept, as it routes to the existing petstore test controllers; a new controller only for the name adds nothing.
  • Log when a patch removes keys (quality, optional part of a medium): declined; patches are already logged, and the migration guide says how to find null in patches.

Open questions

None.

Closes #762

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV

uniqueg and others added 4 commits November 11, 2026 21:50
Patches of API specifications are now merged as a JSON Merge Patch
(RFC 7396): null removes a key, at any depth. This lets patches turn an
API key scheme into an HTTP bearer scheme and replace a reference to a
URL by a local path item, which Connexion otherwise rejects or fetches.

Merged specification files can opt in to the same via the new
SpecConfig.merge_null_removes (off by default, so that null values
such as default: null keep working).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Add the section on merging specification files, describe null in
patches, and add the migration guide for 0.23.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Patches that remove fields of a path item defined via $ref, while
keeping the reference, have no effect, as Connexion uses the fields of
the referenced object; FOCA now refuses to start, as for fields set
next to a $ref. Also merge spec files with deep_merge only, assert the
default of merge_null_removes and rewrap the edited docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Decide after each patch whether it removes fields that only the
referenced object has: also when the patch restates or adds the $ref,
not when it removes fields set next to the reference, and forget the
path once a later patch removes the path item or gives it a $ref.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
@sourcery-ai

sourcery-ai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Implement RFC 7396 null-removal merging and track ineffective removals beside referenced path items across specification layers.

  • foca/api/register_openapi.py L383-507, L554-567 (+2 small edits)
  • foca/config/config_parser.py L38-44, L51-59, L306-312 (+2 small edits)

Configuration

Add the opt-in merge_null_removes setting to specification configuration, defaulting to false.

  • foca/models/config.py L719-726 (+3 small edits)

Expose the new migration guide in the documentation navigation.

  • mkdocs.yml L133

Documentation

Document null-removal behavior for patches and merged specification files, including the 0.23.0 migration guidance and links.

  • README.md L55-56, L173, L181
  • docs/changelog.md L16
  • docs/configuration/api.md L77-132, L143-148, L168-175 (+2 small edits)
  • docs/index.md L30-31
  • docs/migration-0.23.md L1-27

Tests

Cover null-removal merging, configuration defaults, and rejection or acceptance of removals around referenced path items.

  • tests/api/test_register_openapi.py L648-757, L799-998 (+2 small edits)
  • tests/config/test_config_parser.py L108-119, L207-256
  • tests/models/test_config.py L312-314

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (40edb03) to head (f495870).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #763   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           74        74           
  Lines         9448      9472   +24     
=========================================
+ Hits          9448      9472   +24     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 11, 2026 22:04
@sourcery-ai

sourcery-ai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit f495870

#762 feat(spec): let null remove keys in spec patches · 4 of 4 met

# Requirement Status Notes
1 In patches, null removes the key at any depth, with JSON Merge Patch semantics. ✅ Met _apply_patches() uses _merge_layers() with null_removes=True; tests cover nested removals, unset keys, mappings, and lists.
2 Merged specification files support the same behavior as an opt-in, or provide a documented reason not to. ✅ Met SpecConfig.merge_null_removes defaults to false, enables null removals when true, and is documented with the rationale for the default.
3 Removing a $ref and replacing it with a local definition works, and _warn_weakened still warns about security changes made this way. ✅ Met Tests cover replacing a remote path-item reference and verify the resulting operation and security warnings.
4 Add tests and documentation, including the patch reference and upgrade notes. ✅ Met The change adds merge and reference-handling tests, updates the patching documentation, and adds migration guidance for 0.23.0.

@sourcery-ai sourcery-ai 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.

Hey - I've found 5 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/api/register_openapi.py" line_range="415" />
<code_context>
+        if any(
+            key != "$ref"
+            and value is None
+            and not (isinstance(item_before, dict) and key in item_before)
+            for key, value in path_item.items()
+        ):
</code_context>
<issue_to_address>
**Referenced fields stay active**

When a patch removes a field already present beside a retained path-item `$ref`, and the referenced object also defines that field, `_track_removals()` skips the removal because the key exists in `item_before`, so the final guard accepts the path and Connexion restores the referenced field or operation; callers still see it.

Track null removals beside a retained `$ref` even when the removed key existed in the prior local path item.
</issue_to_address>

### Comment 2
<location path="foca/api/register_openapi.py" line_range="524" />
<code_context>
         list_specs = [spec.path] if isinstance(spec.path, Path) else spec.path
-        spec_parsed: dict[str, Any] = ConfigParser.merge_yaml(*list_specs)
+        spec_parsed: dict[str, Any] = ConfigParser.merge_yaml(
+            *list_specs, null_removes=spec.merge_null_removes
+        )
         logger.debug("Parsed spec: %s", list_specs)
</code_context>
<issue_to_address>
**Merged removals leave routes active**

When `merge_null_removes` is enabled and a later spec file sets a path-item field to `null` while retaining that path item's `$ref`, `ConfigParser.merge_yaml()` removes only the local field, and `register_openapi()` does not apply the referenced-path removal guard to merged files; Connexion restores the field from the reference, so the route remains available.

Apply the referenced-path removal tracking and guard to merged specs before passing them to Connexion.

Also at `docs/configuration/api.md:87`.
</issue_to_address>

### Comment 3
<location path="foca/api/register_openapi.py" line_range="404" />
<code_context>
+    """
+    for path, path_item in patch_paths.items():
+        if not isinstance(path_item, dict) or "$ref" in path_item:
+            removed_paths.discard(path)
+        if not isinstance(path_item, dict):
+            continue
</code_context>
<issue_to_address>
**Restated references revive removed operations**

When a patch removes a field from a referenced path item and a later patch restates the same `$ref` without restoring that field, `_track_removals()` discards the pending removal marker when the later patch includes `$ref`, so the final guard accepts the path and Connexion restores the removed field or operation; callers still see it.

Keep the removal marker when a later patch repeats the same `$ref`, clearing it only when a later patch supersedes the removal.
</issue_to_address>

### Comment 4
<location path="foca/api/register_openapi.py" line_range="462" />
<code_context>
             )
-        patched = deep_merge(patched, content)
+            _track_removals(removed_paths, patch_paths, before, patched.get("paths"))
     paths = patched.get("paths")
     overridden = sorted(
         path
</code_context>
<issue_to_address>
**Superseded removals still reject startup**

When one patch removes a field beside a `$ref`, a later patch removes the whole `paths` mapping with `paths: null`, and another patch restores the same path as a ref-only item, `_track_removals()` is not called, so the prior entry in `removed_paths` survives; if a later patch restores that path as a ref-only item, the final guard raises `ValueError` even though the removal was superseded.

Clear removal-tracking state when a patch removes or replaces the entire `paths` mapping.
</issue_to_address>

### Comment 5
<location path="tests/api/test_register_openapi.py" line_range="736" />
<code_context>
+    ) -> None:
+        """Removals are fine once later patches replace the reference."""
+        spec = self._patched(monkeypatch, *self.REFERENCE, *patches)
+        assert set(spec["paths"]["/pets"]) == expected
+
+    def test_removed_field_next_to_reference(
</code_context>
<issue_to_address>
**Replacement reference goes unchecked**

When the patch gives `/pets` a new `$ref`, when a later patch changes `/pets` from `#/x-items` to `#/x-other`, `test_removed_next_to_reference_replaced` only checks the key set at line 736, so it passes if the old reference remains and the path still resolves to the wrong operations.

Assert the complete path item, including the expected `$ref` target, for the replacement case.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and because patches now treat null as removal, a patch can remove an operation’s security requirement or access-control setting and let requests through without the intended protection. Reverting restores the prior behavior, but it cannot undo access that occurred while the weakened specification was active.

Blocking findings: foca/api/register_openapi.py:415, foca/api/register_openapi.py:524, foca/api/register_openapi.py:404, foca/api/register_openapi.py:462, tests/api/test_register_openapi.py:736


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/api/register_openapi.py Resolved
Comment thread foca/api/register_openapi.py Resolved
Comment thread foca/api/register_openapi.py Resolved
Comment thread foca/api/register_openapi.py Resolved
Comment thread tests/api/test_register_openapi.py Resolved
Reject every removal next to a $ref that is kept, also of fields set
next to it, as the referenced object may have them, too. Keep tracking
a removal when a later patch restates the same $ref, and stop when a
later patch removes all paths. Merged spec files with
merge_null_removes get the same guard, so ConfigParser.merge_yaml()
needs no option of its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
@uniqueg
uniqueg merged commit 93e9721 into dev Nov 11, 2026
83 checks passed
@uniqueg
uniqueg deleted the feat/762-null-removes-key branch November 11, 2026 22:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(spec): let null remove keys in spec patches

1 participant