From baca56a1cad1043444f37a5967ba1a0c80ed8423 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 14 Aug 2026 07:51:50 +0000 Subject: [PATCH 01/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 69676480..1448c73b 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -12,6 +12,16 @@ author, follow-up, and review runs. ## Entries +### 2026-08-14: learnings since 2026-08-13T07:50:36Z +- **Context:** PR #241 (mandatory OIDC token exchange) added `FederationProvider`/`CacheEntry` with `#[derive(Debug)]`; both a review bot and a human reviewer flagged that the derived impl prints the raw source JWT and the minted in-house `access_token` in the clear, bypassing the redaction that `AuthConfig` in `src/config.rs` hand-writes. + **Rule:** Never `#[derive(Debug)]` on a type that transitively holds auth tokens/secrets (access tokens, client secrets, JWTs) — hand-write a `Debug` that redacts the secret fields, matching the repo's existing `AuthConfig` redaction convention, and add a test asserting tokens never appear in Debug output. +- **Context:** PR #246 collapsed an ODBC empty `table_types` CSV to `None` because `Some(&[])` now means match-NONE (hiveserver2 #83 reversed the earlier empty==null reading); PR #248's reviewer flagged the mirror case where a C caller passing `""` records `Some("")` and silently selects SP-wide WIF instead of the documented "unset" BYOT branch. + **Rule:** At C-ABI/ODBC boundaries an empty string or empty collection is NOT the same as absent — `required_str`/CSV splits yield `Some("")`/`Some(&[])`, distinct from `None`. Explicitly collapse empty→`None` (or reject it) so the documented "unset" semantics hold, and lock the collapse with a test since downstream match-arms treat `Some(empty)` differently from `None`. +- **Context:** PRs #247 and #241 threaded U2M OAuth defaults; reviewers repeatedly flagged that overriding the OAuth client without pinning its matching scopes and redirect port inherits the kernel's defaults for a *different* registered app — e.g. `databricks-sql-python` requesting `all-apis` → `access_denied`, or the `8030` default port → `redirect_uri_mismatch`. + **Rule:** U2M OAuth `{client_id, scopes, redirect_port}` are a coupled bundle tied to one registered IdP app — when a binding overrides `client_id`, it must also pin the scopes and redirect port for that app (only when the caller relies on the default client); never half-override the bundle. +- **Context:** PR #247's reviewer caught that `napi/index.d.ts` is auto-generated from the Rust doc comments on `ConnectionOptions`, so a doc-only edit to `napi/src/database.rs` that skipped regenerating the `.d.ts` propagated stale values (port `8020`, wrong scopes) into the committed types; the fix hand-synced both sides. + **Rule:** `napi/index.d.ts` is generated from the Rust doc comments in `napi/src/database.rs` — any change to those docs (or to defaults they describe) must regenerate or hand-sync `index.d.ts` in the same PR, or the two silently drift. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From bb24c1b08cc80706493cab72552b45f67c4d1696 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 07:31:22 +0000 Subject: [PATCH 02/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 1448c73b..0cc3c476 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -22,6 +22,18 @@ author, follow-up, and review runs. - **Context:** PR #247's reviewer caught that `napi/index.d.ts` is auto-generated from the Rust doc comments on `ConnectionOptions`, so a doc-only edit to `napi/src/database.rs` that skipped regenerating the `.d.ts` propagated stale values (port `8020`, wrong scopes) into the committed types; the fix hand-synced both sides. **Rule:** `napi/index.d.ts` is generated from the Rust doc comments in `napi/src/database.rs` — any change to those docs (or to defaults they describe) must regenerate or hand-sync `index.d.ts` in the same PR, or the two silently drift. +### 2026-08-18: learnings since 2026-08-17T07:37:07Z +- **Context:** PR #250 (telemetry design) and PR #184 (README quick-start) — reviewers flagged that public `#[non_exhaustive]` config structs (`TelemetryConfig`, `HttpConfig`) can't be built from the pyo3/napi binding crates, which are separate crates. + **Rule:** A `#[non_exhaustive]` public struct cannot be built with struct-literal syntax from another crate — including `..Default::default()` functional-update (hard E0639) — so every `#[non_exhaustive]` config needs a `new()`/builder (repo convention, e.g. `ConnectionConfig::new`) or callers must use construct-then-mutate; remember pyo3/napi/C-ABI bindings are external crates subject to this. +- **Context:** PR #257 replaced the single U2M `redirect_port` with an ordered `redirect_ports` candidate list for the OAuth browser flow. + **Rule:** A U2M OAuth callback port must be a static port pre-registered as the IdP's `redirect_uri`: port `0` binds an OS-ephemeral port that can never match (reject it), and `databricks-sql-python` registers a *discrete* set (`8020`/`8025`), not a contiguous range — so never auto-walk `+N`; require caller-supplied exact ports. Exception: the default in-house app normalizes loopback redirects by dropping the port (RFC 8252 §7.3), so any `http://localhost:{port}` works only for that default client. +- **Context:** PR #184 (connection-parameter reference) — a reviewer claimed `CAN_CLOUD_DOWNLOAD` was an allowlisted server-side `session_conf` key; the code deliberately excludes it (regression tripwire `session_conf_filter_drops_can_cloud_download`, issue #196). + **Rule:** CloudFetch is selected via the SEA request `disposition`, NOT a `session_conf` key — `CAN_CLOUD_DOWNLOAD`/`can_cloud_download` is intentionally not in `SESSION_CONF_ALLOWLIST` and any caller-supplied value is silently dropped; expose the toggle only through `ResultConfig::cloudfetch_enabled` (and the client-only `cloudfetch_enabled` key), never as a server conf. +- **Context:** PR #184 — the README quick-start had two compile errors (E0639 `#[non_exhaustive]` construction, missing `ExecutedStatementHandle` trait import) plus rustdoc `#`-hidden lines rendering literally on GitHub; CI never caught them. + **Rule:** Fenced ```rust blocks in README.md are NOT compiled by `cargo test` unless the file is wired in via `#![doc = include_str!("../README.md")]`; treat README/markdown examples as untested — manually verify imports (traits in scope), `#[non_exhaustive]` construction, and drop the rustdoc `#`-hidden-line convention since GitHub shows those lines verbatim. +- **Context:** PR #257 pyo3 rename thread — engineer-bot repeatedly replied "no code change needed," insisting both `redirect_port` and `redirect_ports` kwargs were present, while the actual HEAD signature exposed only `redirect_ports`; the reviewer had to re-fetch and push back across several rounds before the fix landed. + **Rule:** Before answering a reviewer's claim about the current diff/signature with "no change needed / already present," re-read the file at HEAD and quote the exact current lines — do not rely on a remembered or partial read of the working tree; asserting a symbol is present/absent from stale context burns review rounds. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 79ade781a3d5f784776e006c942159be1984f335 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 19 Aug 2026 07:31:19 +0000 Subject: [PATCH 03/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 0cc3c476..f6e2085a 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -34,6 +34,16 @@ author, follow-up, and review runs. - **Context:** PR #257 pyo3 rename thread — engineer-bot repeatedly replied "no code change needed," insisting both `redirect_port` and `redirect_ports` kwargs were present, while the actual HEAD signature exposed only `redirect_ports`; the reviewer had to re-fetch and push back across several rounds before the fix landed. **Rule:** Before answering a reviewer's claim about the current diff/signature with "no change needed / already present," re-read the file at HEAD and quote the exact current lines — do not rely on a remembered or partial read of the working tree; asserting a symbol is present/absent from stale context burns review rounds. +### 2026-08-19: learnings since 2026-08-18T07:28:49Z +- **Context:** The telemetry model contract (PR #255/#266) hand-serializes the SQL driver telemetry envelope with serde; a reviewer noted that the reference C# ADBC driver serializes the inner `sql_driver_log` (`OssSqlDriverTelemetryLog`) subtree via protobuf `JsonFormatter`, which encodes `int64` as JSON *strings* (`"25"`), while the outer envelope (`workspace_id`, `timestamp_millis`, `upload_time`) uses plain JSON *numbers* — and JDBC emits the same latency field as a number. serde emits every `i64` as a bare number. + **Rule:** When mirroring the Databricks SQL-driver telemetry envelope, the int64 JSON encoding is not uniform — proto-subtree int64 fields follow proto3 JSON (quoted strings) while the hand-written wrapper fields stay numeric; don't blanket-stringify or blanket-number, confirm each field's representation against the backend/reference and pin it with a serialization test (field-name-only assertions miss number-vs-string divergence). +- **Context:** In the connection-telemetry runtime (PR #256/#266/#267) `sanitize_error` populated the telemetry envelope's `DriverErrorInfo.stack_trace` field with `error.sql_state` (a 5-char SQLSTATE like `42P01`); reviewers repeatedly flagged the semantic mismatch, and maintainers confirmed ADBC deliberately omits `stack_trace` for security while JDBC passes messages. + **Rule:** Don't overload a telemetry-envelope field with unrelated data to make it non-empty — a field named `stack_trace` must carry trace/diagnostic text (or be `None`), never a SQLSTATE code; match each envelope field's meaning to the reference ADBC/JDBC proto so downstream consumers aren't misled. +- **Context:** PR #259 refactored SEA statement-failure SQLSTATE extraction to read only the new top-level `status.sql_state`, dropping the prior fallback rungs (nested `status.error.sql_state` and the `"SQLSTATE: XXXXX"` message parse). Reviewers noted the added/updated wiremock `failed_body` fixtures set *both* the new top-level field *and* the message suffix, so the tests passed regardless of whether the dropped fallbacks still existed — the regression was invisible to the suite. + **Rule:** When a value can be sourced from multiple wire locations and a change narrows which locations are consulted, fixtures that populate all locations at once cannot catch a dropped-fallback regression; add a test that exercises each source in isolation (e.g. a FAILED body carrying SQLSTATE only in the legacy/nested field or only in the message text). +- **Context:** In the telemetry model PR (#255/#266), reviewers and maintainers found several `DriverConnectionParameters` fields whose Rust types were copied from the C# ADBC `.proto` port and diverged from the authoritative server-side definition (e.g. `azure_workspace_resource_id`, `azure_tenant_id`, `jwt_key_file`, `jwt_algorithm` typed `Option` vs proto `bool`; `allowed_volume_ingestion_paths` `Option` vs proto `int64`). A maintainer directed using the server-side `universe` proto as source of truth. + **Rule:** When porting telemetry/protocol model structs, treat the server-side `universe` proto as the source of truth (not a sibling driver's C#/JDBC port) and verify every field's type against it — downstream driver ports can and do carry type drift. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 39352ae7d3e3a7258b06e2a6f57a381eb0e98b80 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 07:32:10 +0000 Subject: [PATCH 04/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index f6e2085a..588a10e3 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -44,6 +44,26 @@ author, follow-up, and review runs. - **Context:** In the telemetry model PR (#255/#266), reviewers and maintainers found several `DriverConnectionParameters` fields whose Rust types were copied from the C# ADBC `.proto` port and diverged from the authoritative server-side definition (e.g. `azure_workspace_resource_id`, `azure_tenant_id`, `jwt_key_file`, `jwt_algorithm` typed `Option` vs proto `bool`; `allowed_volume_ingestion_paths` `Option` vs proto `int64`). A maintainer directed using the server-side `universe` proto as source of truth. **Rule:** When porting telemetry/protocol model structs, treat the server-side `universe` proto as the source of truth (not a sibling driver's C#/JDBC port) and verify every field's type against it — downstream driver ports can and do carry type drift. +### 2026-08-20: learnings since 2026-08-19T07:29:09Z +- **Context:** PR #261 added a telemetry client cached per-host in a process-global manager; `TelemetryClientLease` had no `Drop` and its refcount was decremented only via an async `release()` reachable solely through `Session::close()`. Sessions dropped without `close()` leaked the `Arc` and its background timer task forever. + **Rule:** A refcounted/background resource (timer task, pooled client) whose cleanup lives in a `close()`/`release()` that consumes `self` will leak whenever a holder is merely dropped — give the guard a `Drop` impl that fires a best-effort fire-and-forget release (mirroring the session's `initiate_delete()` pattern), never rely on the explicit-close path alone. +- **Context:** PR #261's telemetry exporter called `reqwest::Client::new()` on every batch export just to build a `Request`, then dispatched through the shared `DatabricksHttpClient`; the throwaway client's pool/TLS were never used, and `reqwest::Client::new()` panics if the TLS backend/resolver fails to initialize. + **Rule:** Never construct `reqwest::Client::new()` per request — it allocates a fresh connection pool + TLS state and panics on TLS-init failure (turning a recoverable I/O path into a panic); build requests from the existing shared client's builder (e.g. `http_client.inner()`) and reuse the pooled client. +- **Context:** PR #261's telemetry integration tests injected a `CapturingTelemetryExporter`, which set `bypass_cache=true` and short-circuited the real `DatabricksTelemetryExporter`, so URL construction, JSON serialization, `RequestType` retry wiring, and response handling for the new `/telemetry-ext` POST were never exercised. + **Rule:** Injecting a fake/capturing exporter or transport bypasses the real HTTP dispatch path — a protocol change (new endpoint, request-building, retry classification) needs a wiremock test driving the real exporter against a mock endpoint, asserting the POST path/body and fail-open behavior; an in-memory fake proves nothing about the wire. +- **Context:** PR #261's `TelemetryClientManager` is a process-global singleton keyed on host only; the first session to a host builds the exporter capturing *its* `Arc` (and auth token), so every later session to the same host exports telemetry through the first session's credentials, and its per-session config is silently dropped. + **Rule:** A per-host (or otherwise identity-blind) global client cache captures the first caller's credentials/config for the life of the host entry — later callers with different auth get cross-principal mis-attribution and fail-open on token expiry; key such caches on credential/identity, or document first-writer-wins explicitly, whenever the cached transport carries per-session auth. +- **Context:** In PR #249 `build_client_assertion()` (RSA/EC JWT signing) was called at the top of `get_auth_header`, which runs on every outbound request via `execute_impl`, but the signed assertion is consumed only when a token refresh actually fires — so the fresh-token fast path signed and discarded a JWT on every query. + **Rule:** `auth_header()` runs per-request on the hot path; expensive crypto (JWT/assertion signing) belongs inside the token-refresh closure (capturing `Arc` key + cheaply-cloned claim inputs) so it runs only on the empty/expired/stale-refresh paths, never once per query. +- **Context:** In PR #249 an auth path wrote a manual `if !status.is_success()` branch after `http_client.execute_without_auth(...).await?` to surface the server error body with JDBC-parity wording, but that branch was unreachable — `execute_without_auth` returns `Ok` only for 2xx and `Err(http_error(...))` for every non-2xx status, so the body-reading code and its comment were dead. + **Rule:** The HTTP client's `execute*` methods return `Ok` only on success and `Err` for non-2xx — code after a `?` cannot see a non-success response, so any manual non-success branch there is dead; to include the server response body in the error, capture it inside the client's error path, not at the call site. +- **Context:** PR #249 decrypted PKCS#8 private keys into plaintext PEM `String`s (`decrypt_pkcs8_pem`, `read_key_pem`) that were dropped normally, leaving key material in freed heap memory, even though the repo already pulls in `zeroize` specifically to wipe derived key material on drop. + **Rule:** Decrypted/parsed private-key material must be wrapped in a zeroizing container (or explicitly zeroized before drop) to match the repo's key-handling posture; re-encoding a decrypted key to an unencrypted PEM `String` and dropping it normally leaves the plaintext lingering in freed heap. +- **Context:** PR #249 deliberately pinned `jsonwebtoken` to 9.x (built-in `ring` backend) because 10.x forces an explicit crypto backend whose `rust_crypto` option pulls `rsa` (RUSTSEC-2023-0071, Marvin attack) into the runtime graph; the `deny.toml`/`osv-scanner` ignore for that advisory is global-by-ID and keeps `rsa` acceptable only while it stays dev-only. + **Rule:** Keep `rsa` (RUSTSEC-2023-0071) out of the runtime dependency graph — it is tolerated only as a dev-dependency; avoid crypto-lib upgrades (e.g. jsonwebtoken 10.x `rust_crypto` backend) that pull it into shipped code, since the advisory ignore is unconditional and would silently suppress the CI gate once `rsa` becomes a runtime dep. +- **Context:** PRs #275 and #249 both surfaced that JWT client-assertion M2M (`OAuthM2mJwt`) against an external-IdP-backed workspace (e.g. Entra ID for Azure Databricks) requires a `token_url` override because Databricks-native OIDC discovery does not advertise the `private_key_jwt` grant; the pyo3 and C bindings exposed the override but napi initially hardcoded it to `None`, and only one of the two changed auth arms got test coverage. + **Rule:** JWT/private-key M2M cannot rely on OIDC discovery (Databricks-native OIDC omits `private_key_jwt`) — a token-endpoint override must be exposed and threaded through *every* FFI binding (napi/pyo3/C), and when threading a new arg into multiple auth arms, add a test asserting it reaches the kernel config on each arm, not just one. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 2b544ec9bbe77c1820a2be1aa15625929b7e39ff Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 21 Aug 2026 07:33:32 +0000 Subject: [PATCH 05/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 588a10e3..c57c30cf 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -64,6 +64,16 @@ author, follow-up, and review runs. - **Context:** PRs #275 and #249 both surfaced that JWT client-assertion M2M (`OAuthM2mJwt`) against an external-IdP-backed workspace (e.g. Entra ID for Azure Databricks) requires a `token_url` override because Databricks-native OIDC discovery does not advertise the `private_key_jwt` grant; the pyo3 and C bindings exposed the override but napi initially hardcoded it to `None`, and only one of the two changed auth arms got test coverage. **Rule:** JWT/private-key M2M cannot rely on OIDC discovery (Databricks-native OIDC omits `private_key_jwt`) — a token-endpoint override must be exposed and threaded through *every* FFI binding (napi/pyo3/C), and when threading a new arg into multiple auth arms, add a test asserting it reaches the kernel config on each arm, not just one. +### 2026-08-21: learnings since 2026-08-20T07:29:39Z +- **Context:** PR #279 added `kernel_session_test` (C ABI) / `Session::test_connection`, a `SELECT 1` liveness probe a host wires to `SQL_ATTR_CONNECTION_DEAD`; the reviewer noted the failure tests only asserted `!= Success` / `expect_err` and never pinned the returned status. + **Rule:** When a status/error category is itself the contract a host branches on (e.g. connection-dead → `Unavailable`/`NetworkError`/`Timeout` vs auth/parse errors), assert the concrete `KernelStatusCode` / `Error` category in tests, not merely "not Success" — a test that accepts any error still passes when the mapping silently regresses to the wrong category. +- **Context:** PR #269 exposed `Statement.set_row_limit`; the reviewer flagged that JDBC treats `maxRows == 0` as *unlimited* and omits the wire field when `<= 0`, while the kernel forwards `row_limit` verbatim into the SEA request (an explicit `row_limit: 0`). + **Rule:** Numeric cap/limit parameters diverge from the JDBC connector's sentinel convention — JDBC uses `0`/negative to mean "no limit" and omits the field on the wire, whereas the kernel passes the value through unvalidated. When adding such a knob, document the `0`/negative boundary semantics and test them against a live warehouse rather than assuming JDBC-equivalent behavior. +- **Context:** PR #263 (`azure-sp-m2m`) mints the Azure management token that backs the `X-Databricks-Azure-SP-Management-Token` header; the design pins it to the Entra **v1.0** `resource=` grant so the `aud` is `https://management.core.windows.net/` verbatim (trailing slash included), because the v2.0 `.default` form drops the slash and the control plane rejects it. + **Rule:** For the Azure management-token add-on, use the Entra v1.0 `resource=` grant (not the v2.0 `{resource}/.default` scope) so the audience keeps its exact trailing slash; and gate the management-token fetch + both `X-Databricks-Azure-*` headers on `azure_workspace_resource_id` being set (JDBC parity, `if (resourceId != null)`) so a plain workspace-member SP is never forced through an ARM exchange it cannot complete. +- **Context:** PR #263 round-trips the foreign Entra-issued token through the workspace `/oidc/v1/token` federation exchange with a "non-breaking fallback"; the reviewer noted the fallback keys off *failure* and asked for a wiremock matrix covering non-clean failure modes. + **Rule:** A fallback that only triggers on a clean error will silently ship a broken result on a 200-with-unusable-token, a hang/timeout, or a partial response — when a novel/unproven exchange sits on the request hot path, test every failure mode explicitly (not just a 4xx) and back it with an `#[ignore]`d live E2E, since a mock cannot prove the real endpoint accepts the assertion. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From cb9625fec873c498afcc645dc692ef9a54539913 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Sat, 22 Aug 2026 07:29:50 +0000 Subject: [PATCH 06/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index c57c30cf..7f393d9b 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -74,6 +74,16 @@ author, follow-up, and review runs. - **Context:** PR #263 round-trips the foreign Entra-issued token through the workspace `/oidc/v1/token` federation exchange with a "non-breaking fallback"; the reviewer noted the fallback keys off *failure* and asked for a wiremock matrix covering non-clean failure modes. **Rule:** A fallback that only triggers on a clean error will silently ship a broken result on a 200-with-unusable-token, a hang/timeout, or a partial response — when a novel/unproven exchange sits on the request hot path, test every failure mode explicitly (not just a 4xx) and back it with an `#[ignore]`d live E2E, since a mock cannot prove the real endpoint accepts the assertion. +### 2026-08-22: learnings since 2026-08-21T07:31:26Z +- **Context:** PR #277 fixed a Windows ODBC DriverManager teardown crash in the C ABI (#276). The C ABI owns a process-wide tokio runtime and previously drove every entry point via `Runtime::block_on` on the foreign caller thread. + **Rule:** In a C ABI that owns its own tokio runtime, drive futures by `spawn`ing onto the runtime's own worker threads and blocking on a plain std channel for the result — never `Runtime::block_on` on the foreign caller thread. `block_on` registers tokio's runtime-context TLS on a thread the kernel doesn't own (ODBC/Go caller threads); when that thread is torn down on Windows/MSVC the guard drops out of order and trips the "EnterGuard dropped out of order" panic / "allocator may not use TLS with destructors" abort. +- **Context:** PR #277 — converting C-ABI metadata entry points so their futures are `spawn`ed onto runtime worker threads (which requires the future and its output to be `Send`). + **Rule:** When an FFI async future is moved onto runtime worker threads, marshal raw C-string pointers (which are `!Send`) into owned Rust values (`opt_ident`/`opt_str`/etc.) synchronously on the caller thread BEFORE the `async move` block, and capture only those owned values — otherwise the future captures the `!Send` raw pointers and won't compile / would smuggle non-thread-safe pointers across threads. +- **Context:** PR #277 — a statically-linked kernel running detached tokio worker threads inside an ODBC driver DLL that the DriverManager loads and unloads across connections. + **Rule:** When a static-linked kernel spawns detached runtime worker threads that outlive a single connection inside a host-loaded DLL, pin the containing module (`GetModuleHandleExW` with `FROM_ADDRESS | PIN`, passing the address of a function in the kernel's own code) so the host's `FreeLibrary` cannot unmap code out from under live threads. Since the pin is load-bearing, check its return value and log on failure rather than discarding it — a silent pin failure reintroduces the exact crash with no diagnostic trail. +- **Context:** PR #262 wired telemetry/driver-system config through the napi binding; reviewers repeatedly flagged the ms-duration/size knobs as `Option` versus the PyO3 (`u64`/`usize`) and C-ABI (`u64`) surfaces. + **Rule:** In napi-rs bindings, type millisecond-duration and size knobs as `u32` (napi-rs serializes `u32` as a plain JS `number`) rather than `u64`/`usize`, which surface to JS callers as `BigInt` — a worse ergonomic. This intentionally diverges from the PyO3/C-ABI `u64` surfaces (Python ints are unbounded, FFI wants fixed width); document the divergence and the resulting ~49.7-day ceiling inline, since the value is widened via `u64::from(v)` before use and the cap is irrelevant for real intervals. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 4a84798ba43867bf5b97fe5a04016a5aa625a681 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Sun, 23 Aug 2026 07:30:03 +0000 Subject: [PATCH 07/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 7f393d9b..ce090767 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -84,6 +84,18 @@ author, follow-up, and review runs. - **Context:** PR #262 wired telemetry/driver-system config through the napi binding; reviewers repeatedly flagged the ms-duration/size knobs as `Option` versus the PyO3 (`u64`/`usize`) and C-ABI (`u64`) surfaces. **Rule:** In napi-rs bindings, type millisecond-duration and size knobs as `u32` (napi-rs serializes `u32` as a plain JS `number`) rather than `u64`/`usize`, which surface to JS callers as `BigInt` — a worse ergonomic. This intentionally diverges from the PyO3/C-ABI `u64` surfaces (Python ints are unbounded, FFI wants fixed width); document the divergence and the resulting ~49.7-day ceiling inline, since the value is widened via `u64::from(v)` before use and the cap is irrelevant for real intervals. +### 2026-08-23: learnings since 2026-08-22T07:27:43Z +- **Context:** PR #272 added statement-execution telemetry to the SEA transport; a reviewer caught that `telemetry_is_compressed` reported `true` for any non-empty `result_compression` codec, while the decode path (`CompressionCodec::from_manifest`) treats only `"LZ4_FRAME"` as compressed and maps everything else to `None`. + **Rule:** Derive telemetry/observability flags from the SAME parser the real code path uses (e.g. `CompressionCodec::from_manifest`) rather than re-deriving them with an ad-hoc check — independent classification logic silently drifts from decode behavior and misreports. +- **Context:** PR #272's async statement telemetry uses a one-shot idempotent `finalize()` (latched on an `AtomicBool` swap). Reviewers found it was called on RESUMABLE conditions — the internal poll-timeout in `await_result()` and a premature `fetch_result()` returning `InvalidState` ("not terminal yet") — so the first (recoverable) call latches a failure event and the later real terminal outcome becomes a no-op. + **Rule:** Never fire one-shot/idempotent terminal telemetry (or any latched finalize) on a resumable or non-terminal error; defer finalization to the genuine terminal outcome, and make sure the deferred branch's cancel/cleanup behavior agrees with the recorded state (a branch that fire-and-forget cancels the statement must record the failure, not defer to a later success). +- **Context:** PR #272's sync `execute()` always finalizes exactly one telemetry event, but the async `ExecutedAsyncStatement` only finalized via terminal consumption (`await_result`/`fetch_result`/failed `status()`); submit-then-drop and status-only-then-drop handles emitted no `EXECUTE_STATEMENT_ASYNC` event even though the server-side statement was created and closed on Drop. + **Rule:** To guarantee "one terminal event per operation," finalize telemetry in the `Drop` impl of fire-and-forget/async handles (relying on the idempotent finalize guard to avoid double-emit) — terminal-consumption-only instrumentation silently drops abandoned and status-only lifecycles. +- **Context:** PR #272 shipped telemetry fields that no code path ever populates: `retry_count` initialized to `Some(0)` (retries live in the HTTP transport, unwired to the observer), and sync-path `n_operation_status_calls`/`operation_status_latency_millis` emitted as `Some(0)` because `record_poll` only fires on the async path. Reviewers noted consumers can't distinguish a measured 0 from an unmeasured placeholder. + **Rule:** Emit `None`/omit telemetry fields that aren't yet wired to a real observed value rather than a constant `Some(0)`/`false` placeholder — a hard zero reads downstream as measured ("no retries", "no polls") and corrupts metrics. +- **Context:** In PR #272 the async `operation_latency_ms` stamps `started_at` at `submit()` and reads `elapsed()` at `finalize()`; for submit-and-drop / status-only handles `finalize` runs from `Drop`, so the metric measures how long the application held the handle alive, not server execution time. + **Rule:** Anchor duration/latency telemetry to the terminal observation point (final poll/response), not to `Drop`-time finalization — Drop can be arbitrarily delayed by the caller and turns an execution-latency metric into a handle-lifetime metric. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 2b609663857e374044efc4847f28db88ab989954 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Mon, 24 Aug 2026 07:41:48 +0000 Subject: [PATCH 08/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index ce090767..d2246295 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -96,6 +96,12 @@ author, follow-up, and review runs. - **Context:** In PR #272 the async `operation_latency_ms` stamps `started_at` at `submit()` and reads `elapsed()` at `finalize()`; for submit-and-drop / status-only handles `finalize` runs from `Drop`, so the metric measures how long the application held the handle alive, not server execution time. **Rule:** Anchor duration/latency telemetry to the terminal observation point (final poll/response), not to `Drop`-time finalization — Drop can be arbitrarily delayed by the caller and turns an execution-latency metric into a handle-lifetime metric. +### 2026-08-24: learnings since 2026-08-23T07:28:02Z +- **Context:** PR #278 added a `CallbackLogLayer` tracing layer whose `on_event` only calls `event.record(&mut visitor)` and ignores the `Context`, so fields attached to enclosing spans (e.g. query/statement IDs from `info_span!`) are dropped — while the existing `fmt::layer()` file/stderr path DOES surface span context, making the two sinks silently diverge. + **Rule:** A custom `tracing` Layer that records only event fields delivers strictly less context than `fmt::layer()`; walk `ctx.event_scope()` to include enclosing-span fields (or explicitly document the sink forwards only "event fields", never "structured fields") so consumers relying on span-scoped IDs aren't misled. +- **Context:** PR #278's `kernel_init_logging_callback` documents "Success means this exact callback is the installed sink," but the `OFF` level short-circuits and returns `Success` without installing any sink or consuming the once-only init slot — contradicting the stated invariant, which the file/stderr sibling had guarded with an explicit "(or skipped for level OFF)" clause. + **Rule:** For process-wide first-call-wins init C-ABI functions where a `Success` code can mean either "installed against your request" OR "intentionally skipped/no-op" (e.g. level OFF), the return-value contract MUST spell out the skip case in every entry point, or a host believes a sink is live when nothing was installed. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 6b2fd394c43cddeecc0f042377231862c4490ca9 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 25 Aug 2026 07:34:15 +0000 Subject: [PATCH 09/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index d2246295..e3e1d487 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -102,6 +102,12 @@ author, follow-up, and review runs. - **Context:** PR #278's `kernel_init_logging_callback` documents "Success means this exact callback is the installed sink," but the `OFF` level short-circuits and returns `Success` without installing any sink or consuming the once-only init slot — contradicting the stated invariant, which the file/stderr sibling had guarded with an explicit "(or skipped for level OFF)" clause. **Rule:** For process-wide first-call-wins init C-ABI functions where a `Success` code can mean either "installed against your request" OR "intentionally skipped/no-op" (e.g. level OFF), the return-value contract MUST spell out the skip case in every entry point, or a host believes a sink is live when nothing was installed. +### 2026-08-25: learnings since 2026-08-24T07:40:03Z +- **Context:** PR #289 added `kernel_session_config_set_tls_client_certificate()` to the C ABI, taking the mTLS client cert and private key through a single setter (both required, both copied before return, either null/empty → InvalidArgument) rather than two independent setters. + **Rule:** For C-ABI config values that are only valid together (cert+key, id+secret, endpoint+scope pairs), expose them through one atomic setter so a partially-configured state is unrepresentable at the FFI boundary; validate all parts non-null/non-empty before mutating the config. +- **Context:** PR #289 verified the full C-ABI mTLS path without a live workspace or committed credentials: a hermetic E2E test generates a CA + server + client identities at runtime (rcgen/rustls), and a unit test passes PEM with valid framing but invalid contents so client construction fails at the parser — proving both values traversed C ABI setter → TlsConfig → reqwest without any network I/O. + **Rule:** Test TLS/credential-forwarding paths hermetically — generate CA/identities at runtime instead of committing keys, and prove config reached the client by feeding framing-valid/content-invalid PEM so the failure lands in the parser (before network I/O), asserting on that specific error rather than requiring a live endpoint. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 3728e4beaf63c8db91c42754a44a65dfcc31d1f7 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 26 Aug 2026 07:35:29 +0000 Subject: [PATCH 10/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index e3e1d487..be3b3fca 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -108,6 +108,20 @@ author, follow-up, and review runs. - **Context:** PR #289 verified the full C-ABI mTLS path without a live workspace or committed credentials: a hermetic E2E test generates a CA + server + client identities at runtime (rcgen/rustls), and a unit test passes PEM with valid framing but invalid contents so client construction fails at the parser — proving both values traversed C ABI setter → TlsConfig → reqwest without any network I/O. **Rule:** Test TLS/credential-forwarding paths hermetically — generate CA/identities at runtime instead of committing keys, and prove config reached the client by feeding framing-valid/content-invalid PEM so the failure lands in the parser (before network I/O), asserting on that specific error rather than requiring a live endpoint. +### 2026-08-26: learnings since 2026-08-25T07:31:52Z +- **Context:** PR #291 aligned `Metadata::type_info()` with the Thrift `getTypeInfo` corpus. A review bot repeatedly flagged `CHAR`/`VARCHAR` `CASE_SENSITIVE=false` as inconsistent with `STRING=true` (vanilla HiveServer2 `Type.isCaseSensitive()` marks all three case-sensitive), and the engineer-bot "fixed" them to `true` several times — the maintainer reverted each time, confirming Databricks Thrift actually returns `STRING=true`, `CHAR=false`, `VARCHAR=false`. + **Rule:** Databricks Thrift metadata (e.g. `getTypeInfo` CASE_SENSITIVE) diverges from vanilla HiveServer2 semantics; never "correct" a synthesized metadata cell to match reference/vanilla behavior without confirming against a real Databricks server response — an apparent internal inconsistency may be the correct, intended divergence. +- **Context:** PR #291's `type_info` tests asserted the synthesized `getTypeInfo` output against literals hand-derived from the same `SparkGetTypeInfoUtil`-style synthesis logic; reviewers noted a wrong-but-consistent cell would still pass, and the parity claim couldn't be enforced offline without live-warehouse credentials. + **Rule:** A test that checks synthesized results against values re-derived from the same code proves self-consistency, not parity with the real server — enforce a "matches " claim with a golden fixture captured from a live server, and name the test/doc for what it actually locks (self-consistency) so the claim isn't overstated. +- **Context:** PR #288 matched on the float literal `0.0` (`Some(0.0) => ...`) in the pyo3 bindings when treating zero as "keep default". + **Rule:** Matching on a floating-point literal triggers rustc's `illegal_floating_point_literal_pattern` future-incompat lint, which is promoted to a hard error under the repo's `-D warnings` gate; compare with `==` in a match guard or `if` instead of using a float literal pattern. +- **Context:** PR #288's clippy failure lived in the `pyo3/` crate, which declares its own `[workspace]`, so the repo's root `cargo clippy --all-targets` never covered it and the error could slip through the gate. + **Rule:** Standalone-workspace subcrates (e.g. `pyo3/`) are NOT covered by the root `cargo clippy`/`cargo test` invocation — run clippy and tests from within each standalone-workspace directory explicitly, or lint/test failures there pass CI silently. +- **Context:** PR #288 exposed `request_timeout` to Python/C; the binding docs (echoing the pre-existing `src/config.rs` field doc) claimed it caps one request "from connect through response-body completion," but it is applied as reqwest's `read_timeout` (src/session.rs), with a separate 30s `connect_timeout`. + **Rule:** The kernel's `HttpConfig::request_timeout` is a reqwest `read_timeout` — it bounds the gap between successive reads and resets on each read; it does NOT cap connection establishment nor total body-download time. Document and reason about it as a read-idle timeout, not a total request deadline. +- **Context:** PR #283 (U2M OAuth token-cache control); a reviewer flagged that caller-supplied token stores keyed on `host` alone would diverge from the built-in `DiskTokenCache`, whose cache filename is a SHA-256 of `{host, client_id, scopes}`. + **Rule:** OAuth token persistence must be keyed on the full `{host, client_id, scopes}` triple — keying on `host` alone collides U2M sessions that share a host but differ in `client_id`/`scopes`, letting a `save` overwrite another session's token and a `load` return a token minted for a different client/scope set. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 98cb4598e44fcc1dcb8981a2ee49cfbdc2d2c900 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 27 Aug 2026 10:35:02 +0000 Subject: [PATCH 11/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index be3b3fca..cc9be3b8 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -122,6 +122,10 @@ author, follow-up, and review runs. - **Context:** PR #283 (U2M OAuth token-cache control); a reviewer flagged that caller-supplied token stores keyed on `host` alone would diverge from the built-in `DiskTokenCache`, whose cache filename is a SHA-256 of `{host, client_id, scopes}`. **Rule:** OAuth token persistence must be keyed on the full `{host, client_id, scopes}` triple — keying on `host` alone collides U2M sessions that share a host but differ in `client_id`/`scopes`, letting a `save` overwrite another session's token and a `load` return a token minted for a different client/scope set. +### 2026-08-27: learnings since 2026-08-26T07:33:08Z +- **Context:** PR #298 added `ExecuteOptions.rawParams` (napi) → `StatementSpec::param_raw` so callers can preserve pre-marshalled SEA type names like `INTERVAL MONTH` / `INTERVAL DAY`; routing them through `TypedValue::Interval` collapses the qualifier and loses the exact SQL type. + **Rule:** `TypedValue` marshalling is lossy for qualified SQL types (e.g. interval qualifiers like `INTERVAL MONTH` vs `INTERVAL DAY` collapse to a single `Interval`) — when a caller must preserve the verbatim SEA `sql_type`, bind through the raw param path (`param_raw`), not the typed enum. Raw params cannot be mixed with typed params or combine named+positional markers; that mix must surface `InvalidArgument` before dispatch. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From f12b865dda223e2fdc5c7e27d115607806fa606d Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 28 Aug 2026 10:57:57 +0000 Subject: [PATCH 12/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index cc9be3b8..eb5b49ef 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -126,6 +126,28 @@ author, follow-up, and review runs. - **Context:** PR #298 added `ExecuteOptions.rawParams` (napi) → `StatementSpec::param_raw` so callers can preserve pre-marshalled SEA type names like `INTERVAL MONTH` / `INTERVAL DAY`; routing them through `TypedValue::Interval` collapses the qualifier and loses the exact SQL type. **Rule:** `TypedValue` marshalling is lossy for qualified SQL types (e.g. interval qualifiers like `INTERVAL MONTH` vs `INTERVAL DAY` collapse to a single `Interval`) — when a caller must preserve the verbatim SEA `sql_type`, bind through the raw param path (`param_raw`), not the typed enum. Raw params cannot be mixed with typed params or combine named+positional markers; that mix must surface `InvalidArgument` before dispatch. +### 2026-08-28: learnings since 2026-08-27T10:33:31Z +- **Context:** PR #303 removed the `session_conf` allowlist so caller keys forward verbatim; review flagged that a caller-set `can_cloud_download` now reaches the wire. + **Rule:** SEA accepts a `can_cloud_download` session conf at CreateSession but rejects it at the *first* ExecuteStatement with `CONFIG_NOT_AVAILABLE`, poisoning every subsequent statement on the session — disable CloudFetch per-statement via the SEA `disposition` field (matching JDBC/Thrift), never via a session conf. +- **Context:** PR #303 dropped the case-sensitive `spark.*` conf handling when removing the allowlist. + **Rule:** Dotted `spark.*` Spark conf keys are case-sensitive and must be sent verbatim (lowercase-dotted) — unlike SET-style SQL params (e.g. `ANSI_MODE`) which the server echoes uppercase; uppercasing a Spark key addresses the wrong `SQLConf` entry and is silently ignored server-side. +- **Context:** PR #301 mapped an empty catalog filter to `(None catalog, empty LIKE pattern)` for `list_schemas`/`list_columns` to mean "match nothing." + **Rule:** In metadata_v0, `catalog = None` means "ALL CATALOGS" (the opposite of match-nothing), so an empty-catalog request only stays empty because the empty-pattern short-circuit fires first — keep that ordering dependency explicit or an empty catalog silently broadens to every catalog. Empty schema/table/column LIKE patterns also short-circuit to an empty result with no wire call. +- **Context:** PR #293 narrowed retryable-vs-permanent DNS detection by string-matching reqwest's error source chain (reqwest exposes no typed DNS variant). + **Rule:** Classifying DNS failures by lowercased message substrings is platform-fragile — glibc, macOS, Windows, and musl/Alpine (`EAI_NONAME`) each phrase NXDOMAIN differently; a permanent-failure marker set that omits musl phrasings will retry a non-existent host until the whole retry budget is burned. Cover every target libc's phrasing. +- **Context:** PR #293's transport-retry tests spawn a mock server task that calls `accept()` a fixed N times, then end with `server.await`. + **Rule:** A mock-server test that accepts a fixed number of connections then awaits the server task will *hang* (surfacing only via CI global timeout, with no useful message) if a regression makes the request non-retryable and fewer connections arrive — assert the observed accept count before awaiting the handle, or wrap the client call / `server.await` in a `tokio::time::timeout` so a missing retry fails fast. +- **Context:** PR #287 added a per-session telemetry circuit-breaker whose `CircuitBreakerManager` is a process-global `OnceLock>>` populated with `or_insert_with`. + **Rule:** A process-global cache keyed only by host and filled with `or_insert_with` makes the first session's config win permanently — later sessions' per-session knobs are silently dropped and breaker open/closed state leaks across sessions and across tests sharing a mock host. Key on `(host, config)` (or document first-writer-wins), and give tests unique hosts to avoid shared-state coupling. +- **Context:** PR #287's `valid_config` rejected a zero `circuit_breaker_timeout` unconditionally, while the threshold check was gated on `circuit_breaker_enabled`. + **Rule:** Gate validation of a sub-feature's tuning knob on that sub-feature's enable flag — an ungated check (rejecting a zero timeout even when the breaker is disabled) lets a benign unused value disable the whole parent feature (all telemetry), a footgun that only bites direct-Rust callers since binding validators reject the value up front. +- **Context:** PR #287 moved the pyo3 crate's `extension-module` feature out of the default set so `cargo test` links correctly. + **Rule:** Keep PyO3's `extension-module` feature OFF for plain `cargo test`: it intentionally suppresses libpython linking for extension modules on Unix, which breaks the Rust test binary (undefined Python symbols). Enable it only for maturin wheel builds (via `pyproject.toml`), where the loading interpreter provides the symbols. +- **Context:** PR #274 deferred the success telemetry event until the result stream is exhausted/dropped, but async paths still called `finalize(None)` eagerly on success; review found metrics dropped and errors mis-reported as success. + **Rule:** When statement finalization is guarded by a one-shot `finalized: AtomicBool` shared across cloned handles, the first finalize wins and all later ones are silent no-ops — so an eager success-finalize on any path defeats a deferred finalize (dropping stream/CloudFetch metrics), and a post-attach fetch error unwound through `Drop` gets exported as success with `error = None`. Ensure exactly one finalize site owns the terminal event and that error paths finalize before the stream is dropped. +- **Context:** PR #274 records CloudFetch `initial_chunk_latency` from concurrently-downloaded chunks. + **Rule:** Under concurrent chunk downloads a first-to-complete gate (e.g. `compare_exchange(-1, …)`) records the fastest/smallest chunk's latency, not chunk 0 — gate `initial_chunk_latency` strictly on `chunk_index == 0` to match the JDBC/C# `initialChunkLatency` semantic. Also keep an explicit completed-download counter so a stream dropped before any download finishes reports `None`, not a misleading `Some(0)` (both `slowest`/`sum` atomics init to 0). + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From c491a93129de6944520cc786500a459b40e7e7fa Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Sat, 29 Aug 2026 07:27:18 +0000 Subject: [PATCH 13/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index eb5b49ef..9a9d9304 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -148,6 +148,14 @@ author, follow-up, and review runs. - **Context:** PR #274 records CloudFetch `initial_chunk_latency` from concurrently-downloaded chunks. **Rule:** Under concurrent chunk downloads a first-to-complete gate (e.g. `compare_exchange(-1, …)`) records the fastest/smallest chunk's latency, not chunk 0 — gate `initial_chunk_latency` strictly on `chunk_index == 0` to match the JDBC/C# `initialChunkLatency` semantic. Also keep an explicit completed-download counter so a stream dropped before any download finishes reports `None`, not a misleading `Some(0)` (both `slowest`/`sum` atomics init to 0). +### 2026-08-29: learnings since 2026-08-28T10:54:51Z +- **Context:** PR #299 and PR #306 added telemetry-finalizing `close(&mut self)` inherent methods on `ExecutedStatement`/`ExecutedAsyncStatement` alongside the existing `ExecutedStatementHandle::close(&self)` trait method; the reviewer showed that with the trait in scope (or via `Box`), `exec.close()` silently resolves to the non-finalizing `&self` trait method, reintroducing the telemetry gap — the napi/pyo3 sites only worked because they used UFCS (`Type::close(&mut …)`). + **Rule:** Never rely on an inherent `&mut self` method to shadow a same-named `&self` trait method — Rust method resolution tries the `&self` receiver first and trait-object callers can only reach the trait method; give the two methods distinct names or route all callers through UFCS, and doc-note the divergence. +- **Context:** PR #297 fixed telemetry batch/timer flushes that used ambient `tokio::spawn`, which panics or drops the task when `enqueue` is called from a plain (non-runtime) thread — reachable because the pyo3/napi bindings may invoke the kernel off the runtime. + **Rule:** Capture a `tokio::runtime::Handle` at construction (`Handle::current()`) and spawn background work via that stored handle, never bare `tokio::spawn`, in any kernel code reachable from FFI/binding threads that may not be on a runtime. +- **Context:** PRs #299 and #300 established the close-failure fallback contract for statement and session close: on a wire failure the `closed` flag is deliberately left unset so `Drop`'s fire-and-forget retry runs as a backstop, relying on the server-side close/delete being idempotent. + **Rule:** On an explicit close/delete RPC failure, keep the `closed` flag unset so Drop's fire-and-forget cleanup retries — only set it on success; this depends on the server operation being idempotent, so a redundant duplicate close is harmless while a leaked server resource is not. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From fb33d18944c1f1e6368574e1d11e3d710554b948 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 3 Sep 2026 07:30:45 +0000 Subject: [PATCH 14/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 9a9d9304..1abdb1d1 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -156,6 +156,12 @@ author, follow-up, and review runs. - **Context:** PRs #299 and #300 established the close-failure fallback contract for statement and session close: on a wire failure the `closed` flag is deliberately left unset so `Drop`'s fire-and-forget retry runs as a backstop, relying on the server-side close/delete being idempotent. **Rule:** On an explicit close/delete RPC failure, keep the `closed` flag unset so Drop's fire-and-forget cleanup retries — only set it on success; this depends on the server operation being idempotent, so a redundant duplicate close is harmless while a leaked server resource is not. +### 2026-09-03: learnings since 2026-09-02T07:30:13Z +- **Context:** PR #310 added a per-call deadline to `kernel_session_test`; a reviewer caught the deadline-elapsed error being built with `Error::new(ErrorCode::Timeout, …)` instead of the categorised `Error::timeout()` constructor. `Error::new` defaults `retryable = false`, whereas every other kernel `Timeout` (`Error::timeout()`, `Error::from_http_status(504)`) is `retryable = true`, so retry wrappers that branch on `Error::retryable` would treat it inconsistently. + **Rule:** Build typed errors via the categorised constructors (`Error::timeout()`, etc.), not `Error::new(ErrorCode::…, …)` — the constructors set the correct `retryable` flag; if you deliberately deviate (e.g. a caller-set deadline like `ConnectionTestTimeout` that must NOT auto-retry), make it explicit with `.with_retryable(false)` plus a comment explaining why. +- **Context:** PR #309 changed the HTTP client base `User-Agent` from `DatabricksJDBCDriverOSS/…` to `DatabricksSQLKernel/…`. The UA prefix is not just attribution: the SEA gateway does a `startsWith` prefix match against the `databricks.sqlexecapi.known_driver_prefixes` SAFE flag to enable the `INLINE_OR_EXTERNAL_LINKS` disposition; a prefix not on that allow-list is rejected with HTTP 400 ("not a supported disposition") or redirected to Thrift. + **Rule:** The outbound `User-Agent` prefix is functionally load-bearing — the SEA server gates response disposition on it via a prefix allow-list, so any change to the base UA (or a caller-supplied UA that replaces it) must use a prefix registered in `known_driver_prefixes`, or requests silently lose parallel chunk downloads / fall back to Thrift. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 09fbb5a73ba371354dcc558e4ee161a834e353c3 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 4 Sep 2026 07:30:14 +0000 Subject: [PATCH 15/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 1abdb1d1..90cd4799 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -162,6 +162,14 @@ author, follow-up, and review runs. - **Context:** PR #309 changed the HTTP client base `User-Agent` from `DatabricksJDBCDriverOSS/…` to `DatabricksSQLKernel/…`. The UA prefix is not just attribution: the SEA gateway does a `startsWith` prefix match against the `databricks.sqlexecapi.known_driver_prefixes` SAFE flag to enable the `INLINE_OR_EXTERNAL_LINKS` disposition; a prefix not on that allow-list is rejected with HTTP 400 ("not a supported disposition") or redirected to Thrift. **Rule:** The outbound `User-Agent` prefix is functionally load-bearing — the SEA server gates response disposition on it via a prefix allow-list, so any change to the base UA (or a caller-supplied UA that replaces it) must use a prefix registered in `known_driver_prefixes`, or requests silently lose parallel chunk downloads / fall back to Thrift. +### 2026-09-04: learnings since 2026-09-03T07:29:10Z +- **Context:** PR #312 added a detached result-stream canceller for the C ABI. A reviewer caught that `kernel_result_stream_canceller_new` formed a whole-struct `&ResultStreamInner` via `.as_ref()` while `next_batch` held a whole-struct `&mut` via `.as_mut()` across the fetch — documented as a blessed concurrent-access pattern, but UB. Fix projected each hot path to disjoint fields via `addr_of!`/`addr_of_mut!`. + **Rule:** In FFI handles shared across threads, never materialize a whole-struct `&mut`/`&` (`.as_mut()`/`.as_ref()`) held across an await/fetch when another thread may take ANY reference to the same allocation — `&mut` carries a noalias guarantee over the ENTIRE allocation, so "each side only touches disjoint fields" is sound at the field level but still UB at the reference level; project to the specific field via `std::ptr::addr_of!`/`addr_of_mut!` instead. +- **Context:** PR #312's headline concurrency test (`cancel_interrupts_an_in_flight_next_batch`) originally obtained the canceller BEFORE spawning the fetch thread, so the concurrent-obtain-during-in-flight-next_batch path the docs explicitly bless was never actually exercised; it was reworked to obtain the canceller AFTER the fetch thread parked inside `next_batch`. + **Rule:** A test that claims to cover a documented concurrent/racing path must sequence its operations so the second call genuinely overlaps the in-flight first one (e.g. obtain/fire the racing handle only after the worker thread has parked mid-operation) — otherwise it exercises the sequential case and the blessed race is untested; also flag which arm/shape a shared code path is actually driven by, since a mirror arm can be structurally similar yet never hit. +- **Context:** PR #312's per-stream `CancellationToken` interrupts an in-flight `next_batch` via `tokio::select!`, but it is intentionally not wired into the CloudFetch provider's own `cancel_token`; the provider awaits a spawned download's `JoinHandle`, so firing the token drops the `next_batch` future at its await point without aborting the detached download. + **Rule:** Dropping a future at an await point only bounds the CALLER'S wait — it does not abort work the future was merely awaiting on a spawned task (`JoinHandle`); a client-side cancellation signal gives a bounded caller-return, not reclamation of the in-flight request/connection, so for true bounded teardown either wire the signal into the underlying provider's cancel token or close the resource to release it on its own completion, and document the distinction. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 5c26882978379baed87dd805c24bc54be47b4489 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Sat, 5 Sep 2026 07:26:27 +0000 Subject: [PATCH 16/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 90cd4799..c1eed887 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -170,6 +170,12 @@ author, follow-up, and review runs. - **Context:** PR #312's per-stream `CancellationToken` interrupts an in-flight `next_batch` via `tokio::select!`, but it is intentionally not wired into the CloudFetch provider's own `cancel_token`; the provider awaits a spawned download's `JoinHandle`, so firing the token drops the `next_batch` future at its await point without aborting the detached download. **Rule:** Dropping a future at an await point only bounds the CALLER'S wait — it does not abort work the future was merely awaiting on a spawned task (`JoinHandle`); a client-side cancellation signal gives a bounded caller-return, not reclamation of the in-flight request/connection, so for true bounded teardown either wire the signal into the underlying provider's cancel token or close the resource to release it on its own completion, and document the distinction. +### 2026-09-05: learnings since 2026-09-04T07:28:17Z +- **Context:** PR #314 added the C ABI `kernel_statement_set_query_tags`; a reviewer noted that `statement_conf` (which holds `query_tags`) survives `StatementSpec::sql()`/`kernel_statement_set_sql` — unlike bound parameters, which reset — so a reused statement handle silently carries a prior query's tags/conf into later executions. The fix made an empty string mean "clear" so a reused handle can be reset. + **Rule:** Statement-level conf (e.g. `query_tags` in `statement_conf`) persists across `set_sql` even though bound parameters are reset; any single-entry-point setter on a reusable handle must offer an explicit clear path (empty = clear) or state-leak across executions is inevitable. +- **Context:** In PR #314 a reviewer caught that the public FFI fn's Rustdoc linked to `crate::statement::spec::serialize_query_tags`, a private (non-`pub`) item — a public→private intra-doc link trips rustdoc's warn-by-default `private_intra_doc_links` lint, which surfaces only during `cargo doc`, not the `cargo fmt`/`clippy`/`test` CI gates. + **Rule:** Intra-doc links from a public item to a private item fail under `cargo doc`/`RUSTDOCFLAGS=-D warnings` but pass fmt/clippy/test; in Rustdoc on `pub` items link only to public anchors or use plain code font for private names. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 6815b5f3fb692d38c99df631aa54fea4d9d708c4 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Sun, 6 Sep 2026 07:27:00 +0000 Subject: [PATCH 17/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index c1eed887..c1de35d7 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -176,6 +176,16 @@ author, follow-up, and review runs. - **Context:** In PR #314 a reviewer caught that the public FFI fn's Rustdoc linked to `crate::statement::spec::serialize_query_tags`, a private (non-`pub`) item — a public→private intra-doc link trips rustdoc's warn-by-default `private_intra_doc_links` lint, which surfaces only during `cargo doc`, not the `cargo fmt`/`clippy`/`test` CI gates. **Rule:** Intra-doc links from a public item to a private item fail under `cargo doc`/`RUSTDOCFLAGS=-D warnings` but pass fmt/clippy/test; in Rustdoc on `pub` items link only to public anchors or use plain code font for private names. +### 2026-09-06: learnings since 2026-09-05T07:24:56Z +- **Context:** PR #322 fixed a CloudFetch consumer that looped forever when an initial or incremental link fetch failed. A link fetch fails *before* any `ChunkEntry` exists for the requested chunk and leaves `end_of_stream` unset, so a waiter blocked in `wait_for_chunk` has nothing in `chunks` to observe and no terminal signal. + **Rule:** When a failure can occur *before* the per-item entry a waiter keys off exists, record it in a provider-level terminal-error slot (first-writer-wins to preserve original SQLSTATE/source) and wake all waiters — a per-entry error path alone leaves waiters for the not-yet-created entry looping forever. +- **Context:** In PR #322 a reviewer caught that the provider-level `terminal_error()` check in `wait_for_chunk` was placed *before* the ready-chunk check. Because the download frontier runs ahead of the consumer by up to `max_chunks_in_memory`, chunks between the consumer position and the failed page are often already downloaded; checking terminal-error first discarded that valid buffered data. + **Rule:** Check requested-item readiness BEFORE surfacing a stream-level terminal error, so already-downloaded in-order items are still delivered; the terminal error should only fire once the consumer reaches the item that actually failed — mirror the per-item failure path's ordering. +- **Context:** PR #322's `set_terminal_error` used tokio `Notify::notify_waiters()`, which only wakes waiters already registered when it fires. The `wait_for_chunk` loop constructed its `notified()` future inline in the `select!` *after* the terminal-error/readiness checks, leaving a window where a notification could be missed and the consumer stalled until `chunk_ready_timeout` (30s default). + **Rule:** With tokio `Notify::notify_waiters()`, construct and `.enable()` the `notified()` future BEFORE the state/terminal checks at the top of the wait loop — registering it inline after the checks (in the `select!`) races the notification and can stall a waiter until the timeout fires. +- **Context:** PR #322's `incremental_link_fetch_failure_is_terminal` test claimed to cover the incremental link-fetch path but let chunk 0 fail via the unrelated per-chunk download path and only asserted `Err(_)`, so it would pass even if the new logic were broken. The fix served chunk 0's bytes from a wiremock server with a real downloader (so it succeeds) and asserted the surfaced error carried the injected message + SQLSTATE. + **Rule:** A test that only asserts `Err(_)` cannot distinguish which failure source fired; when validating a specific error path, make every *other* path succeed (e.g. serve real bytes via mock) and assert the error's identity (message/SQLSTATE), not just its presence. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 3023d8c2147828b6eb21fd7cd245e380624bab27 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Mon, 7 Sep 2026 07:39:29 +0000 Subject: [PATCH 18/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index c1de35d7..14fb0437 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -186,6 +186,20 @@ author, follow-up, and review runs. - **Context:** PR #322's `incremental_link_fetch_failure_is_terminal` test claimed to cover the incremental link-fetch path but let chunk 0 fail via the unrelated per-chunk download path and only asserted `Err(_)`, so it would pass even if the new logic were broken. The fix served chunk 0's bytes from a wiremock server with a real downloader (so it succeeds) and asserted the surfaced error carried the injected message + SQLSTATE. **Rule:** A test that only asserts `Err(_)` cannot distinguish which failure source fired; when validating a specific error path, make every *other* path succeed (e.g. serve real bytes via mock) and assert the error's identity (message/SQLSTATE), not just its presence. +### 2026-09-07: learnings since 2026-09-06T07:25:25Z +- **Context:** PR #323 bounded CloudFetch chunk downloads with an end-to-end deadline by setting reqwest's per-request `.timeout()` to the remaining budget; a reviewer noted this *overrides* rather than composes with the client-wide `request_timeout`. + **Rule:** reqwest's per-request `.timeout()` REPLACES the client-wide `.timeout()`, it does not take the min — when narrowing a per-attempt deadline always apply `min(client_request_timeout, remaining_budget)` yourself, or a larger configured budget silently loosens the static per-request safety net. +- **Context:** PR #323's HTTP retry loop rebuilds the request on each attempt; the reviewer/author found a per-request timeout set by the caller was dropped because the rebuild fell back to the client-wide `.timeout()`. + **Rule:** Any per-request setting (timeout, headers, body) must be captured before a retry loop and re-applied on every rebuilt request — reqwest request reconstruction does not carry caller-set per-request state forward across attempts. +- **Context:** In PR #323 a chunk state machine stored failures as `ChunkState::DownloadFailed(String)`, so the typed `Error`'s `ErrorCode::Timeout` was lost and the consumer path re-wrapped it as `Error::io()`; tests that asserted on the function's direct return value passed while the consumer still observed `ErrorCode::Io`. + **Rule:** Preserve the typed `Error` (not a stringified copy) through state machines and channels so `ErrorCode` classification survives to the consumer/C-ABI boundary — and assert error classification on the path a real caller observes (e.g. `wait_for_chunk`/`next_batch`), not on the internal function's direct return, which gives false confidence. +- **Context:** PR #323 claimed an "end-to-end" download deadline but a reviewer found the in-loop link-refresh RPC was a bare `.await` with no deadline cap, letting a stalled refresh overshoot the budget by its own (much larger) `request_timeout`. + **Rule:** An "end-to-end" wall-clock deadline must wrap EVERY await inside the loop (HTTP attempt, refresh RPC, and backoff sleep) via `tokio::time::timeout(remaining, …)` and cap sleeps at the remaining budget — a top-of-loop deadline check alone does not bound a call that stalls mid-iteration. +- **Context:** PR #316 fixed an aarch64 handshake failure against a private/internal CA: `tls-rustls = ["reqwest/rustls-tls"]` resolves to webpki-roots (Mozilla bundle) only, while the `tls-native` (OpenSSL) builds read the OS `/etc/ssl` trust store. + **Rule:** `reqwest/rustls-tls` trusts only bundled Mozilla webpki-roots and ignores the OS system trust store — add `reqwest/rustls-tls-native-roots` for parity with native-tls when private/internal CAs are installed only in the OS store; the two backends also diverge on OCSP and TLS 1.3 behavior. +- **Context:** PR #316 added trust-store crates via a feature change but regenerated only the root and `napi/` `Cargo.lock`, leaving `pyo3/Cargo.lock` drifted (CI hid it by running `cargo test` without `--locked`). + **Rule:** A dependency/feature change in a workspace with multiple committed lockfiles (root, `napi/`, `pyo3/`) must regenerate ALL of them — CI steps that build without `--locked` silently regenerate at build time and mask the drift. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From cc3df5e0835ce9e86271aa50e24b2265a2e52c39 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 9 Sep 2026 07:31:07 +0000 Subject: [PATCH 19/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 14fb0437..51aa3616 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -200,6 +200,12 @@ author, follow-up, and review runs. - **Context:** PR #316 added trust-store crates via a feature change but regenerated only the root and `napi/` `Cargo.lock`, leaving `pyo3/Cargo.lock` drifted (CI hid it by running `cargo test` without `--locked`). **Rule:** A dependency/feature change in a workspace with multiple committed lockfiles (root, `napi/`, `pyo3/`) must regenerate ALL of them — CI steps that build without `--locked` silently regenerate at build time and mask the drift. +### 2026-09-09: learnings since 2026-09-08T07:28:35Z +- **Context:** PR #326 gave the process-wide C-ABI Tokio runtime an explicit `thread_stack_size(2 MiB)` because, without an override, Tokio's thread builder honours the embedding process's `RUST_MIN_STACK`, letting a native consumer's env var (or `ulimit -s`) shrink kernel-owned workers below Tokio's supported default and cause stack overflows in library code. + **Rule:** When a kernel/FFI library owns its own async runtime, pin worker `thread_stack_size` explicitly — never inherit the embedding process's `RUST_MIN_STACK`/ulimit, which the host controls and can set arbitrarily small. +- **Context:** PR #326 verified the runtime's stack-size isolation by re-launching the test binary as a subprocess (`current_exe` + `--exact` + `RUST_MIN_STACK=16384`), because the setting is process-global and the C-ABI runtime is a process-wide `OnceLock` — an in-process test could neither set the ambient variable cleanly nor re-init the singleton. + **Rule:** To test behaviour that depends on process-global state (env vars like `RUST_MIN_STACK`) against a process-wide singleton (`OnceLock` runtime), spawn a child process via `current_exe` with the env set, rather than trying to mutate it in-process. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 3bd502a6f68edf1075d9472560187d3edb7ca40e Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 10 Sep 2026 07:30:36 +0000 Subject: [PATCH 20/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 51aa3616..82fb88ed 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -206,6 +206,10 @@ author, follow-up, and review runs. - **Context:** PR #326 verified the runtime's stack-size isolation by re-launching the test binary as a subprocess (`current_exe` + `--exact` + `RUST_MIN_STACK=16384`), because the setting is process-global and the C-ABI runtime is a process-wide `OnceLock` — an in-process test could neither set the ambient variable cleanly nor re-init the singleton. **Rule:** To test behaviour that depends on process-global state (env vars like `RUST_MIN_STACK`) against a process-wide singleton (`OnceLock` runtime), spawn a child process via `current_exe` with the env set, rather than trying to mutate it in-process. +### 2026-09-10: learnings since 2026-09-09T07:29:33Z +- **Context:** PR #329 fixed the C-ABI Tokio runtime in `src/c_abi/mod.rs`, which called `.thread_stack_size(CONST)` with a fixed 2 MiB value. `thread_stack_size` is an *absolute* setting that makes the underlying std thread builder ignore `RUST_MIN_STACK` entirely, so a host with a larger ambient `RUST_MIN_STACK` (e.g. the databricks-odbc partner at 3194880) had its worker stacks silently *shrunk* to 2 MiB — the opposite of the earlier #326 intent. + **Rule:** When pinning a resource limit that overrides an ambient/env-driven default (e.g. Tokio `thread_stack_size` vs `RUST_MIN_STACK`), decide explicitly whether the constant is a floor or a cap, and compute `max(ambient, floor)` rather than assigning the constant unconditionally — an absolute override both raises small values and shrinks larger ones. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 2fbbaeeaed4e3bbd4ee797c866f5f6a77999e6db Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 11 Sep 2026 07:30:22 +0000 Subject: [PATCH 21/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 82fb88ed..d7ca7864 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -210,6 +210,12 @@ author, follow-up, and review runs. - **Context:** PR #329 fixed the C-ABI Tokio runtime in `src/c_abi/mod.rs`, which called `.thread_stack_size(CONST)` with a fixed 2 MiB value. `thread_stack_size` is an *absolute* setting that makes the underlying std thread builder ignore `RUST_MIN_STACK` entirely, so a host with a larger ambient `RUST_MIN_STACK` (e.g. the databricks-odbc partner at 3194880) had its worker stacks silently *shrunk* to 2 MiB — the opposite of the earlier #326 intent. **Rule:** When pinning a resource limit that overrides an ambient/env-driven default (e.g. Tokio `thread_stack_size` vs `RUST_MIN_STACK`), decide explicitly whether the constant is a floor or a cap, and compute `max(ambient, floor)` rather than assigning the constant unconditionally — an absolute override both raises small values and shrinks larger ones. +### 2026-09-11: learnings since 2026-09-10T07:29:06Z +- **Context:** PR #333 added a PowerShell CI script (`check-release-debuginfo.ps1`) that used `$profile = "release-with-debuginfo"`; a reviewer flagged the collision with PowerShell's built-in automatic variable `$PROFILE` (variable names are case-insensitive), fixed by renaming to `$profileName`. + **Rule:** In PowerShell scripts, never reuse reserved automatic-variable names (`$profile`, `$host`, `$error`, `$input`, `$args`, `$pwd`, etc.) for locals — the shadowing works by accident until it doesn't; pick a distinct name like `$profileName`. +- **Context:** PR #333 added a required cross-platform CI workflow (`release-debuginfo.yml`) and deliberately left it ungated; the author's rationale was that a top-level `paths:` filter on a required check can leave the check stuck **pending** in the merge queue when the path filter skips it, breaking required-check gating. + **Rule:** Do not add a top-level `paths:`/`paths-ignore:` filter to a GitHub Actions workflow whose jobs are required merge checks — a skipped required check stays permanently pending; instead use an always-present change-detector job plus a no-op path when you need to bound CI cost. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 0546bedeef29bf50678df1601faf3974d17b1bff Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 17 Sep 2026 07:34:40 +0000 Subject: [PATCH 22/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index d7ca7864..b5349caf 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -216,6 +216,14 @@ author, follow-up, and review runs. - **Context:** PR #333 added a required cross-platform CI workflow (`release-debuginfo.yml`) and deliberately left it ungated; the author's rationale was that a top-level `paths:` filter on a required check can leave the check stuck **pending** in the merge queue when the path filter skips it, breaking required-check gating. **Rule:** Do not add a top-level `paths:`/`paths-ignore:` filter to a GitHub Actions workflow whose jobs are required merge checks — a skipped required check stays permanently pending; instead use an always-present change-detector job plus a no-op path when you need to bound CI cost. +### 2026-09-17: learnings since 2026-09-16T07:30:40Z +- **Context:** PR #342 rejected non-HTTPS endpoints before connecting when an mTLS client cert+key are configured, adding `validate_mtls_endpoint_scheme` in `Session::open` before auth-provider/client construction. + **Rule:** reqwest silently ignores a configured client-certificate identity on `http://` and still sends the bearer credential in cleartext — validate that a fully-configured mTLS identity has an HTTPS endpoint before building the HTTP client or issuing any request, and normalise host schemes so unknown/explicit non-HTTPS schemes are preserved for validation rather than disguised as part of an HTTPS host. +- **Context:** PR #331 added `SessionAttribution::{Current,Detached}` to the SEA transport so statement-status polls only advance the shared `session_version` when the statement was submitted through this session. + **Rule:** when a transport carries mutable shared session state (e.g. a negotiated session version), only responses from session-owned operations may mutate it — thread an explicit ownership marker through status/poll APIs so detached calls that know only a statement ID cannot corrupt the session's state. +- **Context:** PR #331 began unconditionally sending `execution_mode=FAST` on every SEA `create_session` and negotiating `session_version`, with coverage entirely in wiremock; the reviewer flagged the live-server behavior change. + **Rule:** adding a new field to a wire request or changing session-handshake behavior is a live-server change — confirm older/mixed-fleet servers ignore the unknown field (or gate it behind capability negotiation as sibling drivers do), and add an `#[ignore]` `tests/v0_*_e2e.rs` case, since wiremock/unit tests pin the wire shape but cannot catch a real server rejecting or diverging on the new field. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 65667a188ff2733254f83c32395f88c7a3866866 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 23 Sep 2026 07:33:38 +0000 Subject: [PATCH 23/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index b5349caf..898bb649 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -224,6 +224,14 @@ author, follow-up, and review runs. - **Context:** PR #331 began unconditionally sending `execution_mode=FAST` on every SEA `create_session` and negotiating `session_version`, with coverage entirely in wiremock; the reviewer flagged the live-server behavior change. **Rule:** adding a new field to a wire request or changing session-handshake behavior is a live-server change — confirm older/mixed-fleet servers ignore the unknown field (or gate it behind capability negotiation as sibling drivers do), and add an `#[ignore]` `tests/v0_*_e2e.rs` case, since wiremock/unit tests pin the wire shape but cannot catch a real server rejecting or diverging on the new field. +### 2026-09-23: learnings since 2026-09-22T07:30:33Z +- **Context:** PR #339 made the default `execute()`/`kernel_statement_execute` path unlimited by conditionally skipping the `poll_timeout` ceiling in the shared `wait_for_terminal`/`execute_to_terminal` helper. A reviewer caught that the same helper backs every metadata query (`list_catalogs`, `list_schemas`, `list_tables`, `list_columns`, `list_procedures`), which have no `_with_timeout` escape hatch, so the change silently un-bounded them too. + **Rule:** When adding an opt-in unlimited/no-timeout mode to a poll or execution loop shared by multiple callers, audit every caller of the shared helper — removing a pre-existing ceiling on the shared path silently un-bounds callers (e.g. metadata queries) that have no way to pass a deadline; keep the default bound on paths that lack an opt-out. +- **Context:** PR #339's client-timeout cleanup resolved the server statement id from a shared `inflight_id_observer` mutex to drive best-effort cancel/close. Reviewers flagged that `try_lock().ok()` drops the id under momentary contention (a concurrent `StatementCanceller`) and `.lock().ok()` drops it on a poisoned mutex — exactly the panic case where it matters most — so cleanup dispatched with `None`, leaving the server statement running and billing DBUs. + **Rule:** For best-effort resource cleanup, extract the identifier with a short-lived blocking `lock()` (held across no await/RPC) and recover a poisoned mutex via `unwrap_or_else(|e| e.into_inner())` — never `try_lock().ok()` or `.lock().ok()`, which silently drop the id under contention/poisoning and skip cleanup, leaking the resource. +- **Context:** PR #339 guarded a client deadline with both an outer `tokio::time::timeout_at` and an inner `Instant::now() >= deadline` check inside `wait_for_terminal`. Both are tokio timers that can become ready in the same scheduler tick; when the inner check won, the returned failure flowed through the normal error path and called `close_orphaned_statement().await` synchronously, contradicting the documented contract that timeout cleanup is asynchronous/best-effort and must not delay the native return (and double-closing the statement). + **Rule:** When a deadline is enforced by both an outer timer and an inner elapsed-check that can fire in the same tick, detect an internally-produced timeout error and route it through the same deferred/asynchronous cleanup path as the outer timeout — do not let it fall into the synchronous orphan-close branch, or you break the best-effort/non-blocking cleanup contract. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From c648f62014ad0f768e9faccc5ad4ffc46a9e7d5e Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 24 Sep 2026 07:33:32 +0000 Subject: [PATCH 24/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 898bb649..8dea3c9c 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -232,6 +232,16 @@ author, follow-up, and review runs. - **Context:** PR #339 guarded a client deadline with both an outer `tokio::time::timeout_at` and an inner `Instant::now() >= deadline` check inside `wait_for_terminal`. Both are tokio timers that can become ready in the same scheduler tick; when the inner check won, the returned failure flowed through the normal error path and called `close_orphaned_statement().await` synchronously, contradicting the documented contract that timeout cleanup is asynchronous/best-effort and must not delay the native return (and double-closing the statement). **Rule:** When a deadline is enforced by both an outer timer and an inner elapsed-check that can fire in the same tick, detect an internally-produced timeout error and route it through the same deferred/asynchronous cleanup path as the outer timeout — do not let it fall into the synchronous orphan-close branch, or you break the best-effort/non-blocking cleanup contract. +### 2026-09-24: learnings since 2026-09-23T07:31:40Z +- **Context:** PR #353 added a native Thrift metadata routing path with client-side filters (`process_native_tables`); the catalog filter compared `TABLE_CAT` to the caller's catalog with `==`, while sibling filters used `eq_ignore_ascii_case`. Reviewer flagged it as a regression: the native backend returns canonical (typically lowercased) identifier casing, so a caller passing `MyCatalog` against `mycatalog` silently drops every row and returns an empty result set. + **Rule:** Any client-side filter on Databricks catalog/schema/table identifiers must compare case-insensitively (`eq_ignore_ascii_case`) — server-side `SHOW ... IN CATALOG` matching is case-insensitive, so a native/client-side path that uses `==` is a silent-empty-result regression. +- **Context:** PR #355 split `jdbc_pattern_to_hive` (which had both converted `%`/`_` wildcards AND escaped single quotes) into wildcard-conversion-only plus a separate `escape_show_pattern` that runs `escape_sql_string` afterward, because combining them double-escaped single quotes in `SHOW` command LIKE patterns. + **Rule:** Keep JDBC-pattern→hive-wildcard conversion separate from SQL string-literal escaping; a helper must not both translate wildcards and escape quotes, or callers that later escape the result double-escape — convert wildcards first, then escape the literal exactly once at embedding time. +- **Context:** PR #355 found that native metadata results which bypass the SQL-result reshape still diverged from the JDBC contract: they needed value normalization (null `REMARKS`→`""`, null/empty `TABLE_TYPE`→`"TABLE"`, 1-based `ORDINAL_POSITION` via `checked_add(1)`), not just Arrow type/width casting, to match the reshaped path. + **Rule:** When a native/Thrift metadata result bypasses the SQL reshape path, reattaching the public schema and casting column widths is insufficient — replicate JDBC's per-column value normalization (empty-string defaults, TABLE_TYPE fallback, 1-based ordinal) so native and reshaped responses expose identical values. +- **Context:** PR #353 wired the native-result bypass into `list_tables`/`list_columns`/`foreign_keys`/etc., but the only added wire-level (wiremock) test drove the catalogs path; the new filter helpers were only unit-tested in isolation, so a routing regression (wrong helper, dropped parent filter) in the other native paths would pass CI. + **Rule:** Unit-testing metadata reshape/filter helpers in isolation does not cover the routing that invokes them — add a wiremock test that drives an `is_native_metadata_result: true` manifest through each native metadata path so mis-wired routing is caught. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From f66b9eff3c34290f0df88d7f2280e3f562fdb091 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 25 Sep 2026 07:34:05 +0000 Subject: [PATCH 25/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 8dea3c9c..99a63248 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -242,6 +242,12 @@ author, follow-up, and review runs. - **Context:** PR #353 wired the native-result bypass into `list_tables`/`list_columns`/`foreign_keys`/etc., but the only added wire-level (wiremock) test drove the catalogs path; the new filter helpers were only unit-tested in isolation, so a routing regression (wrong helper, dropped parent filter) in the other native paths would pass CI. **Rule:** Unit-testing metadata reshape/filter helpers in isolation does not cover the routing that invokes them — add a wiremock test that drives an `is_native_metadata_result: true` manifest through each native metadata path so mis-wired routing is caught. +### 2026-09-25: learnings since 2026-09-24T07:31:40Z +- **Context:** PR #364 normalized Thrift-native metadata to the public Arrow schema, casting physical types and converting `GetColumns` `ORDINAL_POSITION` from zero-based (native Thrift) to JDBC one-based (`+1`), while the SHOW fallback path is already one-based. + **Rule:** Native Thrift `GetColumns` ordinals are zero-based and must be `+1`'d to match JDBC one-based `ORDINAL_POSITION`, but the SHOW/reshape fallback is already one-based — when adding a native path for any metadata op, verify which ordinal convention the source uses rather than assuming. +- **Context:** In PR #364 reviewers flagged that the shared `normalize_native_metadata_batch` helper dispatches its zero→one-based ordinal fix off the bare public field name (`field.name() == "ORDINAL_POSITION"`) and zips native columns to public fields strictly positionally, relying on the documented canonical-column-order invariant. + **Rule:** In shared metadata normalizers, don't key value transforms on a bare column name (multiple JDBC schemas reuse names like `ORDINAL_POSITION` with different semantics — e.g. GetColumns vs procedure-columns) and don't rely on positional column zips alone; gate transforms on the specific operation/schema and assert native field names match positions so contract drift fails loudly as DataLoss instead of silently corrupting values. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 1375cd3a562f15d1ce8f10d5075b12d86a282684 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 29 Sep 2026 07:39:20 +0000 Subject: [PATCH 26/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 99a63248..a3faaa72 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -248,6 +248,14 @@ author, follow-up, and review runs. - **Context:** In PR #364 reviewers flagged that the shared `normalize_native_metadata_batch` helper dispatches its zero→one-based ordinal fix off the bare public field name (`field.name() == "ORDINAL_POSITION"`) and zips native columns to public fields strictly positionally, relying on the documented canonical-column-order invariant. **Rule:** In shared metadata normalizers, don't key value transforms on a bare column name (multiple JDBC schemas reuse names like `ORDINAL_POSITION` with different semantics — e.g. GetColumns vs procedure-columns) and don't rely on positional column zips alone; gate transforms on the specific operation/schema and assert native field names match positions so contract drift fails loudly as DataLoss instead of silently corrupting values. +### 2026-09-29: learnings since 2026-09-28T07:45:39Z +- **Context:** PR #356 exposed the caller-driven async statement C ABI; a reviewer caught that the new `extern "C"` entry points wrapped only `block_on_ffi` and not their surrounding synchronous prologue/epilogue. `block_on_ffi` only `catch_unwind`s the *awaited future* — the `fut_builder` closure, `to_cstring_lossy`, `Box::into_raw`/`Box::from_raw`, `std::ptr::write`, and the `match`/`store_and_code` arms all run on the caller thread outside that guard. + **Rule:** In C ABI (`extern "C"`) functions, wrap the ENTIRE body in `catch_ffi` (not just `block_on_ffi`) — a panic in the synchronous prologue/epilogue (Box alloc/free, `ptr::write`, CString build, error-mapping arms) unwinding across the FFI boundary is UB; `block_on_ffi` guards only the awaited future. +- **Context:** PR #356 — a reviewer flagged that `kernel_executed_async_statement_status` drove its poll without first initializing `*out`, so a transport-error (`Err(code)`) return left the caller's out-param holding uninitialized memory, inconsistent with sibling entry points that pre-write a sentinel (`ptr::write(out, null_mut())`). + **Rule:** Every C ABI out-param entry point must pre-write a defined sentinel to `*out` immediately after the null check, before any fallible work, so a non-`Success` return never leaves `*out` uninitialized — keep this uniform across the whole FFI surface. +- **Context:** PR #356 — the async `Cancelled`/`Failed` status arms initially hand-rolled their own cancel/error construction, dropping the SEA extended-status fields (`display_message`/`diagnostic_info`/`error_details_json`) that the Rust `cancelled_error`/`await_result` path carries via `carry_extended_status`, creating a last-error parity gap between the C ABI and the Rust crate. + **Rule:** Terminal error construction (cancel/fail) must funnel through the shared `carry_extended_status` helper / cached `latest_status` rather than re-listing SEA extended-status fields inline, so C ABI and Rust paths can't drift when a server-supplied field is added. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From dd9e0b00f242fd2dda26c550d8950ac0a440aef2 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 30 Sep 2026 07:42:21 +0000 Subject: [PATCH 27/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index a3faaa72..fce34524 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -256,6 +256,16 @@ author, follow-up, and review runs. - **Context:** PR #356 — the async `Cancelled`/`Failed` status arms initially hand-rolled their own cancel/error construction, dropping the SEA extended-status fields (`display_message`/`diagnostic_info`/`error_details_json`) that the Rust `cancelled_error`/`await_result` path carries via `carry_extended_status`, creating a last-error parity gap between the C ABI and the Rust crate. **Rule:** Terminal error construction (cancel/fail) must funnel through the shared `carry_extended_status` helper / cached `latest_status` rather than re-listing SEA extended-status fields inline, so C ABI and Rust paths can't drift when a server-supplied field is added. +### 2026-09-30: learnings since 2026-09-29T07:37:30Z +- **Context:** PR #369 routed `getFunctions` through the Thrift-native metadata path, keeping `SHOW FUNCTIONS` as an executable SQL fallback whose reshape read every column via `utf8_column`/`int16_column`; a reviewer noted this hard-errors (`Error::data_loss`) when the server returns a leaner shape, whereas JDBC's `getRowsForFunctions` reads each column in a per-column try/catch and defaults missing columns to null. + **Rule:** In SEA/Thrift metadata SQL-fallback reshapes, read optional server columns tolerantly (default absent/uncastable columns to null) to match JDBC's per-column graceful degradation instead of failing the whole query, and add wiremock coverage for the non-native fallback branch — testing only the `is_native_metadata_result=true` path leaves the fallback shape unverified. +- **Context:** PR #369's `functions(None, ..)` resolves the catalog by executing a live `SELECT CURRENT_CATALOG()` (falling back to `default_catalog()`/`hive_metastore` only on failure) and, on the native path, overrides `FUNCTION_CAT` with the caller's requested catalog rather than trusting the server's `catalogName` column; reviewers flagged that the SQL-fallback reshape still read `catalogName` and so could diverge. + **Rule:** For catalog-scoped metadata (getFunctions), resolve the current catalog live via `CURRENT_CATALOG()` — not the session `default_catalog`, since `USE CATALOG` changes the current catalog but not the session default — and populate `FUNCTION_CAT` from that resolved/requested catalog in both native and fallback reshapes, because native `GetFunctions` leaves the server catalog column empty. +- **Context:** PR #365 split manifest schema extraction into `extract_logical_schema_from_manifest` (structured manifest = authoritative logical types, used to identify untagged geo attachment structs) and `extract_physical_schema_from_manifest` (decodes `manifest.arrow_schema` = physical attachment shape); a reviewer caught that the empty-result paths now hard-fail on an undecodable/column-mismatched `arrow_schema` while the streaming path swallows the identical error and falls back. + **Rule:** Treat SEA's structured manifest as the logical type contract and `manifest.arrow_schema` as the physical attachment shape, and keep schema-extraction error handling consistent across empty-result and streaming call sites — fall back to the always-valid logical schema on a broken `arrow_schema` rather than hard-failing one path while tolerating it on another. +- **Context:** PR #360 moved WKT/EWKT coordinate formatting into the kernel (emitting `f64` ordinates via Rust's default `Display`), but every WKT test used integer coordinates like `POINT(1 2)`, so fractional/extreme-magnitude formatting parity with the reference JDBC rendering was unverified despite the PR claiming a corpus check. + **Rule:** When the kernel takes ownership of rendering numeric values to text (e.g. WKT coordinates), test fractional and very-large/very-small magnitudes for digit-for-digit parity with the reference driver — integer-only cases do not lock the formatting contract (trailing zeros, precision, scientific-notation avoidance). + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From dbcccc04b44c2e2f9e77a45274a6967d5dfa2b81 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 1 Oct 2026 07:40:23 +0000 Subject: [PATCH 28/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index fce34524..414d6742 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -266,6 +266,12 @@ author, follow-up, and review runs. - **Context:** PR #360 moved WKT/EWKT coordinate formatting into the kernel (emitting `f64` ordinates via Rust's default `Display`), but every WKT test used integer coordinates like `POINT(1 2)`, so fractional/extreme-magnitude formatting parity with the reference JDBC rendering was unverified despite the PR claiming a corpus check. **Rule:** When the kernel takes ownership of rendering numeric values to text (e.g. WKT coordinates), test fractional and very-large/very-small magnitudes for digit-for-digit parity with the reference driver — integer-only cases do not lock the formatting contract (trailing zeros, precision, scientific-notation avoidance). +### 2026-10-01: learnings since 2026-09-30T07:38:45Z +- **Context:** PR #373 fixed `list_functions` so an empty `catalog` is forwarded to native `GetFunctions` (via `Identifier::new_allow_empty`), whereas schema/column metadata calls still turn an empty catalog into an empty match-nothing pattern. + **Rule:** Empty-catalog semantics are per-metadata-call, not uniform — native `GetFunctions` accepts `catalog=""` as a meaningful value, so don't blanket-apply the match-nothing empty-catalog rule across all metadata entrypoints; use `Identifier::new_allow_empty` only where the protocol defines empty-catalog behavior. +- **Context:** In PR #373 the empty-catalog fix was applied only to the napi binding; a reviewer flagged that the pyo3 `functions()` binding still used `Identifier::from_opt`, so a Python caller passing `catalog=""` errors while Node returns native results — the napi module doc even claims it "follows the pyo3 binding pattern." + **Rule:** Parameter-validation/mapping changes to one language binding (napi) must be mirrored in the sibling binding (pyo3) or they silently diverge on contract; when landing a binding-only fix, explicitly track the parity follow-up rather than leaving the bindings inconsistent. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 227b8db9766688376a10c0df9e2c1721c02a8fb8 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 2 Oct 2026 07:37:56 +0000 Subject: [PATCH 29/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 414d6742..93db10c2 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -272,6 +272,14 @@ author, follow-up, and review runs. - **Context:** In PR #373 the empty-catalog fix was applied only to the napi binding; a reviewer flagged that the pyo3 `functions()` binding still used `Identifier::from_opt`, so a Python caller passing `catalog=""` errors while Node returns native results — the napi module doc even claims it "follows the pyo3 binding pattern." **Rule:** Parameter-validation/mapping changes to one language binding (napi) must be mirrored in the sibling binding (pyo3) or they silently diverge on contract; when landing a binding-only fix, explicitly track the parity follow-up rather than leaving the bindings inconsistent. +### 2026-10-02: learnings since 2026-10-01T07:38:57Z +- **Context:** PR #372 added new public enums `TryNextBatch` (in `result_stream.rs` and `reader/mod.rs`), re-exported from `lib.rs` and consumed via the C ABI by PyO3/napi wrappers and external hosts; a reviewer caught that they lacked `#[non_exhaustive]` unlike sibling public enums (`ResultBatch`, `ErrorCode`, `ResultReaderMetrics`). + **Rule:** Mark every new public enum reachable by FFI/PyO3/napi/C-ABI consumers `#[non_exhaustive]` at introduction, matching the crate's existing public enums, so a future variant stays additive instead of forcing a major version bump. +- **Context:** PR #372's new `kernel_result_stream_try_next_batch` matched only `TryNextBatch::Ready(ResultBatch::Arrow(batch))`, while the blocking `next_batch` path routes non-Arrow variants to a graceful `Error::not_implemented("C ABI exports Arrow only")` with an `#[allow(unreachable_patterns)] _ =>` fallback; `ResultBatch` is `#[non_exhaustive]` precisely to grow variants later. + **Rule:** When adding a new match site over a `#[non_exhaustive]` enum, mirror the existing graceful `_ =>` fallback rather than matching only the sole current variant — otherwise a future variant turns the new arm into a hard compile break instead of the intended runtime error. +- **Context:** PR #372 added non-blocking `try_next_batch` siblings that reimplement the blocking path's chunk-state machine (buffer pop, end detection, `Downloaded`/`DownloadFailed`/`ProcessingFailed`/`Cancelled` mapping, `chunks_in_memory` bookkeeping, inline `try_lock`/`try_recv` + `Disconnected`→`End`). Reviewers flagged that the only new tests ran over `MockReader`/`BlockingReader`, which return `Ready`/`Pending`/`End` directly and never touch the providers' bookkeeping, nor the typed-error branch. + **Rule:** A non-blocking `try_*` variant that duplicates-but-diverges from a blocking path needs its own provider-level tests (Pending→Ready→End, empty-chunk skip, terminal-error surfacing) plus a typed-error test asserting both the mapped status code AND that the error is retrievable with typed fields on the caller thread — mock readers that return outcomes directly cannot exercise the provider state machine the new path reimplements. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 7e98fdf3dbac0237f7c1b96db0a00e4ffd5ead14 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Sat, 3 Oct 2026 07:39:15 +0000 Subject: [PATCH 30/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 93db10c2..0a25f7e3 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -280,6 +280,18 @@ author, follow-up, and review runs. - **Context:** PR #372 added non-blocking `try_next_batch` siblings that reimplement the blocking path's chunk-state machine (buffer pop, end detection, `Downloaded`/`DownloadFailed`/`ProcessingFailed`/`Cancelled` mapping, `chunks_in_memory` bookkeeping, inline `try_lock`/`try_recv` + `Disconnected`→`End`). Reviewers flagged that the only new tests ran over `MockReader`/`BlockingReader`, which return `Ready`/`Pending`/`End` directly and never touch the providers' bookkeeping, nor the typed-error branch. **Rule:** A non-blocking `try_*` variant that duplicates-but-diverges from a blocking path needs its own provider-level tests (Pending→Ready→End, empty-chunk skip, terminal-error surfacing) plus a typed-error test asserting both the mapped status code AND that the error is retrievable with typed fields on the caller thread — mock readers that return outcomes directly cannot exercise the provider state machine the new path reimplements. +### 2026-10-03: learnings since 2026-10-02T07:36:06Z +- **Context:** PR #374 added an async submit/poll path (`ExecutedAsyncStatement`) mirroring the existing sync `wait_for_terminal` timeout gating; reviewers caught two divergences — an explicitly-`Unlimited` submit still died at the 600s default `poll_timeout`, and a `Deadline` longer than 600s aborted at 600s with the generic internal poll-timeout error instead of the caller's `Timeout`/HYT00 client-query-timeout. + **Rule:** When adding a parallel consumption mode that mirrors an existing timeout path, replicate the ceiling-gating exactly: a client deadline (and explicit `Unlimited`) must DISABLE the transport's default `poll_timeout` ceiling (the client deadline *is* the ceiling), since `MAX_CLIENT_QUERY_TIMEOUT_MS` permits deadlines far beyond the 600s default — only `Default` keeps the ceiling armed. +- **Context:** PR #374's client deadline was initially enforced on every `status()`/`await_result()` poll with no latch; reviewers showed a caller that observed a terminal `Succeeded` and then polled again after the deadline got `Timeout`/HYT00 plus a wasted cancel+close RPC against an already-finished statement. Fixed with a `terminal_observed` latch (seeded from the initial-submit snapshot). + **Rule:** A client-side query deadline must govern only the pre-terminal window — latch the first observed terminal state and return it on subsequent polls regardless of the deadline, instead of masking a finished outcome with a timeout error and firing best-effort cleanup against a completed statement. +- **Context:** PR #374's `kernel_executed_async_statement_status` C-ABI handler was switched from `.as_ref()` to `.as_mut()` on the raw handle pointer, but it only reads `&handle.exec` and drives `status(&self)` (state advances via `Mutex`/`Atomic*` interior mutability). The canceller surface is explicitly driven from a second thread, so two concurrent status calls would construct aliasing `&mut` references — UB. + **Rule:** In cross-thread FFI handlers, reconstruct a shared `.as_ref()` borrow, not `.as_mut()`, unless the handler actually writes a field directly; interior mutability (`Mutex`/`Atomic`) means read-only paths need only `&self`, and an unnecessary `&mut` asserts exclusive access that concurrent callers violate. +- **Context:** PR #374's best-effort timeout cleanup (`dispatch_timeout_cleanup` → cancel+close RPC pair) performs no dedup; a reviewer noted that a poll loop ignoring the `Timeout` status would re-dispatch cleanup every iteration and exhaust the per-session `MAX_CONCURRENT_TIMEOUT_CLEANUPS` (64-permit) budget, starving genuine cleanups. Resolved by gating dispatch on a one-shot `client_timeout_expired.swap(true, AcqRel)` transition (mirroring the telemetry `finalize` one-shot). + **Rule:** Gate best-effort server cleanup (cancel/close) dispatch on a one-shot flag transition so repeated post-expiry polls short-circuit without re-firing RPCs — cleanup-dispatch helpers that aren't idempotent will burn a bounded permit budget under a caller that keeps polling after a timeout. +- **Context:** PR #374's timeout bug (a `Deadline` > `poll_timeout` aborting early) escaped the existing wiremock test because it only exercised a 25ms timeout, which is far below the 600s `poll_timeout` ceiling, so the ceiling-vs-deadline interaction never fired. + **Rule:** Timeout regression tests must exercise a client deadline that EXCEEDS the configured `poll_timeout` (or configure a small `poll_timeout`), not just a sub-second timeout — only a deadline past the ceiling exercises the gating divergence between the client deadline and the transport poll-timeout. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 94023d403b095ffd7d6d5b59162db9e35d8ba74d Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Mon, 5 Oct 2026 07:52:37 +0000 Subject: [PATCH 31/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 0a25f7e3..0c3b2103 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -292,6 +292,10 @@ author, follow-up, and review runs. - **Context:** PR #374's timeout bug (a `Deadline` > `poll_timeout` aborting early) escaped the existing wiremock test because it only exercised a 25ms timeout, which is far below the 600s `poll_timeout` ceiling, so the ceiling-vs-deadline interaction never fired. **Rule:** Timeout regression tests must exercise a client deadline that EXCEEDS the configured `poll_timeout` (or configure a small `poll_timeout`), not just a sub-second timeout — only a deadline past the ceiling exercises the gating divergence between the client deadline and the transport poll-timeout. +### 2026-10-05: learnings since 2026-10-04T09:25:50Z +- **Context:** PR #381 changed `reshape_foreign_keys` (src/metadata/thrift_shape.rs): `UPDATE_RULE`/`DELETE_RULE` had been hardcoded to typed nulls on the assumption they had "no server source," but newer `SHOW FOREIGN KEYS` and native responses actually ship `updateRule`/`deleteRule` columns. + **Rule:** When reshaping server metadata into JDBC columns, prefer preserve-when-present over hardcoding a column to null — server response shapes evolve and gain columns across versions/variants (SHOW vs native); gate the null only on the column being genuinely absent, and cover both response variants plus the empty-result schema in tests. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 64df56f0b0f99a14eda6b725d9737afe9eb8438e Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 6 Oct 2026 07:39:01 +0000 Subject: [PATCH 32/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 0c3b2103..f3a41013 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -296,6 +296,14 @@ author, follow-up, and review runs. - **Context:** PR #381 changed `reshape_foreign_keys` (src/metadata/thrift_shape.rs): `UPDATE_RULE`/`DELETE_RULE` had been hardcoded to typed nulls on the assumption they had "no server source," but newer `SHOW FOREIGN KEYS` and native responses actually ship `updateRule`/`deleteRule` columns. **Rule:** When reshaping server metadata into JDBC columns, prefer preserve-when-present over hardcoding a column to null — server response shapes evolve and gain columns across versions/variants (SHOW vs native); gate the null only on the column being genuinely absent, and cover both response variants plus the empty-result schema in tests. +### 2026-10-06: learnings since 2026-10-05T07:51:14Z +- **Context:** PR #379 relaxed the `primary_keys` kernel contract from "catalog/schema required (else `InvalidArgument`)" to "missing → resolve from the session"; the reviewer noted this silently changed the C ABI (NULL now triggers a `SELECT CURRENT_CATALOG(), CURRENT_SCHEMA()` round-trip instead of erroring, with no header-doc/test update) while pyo3 still declared the args required — so the fix landed inconsistently across bindings. + **Rule:** When changing a kernel-layer metadata/execution contract (required→optional, error→resolve, timeout policy), audit and update EVERY wrapper surface (C ABI header docs + tests, pyo3, napi) in the same PR or explicitly document the intentional divergence — a kernel-layer change silently alters every unmodified binding. +- **Context:** In PR #379, missing `catalog`/`schema` on `primary_keys` are each filled independently from the session's `CURRENT_CATALOG()`/`CURRENT_SCHEMA()`; the reviewer flagged that `CURRENT_SCHEMA()` is relative to the session's current catalog, so pairing an explicit non-current catalog with the session's current schema (`IN CATALOG IN SCHEMA `) can target a schema that doesn't exist under that catalog. + **Rule:** `CURRENT_SCHEMA()` is scoped to the current catalog — do not resolve a missing schema from the session independently of an explicitly-supplied, non-current catalog; only backfill the session namespace when the companion dimension is also absent (or document that partial override is unsupported). +- **Context:** PR #384's new non-blocking FFI entry point `kernel_result_stream_try_next_batch` returns a status code AND stores a typed error; its test deliberately asserts both the mapped `KernelStatusCode` and that `kernel_get_last_error` reports the structured fields (code/message/retryable) on the caller thread, noting a regression that dropped the error (returning a code with no last-error detail) would otherwise pass CI. + **Rule:** For FFI entry points that return a status code plus a stored last-error, tests must assert BOTH the mapped status code and the `kernel_get_last_error` structured fields on the caller thread — asserting only the code lets a dropped/typeless error regression pass silently. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From cbf955b684c26ef024035bc32619311cf2f42f1e Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 7 Oct 2026 07:40:50 +0000 Subject: [PATCH 33/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index f3a41013..a1023239 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -304,6 +304,20 @@ author, follow-up, and review runs. - **Context:** PR #384's new non-blocking FFI entry point `kernel_result_stream_try_next_batch` returns a status code AND stores a typed error; its test deliberately asserts both the mapped `KernelStatusCode` and that `kernel_get_last_error` reports the structured fields (code/message/retryable) on the caller thread, noting a regression that dropped the error (returning a code with no last-error detail) would otherwise pass CI. **Rule:** For FFI entry points that return a status code plus a stored last-error, tests must assert BOTH the mapped status code and the `kernel_get_last_error` structured fields on the caller thread — asserting only the code lets a dropped/typeless error regression pass silently. +### 2026-10-07: learnings since 2026-10-06T07:37:21Z +- **Context:** PR #385 added an `Accept-Encoding: identity` default for authenticated SEA requests; review (F1) caught that reqwest's `.header()` *appends* rather than replaces, so a caller-supplied `Accept-Encoding` plus the kernel default produced two conflicting headers and ambiguous server behavior. Fix filtered the caller's header (with a warning) before setting the default. + **Rule:** reqwest `RequestBuilder::header()` appends — it does not replace; when the kernel injects a default header (Accept-Encoding, etc.), strip any conflicting caller-supplied header first instead of relying on last-wins, or you get duplicate headers with undefined precedence. +- **Context:** PR #376's feature-flag cache stored expiry as `Instant::now() + ttl` where `ttl` came from an unbounded server-supplied `ttl_seconds`; review (cache.rs:71) noted a near-`i64::MAX` value makes `Instant + Duration` panic, which runs inside the Moka loader on the session-open path and would defeat the module's fail-open contract. Fix used `checked_add` with a `DEFAULT_TTL` fallback. + **Rule:** Never add a server/attacker-controlled Duration to an `Instant` with `+` — it panics on overflow; use `Instant::checked_add(...)` with a sane fallback, especially on fail-open paths where a panic turns graceful degradation into a hard failure. +- **Context:** PR #376's process-wide feature-flag cache keyed entries only on workspace (org-id/host), but the connector-service response is a function of `(workspace, client_type, version)` — all three embedded in the request URL. Reviewers repeatedly flagged (Medium) that a process opening sessions with differing `ClientIdentity` would serve the first identity's flags to later ones — a fail-*wrong*, not fail-open, outcome resting on an unenforced "one driver per process" invariant. + **Rule:** A shared/process-wide cache key must include every request input that varies the response; if you deliberately omit one on an invariant (e.g. "one driver per process"), that invariant must be enforced or asserted at the API boundary — direct Rust use can violate assumptions the bindings uphold. +- **Context:** PR #376's feature-flag fetch wrapped the whole request — including `auth_header()` credential acquisition — in a 5s timeout; review (mod.rs:346) noted interactive auth (browser OAuth login) can exceed 5s, timing out the fetch. Fix acquired Authorization/extra auth headers *before* starting the bounded fetch timeout. + **Rule:** A bounded per-request timeout must not include credential acquisition time — acquire auth headers (OAuth/browser login, token refresh) before starting the request-timeout clock, or slow interactive auth will spuriously exhaust the request budget. +- **Context:** PR #376 awaited a fail-open auxiliary fetch (`prepare_for_session_open().await`) inline on the session-open critical path before `CreateSession`, and cold failures were deliberately not cached. Reviewers (session.rs:428, Medium) noted that when connector-service is unreachable but the warehouse is healthy, *every* session open pays the full ~5s timeout repeatedly, since the failure is never remembered. + **Rule:** Don't block a hot path (session/connection open) on an auxiliary fail-open call without either negative-caching failures for a short backoff window or moving the call off the critical path — otherwise a down auxiliary service becomes a per-operation latency amplifier even though correctness is unaffected. +- **Context:** PR #376 tests exercised the real resolver bound to the process-wide `global_cache()`, relying on a unique `DRIVER_VERSION` for isolation; reviewers (session.rs:2420/2429, F1) showed the version is part of the request path but NOT the cache key, so the "isolation" was ineffective and the `.expect(1)` mock could flake on ephemeral-port reuse colliding with a live cached host entry. + **Rule:** Tests that assert on network calls must not share a process-wide/global cache — inject a dedicated cache via a test seam (e.g. `with_cache`); do not rely on cache-key uniqueness via fields that don't actually participate in the key, or you get latent flakiness. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From b232120d5dea46ef3b175ba7b23b2e1aa38c0ee1 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 9 Oct 2026 07:42:32 +0000 Subject: [PATCH 34/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index a1023239..82d6a1da 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -318,6 +318,24 @@ author, follow-up, and review runs. - **Context:** PR #376 tests exercised the real resolver bound to the process-wide `global_cache()`, relying on a unique `DRIVER_VERSION` for isolation; reviewers (session.rs:2420/2429, F1) showed the version is part of the request path but NOT the cache key, so the "isolation" was ineffective and the `.expect(1)` mock could flake on ephemeral-port reuse colliding with a live cached host entry. **Rule:** Tests that assert on network calls must not share a process-wide/global cache — inject a dedicated cache via a test seam (e.g. `with_cache`); do not rely on cache-key uniqueness via fields that don't actually participate in the key, or you get latent flakiness. +### 2026-10-09: learnings since 2026-10-08T07:40:57Z +- **Context:** PR #388 fixed an intermittent `Session.close()` hang in the pyo3 bindings by wrapping the session-owned tokio runtime in a `KernelRuntime` type. + **Rule:** In pyo3 bindings, never let a tokio `Runtime` drop (which blocks until all workers exit) run while the GIL is held — a worker forwarding a log record through `pyo3_log` blocks on the GIL, so the blocking drop deadlocks; shut the runtime down with the GIL released (`py.detach(|| rt.shutdown_timeout(..))`) on explicit `close()`, and use `shutdown_background()` in `Drop`. Route every handle's `close()` through one shared release helper so whichever `close()` drops the last runtime handle performs the GIL-released wait. +- **Context:** PR #388 added an `atexit` hook + `ExitGuard` log wrapper after a reviewer noted the `Drop` path could crash rather than hang at interpreter exit. + **Rule:** Under `abi3-py39`, pyo3's finalizing-interpreter guard is compiled out (`#[cfg(Py_3_13)]`), so a background worker forwarding a log record while the interpreter finalizes goes straight to `PyGILState_Ensure` and can abort the process. Register a module-init `atexit` hook (runs before finalization starts) that sets an `AtomicBool`, and wrap the logger in a thin `log::Log` that drops records once the flag is set. +- **Context:** PR #388's `KernelRuntime` unit tests exercised a worker blocked waiting for the GIL held by the calling thread. + **Rule:** When testing shutdown/`close()` paths that could deadlock on a GIL-blocked worker, run the code under test on its own attached thread and join with `recv_timeout`, so a regression fails the test with a clear message instead of hanging the whole suite indefinitely. +- **Context:** PR #389 migrated the public `TelemetryConfig::enabled` field from `bool` to `Option` so an unspecified setting defers to a workspace feature flag; a reviewer flagged that a direct `enabled = false` write silently loses its meaning. + **Rule:** When a config field must distinguish "unspecified" (defer to server/feature-flag default) from an explicit "off", a plain `bool` whose default equals "off" cannot preserve an explicit opt-out — the feature flag can silently re-enable it. Use `Option` and route explicit choices through a setter; a bare `field = false` assignment will NOT survive as a hard off-switch. This is privacy-relevant for telemetry/opt-out semantics. +- **Context:** PR #389 hardcoded a `enableTelemetryForKernel` connector-service feature-flag name in kernel code, and reviewers could not confirm the flag is provisioned server-side (the design doc gates the ADBC→Kernel rename on backend-owner confirmation). + **Rule:** Do not hardcode a connector-service feature-flag name in kernel code until the backend/dashboard owner confirms it is provisioned for the kernel's driver-family endpoints (GOLANG/PYTHON/NODEJS/ODBC). An unprovisioned flag makes `get_bool(flag)` return `None` for every workspace, turning the feature-flag precedence tier into dead code — the opposite of the intended behavior. Keep the flag name consistent across PR description, code, and design doc. +- **Context:** PR #391 changed the ARRAY list child field name produced by manifest-only (empty-result) type mapping from arrow-rs's canonical `item` (via `Field::new_list_field`) to `element`. + **Rule:** DBSQL's Arrow IPC names ARRAY/list children `element` (matching Spark's `ArrowUtils`), NOT arrow-rs's default `item` or pyarrow's `item`. Manifest-derived empty-result schemas must use `element` to stay field-for-field equal with the non-empty wire payload; the child name must match the server's convention, not the arrow-rs default, for empty vs non-empty schema parity. +- **Context:** PR #391's wiremock test built both the empty and non-empty Arrow IPC payloads from the same locally-constructed `ListArray` (child named `element`), and a reviewer noted the final schema-equality assertion was circular. + **Rule:** A wiremock/replay test that fabricates both the empty and non-empty payloads from the same local array only proves the two code paths agree with each other — it would pass identically for a wrong-direction choice and cannot catch divergence from what the real server sends. Validating a server-wire-convention premise (e.g. a field name DBSQL actually emits) requires an `#[ignore]` live-warehouse e2e test comparing advertised schemas. +- **Context:** PR #390 added the `Spark:DataType:SqlName` field-metadata key to result schemas, set to the manifest's `type_text`, to match Thrift results and the C# ADBC SEA path. + **Rule:** Thrift-compatible result-schema metadata keys must use the literal server key name (`Spark:DataType:SqlName`), NOT the kernel's `databricks.`-prefixed convention — Thrift-era consumers (Power BI, JDBC) read the literal key. Pin the literal wire string in tests rather than the Rust constant, so a rename can't silently break downstream readers. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From dbe36ce42efa7cca106b4557cdfcad9e646897b4 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 13 Oct 2026 07:44:20 +0000 Subject: [PATCH 35/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 82d6a1da..0b593ff4 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -336,6 +336,12 @@ author, follow-up, and review runs. - **Context:** PR #390 added the `Spark:DataType:SqlName` field-metadata key to result schemas, set to the manifest's `type_text`, to match Thrift results and the C# ADBC SEA path. **Rule:** Thrift-compatible result-schema metadata keys must use the literal server key name (`Spark:DataType:SqlName`), NOT the kernel's `databricks.`-prefixed convention — Thrift-era consumers (Power BI, JDBC) read the literal key. Pin the literal wire string in tests rather than the Rust constant, so a rename can't silently break downstream readers. +### 2026-10-13: learnings since 2026-10-12T07:56:10Z +- **Context:** PR #393 reversed `list_tables`'s `table_types` filter from case-insensitive (`eq_ignore_ascii_case`) to exact case-sensitive matching (`types.contains`), so `["table"]` no longer matches `TABLE` rows — matching Thrift `GetTables` and the JDBC client-side filter. + **Rule:** For SEA metadata ops, mirror Thrift server semantics exactly rather than adding convenience leniency (e.g. case-insensitive matching); a "helpful" relaxation silently diverges from Thrift/JDBC parity and must be case-sensitive to match. +- **Context:** PR #396 copied the SEA manifest's `type_json` into the Thrift-compatible `Spark:DataType:JsonType` field-metadata key, following the existing `Spark:DataType:SqlName` (= `type_text`) pattern, so Thrift-written consumers (Power BI, JDBC) read the same keys off SEA result schemas. + **Rule:** When the SEA manifest exposes column type info the Thrift server also provides, mirror it under the Thrift server's `Spark:DataType:*` metadata key (not only the `databricks.*` key) so Thrift-oriented consumers keep working on the SEA path. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 85a644abf41760a3fe8805039c606091fd474b89 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 16 Oct 2026 07:32:06 +0000 Subject: [PATCH 36/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 0b593ff4..a9c26ef7 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -342,6 +342,12 @@ author, follow-up, and review runs. - **Context:** PR #396 copied the SEA manifest's `type_json` into the Thrift-compatible `Spark:DataType:JsonType` field-metadata key, following the existing `Spark:DataType:SqlName` (= `type_text`) pattern, so Thrift-written consumers (Power BI, JDBC) read the same keys off SEA result schemas. **Rule:** When the SEA manifest exposes column type info the Thrift server also provides, mirror it under the Thrift server's `Spark:DataType:*` metadata key (not only the `databricks.*` key) so Thrift-oriented consumers keep working on the SEA path. +### 2026-10-16: learnings since 2026-10-15T07:32:52Z +- **Context:** PR #399 routed M2M / Azure-v1 OAuth token exchanges through the kernel's retrying HTTP client and added `token_exchange_error` to classify the final failure: only a non-retryable rejection (e.g. 401 `invalid_client`) becomes `Unauthenticated`, while failures the ladder retried and exhausted (429, 5xx, retryable 4xx like 408) keep their own code. + **Rule:** When mapping a token-endpoint / auth exchange failure to an error code, only map genuine non-retryable rejections to Unauthenticated; an exhausted-transient failure (throttling, 5xx, retryable 4xx) must retain its own code so it isn't misreported as bad credentials. +- **Context:** In PR #399 a reviewer flagged (F1) that `token_exchange_error` classifies via `is_non_retryable_status`, which reads the static `IDEMPOTENT_NON_RETRYABLE` list and ignores per-session `override_retryable_codes` that the actual `RetryStrategy` honors — so the post-exhaustion label can disagree with what the retry ladder actually did (e.g. an overridden-retryable 400 gets mislabeled a hard auth rejection). + **Rule:** Classify a post-retry failure from what the retry ladder actually decided (carry a retryable / retries-exhausted marker on the Error), not by re-deriving from a static status-code list — the two diverge whenever per-session retry overrides are in play. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 5528a706c8629571f43e781c79c6b722277d7b99 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Sat, 17 Oct 2026 07:27:49 +0000 Subject: [PATCH 37/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index a9c26ef7..d6f1829a 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -348,6 +348,12 @@ author, follow-up, and review runs. - **Context:** In PR #399 a reviewer flagged (F1) that `token_exchange_error` classifies via `is_non_retryable_status`, which reads the static `IDEMPOTENT_NON_RETRYABLE` list and ignores per-session `override_retryable_codes` that the actual `RetryStrategy` honors — so the post-exhaustion label can disagree with what the retry ladder actually did (e.g. an overridden-retryable 400 gets mislabeled a hard auth rejection). **Rule:** Classify a post-retry failure from what the retry ladder actually decided (carry a retryable / retries-exhausted marker on the Error), not by re-deriving from a static status-code list — the two diverge whenever per-session retry overrides are in play. +### 2026-10-17: learnings since 2026-10-16T07:30:35Z +- **Context:** PR #401 reworked SEA response parsing to avoid copying multi-MB inline-Arrow bodies: `response.text()` + `serde_json::from_str` became `response.bytes()` + `serde_json::from_slice`, and `convert_result_data` / the inline provider constructors switched from taking `Vec`/`.clone()` to borrowing `&[u8]`. + **Rule:** When parsing large HTTP response bodies (inline Arrow / CloudFetch payloads), read with `response.bytes()` and deserialize via `serde_json::from_slice` rather than `.text()` + `from_str`, and thread the attachment as `&[u8]` down to the Arrow parser instead of owning/cloning it — `.text()` forces a full UTF-8 copy of the body and `Vec` params add avoidable clones. +- **Context:** PR #401 replaced the `Option`-based base64 attachment deserializer with a custom serde `Visitor` so the base64 decodes directly from serde_json's borrowed `&str` (zero-copy when the JSON string has no escapes). The added test deliberately used `"\/\/79"` (an escaped `/`) because an escape sequence forces serde_json off its borrowed-string fast path onto the owned-string path. + **Rule:** A zero-copy/borrowing serde deserializer has two code paths (borrowed `&str` vs owned `String`); to exercise the non-borrowed path in tests, feed JSON containing an escape sequence (e.g. `\/`) — plain unescaped strings only ever hit the borrowed path and silently leave the owned branch untested. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From f6d531ab849c577e7d7e22bcecb2e2abbacbd483 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 20 Oct 2026 07:36:31 +0000 Subject: [PATCH 38/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index d6f1829a..58bb3e9d 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -354,6 +354,18 @@ author, follow-up, and review runs. - **Context:** PR #401 replaced the `Option`-based base64 attachment deserializer with a custom serde `Visitor` so the base64 decodes directly from serde_json's borrowed `&str` (zero-copy when the JSON string has no escapes). The added test deliberately used `"\/\/79"` (an escaped `/`) because an escape sequence forces serde_json off its borrowed-string fast path onto the owned-string path. **Rule:** A zero-copy/borrowing serde deserializer has two code paths (borrowed `&str` vs owned `String`); to exercise the non-borrowed path in tests, feed JSON containing an escape sequence (e.g. `\/`) — plain unescaped strings only ever hit the borrowed path and silently leave the owned branch untested. +### 2026-10-20: learnings since 2026-10-19T07:43:05Z +- **Context:** PR #407 bumped the crate to `1.2.0` while shipping a breaking public-API change (`TelemetryConfig::enabled` `bool` → `Option`); the reviewer noted the "we have no direct Rust consumers" rationale doesn't hold because the crate is published to crates.io under `^1`. + **Rule:** For a crates.io-published `1.x` crate, any breaking change to a public Rust type/field (e.g. changing a public field's type) requires a MAJOR version bump under SemVer — the absence of first-party direct consumers is irrelevant since downstream crates resolving within `^1` will fail to compile after `cargo update`; if a lenient pre-2.0 policy is intended, state it in the PR. +- **Context:** In PR #361's new text→native geospatial conversion, reviewers flagged that error paths interpolated the raw value and a third-party parser's `{error}` (`wkt::Wkt::from_str`) into messages, and that a `SRID=...` literal could leak; the module already has a dedicated no-echo invariant test. + **Rule:** Malformed-value conversion errors must never echo result contents — don't interpolate the offending value or a third-party parser's verbatim `Display` error into messages or debug logs (they can leak coordinates/SRIDs); emit a generic reason and assert a distinctive input substring is absent in no-echo tests that actually reach the parser body. +- **Context:** PR #361's text→binary geospatial path parsed child values unconditionally during ARRAY/MAP/STRUCT recursion, so a null outer STRUCT/ARRAY/MAP whose ignored child held a placeholder string returned a spurious `DataLoss` even though the visible value was null. + **Rule:** When recursively converting nested Arrow values, derive each child position's effective validity from ancestor/container null bitmaps (and offsets/sizes for ARRAY/MAP) and skip null-masked slots before parsing — otherwise placeholder values under a null parent trigger false hard errors; add null-container cases alongside the direct-null test. +- **Context:** PR #361 flipped the default `GeospatialResultRepresentation` from `String` to `Binary`, so standard DBSQL warehouses' passthrough WKT/EWKT now routes through `wkt`→`wkb` encoding by default, where any parse/encode gap becomes a hard `Error::data_loss()` that aborts the whole result stream (the PR already needed a `MULTIPOINT(EMPTY,…)` workaround). + **Rule:** Flipping a default so all values flow through a new fallible transform can turn previously-working queries into hard stream-aborting errors on upgrade — on a default path prefer degrading to the original value over failing hard, or exhaustively enumerate the server emitter's output surface against the parser before changing the default. +- **Context:** PR #361's Node option field `enable_geo_spatial_support` auto-generated the TS name `enableGeoSpatialSupport`, diverging from Python/C `enable_geospatial_support`; reviewers noted renaming after publish is a breaking change for Node consumers. + **Rule:** napi-rs derives the public TypeScript option name directly from the Rust field identifier, so word-splitting/casing is locked in at publish time and can't change without a breaking release — choose binding field names for cross-binding (Python/C/Node) spelling parity before the first publish. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 2d74e14aa0a77ee452311f08790c31de97238c99 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 23 Oct 2026 07:35:47 +0000 Subject: [PATCH 39/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 58bb3e9d..5d6a25a9 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -366,6 +366,10 @@ author, follow-up, and review runs. - **Context:** PR #361's Node option field `enable_geo_spatial_support` auto-generated the TS name `enableGeoSpatialSupport`, diverging from Python/C `enable_geospatial_support`; reviewers noted renaming after publish is a breaking change for Node consumers. **Rule:** napi-rs derives the public TypeScript option name directly from the Rust field identifier, so word-splitting/casing is locked in at publish time and can't change without a breaking release — choose binding field names for cross-binding (Python/C/Node) spelling parity before the first publish. +### 2026-10-23: learnings since 2026-10-22T07:35:08Z +- **Context:** PR #410 switched empty-result schema construction to stamp the SEA manifest's per-column `nullable` flag onto Arrow fields (previously every result column was forced to NULLABLE). Reviewers flagged that the tightened field flows into the post-processor, which rebuilds every batch via `RecordBatch::try_new`. + **Rule:** In arrow-rs (59+), declaring an Arrow field non-nullable over a column whose physical array actually contains nulls makes `RecordBatch::try_new` hard-fail (or silently violates the invariant at the C-Data/FFI boundary, where consumers like pyarrow misread/reject it) — before tightening nullability from a server/manifest hint, confirm the invariant (`nullable:false` ⇒ zero nulls) holds against real data, and add a test exercising `nullable:false` against a null-bearing column, since null-free test data hides the failure. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From c6b6648de0a144e0313cfeb09cf700caa155e69c Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Sat, 24 Oct 2026 07:28:37 +0000 Subject: [PATCH 40/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 5d6a25a9..d4b16e73 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -370,6 +370,10 @@ author, follow-up, and review runs. - **Context:** PR #410 switched empty-result schema construction to stamp the SEA manifest's per-column `nullable` flag onto Arrow fields (previously every result column was forced to NULLABLE). Reviewers flagged that the tightened field flows into the post-processor, which rebuilds every batch via `RecordBatch::try_new`. **Rule:** In arrow-rs (59+), declaring an Arrow field non-nullable over a column whose physical array actually contains nulls makes `RecordBatch::try_new` hard-fail (or silently violates the invariant at the C-Data/FFI boundary, where consumers like pyarrow misread/reject it) — before tightening nullability from a server/manifest hint, confirm the invariant (`nullable:false` ⇒ zero nulls) holds against real data, and add a test exercising `nullable:false` against a null-bearing column, since null-free test data hides the failure. +### 2026-10-24: learnings since 2026-10-23T07:34:23Z +- **Context:** PR #411 hand-edited `version`/`checksum` lines in all three `Cargo.lock`s because the Artifactory/JFrog proxy rejected the new crate, and PR #412 regenerated a lockfile under that same degraded proxy — which silently *downgraded* unrelated transitive deps (`windows-sys` 0.61.2→0.52.0, plus `mio`/`rustix`/`tempfile`) and left a duplicate major version, outside the PR's stated scope. Reviewers flagged both. + **Rule:** Never trust a `Cargo.lock` change produced while the registry proxy is failing crates — a hand-edited entry can carry a wrong checksum (breaks every downstream fetch) or a stale `dependencies` block (fails `--locked` builds), and a regenerate in a degraded resolution env can silently downgrade/duplicate unrelated transitive crates; once the proxy is healthy, re-run `cargo update -p ` (or a `--locked` build) and confirm the lockfile diff is limited to exactly the intended crates before merging. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From f5d7d2be880d6832d5f72ebfdde78cd0b8ddb02f Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 28 Oct 2026 07:25:16 +0000 Subject: [PATCH 41/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index d4b16e73..f4c9885f 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -374,6 +374,14 @@ author, follow-up, and review runs. - **Context:** PR #411 hand-edited `version`/`checksum` lines in all three `Cargo.lock`s because the Artifactory/JFrog proxy rejected the new crate, and PR #412 regenerated a lockfile under that same degraded proxy — which silently *downgraded* unrelated transitive deps (`windows-sys` 0.61.2→0.52.0, plus `mio`/`rustix`/`tempfile`) and left a duplicate major version, outside the PR's stated scope. Reviewers flagged both. **Rule:** Never trust a `Cargo.lock` change produced while the registry proxy is failing crates — a hand-edited entry can carry a wrong checksum (breaks every downstream fetch) or a stale `dependencies` block (fails `--locked` builds), and a regenerate in a degraded resolution env can silently downgrade/duplicate unrelated transitive crates; once the proxy is healthy, re-run `cargo update -p ` (or a `--locked` build) and confirm the lockfile diff is limited to exactly the intended crates before merging. +### 2026-10-28: learnings since 2026-10-26T07:44:24Z +- **Context:** PR #380 added `ExecutedAsyncStatement::reader()` — a read-only handle that retains the owner's session routing but not its lifecycle. Review (executed_async.rs:403) caught that after the owner's close/drop issued the server DELETE, the reader's `await_result`/`fetch_result` returned an empty *successful* stream (server reports CLOSED → sea.rs:565 → reader/mod.rs:373 yields an empty stream), instead of erroring; `stmt.submit().reader()` hit this immediately since the temporary owner drops right away. Fixed by sharing an owner-released flag and failing with `InvalidStatementHandle`. + **Rule:** A read-only/derived handle that shares session routing but not lifecycle ownership must track the owner's close/drop and fail with `InvalidStatementHandle`; do NOT infer validity from server status, because a CLOSED statement returns an empty *successful* stream, not an error, so a stale reader silently yields empty results. +- **Context:** PR #380 review (sea.rs:1211) flagged that the explanatory comment on the SEA standard-path session-delete URL was dropped when the `?warehouse_id=` query param was moved into `create_session`. The param is a non-obvious server contract, not cosmetic. + **Rule:** SEA standard-path session close (`DELETE /api/2.0/sql/sessions/{id}`) requires the `?warehouse_id=` query param — without it the server returns HTTP 400 and the session leaks until the idle-timeout reaper drops it; keep a comment on the URL builder so a later 'simplification' can't silently reintroduce the leak. +- **Context:** PR #380 review (executed_async.rs:403) noted the Python reader test closed the parent `stmt` first, which masked the derived-handle invalidation gap — the reader bug only manifests when the *owner* is closed/dropped while the parent statement stays alive. + **Rule:** When testing invalidation of a handle derived from another (reader/canceller/attached handle), exercise the owner's close/drop path independently and keep the parent alive; closing the parent first can mask the derived handle's own release-tracking gap. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 3bb12fcec620860cfe45ec27e447a96ee2c414a8 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 30 Oct 2026 07:24:21 +0000 Subject: [PATCH 42/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index f4c9885f..8e017231 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -382,6 +382,12 @@ author, follow-up, and review runs. - **Context:** PR #380 review (executed_async.rs:403) noted the Python reader test closed the parent `stmt` first, which masked the derived-handle invalidation gap — the reader bug only manifests when the *owner* is closed/dropped while the parent statement stays alive. **Rule:** When testing invalidation of a handle derived from another (reader/canceller/attached handle), exercise the owner's close/drop path independently and keep the parent alive; closing the parent first can mask the derived handle's own release-tracking gap. +### 2026-10-30: learnings since 2026-10-29T07:23:34Z +- **Context:** PR #413 (telemetry shared-client flush) found that the per-host shared `TelemetryClient` grabbed `Handle::current()` in `new`. In PyO3 each Session owns its own tokio runtime, so once the session that created the client closed, `KernelRuntime::release` shut that runtime down. That killed the client's timer and silently turned its batch flushes into no-ops for every other session on the host. The fix moved the client onto a dedicated process-wide runtime and stored its `Handle`. Final-lease `Drop` now calls `stored_handle.spawn(close())`, which works without an ambient runtime (e.g. on a PyO3 GC drop), unlike `tokio::spawn` or `Handle::try_current`. The dedicated runtime lives in a `Mutex>` that only stores a successful build. A `OnceLock>` would have cached a one-off build failure and kept telemetry off for the rest of the process. + **Rule:** Never let a process-shared object (cached per host, lease-counted) capture `Handle::current()` from a per-session runtime. Spawn its background, flush and Drop work on a stored handle to a dedicated process-lifetime runtime. Do not memoize that runtime's build failure in a OnceLock: cache only success, and retry or disable on error. +- **Context:** In PR #413 the new dedicated `dbx-sql-telemetry` tokio runtime was first built without `thread_stack_size`. Its workers would then pick up the host's `RUST_MIN_STACK` (e.g. 16384), overflow during a real HTTP export, and abort the process. The C-ABI runtime already had this guard (#326/#328). The fix moved the guard into `crate::util::runtime::runtime_thread_stack_size(ambient_rust_min_stack())` and shared it between both runtimes. It sets a 2 MiB floor but does not cap the size, so a larger host value such as databricks-odbc's 3194880 is kept. + **Rule:** Every tokio runtime the kernel builds must call `.thread_stack_size(runtime_thread_stack_size(ambient_rust_min_stack()))` from `crate::util::runtime`, which treats 2 MiB as a floor and never caps a larger host value. Otherwise the embedding host's RUST_MIN_STACK can shrink kernel worker stacks and cause a stack overflow that aborts the process. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 527d35d3c3f96c11d7bdc266afbc4acca019e527 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 4 Nov 2026 07:22:27 +0000 Subject: [PATCH 43/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 8e017231..15e8784c 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -388,6 +388,10 @@ author, follow-up, and review runs. - **Context:** In PR #413 the new dedicated `dbx-sql-telemetry` tokio runtime was first built without `thread_stack_size`. Its workers would then pick up the host's `RUST_MIN_STACK` (e.g. 16384), overflow during a real HTTP export, and abort the process. The C-ABI runtime already had this guard (#326/#328). The fix moved the guard into `crate::util::runtime::runtime_thread_stack_size(ambient_rust_min_stack())` and shared it between both runtimes. It sets a 2 MiB floor but does not cap the size, so a larger host value such as databricks-odbc's 3194880 is kept. **Rule:** Every tokio runtime the kernel builds must call `.thread_stack_size(runtime_thread_stack_size(ambient_rust_min_stack()))` from `crate::util::runtime`, which treats 2 MiB as a floor and never caps a larger host value. Otherwise the embedding host's RUST_MIN_STACK can shrink kernel worker stacks and cause a stack overflow that aborts the process. +### 2026-11-04: learnings since 2026-11-03T07:20:17Z +- **Context:** In `Session::open` (PR #423), the feature-flag prefetch was the first thing to trigger OAuth, and it swallows its own errors. So a failed M2M token request (for example a 503 auth-shedding reply) was hidden there, and CreateSession then sent the same token request again. Each failed open hit an overloaded auth endpoint twice. The fix calls `http_client.auth_header()` and `auth_extra_headers()` eagerly, before the prefetch, and both later steps reuse the cached token. The regression tests count requests with wiremock `.expect(n)` plus `server.verify()`. Each test also uses its own workspace id so the process-wide feature-flag cache stays cold. + **Rule:** Run a fallible shared prerequisite such as auth or token fetch on its own, with errors propagated, before any best-effort step that swallows errors. Otherwise the failure is hidden and the next caller retries it. Test this by counting requests with wiremock `.expect(n)`, and give each test a unique cache key (for example the workspace id) so process-wide caches don't leak between tests. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 5c333939be533a84258102d81ef050ca838fa46e Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Sat, 7 Nov 2026 07:21:04 +0000 Subject: [PATCH 44/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 15e8784c..94172e52 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -392,6 +392,12 @@ author, follow-up, and review runs. - **Context:** In `Session::open` (PR #423), the feature-flag prefetch was the first thing to trigger OAuth, and it swallows its own errors. So a failed M2M token request (for example a 503 auth-shedding reply) was hidden there, and CreateSession then sent the same token request again. Each failed open hit an overloaded auth endpoint twice. The fix calls `http_client.auth_header()` and `auth_extra_headers()` eagerly, before the prefetch, and both later steps reuse the cached token. The regression tests count requests with wiremock `.expect(n)` plus `server.verify()`. Each test also uses its own workspace id so the process-wide feature-flag cache stays cold. **Rule:** Run a fallible shared prerequisite such as auth or token fetch on its own, with errors propagated, before any best-effort step that swallows errors. Otherwise the failure is hidden and the next caller retries it. Test this by counting requests with wiremock `.expect(n)`, and give each test a unique cache key (for example the workspace id) so process-wide caches don't leak between tests. +### 2026-11-07: learnings since 2026-11-06T07:20:00Z +- **Context:** PR #425 added `adbc/` as a fourth standalone Cargo workspace (alongside the kernel root, `pyo3/`, `napi/`). Review found several gaps. The license-check path filter listed `adbc/Cargo.toml` but not `adbc/Cargo.lock`, so a lockfile-only `cargo update` would skip `cargo deny`. The docs used `cargo build -p databricks-adbc`, which fails from the repo root because the crate isn't a root-workspace member. Local `make lint` ran clippy without `--features ffi`, so the feature-gated `unsafe` C entry points were never linted locally even though CI lints them. + **Rule:** Standalone sub-workspaces (adbc/, pyo3/, napi/) are invisible to root `cargo` runs. Every tool (fmt, clippy, test, deny, cyclonedx, llvm-cov) must target each one with `--manifest-path /Cargo.toml`, never `-p`. CI path filters must list both `/Cargo.toml` and `/Cargo.lock`. Local Makefile lint/test must pass the same `--features` as CI, so feature-gated code (e.g. `ffi`) gets linted locally too. +- **Context:** In PR #425, `adbc/src/cancellation.rs` had a Drop guard (`OperationGuard::drop` → `remove`) that skipped deregistration when the registry mutex was poisoned. After that, finished operations stayed registered forever, their cancel closures (which hold a kernel canceller and a runtime `Arc`) were never freed, and every later `cancel` call returned a lock error. The fix recovers the lock with `PoisonError::into_inner`. + **Rule:** Cleanup that must always happen (Drop guards, registry removal) should not skip work on a poisoned mutex. Use `lock().unwrap_or_else(PoisonError::into_inner)` so the shared state stays consistent and the resources it holds still get released. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 8dccd651e5641aab1658a0ba3fb884e0a4ec0b2c Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 10 Nov 2026 07:21:43 +0000 Subject: [PATCH 45/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 94172e52..e000e2b3 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -398,6 +398,14 @@ author, follow-up, and review runs. - **Context:** In PR #425, `adbc/src/cancellation.rs` had a Drop guard (`OperationGuard::drop` → `remove`) that skipped deregistration when the registry mutex was poisoned. After that, finished operations stayed registered forever, their cancel closures (which hold a kernel canceller and a runtime `Arc`) were never freed, and every later `cancel` call returned a lock error. The fix recovers the lock with `PoisonError::into_inner`. **Rule:** Cleanup that must always happen (Drop guards, registry removal) should not skip work on a poisoned mutex. Use `lock().unwrap_or_else(PoisonError::into_inner)` so the shared state stays consistent and the resources it holds still get released. +### 2026-11-10: learnings since 2026-11-09T07:22:05Z +- **Context:** PR #426 added a Rust ADBC `User-Agent` built from `adbc.databricks.user_agent_entry`. Review found three problems. First, a caller `User-Agent` passed through `adbc.databricks.http.headers` was accepted and then silently overwritten at `open()`. Second, an entry containing CR/LF or control characters was accepted by `set_option` but only failed later, as a generic HTTP-client build error at `new_connection()`. Non-ASCII values have the same problem, because reqwest only accepts visible ASCII. Third, the only test checked the `custom_headers` vector, not the request actually sent. The fix rejects `user-agent` in the custom-header parser, validates the entry at `set_option` with `InvalidArguments` naming the key, and adds a wiremock test that asserts the exact outbound `User-Agent` on session-create. + **Rule:** When an ADBC/binding option ends up in an HTTP header, validate it at `set_option` (reject control chars and non-visible-ASCII, return InvalidArguments naming the key). Reject driver-owned header names (User-Agent, Authorization, …) in generic custom-header options rather than silently overriding them. Test with wiremock against the real outbound request, not the intermediate config struct. +- **Context:** PR #429 added a CI workflow that dispatches the Rust ADBC integration suite only when `adbc/` changed. Review found two problems with the change detection. It used a two-dot `git diff "$pr.base.sha" "$head"`, so commits that landed on main after the PR branched counted as PR changes. The path filter also left out `src/` and `Cargo.*`, even though `adbc/` builds the kernel through `path = ".."`. + **Rule:** In PR path-filter CI, diff against the merge base (`git diff BASE...HEAD`, three dots, with fetch-depth: 0), not the moving `pull_request.base.sha`. Path filters must include path-dependency crates (the root kernel `src/`, `Cargo.toml` and `Cargo.lock` for `adbc/`, `napi/` and `pyo3/`), or skip them on purpose and say so in a comment. +- **Context:** In PR #429 the sender workflow creates an `in_progress` check run, then fires `repository_dispatch` to databricks-driver-test. Review found that `repository_dispatch` returns 204 even when no receiver workflow handles the event type, so the check stays pending forever. A pending check also blocked later retries. There were two more problems: `checks.listForRef` with no `filter` defaults to `latest` and hides older in-progress runs, and cleanup steps gated on `failure()` alone skip cancelled jobs. The fix added a dedicated rollout variable, `(failure() || cancelled())` reporters, re-labelling as an explicit retry that supersedes older checks, `filter: 'all'`, and an hourly cron that expires stale checks. + **Rule:** Treat `repository_dispatch` as fire-and-forget: a 204 does not mean a receiver ran. Any check run the sender opens needs a dedicated enable flag, a `(failure() || cancelled())` completion path, an expiry or sweeper for stuck `in_progress` checks, and `checks.listForRef` called with `filter: 'all'`. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 54b7baf19fe3d9515012ccd1b53f32a451e4c96d Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 11 Nov 2026 07:21:55 +0000 Subject: [PATCH 46/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index e000e2b3..a12cb15d 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -406,6 +406,14 @@ author, follow-up, and review runs. - **Context:** In PR #429 the sender workflow creates an `in_progress` check run, then fires `repository_dispatch` to databricks-driver-test. Review found that `repository_dispatch` returns 204 even when no receiver workflow handles the event type, so the check stays pending forever. A pending check also blocked later retries. There were two more problems: `checks.listForRef` with no `filter` defaults to `latest` and hides older in-progress runs, and cleanup steps gated on `failure()` alone skip cancelled jobs. The fix added a dedicated rollout variable, `(failure() || cancelled())` reporters, re-labelling as an explicit retry that supersedes older checks, `filter: 'all'`, and an hourly cron that expires stale checks. **Rule:** Treat `repository_dispatch` as fire-and-forget: a 204 does not mean a receiver ran. Any check run the sender opens needs a dedicated enable flag, a `(failure() || cancelled())` completion path, an expiry or sweeper for stuck `in_progress` checks, and `checks.listForRef` called with `filter: 'all'`. +### 2026-11-11: learnings since 2026-11-10T07:20:19Z +- **Context:** PR #430 made TLS certificate failures fail fast. The first version set the returned error's `retryable` flag from `strategy.is_retryable_error(&e)`. That function also applies the request's idempotency policy, so non-idempotent read timeouts and redirect errors were wrongly reported to PyO3, napi and the C ABI as `retryable=false`, and they also fed the CloudFetch short-circuit. The fix moved the flag to a separate `is_permanent_connection_error` predicate covering certificate and DNS failures, and added regression tests. + **Rule:** Keep the decision "should this client retry this request now?" (retry strategy plus idempotency) separate from the error's exported `retryable` flag ("is this failure permanent?"). Compute the flag from its own permanence predicate, and test that non-idempotent timeouts still come back with `retryable=true`. +- **Context:** PR #430 added TLS-error classification for both `tls-native` and `tls-rustls`. Reviewers found two problems. First, the backends disagreed: native-tls matched any message containing `certificate`, which included peer-sent mTLS alerts, while rustls matched only `InvalidCertificate`. Second, native-tls relied on English substrings from OpenSSL, Secure Transport and SChannel, which break on localized Windows and macOS. The fix narrowed matching to local verification failures, matched SChannel by its stable HRESULT `(os error …)` code, and moved the string predicate into a `&str` helper with positive and negative tests for each platform. + **Rule:** When classifying TLS errors, define one policy and apply it on both the native-tls and rustls backends, with tests that pin them together, including peer alerts and revocation-unavailable cases. Match on typed variants or stable OS error codes rather than message text. If text matching can't be avoided, put it in a `&str` helper that is unit-tested against OpenSSL, macOS and SChannel samples plus negative cases. +- **Context:** In PR #430, a unit test gated on `#[cfg(feature = "tls-rustls")]` (it checks `rustls::Error` nested inside `io::Error`) was never compiled or run in CI. The default `cargo test` job builds with `tls-native`, and the new rustls CI step's test filter was too narrow to include it. The fix widened the filter to `--lib client::`. + **Rule:** Whenever you add a test behind a non-default cargo feature (e.g. `tls-rustls`), confirm that some CI job builds with that feature and that its test filter actually matches the new test path. Otherwise the test silently never runs. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 86a57e80713c1e685251a3feca05a7d54f4ceb59 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 12 Nov 2026 07:22:31 +0000 Subject: [PATCH 47/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index a12cb15d..8f38a82d 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -414,6 +414,12 @@ author, follow-up, and review runs. - **Context:** In PR #430, a unit test gated on `#[cfg(feature = "tls-rustls")]` (it checks `rustls::Error` nested inside `io::Error`) was never compiled or run in CI. The default `cargo test` job builds with `tls-native`, and the new rustls CI step's test filter was too narrow to include it. The fix widened the filter to `--lib client::`. **Rule:** Whenever you add a test behind a non-default cargo feature (e.g. `tls-rustls`), confirm that some CI job builds with that feature and that its test filter actually matches the new test path. Otherwise the test silently never runs. +### 2026-11-12: learnings since 2026-11-11T07:20:49Z +- **Context:** PR #432 added `num_modified_rows` getters on `ExecutedAsyncStatement`/`AsyncStatementReader` (Rust + PyO3). The first version of the mocked regression test only checked a zero count on success and `None` on failure. The reviewer pointed out that a zero would also pass if the getter just returned a hard-coded default whenever the field was present, so a `(False, 3)` case was added. + **Rule:** When testing that a numeric field is passed through (row counts, offsets, sizes), assert a distinctive non-zero value as well as zero/absent. A zero/default-only assertion cannot catch a getter that ignores the server value. +- **Context:** PR #432. The reviewer noticed that the new async `num_modified_rows` getters raise `InvalidStatementHandle` after owner close, parent re-submit, or owner release, while `statement_id` is cached and can still be read after close. The author kept this on purpose instead of snapshotting the count, and confirmed the Python connector copies the count to `cursor.rowcount` before closing. `try_num_modified_rows` checks `check_read_validity()` both before and after reading the cached status. + **Rule:** Async statement metadata getters (other than the cached `statement_id`) must check read validity and raise `InvalidStatementHandle` after close, re-submit, or owner release. Callers/connectors must read metadata such as `num_modified_rows` before closing the handle. New getters should check validity both before and after the read, and the wiremock/PyO3 tests should cover the invalidation cases. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 851d7c077d2be0b6f980d44ce3e3c014dc08e99a Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Fri, 13 Nov 2026 07:21:43 +0000 Subject: [PATCH 48/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index 8f38a82d..d5aa9b46 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -420,6 +420,14 @@ author, follow-up, and review runs. - **Context:** PR #432. The reviewer noticed that the new async `num_modified_rows` getters raise `InvalidStatementHandle` after owner close, parent re-submit, or owner release, while `statement_id` is cached and can still be read after close. The author kept this on purpose instead of snapshotting the count, and confirmed the Python connector copies the count to `cursor.rowcount` before closing. `try_num_modified_rows` checks `check_read_validity()` both before and after reading the cached status. **Rule:** Async statement metadata getters (other than the cached `statement_id`) must check read validity and raise `InvalidStatementHandle` after close, re-submit, or owner release. Callers/connectors must read metadata such as `num_modified_rows` before closing the handle. New getters should check validity both before and after the read, and the wiremock/PyO3 tests should cover the invalidation cases. +### 2026-11-13: learnings since 2026-11-12T07:21:08Z +- **Context:** PR #436 changed CloudFetch-disable to send a `can_cloud_download=false` session conf, with the execute disposition fixed at `INLINE_OR_EXTERNAL_LINKS`. The reviewer found that the reader would still follow `external_links` if the server ignored the setting. The fix rejects them in `ResultReaderFactory` before any downloader is built. While settling the error code, the reviewer also found that `Error::invalid_state()` maps to `ErrorCode::InvalidArgument`, which callers read as a caller mistake, and that `data_loss()` overstates the problem. The PR used `Error::internal()`. The reviewer also noted that links on a continuation page still raise a different code, so one root cause can surface as two codes. + **Rule:** When a client opt-out (e.g. `cloudfetch_enabled=false`) relies on the server honouring a capability, check the response client-side and fail loudly on a violation (e.g. non-empty `external_links`). Never silently fall back to the disabled path. Report a server contract violation with one consistent `ErrorCode` on both first-page and continuation-page paths. Don't use `invalid_state()`, because it maps to `InvalidArgument`. +- **Context:** PR #436 had the kernel insert `can_cloud_download` into the CreateSession `session_conf`, but caller-supplied keys are forwarded with their original casing. A caller's `Can_Cloud_Download=true` would then go out next to the kernel's key, and the server would decide which one wins. The fix removes every case-insensitive match before inserting, and a regression test covers the mixed-case conflict. + **Rule:** When the kernel synthesizes or overrides a server-bound `session_conf` key, first remove all case-insensitive matches (`retain(|k,_| !k.eq_ignore_ascii_case(..))`). Then test that a mixed-case caller key cannot produce a duplicate or conflicting entry. +- **Context:** PR #436 brought back a `can_cloud_download` session conf that issue #196 had removed after SEA rejected it at the first ExecuteStatement with `CONFIG_NOT_AVAILABLE`. Wiremock accepts any session conf, so only a live test could show whether the server change was safe. The PR added `#[ignore]` live tests in `tests/v0_execute_e2e.rs`. `.github/workflows/rust-e2e.yml` runs these with `cargo test -- --ignored` on PRs that touch `src/**`. A wiremock test also pins the error callers see on servers without support: the session opens, then the first execute fails. + **Rule:** Wiremock cannot prove a server accepts a session conf or capability. For changes that depend on server behaviour, add an `#[ignore]` live test in `tests/v0_*_e2e.rs` (CI runs it via `--ignored`). Also add a wiremock test that pins the error on servers without support, and document whether that error appears at session open or at the first execute. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From ad8c1bc95adad1f2ffd6f2ba0af22c770f856985 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Sat, 14 Nov 2026 07:21:06 +0000 Subject: [PATCH 49/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index d5aa9b46..f6ae0c4a 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -428,6 +428,10 @@ author, follow-up, and review runs. - **Context:** PR #436 brought back a `can_cloud_download` session conf that issue #196 had removed after SEA rejected it at the first ExecuteStatement with `CONFIG_NOT_AVAILABLE`. Wiremock accepts any session conf, so only a live test could show whether the server change was safe. The PR added `#[ignore]` live tests in `tests/v0_execute_e2e.rs`. `.github/workflows/rust-e2e.yml` runs these with `cargo test -- --ignored` on PRs that touch `src/**`. A wiremock test also pins the error callers see on servers without support: the session opens, then the first execute fails. **Rule:** Wiremock cannot prove a server accepts a session conf or capability. For changes that depend on server behaviour, add an `#[ignore]` live test in `tests/v0_*_e2e.rs` (CI runs it via `--ignored`). Also add a wiremock test that pins the error on servers without support, and document whether that error appears at session open or at the first execute. +### 2026-11-14: learnings since 2026-11-13T07:20:35Z +- **Context:** PR #451 removed redundant GetStatementStatus calls. `ExecutedAsyncStatement` now keeps the terminal `ExecuteResponse` that `status()` or `await_result()` already observed, and `fetch_result()` / `await_result()` reuse it instead of polling again. The review pointed out that a status-only caller (DML, monitoring) would then hold the full response, including base64 inline `attachment` rows and the manifest, for the handle's whole lifetime. Before this change, only the small `StatementStatus` was kept. + **Rule:** When an async statement handle caches a raw SEA `ExecuteResponse` to skip a status RPC, cache only Succeeded/Closed responses and make the cache take-once (`Mutex>::take`). Clear it on error, close, Drop, owner release and client-timeout expiry, and on every new `status()` poll. Document on `status()` that a terminal observation keeps the inline payload until the result is read or the handle is closed. Don't trim or size-cap the cached response, because a partial response can't be materialised into a reader. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 1eb842b4a11e8e11ace52d8b35a7bd9a7b1f50b1 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Mon, 16 Nov 2026 07:34:15 +0000 Subject: [PATCH 50/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index f6ae0c4a..e50ec863 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -432,6 +432,18 @@ author, follow-up, and review runs. - **Context:** PR #451 removed redundant GetStatementStatus calls. `ExecutedAsyncStatement` now keeps the terminal `ExecuteResponse` that `status()` or `await_result()` already observed, and `fetch_result()` / `await_result()` reuse it instead of polling again. The review pointed out that a status-only caller (DML, monitoring) would then hold the full response, including base64 inline `attachment` rows and the manifest, for the handle's whole lifetime. Before this change, only the small `StatementStatus` was kept. **Rule:** When an async statement handle caches a raw SEA `ExecuteResponse` to skip a status RPC, cache only Succeeded/Closed responses and make the cache take-once (`Mutex>::take`). Clear it on error, close, Drop, owner release and client-timeout expiry, and on every new `status()` poll. Document on `status()` that a terminal observation keeps the inline payload until the result is read or the handle is closed. Don't trim or size-cap the cached response, because a partial response can't be materialised into a reader. +### 2026-11-16: learnings since 2026-11-15T07:20:09Z +- **Context:** PR #462 fixed napi `AsyncStatement.close()`. The canceller and the `AsyncResultHandle` result streams each held an `Arc` to the kernel session, so a closed session, and the host's shared telemetry client, stayed alive until JS garbage collection, and the next session reused that client with the wrong settings. In review, the explicit release in `close()` also had to: run from a drop guard created before the close RPC is awaited (so it still runs if the RPC errors or panics); use `try_lock` and hand off to a spawned task, not `lock().await` on a slot an in-flight fetch holds; and spawn through `Handle::try_current()`/`runtime::try_get_handle()`, because an ambient `tokio::spawn` inside `Drop` panics when no runtime is entered, and a panic during unwind aborts the process. + **Rule:** A binding `close()` must explicitly drop every child object that holds the session `Arc` (cancellers, result streams), not leave them to JS GC. Do the release in a drop guard created before the fallible await, never block close on a lock an in-flight fetch holds (`try_lock` plus a spawned waiter), and never call an ambient `tokio::spawn` from `Drop`. +- **Context:** PR #462 reviewers proposed letting an in-flight fetch notice a `closed` `AtomicBool` (Release/Acquire) after `close()` failed `try_lock` on its slot. A litmus test with the same primitives showed both sides missing each other 181 times in 3M iterations; with SeqCst fences it was 0. The fix replaced the flag handoff with a spawned task that waits for the lock and drops the stream. + **Rule:** A Release/Acquire flag handoff paired with tokio `Mutex::try_lock`/unlock is not a reliable "one side will see it" protocol: both sides can miss each other. Use SeqCst fences, or better, have the releasing side spawn a task that waits for the lock, instead of relying on the lock holder to re-check the flag. +- **Context:** PR #454 stopped CloudFetch failures from logging presigned URL credentials (`sig=`, `X-Amz-Signature`). The `Display` of `reqwest::Error` includes the full request URL, query included, and this applies to both `execute()` errors and request-build errors. The fix calls `e.url_mut().set_query(None)` before formatting, and debug request lines stop at `?`. Requests built with `RequestBuilder` move `user:pass@` into an `Authorization` header, so only a directly constructed `reqwest::Request` keeps userinfo in the URL. Server error bodies (S3 `SignatureDoesNotMatch`, and error-envelope `message` fields) can also echo the signed URL, so every arm that copies server text into an error must be redacted. + **Rule:** Never format a raw `reqwest::Error` or request URL on a path that can carry presigned or credentialed URLs: strip the query (`e.url_mut()` → `set_query(None)`) and userinfo first, on every error path (build, execute, and server-echoed body/message). A test with a fake `?sig=SECRET` should assert `SECRET` is absent from both the returned error and the captured logs. +- **Context:** PR #454's log-redaction test captures `tracing` output, so it lives in its own integration-test binary (`tests/presigned_url_logging.rs`). In the unit-test binary, tests that open a session install a process-global subscriber, which made a thread-local capture miss events. PR #462 review found a related issue: `cargo test` runs tests as threads in one process, so process-global `OnceCell`s such as the napi runtime handle get filled by whichever test runs first. + **Rule:** Tests that depend on process-global state (a `tracing` global subscriber, `OnceCell` runtime handles) are not isolated under `cargo test`, because all tests run as threads in one process. Put log-capture tests in their own `tests/*.rs` binary, and don't assume a global is unset in a unit test. +- **Context:** PR #473 (OSV remediation) meant to bump only `quinn-proto` and `quinn-udp`, but regenerating the lockfiles also quietly moved `windows-sys` 0.61→0.52 and `getrandom` 0.4→0.3 for several crates, in all three lockfiles (root, napi, pyo3). Security scans don't flag downgrades like these. + **Rule:** For dependency or security bumps, use `cargo update -p --precise ` on the repo's normal toolchain, and diff each Cargo.lock (root, `napi/`, `pyo3/`) for unrelated transitive changes before pushing. If any appear, revert them or call them out in the PR description. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.* From 9006e324e7d721dbc3b6f273265d8ce28e89d870 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 17 Nov 2026 07:23:01 +0000 Subject: [PATCH 51/51] learn: retrospective learnings Signed-off-by: peco-engineer-bot[bot] --- .claude/knowledge/learning-log.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.claude/knowledge/learning-log.md b/.claude/knowledge/learning-log.md index e50ec863..37c1ae83 100644 --- a/.claude/knowledge/learning-log.md +++ b/.claude/knowledge/learning-log.md @@ -444,6 +444,14 @@ author, follow-up, and review runs. - **Context:** PR #473 (OSV remediation) meant to bump only `quinn-proto` and `quinn-udp`, but regenerating the lockfiles also quietly moved `windows-sys` 0.61→0.52 and `getrandom` 0.4→0.3 for several crates, in all three lockfiles (root, napi, pyo3). Security scans don't flag downgrades like these. **Rule:** For dependency or security bumps, use `cargo update -p --precise ` on the repo's normal toolchain, and diff each Cargo.lock (root, `napi/`, `pyo3/`) for unrelated transitive changes before pushing. If any appear, revert them or call them out in the PR description. +### 2026-11-17: learnings since 2026-11-16T07:33:01Z +- **Context:** PR #466 (cloudfetch link prefetch). A worker was guarded by an `AtomicBool` "in progress" flag claimed with CAS. A `note_scheduled` call that bumped the consumer index while the worker was retiring lost its CAS and returned, and the worker then cleared the flag without seeing the new index. The horizon advance was silently dropped. The fix was to check the predicate before the CAS, use SeqCst on both the index bump and the flag, and have the caught-up exit clear the flag and then re-run `maybe_trigger_prefetch()`. Exits for errors or non-advancing pages (empty page with `has_more` whose continuation does not move the cursor) stay plain stops so they can't spin on the same request. + **Rule:** Lost wakeups with CAS-claimed in-progress flags: when a notifier's CAS on the flag can fail, the owner must clear the flag and then re-check the trigger predicate (SeqCst on both sides). Only re-arm on exits that are known to make progress, never on non-advancing or error exits. +- **Context:** PR #466 replaced a tokio Mutex, which was held across the whole `get_result_chunks` call including up to 900s of retries, with a single-flight page fetch. A short std mutex installs or joins a `watch` channel that carries the `Result`, and the RPC runs in a detached spawned task. Review found two problems. First, joiners adopted an in-flight attempt for a *different* chunk index and took its empty result or error as their own, which created a false hole. Second, a waiter that retried after a shared failure started a second retry budget, roughly doubling time-to-error. + **Rule:** Single-flight / request coalescing: never hold a lock across a network call. Key the in-flight attempt (e.g. by chunk index). Same-key joiners share the original result, including errors, rather than retrying. A joiner that waited on a different key must re-check state and issue its own request. Run the shared attempt in a detached task so one cancelled waiter can't abort it for the others. +- **Context:** PR #431 made `execute_direct` infer DML affected-row counts best-effort by peeking the first batch with `ResultStream::peek_first_batch`. Review found that a failed peek finalized telemetry and buffered nothing. The returned stream could then yield `Ok(None)` on the next fetch, silently losing the error and the row. The fix buffers the outcome (`Option>>`) and replays it through `next_batch`, `try_next_batch` and `into_owned_batches`. The regression reader errors exactly once and then ends, so a passing test proves the replay came from the buffer and not from a second reader failure. The synchronous `execute()` path kept its strict propagate-error contract, chosen explicitly through an enum policy. + **Rule:** A non-consuming peek must buffer errors as well as data and replay them on the caller's next read. Test it with a one-shot-error-then-EOF reader, because a reader that keeps erroring hides a lost error. Optional enrichment (such as a row count) of a server-successful statement must not turn success into an execute error or change an existing path's error contract without saying so. + --- *Add new entries above this line (oldest→newest). The retrospective inserts each new entry just above this footer.*