Skip to content

feat: Introduce CatalogWarehouseOps abstraction - #1435

Merged
c-thiel merged 8 commits into
mainfrom
ct/warehouse-cache
Oct 13, 2025
Merged

c-thiel merged 8 commits into
mainfrom
ct/warehouse-cache

Conversation

@c-thiel

@c-thiel c-thiel commented Oct 8, 2025 •

Copy link
Copy Markdown
Member

BEGIN_COMMIT_OVERRIDE
feat: Introduce CatalogWarehouseOps & CatalogNamespaceOps abstractions

feat: Introduce AuthzWarehouseOps and AuthzNamespaceOps abstractions
feat!: Require warehouse-id in the permissions/check API also for namespace-ids
END_COMMIT_OVERRIDE

Summary by CodeRabbit

  • Refactor
    • Read paths now use direct catalog lookups instead of intermediate transactions, reducing latency and simplifying data access across tables, views, namespaces and S3 signing.
    • Public service exports consolidated for a cleaner API surface.
  • Bug Fixes
    • More specific, user-facing error responses for warehouse/namespace operations (not found, already exists, protected, not empty, unfinished tasks).
    • Improved concurrent-modification detection to reduce transient failures.
  • Chores
    • Unified backend error types and clearer mappings to API error responses; ADLS storage client paths made async for more reliable initialization.

@coderabbitai

coderabbitai Bot commented Oct 8, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Shifts many catalog reads from transaction-bound operations to catalog-state reads via new CatalogWarehouseOps/Authz ops and require_warehouse_by_id; renames many CatalogStore methods to *_impl with explicit catalog error enums; adds CatalogBackendError/DatabaseIntegrityError and updates Postgres implementations and server call sites to use catalog.clone() for begin_read/write.

Changes

Cohort / File(s) Summary
API management — warehouse
crates/lakekeeper/src/api/management/v1/warehouse/mod.rs
Replace transactional reads with catalog-state reads; call require_warehouse_by_id using state.v1_state.catalog (clone where needed); update Service impl bounds to A: Authorizer + Clone.
Postgres backend — catalog & warehouse & dbutils
crates/lakekeeper/src/implementations/postgres/catalog.rs, crates/lakekeeper/src/implementations/postgres/warehouse.rs, crates/lakekeeper/src/implementations/postgres/dbutils.rs
Rename many CatalogStore impl methods to *_impl, accept catalog_state/state for reads, add explicit catalog error enums (CatalogCreate/Delete/Get/List/Rename/etc.), map sqlx errors into CatalogBackendError/DatabaseIntegrityError, and remove some transaction-centric helpers.
Service — catalog_store, errors, warehouse ops
crates/lakekeeper/src/service/catalog_store.rs, crates/lakekeeper/src/service/catalog_store/error.rs, crates/lakekeeper/src/service/catalog_store/warehouse.rs, crates/lakekeeper/src/service/mod.rs
Introduce catalog_store error module and public error types, add CatalogWarehouseOps/CatalogNamespaceOps traits with explicit error types and *_impl methods, and switch to pub use catalog_store::*.
Server call sites — namespace / tables / views / s3 / tasks
crates/lakekeeper/src/server/namespace.rs, crates/lakekeeper/src/server/tables.rs, crates/lakekeeper/src/server/tables/create_table.rs, crates/lakekeeper/src/server/views/commit.rs, crates/lakekeeper/src/server/views/create.rs, crates/lakekeeper/src/server/views/drop.rs, crates/lakekeeper/src/server/views/load.rs, crates/lakekeeper/src/server/s3_signer/sign.rs, crates/lakekeeper/src/service/tasks/tabular_purge_queue.rs, ...crates/lakekeeper/src/server/*
Replace require_warehouse(..., transaction) or transaction-bound reads with require_warehouse_by_id(..., catalog) and clone state.v1_state.catalog before begin_read/write; update call-sites and some function signatures (e.g., try_recursive_drop now takes GetWarehouseResponse).
AuthZ refactor — traits, ops, errors, relations
crates/lakekeeper/src/service/authz/*.rs, crates/authz-openfga/src/*
Add associated action types to Authorizer (WarehouseAction/NamespaceAction), introduce AuthzWarehouseOps/AuthzNamespaceOps traits, add new authz error types (AuthorizationBackendUnavailable, BackendUnavailableOrCountMismatch, AuthZCannotUseWarehouseId, AuthZCannotSeeNamespace, etc.), and adapt OpenFGA integration and tests to use GetNamespaceResponse-based namespace checks.
Tabular & views — signatures and storage-profile changes
crates/lakekeeper/src/implementations/postgres/tabular/table/mod.rs, crates/lakekeeper/src/implementations/postgres/tabular/mod.rs, crates/lakekeeper/src/implementations/postgres/tabular/view/mod.rs, crates/lakekeeper/src/implementations/postgres/tabular/*
Remove load_storage_profile, switch list_views/list_tabulars/list_tables signatures to accept namespace_id: Option<NamespaceId> (or use GetNamespaceResponse), update SQL bindings and call sites accordingly.
I/O async change (ADLS)
crates/io/src/adls.rs, crates/io/tests/integration_tests.rs, crates/lakekeeper/src/service/storage/az.rs, crates/lakekeeper/src/service/storage/mod.rs
Convert several ADLS/io APIs and cache to async (moka::future::Cache), make Adls/IO helpers async and await call sites; adjust tests to await client creation.
Server tests & scaffolding
crates/lakekeeper/src/server/mod.rs, crates/lakekeeper/src/server/views.rs, crates/lakekeeper/src/server/views/list.rs, crates/lakekeeper/src/server/views/rename.rs, test files...
Update tests and helpers to use GetNamespaceResponse instead of NamespaceId/NamespaceIdent, adjust helper return types and assertions, and adapt list/rename view tests to new namespace/auth flows.
Misc: config, cargo, small formatting
crates/lakekeeper/src/server/config.rs, Cargo.toml, docs/docs/api/management-open-api.yaml, minor files...
Use warehouse object for config generation, change moka/sqlx dependency features/versions, and add warehouse-id in OpenAPI namespace schema variant.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant Handler as Server Handler
  participant Authz as AuthzOps
  participant Catalog as CatalogWarehouseOps
  participant Store as CatalogStore (state)
  participant DB as Postgres

  Client->>Handler: Request needing warehouse & namespace checks
  Handler->>Catalog: require_warehouse_by_id(warehouse_id, state)
  Catalog->>Store: get_warehouse_by_id_impl(warehouse_id, state)
  Store->>DB: read via state.read_pool()
  DB-->>Store: GetWarehouseResponse
  Store-->>Catalog: Result<GetWarehouseResponse,...>
  Catalog-->>Handler: Warehouse
  Handler->>Authz: are_allowed_warehouse_actions_arr(metadata, [(warehouse_id, CanUse),(warehouse_id, CanListEverything)])
  Authz-->>Handler: [authz_can_use, authz_can_list]
  alt authz_can_use == false
    Handler-->>Client: AuthZCannotUseWarehouseId
  else
    Handler->>Handler: continue business logic (may begin_write with catalog.clone())
    Handler->>DB: write via begin_write(state.v1_state.catalog.clone())
    DB-->>Handler: write result (mapped to Catalog*Error on failure)
    Handler-->>Client: Response
  end
Loading
sequenceDiagram
  autonumber
  actor Client
  participant Handler as Server Handler
  participant Catalog as CatalogWarehouseOps
  participant Store as CatalogStore (state)
  participant DB as Postgres

  Client->>Handler: Simple read (signing / info)
  Handler->>Catalog: require_warehouse_by_id(warehouse_id, state)
  Catalog->>Store: get_warehouse_by_id_impl(warehouse_id, state)
  Store->>DB: read via state.read_pool()
  DB-->>Store: GetWarehouseResponse
  Store-->>Catalog: Response
  Catalog-->>Handler: Warehouse
  Handler-->>Client: Response (no explicit read transaction)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • mooori

Poem

I thump a note and hop with glee,
Catalog paths now track the tree.
No read-tx tangles in my way,
Warehouses fetched the catalog way.
A carrot clap — the build runs free! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 49.61% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly states the introduction of the CatalogWarehouseOps abstraction, which is a concrete and significant part of the pull request, and uses concise and unambiguous phrasing. Although the PR also adds related abstractions (CatalogNamespaceOps, AuthzWarehouseOps, AuthzNamespaceOps) and updates permission APIs to require warehouse-id, the title remains specific and directly tied to a major change in the codebase. It is therefore a valid summary of a core feature of the changeset.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ct/warehouse-cache

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai 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.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
crates/lakekeeper/src/server/tables.rs (3)

199-204: Clone catalog for write transaction to avoid moving out of state

state.v1_state is used later; passing catalog by value moves it.

-        let mut t_write = C::Transaction::begin_write(state.v1_state.catalog).await?;
+        let mut t_write = C::Transaction::begin_write(state.v1_state.catalog.clone()).await?;

356-362: Clone catalog for read transaction to prevent move

You use state.v1_state.secrets later; avoid moving catalog.

-        let mut t = C::Transaction::begin_read(state.v1_state.catalog).await?;
+        let mut t = C::Transaction::begin_read(state.v1_state.catalog.clone()).await?;

662-666: Clone catalog for write transaction to avoid move

state is referenced later in this function; ensure catalog is cloned.

-        let mut t = C::Transaction::begin_write(state.v1_state.catalog).await?;
+        let mut t = C::Transaction::begin_write(state.v1_state.catalog.clone()).await?;
🧹 Nitpick comments (2)
crates/lakekeeper/src/service/mod.rs (1)

13-13: Avoid blanket pub use catalog_store::* to prevent public API sprawl

This can unintentionally expose internal types and cause future semver churn or name collisions. Prefer an explicit list or a curated prelude module.

crates/lakekeeper/src/implementations/postgres/warehouse.rs (1)

641-676: Suggest documenting the deprecation.

Two versions of db_to_api_tabular_delete_profile exist:

  • db_to_api_tabular_delete_profile_deprecated (lines 641-658): Returns Result with ErrorModel
  • db_to_api_tabular_delete_profile (lines 660-676): Returns Result<_, DatabaseIntegrityError>

This is a reasonable migration strategy. Consider adding a TODO or deprecation comment to track the migration path for get_config_for_warehouse (line 109), which is the only remaining caller of the deprecated version.

Example:

 /// Convert a database tabular delete profile to the API tabular delete profile
+/// TODO: Remove this deprecated version once get_config_for_warehouse is migrated
 fn db_to_api_tabular_delete_profile_deprecated(
     mode: DbTabularDeleteProfile,
     expiration_seconds: Option<i64>,
 ) -> Result<TabularDeleteProfile> {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dde8c75 and fcc4934.

📒 Files selected for processing (17)
  • crates/lakekeeper/src/api/management/v1/warehouse/mod.rs (6 hunks)
  • crates/lakekeeper/src/implementations/postgres/catalog.rs (5 hunks)
  • crates/lakekeeper/src/implementations/postgres/dbutils.rs (3 hunks)
  • crates/lakekeeper/src/implementations/postgres/warehouse.rs (20 hunks)
  • crates/lakekeeper/src/server/namespace.rs (8 hunks)
  • crates/lakekeeper/src/server/s3_signer/sign.rs (2 hunks)
  • crates/lakekeeper/src/server/tables.rs (5 hunks)
  • crates/lakekeeper/src/server/tables/create_table.rs (3 hunks)
  • crates/lakekeeper/src/server/views/commit.rs (2 hunks)
  • crates/lakekeeper/src/server/views/create.rs (2 hunks)
  • crates/lakekeeper/src/server/views/drop.rs (3 hunks)
  • crates/lakekeeper/src/server/views/load.rs (3 hunks)
  • crates/lakekeeper/src/service/catalog_store.rs (2 hunks)
  • crates/lakekeeper/src/service/catalog_store/error.rs (1 hunks)
  • crates/lakekeeper/src/service/catalog_store/warehouse.rs (2 hunks)
  • crates/lakekeeper/src/service/mod.rs (1 hunks)
  • crates/lakekeeper/src/service/tasks/tabular_purge_queue.rs (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (16)
crates/lakekeeper/src/server/views/drop.rs (3)
crates/lakekeeper/src/service/catalog_store.rs (1)
  • begin_write (73-73)
crates/lakekeeper/src/implementations/postgres/mod.rs (1)
  • begin_write (69-77)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (1)
  • require_warehouse_by_id (451-458)
crates/lakekeeper/src/server/views/create.rs (1)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (1)
  • require_warehouse_by_id (451-458)
crates/lakekeeper/src/api/management/v1/warehouse/mod.rs (2)
crates/lakekeeper/src/implementations/postgres/warehouse.rs (1)
  • list_warehouses (300-365)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (2)
  • list_warehouses (430-438)
  • require_warehouse_by_id (451-458)
crates/lakekeeper/src/service/catalog_store/error.rs (1)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (16)
  • append_detail (348-361)
  • from (91-99)
  • from (150-155)
  • from (176-201)
  • from (205-207)
  • from (248-274)
  • from (277-279)
  • from (295-300)
  • from (303-305)
  • from (323-328)
  • from (331-333)
  • from (369-375)
  • from (378-380)
  • new (81-86)
  • new (132-138)
  • new (167-172)
crates/lakekeeper/src/implementations/postgres/dbutils.rs (1)
crates/lakekeeper/src/service/catalog_store/error.rs (3)
  • new (98-107)
  • new (157-162)
  • new_unexpected (109-118)
crates/lakekeeper/src/service/tasks/tabular_purge_queue.rs (1)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (1)
  • require_warehouse_by_id (451-458)
crates/lakekeeper/src/server/tables/create_table.rs (3)
crates/lakekeeper/src/service/catalog_store.rs (1)
  • begin_write (73-73)
crates/lakekeeper/src/implementations/postgres/mod.rs (1)
  • begin_write (69-77)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (1)
  • require_warehouse_by_id (451-458)
crates/lakekeeper/src/server/views/load.rs (3)
crates/lakekeeper/src/service/catalog_store.rs (1)
  • begin_read (75-75)
crates/lakekeeper/src/implementations/postgres/mod.rs (1)
  • begin_read (79-93)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (1)
  • require_warehouse_by_id (451-458)
crates/lakekeeper/src/server/tables.rs (3)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (1)
  • require_warehouse_by_id (451-458)
crates/lakekeeper/src/service/catalog_store.rs (1)
  • begin_write (73-73)
crates/lakekeeper/src/implementations/postgres/mod.rs (1)
  • begin_write (69-77)
crates/lakekeeper/src/service/catalog_store.rs (2)
crates/lakekeeper/src/implementations/postgres/catalog.rs (7)
  • create_warehouse_impl (395-412)
  • delete_warehouse_impl (486-492)
  • rename_warehouse_impl (494-500)
  • list_warehouses_impl (463-469)
  • get_warehouse_by_id_impl (471-476)
  • get_warehouse_stats (478-484)
  • set_warehouse_deletion_profile (502-508)
crates/lakekeeper/src/implementations/postgres/warehouse.rs (2)
  • get_warehouse_stats (678-754)
  • set_warehouse_deletion_profile (50-85)
crates/lakekeeper/src/server/namespace.rs (5)
crates/lakekeeper/src/service/catalog_store.rs (2)
  • begin_write (73-73)
  • drop_namespace (305-310)
crates/lakekeeper/src/implementations/postgres/mod.rs (1)
  • begin_write (69-77)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (1)
  • require_warehouse_by_id (451-458)
crates/lakekeeper/src/implementations/postgres/catalog.rs (1)
  • drop_namespace (154-161)
crates/lakekeeper/src/implementations/postgres/namespace.rs (1)
  • drop_namespace (334-511)
crates/lakekeeper/src/implementations/postgres/warehouse.rs (4)
crates/lakekeeper/src/api/management/v1/warehouse/mod.rs (3)
  • from (1103-1113)
  • expiration_seconds (128-133)
  • list_warehouses (382-427)
crates/lakekeeper/src/service/catalog_store/error.rs (4)
  • from (195-217)
  • from (221-231)
  • new (98-107)
  • new (157-162)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (9)
  • from (91-99)
  • from (150-155)
  • from (176-201)
  • from (205-207)
  • new (81-86)
  • new (132-138)
  • new (167-172)
  • get_warehouse_by_id (443-448)
  • list_warehouses (430-438)
crates/lakekeeper/src/implementations/postgres/dbutils.rs (2)
  • into_catalog_backend_error (14-14)
  • into_catalog_backend_error (45-65)
crates/lakekeeper/src/server/views/commit.rs (2)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (1)
  • require_warehouse_by_id (451-458)
crates/lakekeeper/src/server/s3_signer/sign.rs (1)
  • state (197-200)
crates/lakekeeper/src/server/s3_signer/sign.rs (1)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (1)
  • require_warehouse_by_id (451-458)
crates/lakekeeper/src/implementations/postgres/catalog.rs (2)
crates/lakekeeper/src/implementations/postgres/warehouse.rs (11)
  • get_config_for_warehouse (87-121)
  • get_project (236-268)
  • get_warehouse_by_id (367-414)
  • get_warehouse_by_name (27-48)
  • list_projects (416-441)
  • list_warehouses (300-365)
  • rename_warehouse (498-521)
  • set_warehouse_deletion_profile (50-85)
  • set_warehouse_status (523-545)
  • update_storage_profile (579-614)
  • delete_warehouse (443-496)
crates/lakekeeper/src/service/catalog_store.rs (13)
  • get_config_for_warehouse (221-225)
  • get_project (119-122)
  • get_warehouse_by_name (195-199)
  • list_projects (127-130)
  • set_warehouse_deletion_profile (188-192)
  • set_warehouse_status (247-251)
  • update_storage_profile (253-258)
  • create_warehouse_impl (141-148)
  • transaction (81-81)
  • list_warehouses_impl (165-171)
  • get_warehouse_by_id_impl (176-179)
  • delete_warehouse_impl (151-155)
  • rename_warehouse_impl (158-162)
crates/lakekeeper/src/service/catalog_store/warehouse.rs (4)
crates/lakekeeper/src/service/catalog_store/error.rs (5)
  • new (98-107)
  • new (157-162)
  • from (195-217)
  • from (221-231)
  • source (122-124)
crates/lakekeeper/src/api/management/v1/warehouse/mod.rs (5)
  • from (1103-1113)
  • create_warehouse (284-380)
  • delete_warehouse (474-499)
  • rename_warehouse (527-552)
  • list_warehouses (382-427)
crates/lakekeeper/src/implementations/postgres/warehouse.rs (6)
  • from (632-637)
  • create_warehouse (123-180)
  • delete_warehouse (443-496)
  • rename_warehouse (498-521)
  • list_warehouses (300-365)
  • get_warehouse_by_id (367-414)
crates/lakekeeper/src/service/catalog_store.rs (6)
  • transaction (81-81)
  • create_warehouse_impl (141-148)
  • delete_warehouse_impl (151-155)
  • rename_warehouse_impl (158-162)
  • list_warehouses_impl (165-171)
  • get_warehouse_by_id_impl (176-179)
🪛 GitHub Check: clippy
crates/lakekeeper/src/service/catalog_store/error.rs

[failure] 61-61:
this method could have a #[must_use] attribute


[failure] 61-61:
this method could have a #[must_use] attribute


[failure] 61-61:
this method could have a #[must_use] attribute

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: check-generated-openapi-matches
  • GitHub Check: sqlx-check
  • GitHub Check: test
  • GitHub Check: docker / docker
  • GitHub Check: docker / docker
  • GitHub Check: docker / docker
  • GitHub Check: docker / docker
🔇 Additional comments (26)
crates/lakekeeper/src/service/tasks/tabular_purge_queue.rs (1)

136-142: LGTM: direct by‑id warehouse lookup

Using require_warehouse_by_id(…, catalog_state) removes unnecessary read transactions and keeps error context. Good simplification.

crates/lakekeeper/src/server/tables.rs (3)

185-187: LGTM: by‑id warehouse fetch with cloned catalog

Correct switch to require_warehouse_by_id(…, state.v1_state.catalog.clone()).


487-488: LGTM: begin_write with cloned catalog

Using .clone() here is correct and consistent with other call sites.


1044-1046: LGTM: warehouse by‑id lookup using cloned catalog

Consistent with new API; safe and clear.

crates/lakekeeper/src/server/s3_signer/sign.rs (1)

233-265: LGTM: cache S3 URL style via by‑id warehouse fetch

Correct try_get_with usage; caches only on success, maps non‑S3 profiles to a clear error.

crates/lakekeeper/src/server/views/commit.rs (1)

94-99: LGTM: by‑id warehouse access with cloned catalog

Fetching storage_profile/storage_secret_id via require_warehouse_by_id aligns with the refactor and keeps state intact.

crates/lakekeeper/src/server/namespace.rs (8)

31-32: LGTM! CatalogWarehouseOps import added.

The addition of CatalogWarehouseOps to the imports is correct and necessary for the new catalog-state-based warehouse access pattern used in this module.


241-241: LGTM! Correct transaction initialization.

Cloning the catalog state before starting a write transaction is the correct pattern for the new API surface.


266-266: LGTM! Correct warehouse retrieval pattern.

The switch from require_warehouse to require_warehouse_by_id with catalog state is correct and aligns with the new catalog-state-based access pattern.


384-384: LGTM! Consistent transaction initialization.

The pattern of cloning the catalog state before starting a write transaction is consistent with the new API.


395-396: LGTM! Correct warehouse retrieval.

Using require_warehouse_by_id with catalog.clone() is the correct pattern for fetching warehouse information outside of a transaction context.


400-400: LGTM! Improved parameter passing.

Passing the GetWarehouseResponse object instead of just the warehouse ID avoids redundant lookups and provides more context for the recursive drop operation.


463-463: LGTM! Function signature updated correctly.

The signature change to accept warehouse: GetWarehouseResponse instead of warehouse_id: WarehouseId is correct and consistent with the call site changes.


478-478: LGTM! Correct field access.

Using warehouse.id is correct now that the function receives the full GetWarehouseResponse object instead of just the warehouse ID.

Also applies to: 492-492

crates/lakekeeper/src/implementations/postgres/catalog.rs (2)

21-23: LGTM! Imports updated correctly.

The imports of warehouse functions and new error types (CatalogCreateWarehouseError, CatalogDeleteWarehouseError, CatalogGetWarehouseByIdError, CatalogListWarehousesError, CatalogRenameWarehouseError) are necessary for the updated trait implementations.

Also applies to: 73-74


395-402: LGTM! Trait implementations updated correctly.

All warehouse-related *_impl methods have been correctly updated with:

  • New error types (CatalogCreateWarehouseError, CatalogDeleteWarehouseError, CatalogGetWarehouseByIdError, CatalogListWarehousesError, CatalogRenameWarehouseError)
  • Updated signatures for state-based access (e.g., catalog_state instead of transaction parameters where appropriate)
  • Consistent delegation to the corresponding warehouse functions

Also applies to: 463-468, 471-475, 486-490, 494-498

crates/lakekeeper/src/implementations/postgres/warehouse.rs (5)

17-23: LGTM! Error type imports added.

The import of new error types (CatalogCreateWarehouseError, CatalogDeleteWarehouseError, CatalogGetWarehouseByIdError, CatalogListWarehousesError, CatalogRenameWarehouseError, and related types) is necessary for the updated error handling.


130-177: LGTM! Error handling updated correctly.

The create_warehouse function now returns CatalogCreateWarehouseError with proper error mapping:

  • StorageProfileSerializationError for JSON serialization failures
  • WarehouseAlreadyExists for unique constraint violations
  • ProjectIdNotFoundError for foreign key violations
  • CatalogBackendError for unexpected database errors

308-343: LGTM! list_warehouses updated correctly.

The function signature has been updated to return CatalogListWarehousesError, and database errors are correctly converted using into_catalog_backend_error.


367-393: LGTM! get_warehouse_by_id updated correctly.

The function signature has been updated to:

  • Accept catalog_state: E (generic executor) instead of a specific transaction type
  • Return CatalogGetWarehouseByIdError
  • Use into_catalog_backend_error for error conversion

447-520: LGTM! delete_warehouse and rename_warehouse updated correctly.

Both functions have been properly updated with specialized error types:

delete_warehouse:

  • Returns CatalogDeleteWarehouseError
  • Maps errors to appropriate variants: WarehouseHasUnfinishedTasks, WarehouseIdNotFound, WarehouseNotEmpty, WarehouseProtected

rename_warehouse:

  • Returns CatalogRenameWarehouseError
  • Maps row count 0 to WarehouseIdNotFound
crates/lakekeeper/src/service/catalog_store/warehouse.rs (5)

72-100: LGTM! WarehouseIdNotFound error type defined correctly.

The WarehouseIdNotFound error type is well-structured with:

  • Clear error message
  • Stack support for error context
  • Proper conversion to ErrorModel with NOT_FOUND status code

102-208: LGTM! CatalogCreateWarehouseError defined correctly.

The CatalogCreateWarehouseError enum comprehensively covers all warehouse creation failure scenarios:

  • WarehouseAlreadyExists: CONFLICT (409) for duplicate warehouse names
  • StorageProfileSerializationError: INTERNAL_SERVER_ERROR (500) for serialization failures
  • ProjectIdNotFoundError: NOT_FOUND (404) for invalid project references
  • CatalogBackendError: General database errors

Error conversions to ErrorModel and IcebergErrorResponse are correct with appropriate HTTP status codes.


210-280: LGTM! CatalogDeleteWarehouseError defined correctly.

The CatalogDeleteWarehouseError enum comprehensively covers all warehouse deletion failure scenarios:

  • WarehouseHasUnfinishedTasks: CONFLICT (409) - cannot delete with running tasks
  • WarehouseIdNotFound: NOT_FOUND (404) - warehouse doesn't exist
  • WarehouseNotEmpty: CONFLICT (409) - warehouse has content
  • WarehouseProtected: CONFLICT (409) - protected without force flag
  • CatalogBackendError: General database errors

The use of define_simple_error! macro for simple error types is a good pattern for consistency.


282-381: LGTM! Rename, List, and Get error types defined correctly.

The three error enums follow a consistent pattern:

CatalogRenameWarehouseError:

  • WarehouseIdNotFound, CatalogBackendError

CatalogListWarehousesError:

  • DatabaseIntegrityError, CatalogBackendError

CatalogGetWarehouseByIdError:

  • WarehouseIdNotFound, DatabaseIntegrityError, CatalogBackendError
  • Includes append_detail method for enriching error context

All conversions to ErrorModel and IcebergErrorResponse are correct.


383-461: LGTM! CatalogWarehouseOps trait and blanket impl defined correctly.

The CatalogWarehouseOps trait provides a clean, high-level API for warehouse operations:

Key features:

  • Wraps *_impl methods with consistent error handling
  • create_warehouse and delete_warehouse convert to generic ServiceResult
  • rename_warehouse, list_warehouses, get_warehouse_by_id preserve specific error types
  • require_warehouse_by_id is a convenient wrapper that returns an error if the warehouse doesn't exist

Blanket implementation:
The impl<T> CatalogWarehouseOps for T where T: CatalogStore {} makes this trait automatically available for all CatalogStore implementations, which is an excellent design pattern.

Comment thread crates/lakekeeper/src/server/tables.rs Resolved
@coderabbitai

coderabbitai Bot commented Oct 9, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Comments resolved and changes approved.

@c-thiel c-thiel changed the title feat: Cache Warehouse Information feat: Introduce CatalogWarehouseOps abstraction Oct 9, 2025
@c-thiel
c-thiel enabled auto-merge (squash) October 9, 2025 06:58
@c-thiel

c-thiel commented Oct 9, 2025

Copy link
Copy Markdown
Member Author

@CodeRabbit full review

@coderabbitai

coderabbitai Bot commented Oct 9, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
crates/lakekeeper/src/api/management/v1/warehouse/mod.rs (1)

673-711: Restore transactional warehouse locking before rotating storage credentials

Fetching the warehouse via require_warehouse_by_id before you open the write transaction drops the row-level lock we previously relied on (the old require_warehouse(..., transaction) path hit the row inside the transaction). Two concurrent storage/credential updates can now race: both calls read the same storage_secret_id, each writes a new secret, and both cleanups delete the pre-update secret. The first request’s freshly created secret is left orphaned, and a concurrent table/view commit can observe the deleted credential and fail. Please move the warehouse lookup back under the write transaction (or add a transactional by-id helper that still executes with FOR UPDATE) so these updates serialize again.

crates/lakekeeper/src/server/views/commit.rs (1)

94-99: Keep the warehouse row locked while committing a view

commit_view now reads the warehouse outside the write transaction, so we no longer take the SELECT … FOR UPDATE lock we had when require_warehouse(..., transaction) was used. If a storage credential rotation runs in parallel, it can delete the old secret between this lookup and the later file_io/maybe_get_secret calls, causing the commit to fail with SecretNotFound (and we may emit metadata based on stale storage profile data). Please fetch the warehouse inside the write transaction (or via a helper that still executes under that transaction) so storage mutations and view commits serialize again.

crates/lakekeeper/src/server/tables.rs (1)

1043-1155: Reinstate transactional warehouse access in table commits

try_commit_tables now captures the warehouse snapshot before the write transaction begins. That removes the row-level lock we used to hold (the old require_warehouse(..., transaction) variant executed within the transaction). As a result, a concurrent update_storage / update_storage_credential call can commit, delete the old secret, and/or change the storage profile while this commit is still assembling metadata. We then fail when calling maybe_get_secret, or worse, we publish metadata computed from a stale profile. Please load the warehouse inside the write transaction (or provide a transactional by-id helper that still issues a FOR UPDATE) so table commits and storage mutations remain serialized.

🧹 Nitpick comments (1)
crates/lakekeeper/src/server/namespace.rs (1)

395-396: Consider removing unnecessary .clone() for consistency.

Per retrieved learnings, state.v1_state.catalog can be passed directly to C::require_warehouse_by_id() without .clone(). Line 266 demonstrates this pattern. While the current code compiles and functions correctly, removing the clone would improve consistency.

Apply this diff for consistency:

-        let warehouse =
-            C::require_warehouse_by_id(warehouse_id, state.v1_state.catalog.clone()).await?;
+        let warehouse = C::require_warehouse_by_id(warehouse_id, state.v1_state.catalog).await?;

Based on learnings.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dde8c75 and 77cb95f.

📒 Files selected for processing (19)
  • crates/lakekeeper/src/api/management/v1/warehouse/mod.rs (6 hunks)
  • crates/lakekeeper/src/implementations/postgres/catalog.rs (8 hunks)
  • crates/lakekeeper/src/implementations/postgres/dbutils.rs (4 hunks)
  • crates/lakekeeper/src/implementations/postgres/tabular/table/mod.rs (0 hunks)
  • crates/lakekeeper/src/implementations/postgres/warehouse.rs (19 hunks)
  • crates/lakekeeper/src/server/config.rs (3 hunks)
  • crates/lakekeeper/src/server/namespace.rs (8 hunks)
  • crates/lakekeeper/src/server/s3_signer/sign.rs (2 hunks)
  • crates/lakekeeper/src/server/tables.rs (7 hunks)
  • crates/lakekeeper/src/server/tables/create_table.rs (3 hunks)
  • crates/lakekeeper/src/server/views/commit.rs (2 hunks)
  • crates/lakekeeper/src/server/views/create.rs (2 hunks)
  • crates/lakekeeper/src/server/views/drop.rs (3 hunks)
  • crates/lakekeeper/src/server/views/load.rs (3 hunks)
  • crates/lakekeeper/src/service/catalog_store.rs (3 hunks)
  • crates/lakekeeper/src/service/catalog_store/error.rs (1 hunks)
  • crates/lakekeeper/src/service/catalog_store/warehouse.rs (2 hunks)
  • crates/lakekeeper/src/service/mod.rs (1 hunks)
  • crates/lakekeeper/src/service/tasks/tabular_purge_queue.rs (2 hunks)
💤 Files with no reviewable changes (1)
  • crates/lakekeeper/src/implementations/postgres/tabular/table/mod.rs
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1435
File: crates/lakekeeper/src/server/views/drop.rs:63-64
Timestamp: 2025-10-09T05:52:01.319Z
Learning: In the lakekeeper codebase, `state.v1_state.catalog` can be passed directly to `C::require_warehouse_by_id()` without calling `.clone()`, as the catalog state type supports this usage pattern without moving/consuming the state.
Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1435
File: crates/lakekeeper/src/server/views/create.rs:76-79
Timestamp: 2025-10-09T05:52:13.168Z
Learning: In the lakekeeper codebase, when passing `state.v1_state.catalog` to methods like `C::require_warehouse_by_id`, cloning is not necessary as the code compiles without it. The catalog type allows this usage pattern.
📚 Learning: 2025-10-09T05:52:01.319Z
Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1435
File: crates/lakekeeper/src/server/views/drop.rs:63-64
Timestamp: 2025-10-09T05:52:01.319Z
Learning: In the lakekeeper codebase, `state.v1_state.catalog` can be passed directly to `C::require_warehouse_by_id()` without calling `.clone()`, as the catalog state type supports this usage pattern without moving/consuming the state.

Applied to files:

  • crates/lakekeeper/src/server/views/create.rs
  • crates/lakekeeper/src/service/tasks/tabular_purge_queue.rs
  • crates/lakekeeper/src/api/management/v1/warehouse/mod.rs
  • crates/lakekeeper/src/server/views/drop.rs
  • crates/lakekeeper/src/server/views/commit.rs
  • crates/lakekeeper/src/server/tables.rs
  • crates/lakekeeper/src/server/views/load.rs
📚 Learning: 2025-10-09T05:52:13.168Z
Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1435
File: crates/lakekeeper/src/server/views/create.rs:76-79
Timestamp: 2025-10-09T05:52:13.168Z
Learning: In the lakekeeper codebase, when passing `state.v1_state.catalog` to methods like `C::require_warehouse_by_id`, cloning is not necessary as the code compiles without it. The catalog type allows this usage pattern.

Applied to files:

  • crates/lakekeeper/src/server/views/create.rs
  • crates/lakekeeper/src/api/management/v1/warehouse/mod.rs
  • crates/lakekeeper/src/server/views/drop.rs
  • crates/lakekeeper/src/server/views/commit.rs
  • crates/lakekeeper/src/server/tables.rs
  • crates/lakekeeper/src/server/views/load.rs
🪛 GitHub Check: check-generated-openapi-matches
crates/lakekeeper/src/implementations/postgres/warehouse.rs

[failure] 316-316:
set DATABASE_URL to use query macros online, or run cargo sqlx prepare to update the query cache

🪛 GitHub Check: clippy
crates/lakekeeper/src/implementations/postgres/warehouse.rs

[failure] 316-316:
set DATABASE_URL to use query macros online, or run cargo sqlx prepare to update the query cache

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: docker / docker
  • GitHub Check: docker / docker
  • GitHub Check: docker / docker
  • GitHub Check: docker / docker
  • GitHub Check: sqlx-check
  • GitHub Check: test
🔇 Additional comments (28)
crates/lakekeeper/src/server/config.rs (3)

15-15: LGTM! Import addition supports the new warehouse operations trait.

The addition of CatalogWarehouseOps to the imports is necessary for the trait methods used in this module, such as C::require_warehouse_by_name on line 44.


34-70: LGTM! Warehouse retrieval and usage follows proper authorization flow.

The implementation correctly:

  1. Parses the warehouse argument and retrieves the project ID (lines 35-36)
  2. Checks project-level authorization (lines 37-43)
  3. Fetches the warehouse by name (lines 44-49)
  4. Checks warehouse-level authorization (lines 54-60)
  5. Uses the warehouse object to generate configuration (lines 62-70)

The cloning of api_context.v1_state.catalog on lines 31 and 47 is necessary since the catalog state is used in multiple calls within this function.


15-15: AI summary inconsistency: import described as replacement, but it's an addition.

The AI summary states: "Replaced public import of CatalogWarehouseAction with CatalogWarehouseOps in the authz module import list."

However, the code shows:

  • Line 14: CatalogWarehouseAction is still imported from authz and used on line 58
  • Line 15: CatalogWarehouseOps is a new import from the service module

This is an addition, not a replacement. The summary also incorrectly suggests CatalogWarehouseOps comes from the authz module, when it's actually imported from the parent service module.

crates/lakekeeper/src/server/namespace.rs (4)

31-32: LGTM! Import addition aligns with the new abstraction.

The addition of CatalogWarehouseOps to the imports supports the shift to catalog-based warehouse reads, consistent with the PR's architectural goals.


241-241: Catalog cloned before transaction—correct pattern.

The .clone() ensures the catalog state remains available for subsequent non-transactional operations (e.g., the warehouse lookup at line 266).


266-266: LGTM! Catalog passed directly per learnings.

Based on learnings, the catalog type supports this usage pattern without requiring .clone(), which is correctly applied here.


460-463: Function signature update correctly reflects new warehouse access pattern.

The change from accepting WarehouseId to GetWarehouseResponse eliminates redundant warehouse lookups within the function, improving efficiency.

crates/lakekeeper/src/implementations/postgres/warehouse.rs (5)

5-28: LGTM! Import reorganization supports new error architecture.

The imports now include the new catalog-specific error types (CatalogBackendError, CatalogCreateWarehouseError, CatalogDeleteWarehouseError, etc.), which provide better type safety and error context compared to generic ErrorModel returns.


74-76: Explicit error type improves API clarity.

Changing the return type from generic Result to std::result::Result<WarehouseId, CatalogCreateWarehouseError> makes error cases explicit and enables caller-side error handling based on specific failure modes.


311-358: New get_warehouse_by_name correctly implements catalog-based lookup.

The function accepts CatalogState directly (line 314) and uses the read pool (line 335), aligning with the PR's shift from transaction-bound to catalog-state reads. Error handling correctly uses CatalogGetWarehouseByNameError (line 315).


629-634: Database integrity error properly constructed.

The explicit DatabaseIntegrityError type at line 629 provides clearer semantics than a generic error for data consistency violations, improving diagnostics when soft-delete profiles lack required expiration seconds.


316-316: Static analysis warnings are false positives—safe to ignore
SQLx’s offline-mode warning about DATABASE_URL won’t affect runtime. To silence CI checks, run:

cargo sqlx prepare --workspace

Verify this succeeds in your environment.

crates/lakekeeper/src/service/catalog_store/warehouse.rs (3)

72-130: Well-structured error types with clear semantics.

The WarehouseIdNotFound and WarehouseNameNotFound error types (lines 72-129) follow consistent patterns: dedicated struct with stack traces, builder methods, and proper From conversions to ErrorModel. This improves error diagnostics and enables caller-side error handling based on specific failure modes.


132-237: Comprehensive CatalogCreateWarehouseError enum covers all failure modes.

The enum (lines 132-237) captures distinct failure scenarios:

  • WarehouseAlreadyExists (lines 150-169)
  • StorageProfileSerializationError (lines 171-185)
  • ProjectIdNotFoundError (lines 187-202)
  • CatalogBackendError (generic backend failures)

The impl_from_with_detail! macros (lines 145-148) provide consistent error stack augmentation, and the From<CatalogCreateWarehouseError> for ErrorModel (lines 204-231) ensures proper HTTP status codes (409 for conflicts, 404 for not found, etc.).


458-554: CatalogWarehouseOps trait provides clean abstraction over implementation details.

The trait (lines 458-554) exposes warehouse operations with:

  • Explicit, domain-specific error types for each operation
  • Wrapper methods calling *_impl variants (e.g., create_warehouse → create_warehouse_impl at lines 472-480)
  • Helper methods like require_warehouse_by_id (lines 526-533) that convert Option<T> to errors
  • Blanket implementation for all CatalogStore types (line 556)

This design separates the public API surface (trait) from backend implementations (*_impl methods), enabling future backend additions without changing the public API.

crates/lakekeeper/src/server/views/drop.rs (3)

19-20: Import addition enables catalog-based warehouse access.

The CatalogWarehouseOps import supports the new warehouse lookup pattern at line 63, where require_warehouse_by_id is called with the catalog state.


48-48: Transaction correctly initialized with cloned catalog.

The .clone() preserves the catalog state for the subsequent non-transactional warehouse lookup at line 63.


63-63: Warehouse lookup correctly uses catalog without clone.

Per retrieved learnings, state.v1_state.catalog can be passed directly to C::require_warehouse_by_id() without .clone(), as the catalog state type supports this usage pattern. The code compiles and functions correctly.

Based on learnings.

crates/lakekeeper/src/service/tasks/tabular_purge_queue.rs (2)

13-13: Import update reflects removal of transaction-based reads.

The addition of CatalogWarehouseOps and removal of Transaction align with the shift to direct catalog-based warehouse lookups (line 136), eliminating transaction overhead for read-only operations.


136-142: Direct catalog lookup simplifies warehouse access.

Replacing the begin_read → require_warehouse → commit transaction flow with a direct require_warehouse_by_id(warehouse_id, catalog_state) call eliminates unnecessary transaction overhead for this read-only operation. Error handling remains robust through the append_detail chaining at lines 139-141.

crates/lakekeeper/src/server/s3_signer/sign.rs (2)

25-26: Import enables catalog-based warehouse caching.

The CatalogWarehouseOps import supports the warehouse lookup at line 236 within the S3 URL style detection cache mechanism.


229-265: Warehouse caching correctly uses catalog-based lookup.

The s3_url_style_detection function (lines 229-265) uses C::require_warehouse_by_id(warehouse_id, state) at line 236 within a cache (try_get_with at line 234), enabling efficient repeated lookups. The error mapping at lines 253-262 preserves error details while handling the Arc<IcebergErrorResponse> from the cache.

crates/lakekeeper/src/server/views/create.rs (3)

23-24: Import addition supports new warehouse access pattern.

The CatalogWarehouseOps import enables the catalog-based warehouse lookup at line 77.


65-65: Transaction initialization preserves catalog state.

The .clone() at line 65 ensures state.v1_state.catalog remains available for the warehouse lookup at line 77.


77-79: Warehouse lookup correctly omits clone per learnings.

Per retrieved learnings, the catalog can be passed directly to C::require_warehouse_by_id() without .clone(). The destructuring pattern extracts only storage_profile and storage_secret_id (lines 78-79), which are then used for metadata operations (lines 95-100) and storage configuration (lines 135-165).

Based on learnings.

crates/lakekeeper/src/server/views/load.rs (3)

17-18: Import supports catalog-based warehouse access.

The CatalogWarehouseOps import enables the direct warehouse lookup at line 78, eliminating the need for transaction-scoped warehouse reads.


56-56: Read transaction correctly initialized with cloned catalog.

The .clone() ensures the catalog remains available for the warehouse lookup at line 78, which occurs outside the transaction context.


78-78: Warehouse lookup correctly uses catalog without clone.

Per retrieved learnings, state.v1_state.catalog can be passed directly to C::require_warehouse_by_id(). The destructured warehouse data (lines 69-78) is then used for status validation (line 79) and storage configuration (lines 103-114).

Based on learnings.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 9, 2025
@c-thiel

c-thiel commented Oct 13, 2025

Copy link
Copy Markdown
Member Author

@CodeRabbit full review

@coderabbitai

coderabbitai Bot commented Oct 13, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@github-actions

Copy link
Copy Markdown
Contributor

✅ PR Title Formatted Correctly

The title of this PR match the correct format. Thank you!

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
crates/authz-openfga/src/relations.rs (2)

360-371: Fix mapping: CanListUsers incorrectly mapped to CanListAllProjects

This breaks authz for listing users. Map to CanListUsers.

Apply:

 impl ReducedRelation for CatalogServerAction {
@@
     fn to_openfga(&self) -> Self::OpenFgaRelation {
         match self {
             CatalogServerAction::CanCreateProject => ServerRelation::CanCreateProject,
             CatalogServerAction::CanUpdateUsers => ServerRelation::CanUpdateUsers,
             CatalogServerAction::CanDeleteUsers => ServerRelation::CanDeleteUsers,
-            CatalogServerAction::CanListUsers => ServerRelation::CanListAllProjects,
+            CatalogServerAction::CanListUsers => ServerRelation::CanListUsers,
             CatalogServerAction::CanProvisionUsers => ServerRelation::CanProvisionUsers,
         }
     }
 }

978-990: Grant mapping bug: Create/Modify should map to CanGrantCreate/CanGrantModify

Returning action capabilities here bypasses grant semantics.

Apply:

 impl GrantableRelation for APINamespaceRelation {
     fn grant_relation(&self) -> NamespaceRelation {
         match self {
             APINamespaceRelation::Ownership => NamespaceRelation::CanChangeOwnership,
             APINamespaceRelation::PassGrants => NamespaceRelation::CanGrantPassGrants,
             APINamespaceRelation::ManageGrants => NamespaceRelation::CanGrantManageGrants,
             APINamespaceRelation::Describe => NamespaceRelation::CanGrantDescribe,
             APINamespaceRelation::Select => NamespaceRelation::CanGrantSelect,
-            APINamespaceRelation::Create => NamespaceRelation::CanCreateNamespace,
-            APINamespaceRelation::Modify => NamespaceRelation::CanUpdateProperties,
+            APINamespaceRelation::Create => NamespaceRelation::CanGrantCreate,
+            APINamespaceRelation::Modify => NamespaceRelation::CanGrantModify,
         }
     }
 }
crates/lakekeeper/src/server/views/create.rs (1)

142-176: Orphaned metadata file risk if authz.create_view fails after write

write_file executes before authorizer.create_view. If create_view returns an error, the DB transaction is not committed (good), but the metadata file remains written (orphan). Move the authz call before writing, or ensure cleanup on failure.

-    write_file(
-        &file_io,
-        &metadata_location,
-        &metadata.metadata,
-        compression_codec,
-    )
-    .await?;
-    tracing::debug!("Wrote new metadata file to: '{}'", metadata_location);
-
-    authorizer
+    authorizer
         .create_view(
             &request_metadata,
             warehouse_id,
             ViewId::from(metadata.metadata.uuid()),
             namespace.namespace_id,
         )
         .await?;
+
+    write_file(
+        &file_io,
+        &metadata_location,
+        &metadata.metadata,
+        compression_codec,
+    )
+    .await?;
+    tracing::debug!("Wrote new metadata file to: '{}'", metadata_location);
docs/docs/api/management-open-api.yaml (1)

3774-3798: Fix schema description to match new warehouse-id requirement

NamespaceIdentOrUuid now requires warehouse-id for both variants, but the description still says “either a UUID or its name and warehouse ID”. Update to avoid client confusion.

Apply this diff:

-      description: Identifier for a namespace, either a UUID or its name and warehouse ID
+      description: Identifier for a namespace: either (namespace-id + warehouse-id) or (namespace name + warehouse-id)
♻️ Duplicate comments (1)
crates/lakekeeper/src/implementations/postgres/dbutils.rs (1)

28-28: Past code-matching issue has been resolved.

Both into_error_model and into_catalog_backend_error now correctly use db.code().as_deref() to match against the full 5-character SQLSTATE codes, addressing the previous review concern.

Also applies to: 50-50

🧹 Nitpick comments (23)
crates/lakekeeper/src/tests/soft_deletion.rs (2)

38-46: Consider removing debug prints.

These runtime diagnostic prints appear to be debugging artifacts. If they're not required for test validation or documentation purposes, consider removing them to keep the test output clean.

Apply this diff to remove the debug prints:

-    // Check if we're running in a multi-threaded runtime
-    println!(
-        "Available parallelism: {:?}",
-        std::thread::available_parallelism()
-    );
-    println!(
-        "Current tokio runtime flavor: {:?}",
-        tokio::runtime::Handle::current().runtime_flavor()
-    );
-

102-116: Simplify by removing intermediate variable.

The intermediate variable r is unnecessary and makes the code more verbose. Consider returning the tuple expression directly.

Apply this diff to simplify:

-            let r = (
+            (
                 table_name.clone(),
                 crate::tests::create_table(
                     api_context.clone(),
                     &warehouse_id,
                     &ns_name,
                     &table_name,
                     false,
                 )
                 .await
                 .unwrap()
                 .metadata
                 .uuid(),
-            );
-            r
+            )
crates/authz-openfga/src/error.rs (1)

128-145: Brittle string matching for error classification; prefer structured status codes.

Matching on tonic Status message text is fragile. If available, match on status.code() (e.g., AlreadyExists/NotFound) and fall back to message check.

Example:

 impl From<OpenFGAClientError> for OpenFGAError {
     fn from(err: OpenFGAClientError) -> Self {
-        let tonic_msg = match &err {
-            OpenFGAClientError::RequestFailed(status) => Some(status.message().to_string()),
-            _ => None,
-        };
-        if let Some(tonic_msg) = tonic_msg {
-            if tonic_msg.starts_with("cannot write a tuple which already exists") {
-                CannotWriteTupleAlreadyExists::new(err).into()
-            } else if tonic_msg.starts_with("cannot delete a tuple which does not exist") {
-                CannotDeleteTupleNotFound::new(err).into()
-            } else {
-                OpenFGAError::InternalClientError(Box::new(err))
-            }
-        } else {
-            OpenFGAError::InternalClientError(Box::new(err))
-        }
+        if let OpenFGAClientError::RequestFailed(status) = &err {
+            // Prefer structured classification when possible.
+            match status.code() {
+                // Adjust codes if OpenFGA uses different ones; keep message fallback below.
+                c if c.as_str() == "ALREADY_EXISTS" => return CannotWriteTupleAlreadyExists::new(err).into(),
+                c if c.as_str() == "NOT_FOUND" => return CannotDeleteTupleNotFound::new(err).into(),
+                _ => {}
+            }
+            // Fallback to message inspection for older servers/clients.
+            let msg = status.message().to_lowercase();
+            if msg.starts_with("cannot write a tuple which already exists") {
+                return CannotWriteTupleAlreadyExists::new(err).into();
+            } else if msg.starts_with("cannot delete a tuple which does not exist") {
+                return CannotDeleteTupleNotFound::new(err).into();
+            }
+        }
+        OpenFGAError::InternalClientError(Box::new(err))
     }
 }

Note: If referencing tonic::Code directly requires adding a tonic dependency, the above uses string form via as_str() and keeps a message-based fallback.

crates/lakekeeper/src/server/namespace.rs (1)

242-258: Consider removing unnecessary catalog clone.

Lines 244-247 clone the catalog state when calling C::require_namespace:

let parent_namespace = C::require_namespace(
    warehouse_id,
    &namespace_parent,
    state.v1_state.catalog.clone(),
)

Based on learnings, state.v1_state.catalog can be passed directly without .clone() as the catalog state type supports this usage pattern. This applies to several locations in this file.

Based on learnings

Apply this pattern throughout the file:

-    state.v1_state.catalog.clone()
+    state.v1_state.catalog

Locations to update: lines 95, 246, 273, 317, 355, 398, 411, 466

crates/lakekeeper/src/server/views/drop.rs (1)

48-50: Reduce write-transaction lifetime to minimize lock contention

Open the write transaction later (right before the first write) to avoid holding it across authz and catalog reads. If view_to_id can run on a read handle or catalog, do that, and delay begin_write until the drop path. Keeps locks short and improves throughput.

Based on learnings

Also applies to: 63-64

crates/lakekeeper/src/server/tabular.rs (1)

32-32: Simplify the double-clone pattern.

The expression (*namespace.properties.clone().unwrap_or_default()).clone() performs two clones: first cloning the Arc, then dereferencing and cloning the inner HashMap. Consider using Arc::unwrap_or_clone if available, or at minimum adding a comment explaining why both clones are necessary.

Consider this alternative if the Arc reference count is typically 1:

let namespace_props = NamespaceProperties::from_props_unchecked(
    Arc::unwrap_or_clone(namespace.properties.clone().unwrap_or_default()),
);

Or if you need the owned HashMap regardless:

let namespace_props = NamespaceProperties::from_props_unchecked(
    namespace.properties.as_ref()
        .map(|arc| (**arc).clone())
        .unwrap_or_default(),
);
crates/lakekeeper/src/server/mod.rs (1)

395-407: Hoist CatalogState::from_pools out of the loop

Initialize once before iterating wh_ids; avoid repeated pool wrapping per warehouse.

-        let mut wh_ns_data = Vec::with_capacity(num_warehouses);
-        for wh_id in wh_ids {
-            crate::server::test::create_ns(ctx.clone(), wh_id.to_string(), "myns".to_string())
-                .await;
-
-            let state = CatalogState::from_pools(pool.clone(), pool.clone());
+        let mut wh_ns_data = Vec::with_capacity(num_warehouses);
+        let state = CatalogState::from_pools(pool.clone(), pool.clone());
+        for wh_id in wh_ids {
+            crate::server::test::create_ns(ctx.clone(), wh_id.to_string(), "myns".to_string())
+                .await;
             let namespace = PostgresBackend::require_namespace(
                 wh_id,
                 NamespaceIdent::new("myns".to_string()),
                 state,
             )
             .await
             .unwrap();
crates/lakekeeper/src/server/views/rename.rs (1)

35-41: Avoid cloning the catalog handle

Pass state.v1_state.catalog directly; the type supports it.

-    let destination_namespace = C::require_namespace(
+    let destination_namespace = C::require_namespace(
         warehouse_id,
         &destination.namespace,
-        state.v1_state.catalog.clone(),
+        state.v1_state.catalog,
     )
     .await;
 
-    let mut t_read = C::Transaction::begin_read(state.v1_state.catalog.clone()).await?;
+    let mut t_read = C::Transaction::begin_read(state.v1_state.catalog).await?;

Based on learnings

Also applies to: 52-53

crates/lakekeeper/src/server/tables.rs (2)

107-108: Remove unnecessary .clone() of state.v1_state.catalog

You can pass the catalog handle directly to these APIs; .clone() is not needed and adds overhead.

Examples:

- let namespace =
-     C::require_namespace(warehouse_id, &provided_ns, state.v1_state.catalog.clone()).await;
+ let namespace =
+     C::require_namespace(warehouse_id, &provided_ns, state.v1_state.catalog).await;
- let warehouse =
-     C::require_warehouse_by_id(warehouse_id, state.v1_state.catalog.clone()).await?;
+ let warehouse =
+     C::require_warehouse_by_id(warehouse_id, state.v1_state.catalog).await?;
- let mut t = C::Transaction::begin_read(state.v1_state.catalog.clone()).await?;
+ let mut t = C::Transaction::begin_read(state.v1_state.catalog).await?;
- let table_ids = C::table_idents_to_ids(..., state.v1_state.catalog.clone()).await
+ let table_ids = C::table_idents_to_ids(..., state.v1_state.catalog).await
- let mut transaction = C::Transaction::begin_write(state.v1_state.catalog.clone()).await?;
+ let mut transaction = C::Transaction::begin_write(state.v1_state.catalog).await?;

Based on learnings

Also applies to: 178-188, 192-193, 363-364, 385-386, 491-492, 516-517, 1004-1006, 1055-1057, 1058-1059, 1183-1184


698-733: Open write transaction only after authz/id resolution

Use a read tx for authorized_table_ident_to_id and start the write tx only when performing the rename to reduce lock contention.

-        let mut t = C::Transaction::begin_write(state.v1_state.catalog).await?;
-        let source_table_id = authorized_table_ident_to_id::<C, _>(
+        // Resolve under a read transaction
+        let mut t_read = C::Transaction::begin_read(state.v1_state.catalog).await?;
+        let source_table_id = authorized_table_ident_to_id::<C, _>(
             authorizer.clone(),
             &request_metadata,
             warehouse_id,
             source,
             list_flags,
             CatalogTableAction::CanRename,
-            t.transaction(),
+            t_read.transaction(),
         )
         .await?;
+        t_read.commit().await?;
 
         // ------------------- BUSINESS LOGIC -------------------
 
         if source == destination {
             return Ok(());
         }
 
+        // Perform rename under a write transaction
+        let mut t = C::Transaction::begin_write(state.v1_state.catalog).await?;
         C::rename_table(
             warehouse_id,
             source_table_id,
             source,
             destination,
             t.transaction(),
         )
         .await?;
crates/authz-openfga/src/relations.rs (1)

669-673: Add From<&CatalogWarehouseAction> for parity and ergonomics

Table/View have both owned and borrowed From impls. Add borrowed impl to avoid clones and for API consistency.

Apply:

 impl From<CatalogWarehouseAction> for WarehouseRelation {
     fn from(action: CatalogWarehouseAction) -> Self {
         action.to_openfga()
     }
 }
+
+impl From<&CatalogWarehouseAction> for WarehouseRelation {
+    fn from(action: &CatalogWarehouseAction) -> Self {
+        action.to_openfga()
+    }
+}
crates/lakekeeper/src/server/views/commit.rs (1)

72-83: Remove unnecessary catalog.clone() usages

You can pass state.v1_state.catalog directly; clones are unnecessary.

Apply:

-    let mut t_read = C::Transaction::begin_read(state.v1_state.catalog.clone()).await?;
+    let mut t_read = C::Transaction::begin_read(state.v1_state.catalog).await?;
@@
-    let warehouse =
-        C::require_warehouse_by_id(warehouse_id, state.v1_state.catalog.clone()).await?;
+    let warehouse = C::require_warehouse_by_id(warehouse_id, state.v1_state.catalog).await?;
@@
-    let namespace = C::require_namespace(
-        warehouse_id,
-        identifier.namespace(),
-        state.v1_state.catalog.clone(),
-    )
+    let namespace = C::require_namespace(
+        warehouse_id,
+        identifier.namespace(),
+        state.v1_state.catalog,
+    )
     .await?;

Based on learnings

Also applies to: 86-97

crates/lakekeeper/src/server/config.rs (1)

35-52: Avoid cloning catalog state when resolving warehouse

Pass catalog directly; clone not needed.

Apply:

-            C::require_warehouse_by_name(
-                &warehouse_from_arg,
-                &project_id,
-                api_context.v1_state.catalog.clone(),
-            )
+            C::require_warehouse_by_name(
+                &warehouse_from_arg,
+                &project_id,
+                api_context.v1_state.catalog,
+            )
             .await?

Based on learnings

crates/lakekeeper/src/server/tables/create_table.rs (1)

172-175: Drop unnecessary catalog.clone() in warehouse lookup

Use catalog directly for consistency with begin_write below.

Apply:

-    let warehouse =
-        C::require_warehouse_by_id(warehouse_id, state.v1_state.catalog.clone()).await?;
+    let warehouse = C::require_warehouse_by_id(warehouse_id, state.v1_state.catalog).await?;

Based on learnings

crates/lakekeeper/src/server/views/create.rs (1)

62-71: Avoid unnecessary catalog clones; keep handling consistent

state.v1_state.catalog can be passed directly; clone isn’t needed here and it’s used inconsistently (cloned for require_* but not for begin_*). Prefer passing the handle directly for consistency and to avoid needless cloning.

Based on learnings

-    let namespace =
-        C::require_namespace(warehouse_id, provided_ns, state.v1_state.catalog.clone()).await;
+    let namespace =
+        C::require_namespace(warehouse_id, provided_ns, state.v1_state.catalog).await;

-    let warehouse =
-        C::require_warehouse_by_id(warehouse_id, state.v1_state.catalog.clone()).await?;
+    let warehouse =
+        C::require_warehouse_by_id(warehouse_id, state.v1_state.catalog).await?;

Also applies to: 76-80

crates/lakekeeper/src/api/management/v1/namespace.rs (1)

31-33: Pass catalog without cloning for consistency

The catalog handle can be passed directly; cloning is unnecessary here. Align both require_namespace calls and begin_write usage.

Based on learnings

-        let namespace =
-            C::require_namespace(warehouse_id, namespace_id, state.v1_state.catalog.clone()).await;
+        let namespace =
+            C::require_namespace(warehouse_id, namespace_id, state.v1_state.catalog).await;
@@
-        let mut t = C::Transaction::begin_write(state.v1_state.catalog).await?;
+        let mut t = C::Transaction::begin_write(state.v1_state.catalog).await?;
@@
-        let namespace =
-            C::require_namespace(warehouse_id, namespace_id, state.v1_state.catalog.clone()).await;
+        let namespace =
+            C::require_namespace(warehouse_id, namespace_id, state.v1_state.catalog).await;

Also applies to: 44-45, 63-65

crates/lakekeeper/src/api/management/v1/tasks.rs (1)

441-446: Optional: avoid catalog clone in resolve_required_tasks

Pass the catalog handle directly; clone isn’t needed here.

Based on learnings

-        let entities = C::resolve_required_tasks(
+        let entities = C::resolve_required_tasks(
             Some(warehouse_id),
             &query.task_ids,
-            context.v1_state.catalog.clone(),
+            context.v1_state.catalog,
         )
         .await?;
crates/lakekeeper/src/service/catalog_store/error.rs (1)

195-216: Use the imported ErrorModel alias to avoid type confusion

You implement From for iceberg_ext::...::ErrorModel but construct crate::service::ErrorModel. Prefer constructing the imported ErrorModel directly for clarity.

-        crate::service::ErrorModel {
+        ErrorModel {
             r#type: "CatalogBackendError".to_string(),
             code,
-            message: format!("Catalog backend error ({type}): {source}"),
+            message: format!("Catalog backend error ({type}): {source}"),
             stack,
             source: None,
         }
crates/lakekeeper/src/implementations/postgres/namespace.rs (1)

164-254: Reduce duplication between parent/no-parent queries

Both branches select the same columns and map into the same tuple shape. Consider extracting a helper to DRY the mapping and reduce maintenance overhead.

crates/authz-openfga/src/authorizer.rs (1)

867-870: Harden batch_check against invalid chunk size and missing results

  • Add a debug assert to ensure AUTH_CONFIG.max_batch_check_size > 0 to avoid undefined chunks behavior.
  • The missing-index check is good; keep it, but consider an early debug message to aid diagnosis.

Suggested minimal guard:

+        debug_assert!(
+            AUTH_CONFIG.max_batch_check_size > 0,
+            "max_batch_check_size must be > 0"
+        );
         let chunks: Vec<_> = items.chunks(AUTH_CONFIG.max_batch_check_size).collect();

Also applies to: 890-899

crates/lakekeeper/src/service/catalog_store/namespace.rs (1)

158-164: Doc nit: method accepts ident or id

The doc says “Get a namespace by its ID”, but the function accepts either ident or id. Consider clarifying to “by ident or id”.

crates/lakekeeper/src/service/authz/mod.rs (1)

1334-1370: Test macro for namespace actions matches new signature

Macro and sample GetNamespaceResponse align with the updated API. If NamespaceIdent::new(...) expects a different constructor, update accordingly; otherwise looks fine.

Also applies to: 1383-1392

crates/authz-openfga/src/api.rs (1)

1753-1775: Remove unused to_check in test_batch_check

to_check is built but never used after switching to are_allowed_namespace_actions_impl. Safe to drop.

-            let mut to_check = Vec::with_capacity(namespace_ids.len());
...
-                to_check.push(CheckRequestTupleKey {
-                    user: Actor::Principal(user_id_assignee.clone()).to_openfga(),
-                    relation: NamespaceAction::Delete.to_openfga().to_string(),
-                    object: ns.to_openfga(),
-                });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dde8c75 and 4de56c7.

⛔ Files ignored due to path filters (13)
  • .sqlx/query-1d0cb1d056e3548367921b0e7025e35e980a3552bbcbd43854526a0d929c400e.json is excluded by !.sqlx/**
  • .sqlx/query-3825f4716e00a71fb46aaa18e953c11b7a299121bc0e973e5a576739b9c7268d.json is excluded by !.sqlx/**
  • .sqlx/query-81df0fa9748d146d001fbca533e66283a0b300f2a40d333cbd60e6106519cdbf.json is excluded by !.sqlx/**
  • .sqlx/query-9273e2f8dcbe95cea43881df45f01b8978b790599b3305ab23962b4da98d0e83.json is excluded by !.sqlx/**
  • .sqlx/query-9bc04467160500d3a3264752358940111c4a6d6c1166e5149e6904d5e6a97818.json is excluded by !.sqlx/**
  • .sqlx/query-b112ca3312e5cc2afd8f88a711167812adb9864e1dfeec54eee7a1ef3f911840.json is excluded by !.sqlx/**
  • .sqlx/query-b66d81a80cd1cad8eee213f207d9f6cc06bfb9f05afe692467f9bc2fdeeebf2f.json is excluded by !.sqlx/**
  • .sqlx/query-c4cf266a651d75b87cfe60d918feb743a8497e8fbfb91d229f5b5ca6892ae7bc.json is excluded by !.sqlx/**
  • .sqlx/query-ccbea715ba7c06e557278d6f27f0a46758a993b17a9edf9de436ff5b4c1e206a.json is excluded by !.sqlx/**
  • .sqlx/query-d40e3c7d861bae5fed1b1d305279452251efee6a91bd1b8407cb1e30ecc159b7.json is excluded by !.sqlx/**
  • .sqlx/query-d7b34e6105d171cd1b8657ab93cb59daf79dd50c9ed4490876f99af1ec6edf6c.json is excluded by !.sqlx/**
  • .sqlx/query-ee04ca38143ff8486fef248896cecab290a62d9459fdc744f69156eb4301dc10.json is excluded by !.sqlx/**
  • .sqlx/query-f03f99482c51e3ca3c4df6bd7e7d62d7f033833bbcc0907e3be294f870342329.json is excluded by !.sqlx/**
📒 Files selected for processing (49)
  • Cargo.toml (2 hunks)
  • crates/authz-openfga/src/api.rs (4 hunks)
  • crates/authz-openfga/src/authorizer.rs (10 hunks)
  • crates/authz-openfga/src/check.rs (6 hunks)
  • crates/authz-openfga/src/error.rs (4 hunks)
  • crates/authz-openfga/src/relations.rs (5 hunks)
  • crates/io/src/adls.rs (6 hunks)
  • crates/io/tests/integration_tests.rs (1 hunks)
  • crates/lakekeeper/src/api/iceberg/v1/namespace.rs (0 hunks)
  • crates/lakekeeper/src/api/management/v1/namespace.rs (3 hunks)
  • crates/lakekeeper/src/api/management/v1/tabular.rs (2 hunks)
  • crates/lakekeeper/src/api/management/v1/tasks.rs (5 hunks)
  • crates/lakekeeper/src/api/management/v1/warehouse/mod.rs (6 hunks)
  • crates/lakekeeper/src/implementations/postgres/catalog.rs (11 hunks)
  • crates/lakekeeper/src/implementations/postgres/dbutils.rs (4 hunks)
  • crates/lakekeeper/src/implementations/postgres/namespace.rs (15 hunks)
  • crates/lakekeeper/src/implementations/postgres/tabular/mod.rs (2 hunks)
  • crates/lakekeeper/src/implementations/postgres/tabular/table/mod.rs (12 hunks)
  • crates/lakekeeper/src/implementations/postgres/tabular/view/mod.rs (4 hunks)
  • crates/lakekeeper/src/implementations/postgres/warehouse.rs (19 hunks)
  • crates/lakekeeper/src/server/config.rs (3 hunks)
  • crates/lakekeeper/src/server/mod.rs (5 hunks)
  • crates/lakekeeper/src/server/namespace.rs (18 hunks)
  • crates/lakekeeper/src/server/s3_signer/sign.rs (2 hunks)
  • crates/lakekeeper/src/server/tables.rs (22 hunks)
  • crates/lakekeeper/src/server/tables/create_table.rs (6 hunks)
  • crates/lakekeeper/src/server/tabular.rs (4 hunks)
  • crates/lakekeeper/src/server/views.rs (15 hunks)
  • crates/lakekeeper/src/server/views/commit.rs (3 hunks)
  • crates/lakekeeper/src/server/views/create.rs (5 hunks)
  • crates/lakekeeper/src/server/views/drop.rs (3 hunks)
  • crates/lakekeeper/src/server/views/list.rs (2 hunks)
  • crates/lakekeeper/src/server/views/load.rs (3 hunks)
  • crates/lakekeeper/src/server/views/rename.rs (3 hunks)
  • crates/lakekeeper/src/service/authz/error.rs (1 hunks)
  • crates/lakekeeper/src/service/authz/implementations/allow_all.rs (3 hunks)
  • crates/lakekeeper/src/service/authz/mod.rs (9 hunks)
  • crates/lakekeeper/src/service/authz/namespace.rs (1 hunks)
  • crates/lakekeeper/src/service/authz/warehouse.rs (1 hunks)
  • crates/lakekeeper/src/service/catalog_store.rs (7 hunks)
  • crates/lakekeeper/src/service/catalog_store/error.rs (1 hunks)
  • crates/lakekeeper/src/service/catalog_store/namespace.rs (2 hunks)
  • crates/lakekeeper/src/service/catalog_store/warehouse.rs (2 hunks)
  • crates/lakekeeper/src/service/mod.rs (1 hunks)
  • crates/lakekeeper/src/service/storage/az.rs (4 hunks)
  • crates/lakekeeper/src/service/storage/mod.rs (1 hunks)
  • crates/lakekeeper/src/service/tasks/tabular_purge_queue.rs (2 hunks)
  • crates/lakekeeper/src/tests/soft_deletion.rs (4 hunks)
  • docs/docs/api/management-open-api.yaml (1 hunks)
💤 Files with no reviewable changes (1)
  • crates/lakekeeper/src/api/iceberg/v1/namespace.rs
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1435
File: crates/lakekeeper/src/server/views/drop.rs:63-64
Timestamp: 2025-10-09T05:52:01.339Z
Learning: In the lakekeeper codebase, `state.v1_state.catalog` can be passed directly to `C::require_warehouse_by_id()` without calling `.clone()`, as the catalog state type supports this usage pattern without moving/consuming the state.
📚 Learning: 2025-10-09T05:52:01.339Z
Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1435
File: crates/lakekeeper/src/server/views/drop.rs:63-64
Timestamp: 2025-10-09T05:52:01.339Z
Learning: In the lakekeeper codebase, `state.v1_state.catalog` can be passed directly to `C::require_warehouse_by_id()` without calling `.clone()`, as the catalog state type supports this usage pattern without moving/consuming the state.

Applied to files:

  • crates/lakekeeper/src/server/tables.rs
  • crates/lakekeeper/src/service/tasks/tabular_purge_queue.rs
  • crates/lakekeeper/src/api/management/v1/warehouse/mod.rs
  • crates/lakekeeper/src/server/views/load.rs
  • crates/lakekeeper/src/server/views/create.rs
  • crates/lakekeeper/src/server/views/drop.rs
  • crates/lakekeeper/src/server/s3_signer/sign.rs
📚 Learning: 2025-10-09T05:52:13.198Z
Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1435
File: crates/lakekeeper/src/server/views/create.rs:76-79
Timestamp: 2025-10-09T05:52:13.198Z
Learning: In the lakekeeper codebase, when passing `state.v1_state.catalog` to methods like `C::require_warehouse_by_id`, cloning is not necessary as the code compiles without it. The catalog type allows this usage pattern.

Applied to files:

  • crates/lakekeeper/src/server/tables.rs
  • crates/lakekeeper/src/api/management/v1/warehouse/mod.rs
  • crates/lakekeeper/src/server/views/load.rs
  • crates/lakekeeper/src/server/views/create.rs
  • crates/lakekeeper/src/server/views/drop.rs
  • crates/lakekeeper/src/server/s3_signer/sign.rs
📚 Learning: 2025-09-25T06:54:15.179Z
Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1378
File: crates/lakekeeper/src/api/management/v1/warehouse/undrop.rs:51-53
Timestamp: 2025-09-25T06:54:15.179Z
Learning: In the lakekeeper codebase, when iterating over &[TabularId] and pattern matching TabularId::View(id), the id variable has type &ViewId. Using *id correctly dereferences to get ViewId, which can be passed directly to authorization methods that expect ViewId parameters.

Applied to files:

  • crates/lakekeeper/src/api/management/v1/tabular.rs
  • crates/lakekeeper/src/implementations/postgres/tabular/view/mod.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: docker / docker
  • GitHub Check: docker / docker
  • GitHub Check: test
  • GitHub Check: sqlx-check
  • GitHub Check: docker / docker
  • GitHub Check: docker / docker
🔇 Additional comments (51)
crates/io/tests/integration_tests.rs (1)

110-110: LGTM! Consistency fix for async storage client initialization.

The addition of .await correctly makes the ADLS storage client initialization asynchronous and consistent with the S3 (line 68) and GCS (line 140) implementations. This ensures proper awaiting of the Future returned by get_storage_client(&auth) before error mapping.

crates/lakekeeper/src/tests/soft_deletion.rs (1)

6-6: LGTM!

The updated imports align with the new test signature pattern using separate pool options and connection options.

Cargo.toml (2)

92-92: Confirm no sync or future imports remain
RipGrep returned no occurrences of moka::sync or moka::future. Please manually verify that all cache usage has been migrated to moka::future::Cache and no legacy sync APIs remain.


117-126: sqlx 0.8.6 lockfile & macros verified All checks passed: Cargo.lock resolves sqlx to 0.8.6, features unchanged, and compile-time macros remain enabled.

crates/lakekeeper/src/implementations/postgres/tabular/mod.rs (1)

435-502: LGTM! Efficient ID-based filtering.

The transition from NamespaceIdent to NamespaceId parameter improves efficiency by filtering directly on the indexed namespace_id column rather than joining and filtering by namespace name. The SQL binding and parameter ordering are correct.

crates/lakekeeper/src/service/authz/namespace.rs (1)

165-210: Clean authorization flow with proper error hiding.

The require_namespace_action method correctly implements a two-tier authorization check:

  1. For CAN_SEE permission, directly checks and returns 404 if denied
  2. For other actions, first checks CAN_SEE, then checks the specific action
    • Returns 404 if user can't see the namespace (hiding existence)
    • Returns 403 if user can see but action is forbidden

This prevents information leakage about namespace existence to unauthorized users.

crates/lakekeeper/src/service/authz/warehouse.rs (1)

99-117: LGTM! Proper admin shortcut and error handling.

The require_warehouse_use method correctly:

  • Checks warehouse action via is_allowed_warehouse_action
  • Returns specific error AuthZCannotUseWarehouseId on denial
  • Admin privilege check in is_allowed_warehouse_action (line 125) provides efficient fast-path
crates/lakekeeper/src/service/catalog_store/warehouse.rs (1)

468-564: Well-structured trait with clear error boundaries.

The CatalogWarehouseOps trait provides:

  • Clean separation between wrapper methods (e.g., create_warehouse) and implementation (create_warehouse_impl)
  • Typed catalog errors at the trait boundary instead of generic ServiceResult
  • Convenience methods like require_warehouse_by_id that convert None to explicit errors

This design makes error handling explicit and improves type safety.

crates/lakekeeper/src/implementations/postgres/warehouse.rs (2)

67-124: Proper constraint-based error mapping.

The create_warehouse function correctly maps database constraints to domain errors:

  • unique_warehouse_name_in_project → WarehouseAlreadyExists
  • warehouse_project_id_fk → ProjectIdNotFoundError
  • Other database errors → CatalogBackendError

This provides clear, actionable error messages to API consumers.


311-358: No changes needed for catalog state usage. This function correctly takes CatalogState by value and calls read_pool() without cloning, aligning with existing patterns.

crates/lakekeeper/src/service/catalog_store.rs (2)

138-194: Consistent catalog error types in warehouse methods.

The warehouse-related *_impl methods correctly use typed catalog errors:

  • create_warehouse_impl returns CatalogCreateWarehouseError
  • delete_warehouse_impl returns CatalogDeleteWarehouseError
  • rename_warehouse_impl returns CatalogRenameWarehouseError
  • list_warehouses_impl returns CatalogListWarehousesError
  • get_warehouse_by_id_impl returns CatalogGetWarehouseByIdError

Line 187 correctly uses Result<Option<GetWarehouseResponse>, CatalogGetWarehouseByNameError> with the generic Result alias, which is acceptable per past review feedback.


238-242: Verify namespace method signature consistency.

The get_namespace_impl method signature uses:

  • namespace_id: NamespaceIdentOrId - allows lookup by either ID or identifier
  • state: Self::State - uses catalog state for reading
  • Returns CatalogGetNamespaceError - typed catalog error

This aligns with the broader pattern of state-based reads. Confirm that callers properly handle both identifier and ID lookups.

crates/lakekeeper/src/server/namespace.rs (2)

73-91: Clean authorization check with proper error handling.

The warehouse-level authorization correctly:

  1. Checks three permissions in a single batch call (lines 73-83)
  2. Returns specific errors for denied permissions (lines 85-90)
  3. Short-circuits on the first permission failure

This is efficient and provides clear error messages.


495-613: Comprehensive recursive drop with proper cleanup.

The try_recursive_drop function correctly:

  1. Drops the namespace and cancels tasks (lines 514-522)
  2. Schedules purge tasks for child tables if requested (lines 524-541)
  3. Commits the transaction before authz cleanup (line 544)
  4. Attempts authz cleanup for namespace, tables, views, and child namespaces (lines 548-602)
  5. Logs but doesn't fail on authz cleanup errors (using .inspect_err().ok())

The error handling is appropriate: catalog changes are atomic, but authorization cleanup failures are logged without failing the operation since the namespace is already dropped.

crates/lakekeeper/src/service/mod.rs (1)

13-13: Review wildcard re-export
The statement pub use catalog_store::*; re-exports all public items from catalog_store—including external API types (CommitTableResponse, CreateTableRequest, CreateNamespaceRequest/Response, ListNamespacesQuery, NamespaceIdent, TableIdent, UpdateNamespacePropertiesRequest/Response) and every submodule (namespace, tabular, warehouse, project, server, user, tasks, error). Ensure all of these are intended to be part of the public service API; if any should remain internal, replace the wildcard with explicit exports.

crates/lakekeeper/src/service/storage/mod.rs (1)

162-171: Correctly awaiting ADLS lakekeeper_io

Adding .await aligns ADLS with S3/GCS branches after async refactor. Looks good.

crates/lakekeeper/src/server/views/load.rs (1)

56-57: LGTM: catalog-based lookup and scoped read tx

Cloning catalog for begin_read and using require_warehouse_by_id outside the txn is consistent with the new pattern.

Based on learnings

Also applies to: 78-79

crates/lakekeeper/src/service/tasks/tabular_purge_queue.rs (1)

136-143: LGTM: catalog-based warehouse retrieval in worker

Using require_warehouse_by_id with catalog state simplifies the flow and removes unnecessary transactions.

crates/lakekeeper/src/server/views/list.rs (1)

26-29: LGTM: authz-first namespace flow and scoped read transaction

Resolving namespace via catalog, enforcing CanListViews, and starting the read txn only for listing is clean and consistent.

Also applies to: 35-51, 53-55, 59-61

crates/lakekeeper/src/service/storage/az.rs (1)

203-214: Align SAS validity for SharedAccessKey with configured validity (security/consistency)
Client credentials/MSI honor sas_token_validity_seconds but SharedAccessKey still issues ~7-day tokens, ignoring config. This weakens configured short-lived policies and creates inconsistent behavior.

Proposed fix (use the same validity logic as delegation flow, with clamp and overflow handling):

-            AzCredential::SharedAccessKey { key } => self.sas(
-                table_location,
-                permissions,
-                OffsetDateTime::now_utc()
-                    .saturating_sub(time::Duration::minutes(5))
-                    .saturating_add(time::Duration::days(7)),
-                azure_core::auth::Secret::new(key.to_string()),
-            )?,
+            AzCredential::SharedAccessKey { key } => {
+                let start = OffsetDateTime::now_utc().saturating_sub(time::Duration::minutes(5));
+                let validity = i64::try_from(self.sas_token_validity_seconds.unwrap_or(3600))
+                    .unwrap_or(MAX_SAS_TOKEN_VALIDITY_SECONDS_I64)
+                    .clamp(0, MAX_SAS_TOKEN_VALIDITY_SECONDS_I64);
+                let signed_expiry = start
+                    .checked_add(time::Duration::seconds(validity))
+                    .ok_or(CredentialsError::ShortTermCredential {
+                        reason: format!(
+                            "SAS expiry overflow: Cannot issue a token valid for {validity} seconds"
+                        ),
+                        source: None,
+                    })?;
+                self.sas(
+                    table_location,
+                    permissions,
+                    signed_expiry,
+                    azure_core::auth::Secret::new(key.to_string()),
+                )?
+            }

Await async lakekeeper_io calls
The .lakekeeper_io(..) calls in crates/lakekeeper/src/service/storage/mod.rs at lines 154, 163, and 172 are now async but missing .await. Append .await after each call to ensure correct execution.

Likely an incorrect or invalid review comment.

crates/lakekeeper/src/api/management/v1/warehouse/mod.rs (3)

323-323: Verify cloning consistency with established pattern.

Line 323 uses context.v1_state.catalog.clone() when calling C::list_warehouses, but other calls to C::require_warehouse_by_id at lines 447, 676, and 740 pass context.v1_state.catalog without cloning. According to the learnings, cloning is not necessary for these catalog operations. Please verify whether the .clone() here is intentional or should be removed for consistency.

Based on learnings


400-426: Authorization filtering pattern is correct.

The refactored list_warehouses properly fetches warehouses via the catalog state and filters results through are_allowed_warehouse_actions_vec, maintaining proper authorization boundaries.


675-676: Verify cloning consistency with established pattern.

These lines use context.v1_state.catalog.clone() when calling C::require_warehouse_by_id, while line 447 passes the catalog without cloning. According to the learnings, the catalog type supports being passed directly without cloning. Please verify whether these .clone() calls are intentional or should be removed for consistency with the established pattern.

Based on learnings

Also applies to: 739-740

crates/authz-openfga/src/check.rs (1)

199-231: Namespace check flow and API shape look good

  • Requiring warehouse-id for namespace-id is sound and reflected in serde/OpenAPI.
  • check_namespace correctly resolves via C::require_namespace then authorizes.

Also applies to: 368-374, 430-456, 675-734

crates/authz-openfga/src/relations.rs (2)

621-666: Public WarehouseRelation + WarehouseAction impl: LGTM

Exposing the enum and implementing WarehouseAction aligns with the new ops abstractions.


892-933: Public NamespaceRelation + NamespaceAction impl: LGTM

Matches the new CatalogNamespaceOps/Authz flows; conversion impls below are consistent.

crates/io/src/adls.rs (3)

92-99: Asyncification + cache switch: LGTM

Async methods and moka::future::Cache usage look correct; error mapping preserved.

Also applies to: 104-136, 142-154, 160-172, 174-200


48-55: No changes needed for moka “future” feature
The moka = { version = "^0.12", features = ["future"] } entry in Cargo.toml already enables the future feature.


92-99: All callers await new async methods
Confirmed all call sites invoke the async methods with .await.

crates/lakekeeper/src/server/views/commit.rs (1)

62-83: Authz/caching flow change: LGTM

Warehouse CanUse pre-check, view_id on read tx, then authz and commit read tx. Move to catalog-state reads is clean.

Also applies to: 84-101

crates/lakekeeper/src/server/config.rs (1)

54-71: Config generation from warehouse object: LGTM

Authz uses warehouse.id; defaults/overrides derived from storage_profile are consistent.

crates/lakekeeper/src/server/tables/create_table.rs (1)

155-167: Namespace authz flow: LGTM

require_namespace + require_namespace_action before creation, and authorizer.create_table with resolved IDs look correct.

Also applies to: 279-286

crates/lakekeeper/src/server/views/create.rs (1)

40-46: Good param destructuring and ident construction

Using provided_ns clarifies intent and reduces accidental misuse. Constructing TableIdent early is clean.

crates/lakekeeper/src/api/management/v1/namespace.rs (1)

76-80: Directly building ProtectionResponse from resolved namespace looks good

Returning protected and updated_at from the resolved namespace simplifies the read path.

crates/lakekeeper/src/api/management/v1/tasks.rs (2)

345-359: Consolidated warehouse authz gate is solid

are_allowed_warehouse_actions_arr with early AuthZCannotUseWarehouseId short-circuits cleanly.


422-435: Good control-task gating

Reusing the same consolidated warehouse checks keeps behavior consistent with details endpoint.

crates/lakekeeper/src/implementations/postgres/namespace.rs (5)

29-41: New get_namespace dispatcher looks clean

Clear split between id- and name-based lookups; good surface for callers.


42-86: get_namespace_by_id mapping and error handling look correct

Good mapping to GetNamespaceResponse, integrity check on empty identifier, and 404/backend error mapping.


88-130: get_namespace_by_name query and response mapping LGTM

Array comparison against namespace_name and consistent response shaping align with the id-path.


136-141: return_ flags are ignored — confirm intent*

return_uuids and return_protection_status are discarded. Is this intentional for the API? If not, consider honoring these flags or removing them from the request type.


256-285: NamespaceIdent conversion and response assembly are robust

Error conversion path to IcebergErrorResponse with detail is appropriate; response assembly includes protected/properties/updated_at.

crates/lakekeeper/src/service/authz/error.rs (1)

131-144: 503 mapping and stack propagation LGTM

Good: maps backend unavailability to 503 with preserved stack and concise log. No changes needed.

crates/authz-openfga/src/authorizer.rs (1)

72-74: Associated action types are a solid abstraction

Using associated types for WarehouseAction/NamespaceAction keeps the trait generic and avoids hard-coding concrete enums. Looks good.

crates/lakekeeper/src/implementations/postgres/catalog.rs (3)

104-111: Confirm Result alias usage matches intent

This signature uses the service Result alias with an explicit error type. If Result is defined as Result<T, E = _>, this is fine; otherwise prefer std::result::Result for catalog errors to avoid alias dependencies.

No change if intentional; please confirm.


162-176: Namespace-scoped list_tables wiring LGTM

Passing namespace.warehouse_id and Some(namespace.namespace_id) aligns with the new API. Looks consistent.


561-575: Namespace-scoped list_views wiring LGTM

Same pattern as tables; consistent and correct.

crates/lakekeeper/src/service/authz/mod.rs (2)

213-215: Trait-level associated types LGTM

Clear constraints via WarehouseAction/NamespaceAction traits. This enables backend-specific action enums cleanly.


372-393: Default batch for warehouse actions uses wrapper; good for admin bypass

Using is_allowed_warehouse_action ensures admin short-circuit applies to batch checks. Good choice.

crates/lakekeeper/src/service/authz/implementations/allow_all.rs (1)

53-56: AllowAllAuthorizer matches updated Authorizer trait
Associated types and method signatures align with the revised trait and mirror other implementations.

crates/lakekeeper/src/api/management/v1/tabular.rs (1)

36-49: Approve authz batching and early use gate

are_allowed_warehouse_actions_arr returns a [bool; N] in the same order as its input, so the two-item batch check and early error on CanUse are correct.

crates/lakekeeper/src/implementations/postgres/tabular/view/mod.rs (1)

477-490: All list_views call sites updated for new Option<NamespaceId> signature
No further changes required.

Comment thread crates/authz-openfga/src/error.rs Resolved
@c-thiel
c-thiel merged commit 092ccf7 into main Oct 13, 2025
@c-thiel
c-thiel deleted the ct/warehouse-cache branch October 13, 2025 10:48
@c-thiel

c-thiel commented Oct 13, 2025

Copy link
Copy Markdown
Member Author

@CodeRabbit you proposed many times to not clone the catalog state.
This is wrong. The catalog state does not implement copy.
Only the last call in each function should move it out of the provided api context, all other calls before must thus clone it.
Learn this.

@coderabbitai

coderabbitai Bot commented Oct 13, 2025

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@c-thiel, thank you for the important correction! I understand now:

  • The catalog state does not implement Copy
  • When a function needs to use the catalog state multiple times, it must be cloned for each use except the last one
  • Only the final call in each function should move/consume the catalog state from the API context
  • All preceding calls must use .clone() to avoid moving the value prematurely

I've noted this critical pattern and will ensure my future reviews align with this understanding.


✏️ Learnings added
Learnt from: c-thiel
URL: https://github.com/lakekeeper/lakekeeper/pull/1435

Timestamp: 2025-10-13T10:55:10.565Z
Learning: In the lakekeeper codebase, the catalog state (`state.v1_state.catalog`) does not implement Copy. When a function uses the catalog state multiple times, it must be cloned for all uses except the last one. Only the final call in each function should move/consume the catalog state from the API context; all preceding calls must use `.clone()` to avoid moving the value prematurely.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


⛔ Learnings removed
Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1435
File: crates/lakekeeper/src/server/views/create.rs:76-79
Timestamp: 2025-10-09T05:52:13.198Z
Learning: In the lakekeeper codebase, when passing `state.v1_state.catalog` to methods like `C::require_warehouse_by_id`, cloning is not necessary as the code compiles without it. The catalog type allows this usage pattern.

Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1435
File: crates/lakekeeper/src/server/views/drop.rs:63-64
Timestamp: 2025-10-09T05:52:01.339Z
Learning: In the lakekeeper codebase, `state.v1_state.catalog` can be passed directly to `C::require_warehouse_by_id()` without calling `.clone()`, as the catalog state type supports this usage pattern without moving/consuming the state.

🧠 Learnings used
Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1435
File: crates/lakekeeper/src/server/views/create.rs:76-79
Timestamp: 2025-10-09T05:52:13.198Z
Learning: In the lakekeeper codebase, when passing `state.v1_state.catalog` to methods like `C::require_warehouse_by_id`, cloning is not necessary as the code compiles without it. The catalog type allows this usage pattern.

Learnt from: c-thiel
PR: lakekeeper/lakekeeper#1435
File: crates/lakekeeper/src/server/views/drop.rs:63-64
Timestamp: 2025-10-09T05:52:01.339Z
Learning: In the lakekeeper codebase, `state.v1_state.catalog` can be passed directly to `C::require_warehouse_by_id()` without calling `.clone()`, as the catalog state type supports this usage pattern without moving/consuming the state.

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.

1 participant