Repository navigation
chore: Improve OpenAPI for generators - #1942
Conversation
`StorageCredential` is the only two-level union in the spec: `type` selects
s3/az/gcs, and `credential-type` then selects within `S3Credential` /
`AzCredential` / `GcsCredential`, which are unions in their own right. On the
wire that is `{"type": "s3", "credential-type": "access-key", ...}`.
Nested unions do not survive code generation. A generator asked to compose a
`oneOf` into an object flattens it into one struct carrying every branch's
fields as required, and an OpenAPI `discriminator` names only one property, so
the nesting cannot be described away either. Generated clients therefore
rejected every valid credential payload.
`expand_unions_composing_unions` multiplies the two levels out into nine flat
leaves, each carrying the inner payload plus both tags, discriminated on
`credential-type`. That works because `credential-type` values are unique
across all three providers; `type` alone maps `s3` to four leaves. If a future
variant reuses a `credential-type` value under a different `type`, no single
discriminator exists and the pass skips the union rather than emit something
misleading.
Also adds `tracing::warn!` diagnostics to every schema pass, so a schema change
that silently degrades the published spec is reported instead of being noticed
only when a generated client misbehaves. They are quiet on the current schema
and fire on: a union that nests another union but cannot be flattened, an
expanded union with no usable discriminator, a variant that cannot be named, a
union whose members disagree on the tag or reuse a tag value, and `UserOrRole`
being renamed or reshaped. Verified by simulating a `credential-type` collision
between GCS and S3, which produces the expected warning.
`flatten_user_or_role` now runs before the expansion pass. In the other order
the `*Assignment` unions still nest `UserOrRole`, so they were multiplied out
pointlessly and then warned about — the published spec was unaffected, but the
diagnostics were noisy.
This commit is self-contained and can be dropped without affecting the rest of
the series: the passes that skip this union compute the skip from schema state,
so removing the expansion restores the previous output exactly. The diagnostics
belong with it because one of them reports unions this pass failed to flatten,
which without the pass would be every credential union.
Co-Authored-By: Claude Opus 5 <[email protected]>
The schema passes in `api_doc()` rewrite `components/schemas` in place —
hoisting members, rewriting them to `$ref`s, attaching discriminators. Every one
of those edits can leave the document internally inconsistent in a way that
still serialises fine and is only noticed when a generated client misbehaves.
Nothing checked for that: CI regenerated the specs and diffed them, which
catches drift but not incoherence.
Two layers:
Unit — `spec_integrity_tests` asserts, for both the management and
generic-table documents, that every `$ref` resolves, that every inline union
member carries a title, and that every discriminator is usable: the mapping
covers each member exactly once, targets are real schemas and members of that
union, and each mapping key is the value its target actually pins for the
discriminator property. That last one matters most — a key matching nothing on
the wire makes generators dispatch on a value they will never see — and it is
the check that fails when either `mapping.insert` call site is mutated, which
is how it was verified rather than assumed.
CI — run openapi-generator over both specs for go, python and typescript-fetch.
The existing hey-api step exercises a different code path and has been happy
with specs openapi-generator rejects; this pins the generator the downstream
SDKs actually use. It asserts only that generation succeeds — whether the
emitted client behaves correctly belongs to the SDK repos. Confirmed to fail
(exit 1) on a spec with a dangling `$ref`, and the passing runs log no errors.
Also extends the hey-api step to the generic-table spec, which was uncovered.
Not asserted: validity against the OpenAPI meta-schema. Round-tripping the
document through utoipa's own model was tried and rejected — `QueueConfig`
serialises as an empty `{}` schema, which is legal OpenAPI but which utoipa
cannot deserialise back into `RefOr<Schema>`. That predates these passes, so
the test would have asserted utoipa's internal symmetry rather than anything
about the spec.
Co-Authored-By: Claude Opus 5 <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (9)
🚧 Files skipped from review as they are similar to previous changes (7)
Included review availability: Your plan includes up to 4 reviews per rolling hour; 2 remain after this review. WalkthroughThe change switches query extraction to ChangesManagement API contracts and query handling
Estimated code review effort: 4 (Complex) | ~60 minutes Merge Risk: ⚪ Minimal · up to The current PR introduces no identified merge-blocking risk and is merge-ready after normal checks and review. Sequence Diagram(s)sequenceDiagram
participant api_doc
participant UserOrRole
participant OpenAPIUnionSchemas
participant OpenAPIComponents
participant IntegrityChecks
api_doc->>UserOrRole: flatten the custom union schema
api_doc->>OpenAPIUnionSchemas: expand and normalize union variants
OpenAPIUnionSchemas->>OpenAPIComponents: hoist named variants and discriminator mappings
OpenAPIComponents->>IntegrityChecks: verify references and discriminator targets
Suggested reviewers: Poem Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ast-grep (0.45.1)crates/lakekeeper/src/api/management/mod.rsast-grep timed out on this file Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (3)
crates/lakekeeper/src/api/management/v1/openapi.rs (3)
256-256: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a regression test over the normalized document.
The four passes fail soft. Each refusal path emits a
tracing::warn!and leaves the schema unchanged. A regression inmultiply_outorsole_discriminatortherefore produces a log line at startup, not a test failure, and the broken schema reaches the generated clients.A snapshot assertion over
api_doc()would pin the generated component names, the discriminatorproperty_name, and the mapping entries forStorageCredentialand one*Assignmentunion.I can generate that test if you want it.
#!/bin/bash # Description: Look for existing tests over api_doc or the new normalization passes. set -euo pipefail rg -nP --type=rust -C3 '\bapi_doc\s*(::<|\()' crates/ | head -40 echo "=== direct references to the new passes ===" rg -nP --type=rust 'expand_unions_composing_unions|flatten_user_or_role|hoist_and_discriminate_one_of_variants|name_anonymous_one_of_variants' crates/🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/lakekeeper/src/api/management/v1/openapi.rs` at line 256, Add a regression test for the normalized document returned by api_doc(), covering generated component names, discriminator property_name, and mapping entries for StorageCredential and one *Assignment union. Use a snapshot assertion so failures in the union-normalization passes become test failures rather than only tracing warnings.
604-618: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSkip the distinct-value and distinct-title computation when
refusedis already set.Lines 604-613 build two
BTreeSets overmemberseven when the loop broke early at lines 581, 589, 594, or 598. In that casemembersis partial and both counts are discarded by therefused.is_none()guards at lines 614 and 616.Move the two computations inside a
if refused.is_none()block. This removes the wasted allocation and makes it clear that the counts apply only to a complete member list.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/lakekeeper/src/api/management/v1/openapi.rs` around lines 604 - 618, Wrap the distinct_values and distinct_titles BTreeSet computations in an if refused.is_none() block after member collection. Keep the existing duplicate-value and duplicate-title refusal checks inside that block, so partial members are not scanned when an earlier refusal already exists.
734-743: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsolidate the three title accessors into one.
set_schema_title_none,schema_title, andset_schema_titlerepeat the same match overObject,AllOf,OneOf, andArray. A new schema variant requires an edit in three places.Schema::AnyOfis absent from all three, so ananyOfmember is never named and never cleared.Return a mutable handle to the title field once and build the other operations on it.
♻️ Proposed refactor
fn schema_title_mut(schema: &mut utoipa::openapi::Schema) -> Option<&mut Option<String>> { use utoipa::openapi::Schema; match schema { Schema::Object(object) => Some(&mut object.title), Schema::AllOf(all_of) => Some(&mut all_of.title), Schema::OneOf(one_of) => Some(&mut one_of.title), Schema::AnyOf(any_of) => Some(&mut any_of.title), Schema::Array(array) => Some(&mut array.title), _ => None, } } fn set_schema_title_none(schema: &mut utoipa::openapi::Schema) { if let Some(title) = schema_title_mut(schema) { *title = None; } } fn set_schema_title(schema: &mut utoipa::openapi::Schema, value: String) { if let Some(title) = schema_title_mut(schema) { *title = Some(value); } }Keep
schema_titleas the shared read accessor and add theAnyOfarm to it.#!/bin/bash # Description: Confirm utoipa's AnyOf carries a `title` field and enumerate Schema variants. set -euo pipefail rg -nP --type=rust -C3 '\bstruct\s+AnyOf\b' || echo "AnyOf not defined in repo; check utoipa docs"Also applies to: 804-824
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/lakekeeper/src/api/management/v1/openapi.rs` around lines 734 - 743, Consolidate the repeated schema-title matches by adding a shared mutable accessor, schema_title_mut, covering Object, AllOf, OneOf, AnyOf, and Array. Refactor set_schema_title_none and set_schema_title to update the title through this accessor, while retaining schema_title as the shared read accessor and adding its AnyOf arm.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@crates/authz-openfga/src/api.rs`:
- Line 23: Add axum-extra to the [dependencies] section of
crates/authz-openfga/Cargo.toml, matching the version and feature configuration
required by the existing axum_extra::extract::Query import in api.rs. Preserve
the current Query usage.
In `@crates/lakekeeper/src/api/management/v1/openapi.rs`:
- Around line 416-425: When constructing each expanded leaf in the loop over
inner_member, copy the outer member’s description onto the new AllOf before
pushing it, while preserving the existing items and extras handling. Use the
description field exposed by AllOf and the existing member description value so
StorageCredential payload examples remain on generated leaves.
- Around line 345-353: Prevent generated OpenAPI components from silently
overwriting existing schemas by adding a shared checked-insert helper, or
equivalent consistent logic, and use it in both hoisting passes: the insertion
loop around lines 345-353 and the hoisted-member insertion around lines 635-664
in crates/lakekeeper/src/api/management/v1/openapi.rs. Before inserting each
title, detect an existing component and emit tracing::warn! naming the relevant
union and colliding component, while preserving the insertion behavior required
by the existing flow.
- Around line 396-415: Update the branch-processing logic around inner and
extras so encountering more than one composed inner union marks the member as
Unsupported. Do not retain the second union reference in extras or emit a
nested-union leaf; instead preserve the documented untouched-union behavior and
ensure the pass does not report success for this case.
In `@crates/lakekeeper/src/service/storage/mod.rs`:
- Around line 1061-1077: Add the literal TBD anchor to the StorageCredential
documentation block in service::storage, or update the openapi.rs reference to
use an existing stable token. Inspect S3Credential, AzCredential, and
GcsCredential and verify the documented leaf total and per-provider counts;
correct the “nine flat leaves — four S3, three Azure, two GCS” statement if it
does not match the current enum variants.
---
Nitpick comments:
In `@crates/lakekeeper/src/api/management/v1/openapi.rs`:
- Line 256: Add a regression test for the normalized document returned by
api_doc(), covering generated component names, discriminator property_name, and
mapping entries for StorageCredential and one *Assignment union. Use a snapshot
assertion so failures in the union-normalization passes become test failures
rather than only tracing warnings.
- Around line 604-618: Wrap the distinct_values and distinct_titles BTreeSet
computations in an if refused.is_none() block after member collection. Keep the
existing duplicate-value and duplicate-title refusal checks inside that block,
so partial members are not scanned when an earlier refusal already exists.
- Around line 734-743: Consolidate the repeated schema-title matches by adding a
shared mutable accessor, schema_title_mut, covering Object, AllOf, OneOf, AnyOf,
and Array. Refactor set_schema_title_none and set_schema_title to update the
title through this accessor, while retaining schema_title as the shared read
accessor and adding its AnyOf arm.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e5319086-3336-4ff5-a41a-79e2cfe356c5
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (10)
crates/authz-openfga/src/api.rscrates/lakekeeper-integration-tests/tests/management_query_arrays.rscrates/lakekeeper-storage-postgres/Cargo.tomlcrates/lakekeeper/Cargo.tomlcrates/lakekeeper/src/api/management/mod.rscrates/lakekeeper/src/api/management/v1/check.rscrates/lakekeeper/src/api/management/v1/openapi.rscrates/lakekeeper/src/lib.rscrates/lakekeeper/src/service/storage/mod.rsdocs/docs/api/management-open-api.yaml
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@crates/lakekeeper/src/api/management/v1/openapi.rs`:
- Around line 338-346: In
crates/lakekeeper/src/api/management/v1/openapi.rs#L338-L346, update the
leaf-title allocation to reserve every generated name in a shared allocation set
and retry with checked suffixes until unused, including the Variant suffix; add
regression cases for normalized tag collisions and occupied Variant names. At
`#L366-L370`, rewrite the union only after all schemas for that rewrite are
successfully preflighted or inserted. Apply the same preflight behavior to
titled variants at `#L714-L719`, preserving unsupported unions on title
collisions, and reserve each anonymous-variant title in the same allocation set
at `#L866-L882`.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e0ad7aff-bf2e-47a6-9f98-e18c4593cfe2
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (6)
.github/workflows/unittests.ymlcrates/authz-openfga/src/api.rscrates/lakekeeper/src/api/management/mod.rscrates/lakekeeper/src/api/management/v1/openapi.rscrates/lakekeeper/src/service/storage/mod.rsdocs/docs/api/management-open-api.yaml
🚧 Files skipped from review as they are similar to previous changes (3)
- crates/lakekeeper/src/api/management/mod.rs
- crates/authz-openfga/src/api.rs
- crates/lakekeeper/src/service/storage/mod.rs
✅ PR Title Formatted CorrectlyThe title of this PR match the correct format. Thank you! |
Summary by CodeRabbit
New Features
Bug Fixes
Tests