:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add deltalite streaming partition upsert crate (#73588)
Tom Owers87487312bedd
diff --git a/.github/workflows/ci-deltalite-python.yml b/.github/workflows/ci-deltalite-python.ymlnew file mode 100644index 000000000000..cb641d3663e5--- /dev/null+++ b/.github/workflows/ci-deltalite-python.yml@@ -0,0 +1,98 @@+name: Deltalite Python tests++# The differential parity suite for rust/deltalite: the same batch sequences run+# through the real delta-rs Python `merge` (as `DeltaTableHelper` drives it) and+# through `deltalite.upsert`, asserting identical logical table content. This is+# the compatibility check that replaces version-lockstep between the `deltalake`+# Rust crate and the `deltalake` Python package (see rust/deltalite/README.md).+#+# ci-rust.yml covers the crates' build/lint/test; this workflow adds the thing+# cargo cannot do -- build the actual wheel with maturin and run the Python+# suite against the repo's pinned deltalake/pyarrow versions.++on:+ pull_request:+ paths:+ - rust/deltalite/**+ - .github/workflows/ci-deltalite-python.yml+ # The parity suite runs against the repo's pinned deltalake/pyarrow/duckdb, so+ # re-run it whenever those pins move.+ - pyproject.toml+ - uv.lock+ push:+ branches:+ - master+ paths:+ - rust/deltalite/**+ - .github/workflows/ci-deltalite-python.yml+ - pyproject.toml+ - uv.lock++concurrency:+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read++jobs:+ test:+ name: Build wheel and run parity suite+ runs-on: depot-ubuntu-22.04-4+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ sparse-checkout: |+ rust/+ pyproject.toml+ sparse-checkout-cone-mode: false+ clean: false++ - name: Install rust+ uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9+ with:+ toolchain: 1.91.1+ components: clippy,rustfmt++ - name: Cache Rust dependencies+ uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2.8.2+ with:+ shared-key: 'v1-deltalite-python'+ workspaces: rust+ save-if: ${{ github.ref == 'refs/heads/master' }}++ - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0+ with:+ python-version: '3.13'++ - name: Install uv+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ with:+ version: '0.11.28' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit++ - name: Create venv with test dependencies+ # Versions are read straight from the repo's pyproject.toml so parity is+ # asserted against exactly what production installs -- no second copy of the+ # pins here to silently drift. pyproject.toml/uv.lock are in this workflow's+ # path filter, so a pin bump re-runs the suite.+ run: |+ uv venv .venv-deltalite --python 3.13+ pin() { grep -oE "\"${1}[^\"]*\"" pyproject.toml | tr -d '"' | head -1; }+ DELTALAKE=$(pin 'deltalake\[pyarrow\]==')+ PYARROW=$(pin 'pyarrow==')+ DUCKDB=$(pin 'duckdb~=')+ echo "Resolved pins: $DELTALAKE $PYARROW $DUCKDB"+ test -n "$DELTALAKE" && test -n "$PYARROW" && test -n "$DUCKDB" \+ || { echo "failed to resolve a pin from pyproject.toml" >&2; exit 1; }+ VIRTUAL_ENV=$PWD/.venv-deltalite uv pip install \+ maturin pytest \+ "$DELTALAKE" "$PYARROW" "$DUCKDB"++ - name: Build and install the extension+ run: |+ VIRTUAL_ENV=$PWD/.venv-deltalite .venv-deltalite/bin/python -m maturin develop \+ --release --manifest-path rust/deltalite/python/Cargo.toml++ - name: Run pytest+ run: .venv-deltalite/bin/python -m pytest rust/deltalite/python/tests -qdiff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex 7fe1d45a06b1..8be4a491b6b2 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -139,6 +139,9 @@ jobs:"cyclotron-janitor": 139,"cyclotron-node": 31,"cymbal": 168,+ # Compile-heavy (deltalake dependency tree), light tests.+ "deltalite-core": 180,+ "deltalite-python": 60,"embedding-worker": 25,"feature-flags": 181,"health": 27,diff --git a/pyproject.toml b/pyproject.tomlindex 646fcd5c57a1..d3de74b2a8c5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -371,6 +371,11 @@ select = [# descriptors into the pool before AddSerializedFile() — ruff must not strip them."posthog/personhog_client/proto/generated/**/*.pyi" = ["F401"]"posthog/personhog_client/proto/generated/**/*_pb2.py" = ["F401", "E402"]+# deltalite's test suite bootstraps its harness/planner via sys.path (the package is a+# maturin-built extension living under rust/, not part of the Django app), so imports+# are necessarily lazy / post-path-insert (PLC0415, E402); the planner's small CLI+# prints its report (T201).+"rust/deltalite/python/**" = ["PLC0415", "E402", "T201"]# Django settings aggregator: star imports are how settings modules merge into one namespace.# Not portable to explicit re-exports without losing the settings-loading semantics."posthog/settings/**" = ["F403", "F405"]@@ -450,7 +455,9 @@ ignore_missing_imports = trueexclude_gitignore = true# conftest.py: the root pytest bootstrap collides with services/stripe-mock/tests/conftest.py# (both resolve to top-level module "conftest")-exclude = ["^(bin/.*|tools/.*|products/[^/]+/skills/[^/]+/scripts/.*|gunicorn\\.config\\.py|manage\\.py|conftest\\.py)$"]+# rust/deltalite/python: pytest suite for the maturin-built extension; nothing Django+# imports it and it has its own CI (ci-deltalite-python.yml).+exclude = ["^(bin/.*|tools/.*|rust/deltalite/python/.*|products/[^/]+/skills/[^/]+/scripts/.*|gunicorn\\.config\\.py|manage\\.py|conftest\\.py)$"][[tool.mypy.overrides]]module = "bin.*"@@ -486,6 +493,7 @@ exclude = ["posthog/schema_enums.py","posthog/temporal/proxy_service/proto/**","products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/**",+ "rust/deltalite/python/**",]# ---------------------------------------------------------------------------diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex bb2e603bff49..595da6b1352c 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -66,6 +66,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"dependencies = ["cfg-if",+ "const-random","getrandom 0.3.4","once_cell","version_check",@@ -190,7 +191,7 @@ checksum = "36fa98bc79671c7981272d91a8753a928ff6a1cd8e4f20a44c45bd5d313840bf"dependencies = ["bigdecimal","bon",- "digest",+ "digest 0.10.7","log","miniz_oxide","num-bigint",@@ -240,6 +241,241 @@ version = "0.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"+[[package]]+name = "arrow"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6cfdd0833e32a9874d2b55089333ad310c0be208aafa277385ce2461dec90be3"+dependencies = [+ "arrow-arith",+ "arrow-array",+ "arrow-buffer",+ "arrow-cast",+ "arrow-csv",+ "arrow-data",+ "arrow-ipc",+ "arrow-json",+ "arrow-ord",+ "arrow-pyarrow",+ "arrow-row",+ "arrow-schema",+ "arrow-select",+ "arrow-string",+]++[[package]]+name = "arrow-arith"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0a41203398f0eaa6f7ec8e62c0da742a21abf282c148fc157f6c35c90e29981a"+dependencies = [+ "arrow-array",+ "arrow-buffer",+ "arrow-data",+ "arrow-schema",+ "chrono",+ "num-traits",+]++[[package]]+name = "arrow-array"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae33dad492b7df00a217563a7b0ef2874df68a0deea1b1a3acf628152f7f7a69"+dependencies = [+ "ahash 0.8.12",+ "arrow-buffer",+ "arrow-data",+ "arrow-schema",+ "chrono",+ "chrono-tz",+ "half",+ "hashbrown 0.17.1",+ "num-complex",+ "num-integer",+ "num-traits",+]++[[package]]+name = "arrow-buffer"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9552f96391c005e6ab449fa941420935e7e062489b12b8b1b08879b2163f5b5"+dependencies = [+ "bytes",+ "half",+ "num-bigint",+ "num-traits",+]++[[package]]+name = "arrow-cast"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a8a327c9649f30d8406995f27642b68df354713cca3baaaf100f076f18d5f34"+dependencies = [+ "arrow-array",+ "arrow-buffer",+ "arrow-data",+ "arrow-ord",+ "arrow-schema",+ "arrow-select",+ "atoi",+ "base64 0.22.1",+ "chrono",+ "half",+ "lexical-core",+ "num-traits",+ "ryu",+]++[[package]]+name = "arrow-csv"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af0dd6d90d1955e9f9a014c1e563ee8aeffc21909085d25623e1da44d96eca26"+dependencies = [+ "arrow-array",+ "arrow-cast",+ "arrow-schema",+ "chrono",+ "csv",+ "csv-core",+ "regex",+]++[[package]]+name = "arrow-data"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b24852db04738907e06c04ea61e42fe7fda962a34513022dc0d0e754fb7976b"+dependencies = [+ "arrow-buffer",+ "arrow-schema",+ "half",+ "num-integer",+ "num-traits",+]++[[package]]+name = "arrow-ipc"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29a908a11fcfb3fb2f6730f4ac15e367bc644e419155e96238f68cf3adde572b"+dependencies = [+ "arrow-array",+ "arrow-buffer",+ "arrow-data",+ "arrow-schema",+ "arrow-select",+ "flatbuffers",+]++[[package]]+name = "arrow-json"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8a96aed3931c076adee39ec2a40d8219fc7f09e79bcdaca1df16272993e1e14"+dependencies = [+ "arrow-array",+ "arrow-buffer",+ "arrow-cast",+ "arrow-ord",+ "arrow-schema",+ "arrow-select",+ "chrono",+ "half",+ "indexmap 2.13.0",+ "itoa",+ "lexical-core",+ "memchr",+ "num-traits",+ "ryu",+ "serde_core",+ "serde_json",+ "simdutf8",+]++[[package]]+name = "arrow-ord"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63a083ec750f5c043f02946b4baf05fcdbb55f4560a3277055caca5cc99f3eb0"+dependencies = [+ "arrow-array",+ "arrow-buffer",+ "arrow-data",+ "arrow-schema",+ "arrow-select",+]++[[package]]+name = "arrow-pyarrow"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ffb9be5a873590f825aef50df20e0f8dff5fd42a77058e28bbe7bd44bb53dec"+dependencies = [+ "arrow-array",+ "arrow-data",+ "arrow-schema",+ "pyo3",+]++[[package]]+name = "arrow-row"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "514ba0ef0d4c5896202dae736251ce415abb43a950bed570fb7981b8716c0e4c"+dependencies = [+ "arrow-array",+ "arrow-buffer",+ "arrow-data",+ "arrow-schema",+ "half",+]++[[package]]+name = "arrow-schema"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "21ca356ad6425cecb6eb7b28e4f659f1ee7880fbb1a16127de7dd62901efee9e"+dependencies = [+ "bitflags 2.11.0",+ "serde",+ "serde_core",+]++[[package]]+name = "arrow-select"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c58da39eb3d8350ad4a549e5c2bc49284dac554016c69829310350f1731b0aad"+dependencies = [+ "ahash 0.8.12",+ "arrow-array",+ "arrow-buffer",+ "arrow-data",+ "arrow-schema",+ "num-traits",+]++[[package]]+name = "arrow-string"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6789b388467525e3271326b6b4915666ecfdf5142aef09779445c954b67543c"+dependencies = [+ "arrow-array",+ "arrow-buffer",+ "arrow-data",+ "arrow-schema",+ "arrow-select",+ "memchr",+ "num-traits",+ "regex",+ "regex-syntax",+]+[[package]]name = "ascii"version = "1.1.0"@@ -565,8 +801,8 @@ dependencies = ["aws-sdk-ssooidc","aws-sdk-sts","aws-smithy-async",- "aws-smithy-http 0.63.5",- "aws-smithy-json 0.62.4",+ "aws-smithy-http 0.63.6",+ "aws-smithy-json 0.62.7","aws-smithy-runtime","aws-smithy-runtime-api","aws-smithy-types",@@ -585,9 +821,9 @@ dependencies = [[[package]]name = "aws-credential-types"-version = "1.2.13"+version = "1.2.14"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6d203b0bf2626dcba8665f5cd0871d7c2c0930223d6b6be9097592fea21242d0"+checksum = "8f20799b373a1be121fe3005fba0c2090af9411573878f224df44b42727fcaf7"dependencies = ["aws-smithy-async","aws-smithy-runtime-api",@@ -619,15 +855,15 @@ dependencies = [[[package]]name = "aws-runtime"-version = "1.7.1"+version = "1.7.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ede2ddc593e6c8acc6ce3358c28d6677a6dc49b65ba4b37a2befe14a11297e75"+checksum = "6c9b9de216a988dd54b754a82a7660cfe14cee4f6782ae4524470972fa0ccb39"dependencies = ["aws-credential-types","aws-sigv4","aws-smithy-async","aws-smithy-eventstream",- "aws-smithy-http 0.63.5",+ "aws-smithy-http 0.63.6","aws-smithy-runtime","aws-smithy-runtime-api","aws-smithy-types",@@ -645,6 +881,31 @@ dependencies = ["uuid",]+[[package]]+name = "aws-sdk-dynamodb"+version = "1.116.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c937c55ae3030bec4431c0d9146e33d2b3e5f54bb47ed32597068200c56affc"+dependencies = [+ "arc-swap",+ "aws-credential-types",+ "aws-runtime",+ "aws-smithy-async",+ "aws-smithy-http 0.63.6",+ "aws-smithy-json 0.62.7",+ "aws-smithy-observability",+ "aws-smithy-runtime",+ "aws-smithy-runtime-api",+ "aws-smithy-types",+ "aws-types",+ "bytes",+ "fastrand",+ "http 0.2.12",+ "http 1.4.0",+ "regex-lite",+ "tracing",+]+[[package]]name = "aws-sdk-s3"version = "1.119.0"@@ -667,14 +928,14 @@ dependencies = ["bytes","fastrand","hex",- "hmac",+ "hmac 0.12.1","http 0.2.12","http 1.4.0","http-body 0.4.6","lru","percent-encoding","regex-lite",- "sha2",+ "sha2 0.10.9","tracing","url",]@@ -688,8 +949,8 @@ dependencies = ["aws-credential-types","aws-runtime","aws-smithy-async",- "aws-smithy-http 0.63.5",- "aws-smithy-json 0.62.4",+ "aws-smithy-http 0.63.6",+ "aws-smithy-json 0.62.7","aws-smithy-observability","aws-smithy-runtime","aws-smithy-runtime-api",@@ -712,8 +973,8 @@ dependencies = ["aws-credential-types","aws-runtime","aws-smithy-async",- "aws-smithy-http 0.63.5",- "aws-smithy-json 0.62.4",+ "aws-smithy-http 0.63.6",+ "aws-smithy-json 0.62.7","aws-smithy-observability","aws-smithy-runtime","aws-smithy-runtime-api",@@ -729,15 +990,16 @@ dependencies = [[[package]]name = "aws-sdk-sts"-version = "1.99.0"+version = "1.107.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9acba7c62f3d4e2408fa998a3a8caacd8b9a5b5549cf36e2372fbdae329d5449"+checksum = "3d0d328ba962af23ecfa3c9f23b98d3d35e325fa218d7f13d17a6bf522f8a560"dependencies = [+ "arc-swap","aws-credential-types","aws-runtime","aws-smithy-async",- "aws-smithy-http 0.63.5",- "aws-smithy-json 0.62.4",+ "aws-smithy-http 0.63.6",+ "aws-smithy-json 0.62.7","aws-smithy-observability","aws-smithy-query","aws-smithy-runtime",@@ -754,26 +1016,25 @@ dependencies = [[[package]]name = "aws-sigv4"-version = "1.4.1"+version = "1.4.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "37411f8e0f4bea0c3ca0958ce7f18f6439db24d555dbd809787262cd00926aa9"+checksum = "bae38512beae0ffee7010fc24e7a8a123c53efdfef42a61e80fda4882418dc71"dependencies = ["aws-credential-types","aws-smithy-eventstream",- "aws-smithy-http 0.63.5",+ "aws-smithy-http 0.63.6","aws-smithy-runtime-api","aws-smithy-types","bytes",- "crypto-bigint 0.5.5",+ "crypto-bigint","form_urlencoded","hex",- "hmac",+ "hmac 0.13.0","http 0.2.12","http 1.4.0","p256","percent-encoding",- "ring 0.17.14",- "sha2",+ "sha2 0.11.0","subtle","time","tracing",@@ -782,9 +1043,9 @@ dependencies = [[[package]]name = "aws-smithy-async"-version = "1.2.13"+version = "1.2.14"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5cc50d0f63e714784b84223abd7abbc8577de8c35d699e0edd19f0a88a08ae13"+checksum = "2ffcaf626bdda484571968400c326a244598634dc75fd451325a54ad1a59acfc"dependencies = ["futures-util","pin-project-lite",@@ -807,15 +1068,15 @@ dependencies = ["md-5","pin-project-lite","sha1",- "sha2",+ "sha2 0.10.9","tracing",][[package]]name = "aws-smithy-eventstream"-version = "0.60.19"+version = "0.60.21"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1c0b3e587fbaa5d7f7e870544508af8ce82ea47cd30376e69e1e37c4ac746f79"+checksum = "78d8391e65fcea47c586a22e1a41f173b38615b112b2c6b7a44e80cec3e6b706"dependencies = ["aws-smithy-types","bytes",@@ -846,9 +1107,9 @@ dependencies = [[[package]]name = "aws-smithy-http"-version = "0.63.5"+version = "0.63.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d619373d490ad70966994801bc126846afaa0d1ee920697a031f0cf63f2568e7"+checksum = "ba1ab2dc1c2c3749ead27180d333c42f11be8b0e934058fb4b2258ee8dbe5231"dependencies = ["aws-smithy-runtime-api","aws-smithy-types",@@ -867,9 +1128,9 @@ dependencies = [[[package]]name = "aws-smithy-http-client"-version = "1.1.11"+version = "1.1.13"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "00ccbb08c10f6bcf912f398188e42ee2eab5f1767ce215a02a73bc5df1bbdd95"+checksum = "5c3ef8931ad1c98aa6a55b4256f847f3116090819844e0dd41ea682cac5dd2d3"dependencies = ["aws-smithy-async","aws-smithy-runtime-api",@@ -906,27 +1167,29 @@ dependencies = [[[package]]name = "aws-smithy-json"-version = "0.62.4"+version = "0.62.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "27b3a779093e18cad88bbae08dc4261e1d95018c4c5b9356a52bcae7c0b6e9bb"+checksum = "701a947f4797e52a911e114a898667c746c39feea467bbd1abd7b3721f702ffa"dependencies = [+ "aws-smithy-runtime-api",+ "aws-smithy-schema","aws-smithy-types",][[package]]name = "aws-smithy-observability"-version = "0.2.5"+version = "0.2.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4d3f39d5bb871aaf461d59144557f16d5927a5248a983a40654d9cf3b9ba183b"+checksum = "a06c2315d173edbf1920da8ba3a7189695827002e4c0fc961973ab1c54abca9c"dependencies = ["aws-smithy-runtime-api",][[package]]name = "aws-smithy-query"-version = "0.60.14"+version = "0.60.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "05f76a580e3d8f8961e5d48763214025a2af65c2fa4cd1fb7f270a0e107a71b0"+checksum = "1a56d79744fb3edb5d722ef79d86081e121d3b9422cb209eb03aea6aa4f21ebd"dependencies = ["aws-smithy-types","urlencoding",@@ -934,15 +1197,16 @@ dependencies = [[[package]]name = "aws-smithy-runtime"-version = "1.10.2"+version = "1.11.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "22ccf7f6eba8b2dcf8ce9b74806c6c185659c311665c4bf8d6e71ebd454db6bf"+checksum = "b8e6f5caf6fea86f8c2206541ab5857cfcda9013426cdbe8fa0098b9e2d32182"dependencies = ["aws-smithy-async",- "aws-smithy-http 0.63.5",+ "aws-smithy-http 0.63.6","aws-smithy-http-client","aws-smithy-observability","aws-smithy-runtime-api",+ "aws-smithy-schema","aws-smithy-types","bytes","fastrand",@@ -959,11 +1223,12 @@ dependencies = [[[package]]name = "aws-smithy-runtime-api"-version = "1.11.5"+version = "1.12.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b4af6e5def28be846479bbeac55aa4603d6f7986fc5da4601ba324dd5d377516"+checksum = "9db177daa6ba8afb9ee1aefcf548c907abcf52065e394ee11a92780057fe0e8c"dependencies = ["aws-smithy-async",+ "aws-smithy-runtime-api-macros","aws-smithy-types","bytes","http 0.2.12",@@ -974,11 +1239,33 @@ dependencies = ["zeroize",]+[[package]]+name = "aws-smithy-runtime-api-macros"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d7396fd9500589e62e460e987ecb671bad374934e55ec3b5f498cc7a8a8a7b7"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "aws-smithy-schema"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7442cb268338f0eb8278140a107c046756aa01093d8ef5e99628d34ae09c94f5"+dependencies = [+ "aws-smithy-runtime-api",+ "aws-smithy-types",+ "http 1.4.0",+]+[[package]]name = "aws-smithy-types"-version = "1.4.5"+version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8ca2734c16913a45343b37313605d84e7d8b34a4611598ce1d25b35860a2bed3"+checksum = "32b42fcf341259d85ca10fac9a2f6448a8ec691c6955a18e45bc3b71a85fab85"dependencies = ["base64-simd","bytes",@@ -1002,22 +1289,23 @@ dependencies = [[[package]]name = "aws-smithy-xml"-version = "0.60.14"+version = "0.60.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b53543b4b86ed43f051644f704a98c7291b3618b67adf057ee77a366fa52fcaa"+checksum = "0ce02add1aa3677d022f8adf81dcbe3046a95f17a1b1e8979c145cd21d3d22b3"dependencies = ["xmlparser",][[package]]name = "aws-types"-version = "1.3.13"+version = "1.3.16"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0470cc047657c6e286346bdf10a8719d26efd6a91626992e0e64481e44323e96"+checksum = "d16bf10b03a3c01e6b3b7d47cd964e873ffe9e7d4e80fad16bd4c077cb068531"dependencies = ["aws-credential-types","aws-smithy-async","aws-smithy-runtime-api",+ "aws-smithy-schema","aws-smithy-types","rustc_version","tracing",@@ -1217,6 +1505,16 @@ dependencies = ["rand 0.8.5",]+[[package]]+name = "backon"+version = "1.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef"+dependencies = [+ "fastrand",+ "tokio",+]+[[package]]name = "backtrace"version = "0.3.76"@@ -1234,9 +1532,9 @@ dependencies = [[[package]]name = "base16ct"-version = "0.1.1"+version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce"+checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"[[package]]name = "base64"@@ -1468,6 +1766,15 @@ dependencies = ["generic-array",]+[[package]]+name = "block-buffer"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"+dependencies = [+ "hybrid-array",+]+[[package]]name = "block-padding"version = "0.3.3"@@ -1689,6 +1996,50 @@ version = "3.20.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"+[[package]]+name = "buoyant_kernel"+version = "0.22.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2235eb320cd7178862a32dd111bd0c0f71a368e393add4914c50129add478eab"+dependencies = [+ "arrow",+ "buoyant_kernel_derive",+ "bytes",+ "chrono",+ "crc",+ "futures",+ "indexmap 2.13.0",+ "itertools 0.14.0",+ "object_store",+ "parquet",+ "percent-encoding",+ "rand 0.9.2",+ "reqwest 0.13.4",+ "roaring",+ "rustc_version",+ "serde",+ "serde_json",+ "strum 0.27.2",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "tracing-subscriber",+ "url",+ "uuid",+ "z85",+]++[[package]]+name = "buoyant_kernel_derive"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d5cdc90bb920438aa9a39089b76f0614183af303f181bf18d05b456a30dd9740"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "bytecheck"version = "0.6.12"@@ -1819,7 +2170,7 @@ dependencies = ["flate2","futures","hex",- "hmac",+ "hmac 0.12.1","http-body-util","httparse","hyper 1.9.0",@@ -1846,7 +2197,7 @@ dependencies = ["serde","serde_json","serde_urlencoded",- "sha2",+ "sha2 0.10.9","thiserror 2.0.18","time","tokio",@@ -2092,7 +2443,7 @@ version = "0.4.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"dependencies = [- "crypto-common",+ "crypto-common 0.1.7","inout",]@@ -2169,7 +2520,7 @@ dependencies = ["hyper 1.9.0","hyper-rustls 0.27.7","hyper-util",- "lz4_flex",+ "lz4_flex 0.11.5","quanta 0.12.6","replace_with","rustls 0.23.37",@@ -2204,6 +2555,12 @@ dependencies = ["cc",]+[[package]]+name = "cmov"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"+[[package]]name = "cmsketch"version = "0.2.4"@@ -2222,7 +2579,7 @@ dependencies = ["petgraph 0.8.3","serde","serde_json",- "sha2",+ "sha2 0.10.9","sqlx","thiserror 2.0.18","tracing",@@ -2329,7 +2686,7 @@ dependencies = ["rocksdb","serde","serde_json",- "sha2",+ "sha2 0.10.9","sqlx","tempfile","thiserror 2.0.18",@@ -2487,7 +2844,7 @@ dependencies = ["serde","serde-pickle","serde_json",- "sha2",+ "sha2 0.10.9","thiserror 2.0.18","tokio","tracing",@@ -2681,12 +3038,47 @@ version = "0.9.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"+[[package]]+name = "const-oid"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"++[[package]]+name = "const-random"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"+dependencies = [+ "const-random-macro",+]++[[package]]+name = "const-random-macro"+version = "0.1.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"+dependencies = [+ "getrandom 0.2.17",+ "once_cell",+ "tiny-keccak",+]+[[package]]name = "constant_time_eq"version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6"+[[package]]+name = "convert_case"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db05ffb6856bf0ecdf6367558a76a0e8a77b1713044eb92845c692100ed50190"+dependencies = [+ "unicode-segmentation",+]+[[package]]name = "convert_case"version = "0.10.0"@@ -2782,7 +3174,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6ddc2d09feefeee8bd78101665bd8645637828fa9317f9f292496dbbd8c65ff3"dependencies = ["crc",- "digest",+ "digest 0.10.7","rand 0.9.2","regex","rustversion",@@ -2892,9 +3284,9 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"[[package]]name = "crypto-bigint"-version = "0.4.9"+version = "0.5.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ef2b4b23cddf68b89b8f8069890e8c270d54e2d5fe1b143820234805e4cb17ef"+checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"dependencies = ["generic-array","rand_core 0.6.4",@@ -2903,23 +3295,22 @@ dependencies = [][[package]]-name = "crypto-bigint"-version = "0.5.5"+name = "crypto-common"+version = "0.1.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"dependencies = [- "rand_core 0.6.4",- "subtle",+ "generic-array",+ "typenum",][[package]]name = "crypto-common"-version = "0.1.7"+version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"dependencies = [- "generic-array",- "typenum",+ "hybrid-array",][[package]]@@ -2943,6 +3334,32 @@ dependencies = ["memchr",]+[[package]]+name = "ctor"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83cf0d42651b16c6dfe68685716d18480d18a9c39c62d76e8cf3eb6ed5d8bcbf"+dependencies = [+ "ctor-proc-macro",+ "dtor",+ "link-section",+]++[[package]]+name = "ctor-proc-macro"+version = "0.0.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a949c44fcacbbbb7ada007dc7acb34603dd97cd47de5d054f2b6493ecebb483"++[[package]]+name = "ctutils"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"+dependencies = [+ "cmov",+]+[[package]]name = "cyclotron-core"version = "0.1.0"@@ -3040,7 +3457,7 @@ dependencies = ["semver","serde","serde_json",- "sha2",+ "sha2 0.10.9","sourcemap","sqlx","subtle",@@ -3240,13 +3657,145 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "26bf8fc351c5ed29b5c2f0cbbac1b209b74f60ecd62e675a998df72c49af5204"[[package]]-name = "der"-version = "0.6.1"+name = "deltalake"+version = "0.32.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de"+checksum = "2695b91fd02afd5b4726a190fd58019674492d824e30598391390b0307644da8"dependencies = [- "const-oid",- "zeroize",+ "buoyant_kernel",+ "ctor",+ "deltalake-aws",+ "deltalake-core",+]++[[package]]+name = "deltalake-aws"+version = "0.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3ef837d5d58bb0cd62dc9ee3bc201805751090f4bab2ca0ff09669661814fd4"+dependencies = [+ "async-trait",+ "aws-config",+ "aws-credential-types",+ "aws-sdk-dynamodb",+ "aws-sdk-sts",+ "aws-smithy-runtime-api",+ "backon",+ "bytes",+ "chrono",+ "deltalake-core",+ "futures",+ "object_store",+ "regex",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "typed-builder",+ "url",+ "uuid",+]++[[package]]+name = "deltalake-core"+version = "0.32.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4588e95ff3b2ccdba56d9ec262bd3467c0593000f729402528706f62be8be1ca"+dependencies = [+ "arrow",+ "arrow-arith",+ "arrow-array",+ "arrow-buffer",+ "arrow-cast",+ "arrow-ipc",+ "arrow-json",+ "arrow-ord",+ "arrow-row",+ "arrow-schema",+ "arrow-select",+ "async-trait",+ "buoyant_kernel",+ "bytes",+ "cfg-if",+ "chrono",+ "dashmap 6.1.0",+ "deltalake-derive",+ "dirs",+ "either",+ "futures",+ "humantime",+ "indexmap 2.13.0",+ "itertools 0.14.0",+ "num_cpus",+ "object_store",+ "parking_lot",+ "parquet",+ "percent-encoding",+ "percent-encoding-rfc3986",+ "pin-project-lite",+ "rand 0.10.2",+ "regex",+ "serde",+ "serde_json",+ "sqlparser",+ "strum 0.27.2",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "url",+ "uuid",+ "validator",+]++[[package]]+name = "deltalake-derive"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d5a646e2b05608db1e5f91e75b6af841d92294ea0864789bb01f3f818e5f7b25"+dependencies = [+ "convert_case 0.9.0",+ "itertools 0.14.0",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "deltalite-core"+version = "0.1.0"+dependencies = [+ "arrow-array",+ "arrow-buffer",+ "arrow-cast",+ "arrow-data",+ "arrow-row",+ "arrow-schema",+ "arrow-select",+ "async-trait",+ "bytes",+ "deltalake",+ "futures",+ "metrics",+ "object_store",+ "parquet",+ "serde_json",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "uuid",+]++[[package]]+name = "deltalite-python"+version = "0.1.0"+dependencies = [+ "arrow",+ "arrow-array",+ "arrow-schema",+ "deltalake",+ "deltalite-core",+ "pyo3",+ "serde_json",+ "tokio",][[package]]@@ -3255,7 +3804,7 @@ version = "0.7.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"dependencies = [- "const-oid",+ "const-oid 0.9.6","pem-rfc7468","zeroize",]@@ -3327,7 +3876,7 @@ version = "2.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"dependencies = [- "convert_case",+ "convert_case 0.10.0","proc-macro2","quote","rustc_version",@@ -3367,12 +3916,33 @@ version = "0.10.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = [- "block-buffer",- "const-oid",- "crypto-common",+ "block-buffer 0.10.4",+ "const-oid 0.9.6",+ "crypto-common 0.1.7","subtle",]+[[package]]+name = "digest"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"+dependencies = [+ "block-buffer 0.12.1",+ "const-oid 0.10.2",+ "crypto-common 0.2.2",+ "ctutils",+]++[[package]]+name = "dirs"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"+dependencies = [+ "dirs-sys",+]+[[package]]name = "dirs-next"version = "2.0.0"@@ -3383,6 +3953,18 @@ dependencies = ["dirs-sys-next",]+[[package]]+name = "dirs-sys"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"+dependencies = [+ "libc",+ "option-ext",+ "redox_users 0.5.2",+ "windows-sys 0.61.2",+]+[[package]]name = "dirs-sys-next"version = "0.1.2"@@ -3390,7 +3972,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d"dependencies = ["libc",- "redox_users",+ "redox_users 0.4.6","winapi",]@@ -3438,6 +4020,21 @@ version = "0.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1"+[[package]]+name = "dtor"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edf234dd1594d6dd434a8fb8cada51ddbbc593e40e4a01556a0b31c62da2775b"+dependencies = [+ "dtor-proc-macro",+]++[[package]]+name = "dtor-proc-macro"+version = "0.0.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2647271c92754afcb174e758003cfd1cbf1e43e5a7853d7b1813e63e19e39a73"+[[package]]name = "dunce"version = "1.0.5"@@ -3452,14 +4049,16 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"[[package]]name = "ecdsa"-version = "0.14.8"+version = "0.16.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c"+checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"dependencies = [- "der 0.6.1",+ "der",+ "digest 0.10.7","elliptic-curve","rfc6979",- "signature 1.6.4",+ "signature",+ "spki",][[package]]@@ -3494,18 +4093,18 @@ dependencies = [[[package]]name = "elliptic-curve"-version = "0.12.3"+version = "0.13.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3"+checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"dependencies = ["base16ct",- "crypto-bigint 0.4.9",- "der 0.6.1",- "digest",+ "crypto-bigint",+ "digest 0.10.7","ff","generic-array","group",- "pkcs8 0.9.0",+ "pem-rfc7468",+ "pkcs8","rand_core 0.6.4","sec1","subtle",@@ -3885,7 +4484,7 @@ dependencies = ["serde-pickle","serde_json","sha1",- "sha2",+ "sha2 0.10.9","sqlx","strum 0.28.0","subtle",@@ -3914,9 +4513,9 @@ dependencies = ["byteorder","cbc","getrandom 0.2.17",- "hmac",+ "hmac 0.12.1","openssl",- "sha2",+ "sha2 0.10.9","subtle","zeroize",]@@ -3934,9 +4533,9 @@ dependencies = [[[package]]name = "ff"-version = "0.12.1"+version = "0.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d013fc25338cc558c5c2cfbad646908fb23591e2404481826742b651c9af7160"+checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"dependencies = ["rand_core 0.6.4","subtle",@@ -4012,6 +4611,16 @@ dependencies = ["uuid",]+[[package]]+name = "flatbuffers"+version = "25.12.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3"+dependencies = [+ "bitflags 2.11.0",+ "rustc_version",+]+[[package]]name = "flate2"version = "1.1.9"@@ -4381,6 +4990,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"dependencies = ["typenum","version_check",+ "zeroize",][[package]]@@ -4506,9 +5116,9 @@ dependencies = [[[package]]name = "group"-version = "0.12.1"+version = "0.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5dfbfb3a6cfbd390d5c9564ab283a0349b9b9fcd46a706c1eb10e0db70bfbac7"+checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"dependencies = ["ff","rand_core 0.6.4",@@ -4612,6 +5222,7 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"dependencies = ["cfg-if","crunchy",+ "num-traits","zerocopy",]@@ -4667,6 +5278,12 @@ dependencies = ["foldhash 0.2.0",]+[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+[[package]]name = "hashlink"version = "0.10.0"@@ -4749,7 +5366,7 @@ version = "0.12.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"dependencies = [- "hmac",+ "hmac 0.12.1",][[package]]@@ -4758,7 +5375,16 @@ version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"dependencies = [- "digest",+ "digest 0.10.7",+]++[[package]]+name = "hmac"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"+dependencies = [+ "digest 0.11.3",][[package]]@@ -4776,7 +5402,7 @@ dependencies = ["base64 0.22.1","chrono","chrono-tz",- "hmac",+ "hmac 0.12.1","indexmap 2.13.0","md-5","once_cell",@@ -4785,7 +5411,7 @@ dependencies = ["regex","serde","serde_json",- "sha2",+ "sha2 0.10.9","thiserror 2.0.18",]@@ -4922,7 +5548,16 @@ dependencies = [name = "humantime"version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"+checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"++[[package]]+name = "hybrid-array"+version = "0.4.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3944cf8cf766b40e2a1a333ee5e9b563f854d5fa49d6a8ca2764e97c6eddb214"+dependencies = [+ "typenum",+][[package]]name = "hyper"@@ -5515,6 +6150,12 @@ dependencies = ["cfg-if",]+[[package]]+name = "integer-encoding"+version = "3.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"+[[package]]name = "inventory"version = "0.3.24"@@ -5950,7 +6591,7 @@ dependencies = ["serde","serde_json","serve-metrics",- "sha2",+ "sha2 0.10.9","strum 0.27.2","strum_macros 0.27.2","tempfile",@@ -6139,6 +6780,63 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "db13adb97ab515a3691f56e4dbab09283d0b86cb45abd991d8634a9d6f501760"+[[package]]+name = "lexical-core"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d8d125a277f807e55a77304455eb7b1cb52f2b18c143b60e766c120bd64a594"+dependencies = [+ "lexical-parse-float",+ "lexical-parse-integer",+ "lexical-util",+ "lexical-write-float",+ "lexical-write-integer",+]++[[package]]+name = "lexical-parse-float"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52a9f232fbd6f550bc0137dcb5f99ab674071ac2d690ac69704593cb4abbea56"+dependencies = [+ "lexical-parse-integer",+ "lexical-util",+]++[[package]]+name = "lexical-parse-integer"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a7a039f8fb9c19c996cd7b2fcce303c1b2874fe1aca544edc85c4a5f8489b34"+dependencies = [+ "lexical-util",+]++[[package]]+name = "lexical-util"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2604dd126bb14f13fb5d1bd6a66155079cb9fa655b37f875b3a742c705dbed17"++[[package]]+name = "lexical-write-float"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50c438c87c013188d415fbabbb1dceb44249ab81664efbd31b14ae55dabb6361"+dependencies = [+ "lexical-util",+ "lexical-write-integer",+]++[[package]]+name = "lexical-write-integer"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "409851a618475d2d5796377cad353802345cba92c867d9fbcde9cf4eac4e14df"+dependencies = [+ "lexical-util",+]+[[package]]name = "libbz2-rs-sys"version = "0.2.2"@@ -6309,6 +7007,12 @@ dependencies = ["tracing",]+[[package]]+name = "link-section"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b685d66585d646efe09fec763d796c291049c8b6bf84e04954bffc8748341f0d"+[[package]]name = "linkme"version = "0.3.35"@@ -6411,6 +7115,15 @@ version = "0.11.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "08ab2867e3eeeca90e844d1940eab391c9dc5228783db2ed999acbc0a9ed375a"+[[package]]+name = "lz4_flex"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e"+dependencies = [+ "twox-hash",+]+[[package]]name = "mach"version = "0.3.2"@@ -6477,7 +7190,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"dependencies = ["cfg-if",- "digest",+ "digest 0.10.7",][[package]]@@ -7216,28 +7929,32 @@ dependencies = [[[package]]name = "object_store"-version = "0.13.1"+version = "0.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c2858065e55c148d294a9f3aae3b0fa9458edadb41a108397094566f4e3c0dfb"+checksum = "622acbc9100d3c10e2ee15804b0caa40e55c933d5aa53814cd520805b7958a49"dependencies = ["async-trait","base64 0.22.1","bytes","chrono","form_urlencoded",- "futures",+ "futures-channel",+ "futures-core",+ "futures-util","http 1.4.0","http-body-util",+ "httparse","humantime","hyper 1.9.0","itertools 0.14.0","md-5","parking_lot","percent-encoding",- "quick-xml 0.38.4",- "rand 0.9.2",+ "quick-xml 0.39.4",+ "rand 0.10.2","reqwest 0.12.28","ring 0.17.14",+ "rustls-pki-types","serde","serde_json","serde_urlencoded",@@ -7449,6 +8166,12 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "option-ext"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"+[[package]]name = "ordered-float"version = "2.10.1"@@ -7491,13 +8214,14 @@ checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"[[package]]name = "p256"-version = "0.11.1"+version = "0.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594"+checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"dependencies = ["ecdsa","elliptic-curve",- "sha2",+ "primeorder",+ "sha2 0.10.9",][[package]]@@ -7529,6 +8253,42 @@ dependencies = ["windows-link",]+[[package]]+name = "parquet"+version = "58.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d298093b2dec60289dce0684c986d0f7679e9dd15771c2c65406e1aaf604a704"+dependencies = [+ "ahash 0.8.12",+ "arrow-array",+ "arrow-buffer",+ "arrow-data",+ "arrow-ipc",+ "arrow-schema",+ "arrow-select",+ "base64 0.22.1",+ "brotli 8.0.2",+ "bytes",+ "chrono",+ "flate2",+ "futures",+ "half",+ "hashbrown 0.17.1",+ "lz4_flex 0.13.1",+ "num-bigint",+ "num-integer",+ "num-traits",+ "object_store",+ "paste",+ "seq-macro",+ "simdutf8",+ "snap",+ "thrift",+ "tokio",+ "twox-hash",+ "zstd",+]+[[package]]name = "parse-display"version = "0.9.1"@@ -7597,8 +8357,8 @@ version = "0.12.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"dependencies = [- "digest",- "hmac",+ "digest 0.10.7",+ "hmac 0.12.1",][[package]]@@ -7660,6 +8420,12 @@ version = "2.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+[[package]]+name = "percent-encoding-rfc3986"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3637c05577168127568a64e9dc5a6887da720efef07b3d9472d45f63ab191166"+[[package]]name = "personhog-common"version = "0.1.0"@@ -7950,7 +8716,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "89815c69d36021a140146f26659a81d6c2afa33d216d736dd4be5381a7362220"dependencies = ["pest",- "sha2",+ "sha2 0.10.9",][[package]]@@ -8100,19 +8866,9 @@ version = "0.7.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"dependencies = [- "der 0.7.10",- "pkcs8 0.10.2",- "spki 0.7.3",-]--[[package]]-name = "pkcs8"-version = "0.9.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9eca2c590a5f85da82668fa685c09ce2888b9430e83299debf1f34b65fd4a4ba"-dependencies = [- "der 0.6.1",- "spki 0.6.0",+ "der",+ "pkcs8",+ "spki",][[package]]@@ -8121,8 +8877,8 @@ version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"dependencies = [- "der 0.7.10",- "spki 0.7.3",+ "der",+ "spki",][[package]]@@ -8215,7 +8971,7 @@ dependencies = ["anyhow","base64 0.22.1","flate2",- "hmac",+ "hmac 0.12.1","image","jpeg-decoder","libdeflater",@@ -8223,7 +8979,7 @@ dependencies = ["memchr","serde","serde_json",- "sha2",+ "sha2 0.10.9","simd-json","url","zstd",@@ -8394,6 +9150,15 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "primeorder"+version = "0.13.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"+dependencies = [+ "elliptic-curve",+]+[[package]]name = "proc-macro-crate"version = "3.4.0"@@ -8403,6 +9168,28 @@ dependencies = ["toml_edit",]+[[package]]+name = "proc-macro-error-attr2"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"+dependencies = [+ "proc-macro2",+ "quote",+]++[[package]]+name = "proc-macro-error2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"+dependencies = [+ "proc-macro-error-attr2",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "proc-macro2"version = "1.0.106"@@ -8964,6 +9751,15 @@ name = "quick-xml"version = "0.38.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c"+dependencies = [+ "memchr",+]++[[package]]+name = "quick-xml"+version = "0.39.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdcc8dd4e2f670d309a5f0e83fe36dfdc05af317008fea29144da1a2ac858e5e"dependencies = ["memchr","serde",@@ -9234,6 +10030,26 @@ dependencies = ["pkg-config",]+[[package]]+name = "recursive"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0786a43debb760f491b1bc0269fe5e84155353c67482b9e60d0cfb596054b43e"+dependencies = [+ "recursive-proc-macro-impl",+ "stacker",+]++[[package]]+name = "recursive-proc-macro-impl"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b"+dependencies = [+ "quote",+ "syn 2.0.117",+]+[[package]]name = "redis"version = "0.32.7"@@ -9293,6 +10109,17 @@ dependencies = ["thiserror 1.0.69",]+[[package]]+name = "redox_users"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"+dependencies = [+ "getrandom 0.2.17",+ "libredox",+ "thiserror 2.0.18",+]+[[package]]name = "ref-cast"version = "1.0.25"@@ -9481,9 +10308,11 @@ checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"dependencies = ["base64 0.22.1","bytes",+ "encoding_rs","futures-channel","futures-core","futures-util",+ "h2 0.4.13","http 1.4.0","http-body 1.0.1","http-body-util",@@ -9492,6 +10321,7 @@ dependencies = ["hyper-util","js-sys","log",+ "mime","percent-encoding","pin-project-lite","quinn",@@ -9514,13 +10344,12 @@ dependencies = [[[package]]name = "rfc6979"-version = "0.3.1"+version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb"+checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"dependencies = [- "crypto-bigint 0.4.9",- "hmac",- "zeroize",+ "hmac 0.12.1",+ "subtle",][[package]]@@ -9596,6 +10425,16 @@ version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422"+[[package]]+name = "roaring"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1dedc5658c6ecb3bdb5ef5f3295bb9253f42dcf3fd1402c03f6b1f7659c3c4a9"+dependencies = [+ "bytemuck",+ "byteorder",+]+[[package]]name = "rocksdb"version = "0.24.0"@@ -9612,16 +10451,16 @@ version = "0.9.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"dependencies = [- "const-oid",- "digest",+ "const-oid 0.9.6",+ "digest 0.10.7","num-bigint-dig","num-integer","num-traits","pkcs1",- "pkcs8 0.10.2",+ "pkcs8","rand_core 0.6.4",- "signature 2.2.0",- "spki 0.7.3",+ "signature",+ "spki","subtle","zeroize",]@@ -10003,14 +10842,14 @@ dependencies = [[[package]]name = "sec1"-version = "0.3.0"+version = "0.7.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928"+checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"dependencies = ["base16ct",- "der 0.6.1",+ "der","generic-array",- "pkcs8 0.9.0",+ "pkcs8","subtle","zeroize",]@@ -10302,7 +11141,7 @@ checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"dependencies = ["cfg-if","cpufeatures 0.2.17",- "digest",+ "digest 0.10.7",][[package]]@@ -10319,7 +11158,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"dependencies = ["cfg-if","cpufeatures 0.2.17",- "digest",+ "digest 0.10.7",+]++[[package]]+name = "sha2"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.0",+ "digest 0.11.3",][[package]]@@ -10347,23 +11197,13 @@ dependencies = ["libc",]-[[package]]-name = "signature"-version = "1.6.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c"-dependencies = [- "digest",- "rand_core 0.6.4",-]-[[package]]name = "signature"version = "2.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"dependencies = [- "digest",+ "digest 0.10.7","rand_core 0.6.4",]@@ -10472,6 +11312,12 @@ dependencies = ["version_check",]+[[package]]+name = "snap"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886"+[[package]]name = "socket2"version = "0.5.10"@@ -10536,22 +11382,22 @@ dependencies = [[[package]]name = "spki"-version = "0.6.0"+version = "0.7.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b"+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"dependencies = ["base64ct",- "der 0.6.1",+ "der",][[package]]-name = "spki"-version = "0.7.3"+name = "sqlparser"+version = "0.61.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"+checksum = "dbf5ea8d4d7c808e1af1cbabebca9a2abe603bcefc22294c5b95018d53200cb7"dependencies = [- "base64ct",- "der 0.7.10",+ "log",+ "recursive",][[package]]@@ -10595,7 +11441,7 @@ dependencies = ["rust_decimal","serde","serde_json",- "sha2",+ "sha2 0.10.9","smallvec","thiserror 2.0.18","tokio",@@ -10633,7 +11479,7 @@ dependencies = ["quote","serde","serde_json",- "sha2",+ "sha2 0.10.9","sqlx-core","sqlx-mysql","sqlx-postgres",@@ -10656,7 +11502,7 @@ dependencies = ["bytes","chrono","crc",- "digest",+ "digest 0.10.7","dotenvy","either","futures-channel",@@ -10666,7 +11512,7 @@ dependencies = ["generic-array","hex","hkdf",- "hmac",+ "hmac 0.12.1","itoa","log","md-5",@@ -10678,7 +11524,7 @@ dependencies = ["rust_decimal","serde","sha1",- "sha2",+ "sha2 0.10.9","smallvec","sqlx-core","stringprep",@@ -10707,7 +11553,7 @@ dependencies = ["futures-util","hex","hkdf",- "hmac",+ "hmac 0.12.1","home","itoa","log",@@ -10718,7 +11564,7 @@ dependencies = ["rust_decimal","serde","serde_json",- "sha2",+ "sha2 0.10.9","smallvec","sqlx-core","stringprep",@@ -10893,6 +11739,9 @@ name = "strum"version = "0.27.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"+dependencies = [+ "strum_macros 0.27.2",+][[package]]name = "strum"@@ -11578,6 +12427,17 @@ dependencies = ["cfg-if",]+[[package]]+name = "thrift"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e54bc85fc7faa8bc175c4bab5b92ba8d9a3ce893d0e9f42cc455c8ab16a9e09"+dependencies = [+ "byteorder",+ "integer-encoding",+ "ordered-float 2.10.1",+]+[[package]]name = "tiktoken-rs"version = "0.7.0"@@ -12241,6 +13101,26 @@ dependencies = ["rand 0.9.2",]+[[package]]+name = "typed-builder"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "31aa81521b70f94402501d848ccc0ecaa8f93c8eb6999eb9747e72287757ffda"+dependencies = [+ "typed-builder-macro",+]++[[package]]+name = "typed-builder-macro"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "076a02dc54dd46795c2e9c8282ed40bcfb1e22747e955de9389a1de28190fb26"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "typed-path"version = "0.12.3"@@ -12448,11 +13328,42 @@ checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9"dependencies = ["getrandom 0.4.1","js-sys",+ "rand 0.10.2","serde_core","sha1_smol","wasm-bindgen",]+[[package]]+name = "validator"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0b4a29d8709210980a09379f27ee31549b73292c87ab9899beee1c0d3be6303"+dependencies = [+ "idna",+ "once_cell",+ "regex",+ "serde",+ "serde_derive",+ "serde_json",+ "url",+ "validator_derive",+]++[[package]]+name = "validator_derive"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bac855a2ce6f843beb229757e6e570a42e837bcb15e5f449dd48d5747d41bf77"+dependencies = [+ "darling 0.20.11",+ "once_cell",+ "proc-macro-error2",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "valuable"version = "0.1.1"@@ -13187,6 +14098,12 @@ dependencies = ["synstructure",]+[[package]]+name = "z85"+version = "3.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6e61e59a957b7ccee15d2049f86e8bfd6f66968fcd88f018950662d9b86e675"+[[package]]name = "zerocopy"version = "0.8.39"@@ -13295,7 +14212,7 @@ dependencies = ["deflate64","flate2","getrandom 0.3.4",- "hmac",+ "hmac 0.12.1","indexmap 2.13.0","liblzma","memchr",diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 312fbb66da1f..a89bb7ac17cd 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -49,6 +49,8 @@ members = ["common/geoip","common/hogvm","common/ingestion_warnings",+ "deltalite/core",+ "deltalite/python","hogql/parser","kafka-assigner","kafka-assigner-proto",@@ -69,6 +71,11 @@ members = ["property-vals-rs",]+# NOTE: cargo allows only one crate with `links = "python"` (i.e. one pyo3 version) per+# dependency graph. `hogql/parser` and `deltalite/python` must therefore agree on their+# pyo3 major (currently 0.28, dictated by arrow 58's `pyarrow` feature in deltalite) --+# bumping pyo3 in one means bumping it in the other, or the workspace stops resolving.+[workspace.lints.rust]# See https://doc.rust-lang.org/stable/rustc/lints/listing/allowed-by-default.htmlunexpected_cfgs = { level = "warn", check-cfg = ['cfg(tokio_unstable)'] }diff --git a/rust/deltalite/README.md b/rust/deltalite/README.mdnew file mode 100644index 000000000000..fedd6798149a--- /dev/null+++ b/rust/deltalite/README.md@@ -0,0 +1,139 @@+# deltalite++Streaming partition-level upsert for Delta tables, replacing delta-rs's SQL+`MERGE` for the warehouse-sync incremental path. delta-rs stays the storage and+protocol layer (log, checkpoints, Parquet writing, Add-action statistics, S3+conditional-put commits, conflict resolution); only the *merge execution* is+replaced.++Why: MERGE executes a DataFusion hash join whose memory scales with the scanned+target and which deadlocks under a bounded memory pool+([delta-io/delta-rs#4614](https://github.com/delta-io/delta-rs/issues/4614),+reproduced). deltalite builds a PK hash set over the (small) source, streams the+(large) target one row group at a time, drops replaced rows, writes survivors+plus the source rows, and commits every partition in ONE atomic commit. Peak+memory is bounded by the source and the concurrency knobs — never by table+size. The validation spike measured memory flat from 62k to 1M-row partitions,+~4x below MERGE, at matching write volume via exact content-based file+selection; the semantics are proven by the differential parity suite in+`python/tests/`.++## Layout — and why it is two crates++| Path | What |+|---|---|+| `core/` | `deltalite-core`: all the logic (upsert pipeline, PK set, pruning/probing, schema casting, decimal realignment, process-global limits, multipart store). Pure Rust, no pyo3. **Workspace member** — normal CI (build, nextest, clippy, fmt) applies. All Rust unit tests live here. |+| `python/` | `deltalite-python`: thin pyo3 binding, built by maturin, imported as `deltalite`. Workspace member shaped like `rust/hogql/parser` (cdylib+rlib, `extension-module`, abi3-py312) — no Rust tests, see below. |+| `python/tests/` | The differential parity suite plus probe/operations/types/crash-redelivery/interop/planner/guard tests (pytest, 159 tests). Runs the same batch sequences through real delta-rs `merge` and through `deltalite.upsert` and asserts identical logical content. |+| `python/harness/` | The two write paths + logical comparison used by the tests. `merge_path` is a faithful transcription of the production incremental branch of `DeltaTableHelper.write_to_deltalake`. |+| `python/deltalite_planner.py` | Rough knob tuning: given concurrent upserts and pod memory, suggests starting values for `max_parallel_partitions` / `max_parallel_files` / the byte budget and the process-global env ceilings. A heuristic, not a capacity model. |++Two crates because pyo3's `extension-module` feature suppresses the libpython+link, so a `cargo test` harness binary for an extension crate **cannot link on+Linux**. `hogql/parser` sidesteps this by having no Rust tests; deltalite needs+Rust unit tests for its pure logic, so the logic lives in a pyo3-free crate and+the binding crate stays test-free.++Related constraint: cargo permits only **one pyo3 version per dependency graph**+(pyo3 has `links = "python"`). deltalite's pyarrow ingest uses arrow 58's+`pyarrow` feature (arrow major fixed by `deltalake` 0.32), which requires+pyo3 0.28 — so `rust/hogql/parser` was migrated from pyo3 0.22 to 0.28 to share+the workspace, and the two must bump pyo3 in lockstep from here on.++`deltalite-core` pins `deltalake = "=0.32.4"` — the newest *published*+crates.io release, deliberately NOT "the same delta-rs as the Python package"+(that tree is unbuildable as published: it pins a moving git branch and ships+no lockfile — see the comment in `core/Cargo.toml`). The parity suite, not+version equality, is the compatibility check; every bump of either side must+keep it green.++## Building locally++```bash+# Editable install of the extension into the active venv:+uv pip install -e rust/deltalite/python++# Or via maturin directly (faster incremental):+maturin develop --release --manifest-path rust/deltalite/python/Cargo.toml++# Sanity check+python -c "import deltalite; print(deltalite.DeltaLiteTable)"++# Rust unit tests / lints (workspace tooling covers core):+cd rust && cargo test -p deltalite-core && cargo clippy -p deltalite-core --all-targets++# Note for non-flox shells on macOS: rust/.cargo/config.toml adds -fuse-ld=lld,+# which only exists inside the flox env. Outside it, override with+# RUSTFLAGS="--cfg tokio_unstable" cargo <cmd>+```++The Python test suite (needs `deltalake`, `pyarrow`, `duckdb`, `pytest` —+versions matching the repo's `pyproject.toml` pins):++```bash+uv venv /tmp/deltalite-venv --python 3.13+VIRTUAL_ENV=/tmp/deltalite-venv uv pip install maturin pytest \+ 'deltalake==1.6.1' 'pyarrow==23.0.1' 'duckdb~=1.5.2'+VIRTUAL_ENV=/tmp/deltalite-venv /tmp/deltalite-venv/bin/python -m maturin develop \+ --release --manifest-path rust/deltalite/python/Cargo.toml+/tmp/deltalite-venv/bin/python -m pytest rust/deltalite/python/tests -q+```++CI runs exactly this in `.github/workflows/ci-deltalite-python.yml`,+path-filtered to `rust/deltalite/**`.++## How the wheel is built and consumed++Mirrors `hogql-parser-rs` (see `.github/workflows/build-hogql-parser-rs.yml`):++- maturin builds a single `cp312-abi3` wheel per platform that works on every+ Python 3.12+ (including the pinned prod 3.13). `[project] name = "deltalite"`,+ module name `deltalite`.+- When a release is cut, a `build-deltalite` workflow (to be cloned from+ `build-hogql-parser-rs.yml` at rollout time: version-bump detection on+ `rust/deltalite/python/**`, maturin-action wheel matrix for manylinux 2_28 ++ musllinux x86_64/aarch64 and macOS arm64/x86_64, publish, then a follow-up PR+ pinning `deltalite==<version>` in `pyproject.toml`) publishes it; the posthog+ image then installs it like any other wheel via `uv sync` — no Rust toolchain+ in the image.+- Version lives in BOTH `python/Cargo.toml` and `python/pyproject.toml`+ (always identical); bump both together.++Until that workflow lands, the wheel is dev-installed as above; nothing in the+Django app imports `deltalite` yet (the `DeltaTableHelper` seam is a separate,+flag-gated change).++## Operational knobs++Per-call (arguments to `DeltaLiteTable.upsert`): `max_parallel_partitions` (2),+`max_parallel_files` (4), `max_buffered_bytes` (64 MiB), `prune_strategy`+(`probe`), `probe_concurrency` (8), `read_batch_size` (8192),+`target_file_size` (table's `delta.targetFileSize`, else delta-rs's 100 MiB),+`max_source_bytes` (2 GiB guard), `multipart_threshold` (64 MiB) /+`multipart_part_size` (16 MiB), `commit_max_retries` (15).++Process-global (environment, enforced on top of the per-call knobs so that+~15 concurrent upsert threads in one Temporal worker cannot multiply the+budgets): `DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS` (8),+`DELTALITE_PROCESS_MAX_PARALLEL_FILES` (16),+`DELTALITE_PROCESS_MAX_BUFFERED_BYTES` (256 MiB), `DELTALITE_MAX_SOURCE_BYTES`,+`DELTALITE_MULTIPART_THRESHOLD_BYTES`, `DELTALITE_MULTIPART_PART_SIZE_BYTES`.++For a rough starting point on a given pod, `python/deltalite_planner.py`+suggests knob values from concurrency + pod memory, e.g.+`python deltalite_planner.py 15 8000 --source-mb 250`.++Metrics (`metrics` crate, static labels only): `deltalite_upserts_total`+(`outcome`, `prune_strategy`, `error_kind`), `deltalite_upsert_duration_seconds`,+`deltalite_files_{added,removed,carried_over,probed}_total`,+`deltalite_rows_{updated,inserted,copied}_total`.++## Pre-rollout conditions (from the spike verdict, still open)++- Verify against real AWS S3 (spike verified MinIO/SeaweedFS only).+- Gate rollout on a conditional-put startup probe: an endpoint that silently+ ignores `If-None-Match: *` loses concurrent commits with no error anywhere.+- Adopt a `vacuum(full=True)` policy where deltalite ships: lite vacuum never+ reclaims crash orphans, and a late crash orphans a whole batch's files.+- Check rollout tables for pre-existing duplicate-key batches: deltalite+ rejects duplicate source PKs that MERGE silently double-inserts.diff --git a/rust/deltalite/core/Cargo.toml b/rust/deltalite/core/Cargo.tomlnew file mode 100644index 000000000000..68fa13c7a950--- /dev/null+++ b/rust/deltalite/core/Cargo.toml@@ -0,0 +1,55 @@+[package]+name = "deltalite-core"+version = "0.1.0"+edition = "2021"+# CI compiles with this exact toolchain; cargo's MSRV-aware resolver uses it to+# avoid picking dependency versions CI cannot build (aws-* crates move MSRV often).+rust-version = "1.91.1"+publish = false++[lib]+name = "deltalite_core"++[lints]+workspace = true++[dependencies]+# VERSION SKEW WITH THE PYTHON `deltalake` PACKAGE IS DELIBERATE.+#+# The delta-rs tree behind Python `deltalake==1.6.1` (pinned in the repo's+# pyproject.toml) is the in-repo crate version 1.0.0 at git tag `python-v1.6.1`.+# That tag is NOT buildable as published: it pins its delta kernel dependency to+# a MOVING BRANCH (`buoyant/main`) rather than a rev, delta-rs gitignores its+# Cargo.lock so nothing records the rev the wheel was built from, and the branch+# has since diverged in two mutually incompatible directions (package rename vs+# removed feature), so no reachable revision satisfies the tag's requirements.+#+# We therefore pin the newest PUBLISHED crates.io release exactly and commit the+# lockfile. Both writers emit the same Delta protocol; the Python differential+# parity suite (rust/deltalite/python/tests/) -- not version equality -- is the+# real compatibility check, and every bump of either side must keep it green.+#+# Built WITHOUT the `datafusion` feature: no DataFusion in the dependency tree+# means the delta-io/delta-rs#4614 merge deadlock is impossible by construction.+deltalake = { version = "=0.32.4", default-features = false, features = ["s3", "rustls"] }++# arrow/parquet major version must match what `deltalake` links (arrow 58).+arrow-array = { version = "58" }+arrow-buffer = { version = "58" }+arrow-cast = { version = "58" }+arrow-data = { version = "58" }+arrow-row = { version = "58" }+arrow-schema = { version = "58" }+arrow-select = { version = "58" }+parquet = { version = "58", features = ["async", "object_store"] }+object_store = { version = "0.13.2" }++async-trait = { workspace = true }+bytes = { workspace = true }+futures = { workspace = true }+metrics = { workspace = true }+serde_json = { workspace = true }+thiserror = { workspace = true }+tokio = { workspace = true }+tracing = { workspace = true }+uuid = { workspace = true }diff --git a/rust/deltalite/core/src/errors.rs b/rust/deltalite/core/src/errors.rsnew file mode 100644index 000000000000..ee4ba9c1143f--- /dev/null+++ b/rust/deltalite/core/src/errors.rs@@ -0,0 +1,87 @@+//! Typed error hierarchy for deltalite.+//!+//! The Python binding crate maps each variant onto a dedicated exception class so+//! callers can branch on error *kind* instead of sniffing error text (the pattern the+//! existing `delta_table_helper.py` is stuck with for the Python package's errors).++pub type Result<T> = std::result::Result<T, Error>;++/// All errors deltalite can surface.+#[derive(Debug, thiserror::Error)]+pub enum Error {+ /// Anything without a more specific classification.+ #[error("{0}")]+ Generic(String),++ /// The source batch cannot be reconciled with the table schema (unknown columns,+ /// uncastable types, missing PK/partition columns).+ #[error("{0}")]+ SchemaMismatch(String),++ /// The URI does not point at a loadable Delta table.+ #[error("{0}")]+ NotFound(String),++ /// The table declares features deltalite cannot safely rewrite (deletion vectors,+ /// column mapping, multiple partition columns).+ #[error("{0}")]+ Unsupported(String),++ /// The transaction layer exhausted its retries or hit a true logical conflict.+ #[error("{0}")]+ Conflict(String),++ /// The source batch (resident bytes + estimated PK-set size) exceeds the configured+ /// ceiling. Raised at the front door instead of growing RSS until the pod OOMs:+ /// deltalite's memory is bounded in the *target* by construction, but scales+ /// linearly with the *source*, and this is the guard on that term.+ #[error("{0}")]+ SourceTooLarge(String),+}++impl From<deltalake::DeltaTableError> for Error {+ fn from(e: deltalake::DeltaTableError) -> Self {+ use deltalake::DeltaTableError as D;+ match &e {+ D::NotATable(_) | D::InvalidTableLocation(_) => Error::NotFound(e.to_string()),+ D::SchemaMismatch { .. } => Error::SchemaMismatch(e.to_string()),+ // The transaction layer surfaces exhausted-retry / logical conflicts here.+ D::Transaction { .. } => Error::Conflict(e.to_string()),+ _ => Error::Generic(e.to_string()),+ }+ }+}++impl From<arrow_schema::ArrowError> for Error {+ fn from(e: arrow_schema::ArrowError) -> Self {+ Error::Generic(format!("arrow: {e}"))+ }+}++impl From<parquet::errors::ParquetError> for Error {+ fn from(e: parquet::errors::ParquetError) -> Self {+ Error::Generic(format!("parquet: {e}"))+ }+}++impl From<object_store::Error> for Error {+ fn from(e: object_store::Error) -> Self {+ Error::Generic(format!("object_store: {e}"))+ }+}++impl Error {+ /// Static label for metrics/tracing, one per variant. `&'static str` on purpose:+ /// per rust/CLAUDE.md, metric label values must never be freshly-allocated+ /// `String`s, and a fixed variant name needs no `Arc<str>` either.+ pub fn kind(&self) -> &'static str {+ match self {+ Error::Generic(_) => "generic",+ Error::SchemaMismatch(_) => "schema_mismatch",+ Error::NotFound(_) => "not_found",+ Error::Unsupported(_) => "unsupported",+ Error::Conflict(_) => "conflict",+ Error::SourceTooLarge(_) => "source_too_large",+ }+ }+}diff --git a/rust/deltalite/core/src/lib.rs b/rust/deltalite/core/src/lib.rsnew file mode 100644index 000000000000..b8cd7817ade3--- /dev/null+++ b/rust/deltalite/core/src/lib.rs@@ -0,0 +1,42 @@+//! deltalite -- a purpose-built streaming partition upsert on top of the `deltalake`+//! crate, replacing delta-rs's SQL MERGE for PostHog's warehouse-sync incremental path.+//!+//! Storage and protocol (log, checkpoints, Parquet writing, Add-action statistics,+//! S3 conditional-put commits, conflict resolution) all come from `deltalake`. Only the+//! *merge execution* is replaced: MERGE runs a DataFusion hash join whose memory scales+//! with the scanned target and which deadlocks under a bounded memory pool+//! (delta-io/delta-rs#4614); deltalite builds a PK hash set over the (small) source,+//! streams the (large) target a row group at a time, drops replaced rows, writes+//! survivors plus source rows, and commits every partition in ONE atomic commit. Peak+//! memory is bounded by the source and the concurrency knobs, never by table size.+//!+//! Semantics contract (equal to the production merge, proven by the differential parity+//! suite in `rust/deltalite/python/tests/`):+//!+//! - Row identity is `(primary_keys..., partition)`; a PK whose partition value changed+//! inserts into the new partition and leaves the old row behind.+//! - SQL NULL semantics on primary keys: a NULL in any PK component never matches and+//! always inserts.+//! - Matched target rows are replaced wholesale by the source row+//! (`when_matched_update_all`); unmatched source rows insert; unmatched target rows+//! survive verbatim.+//! - Duplicate source PK tuples are rejected (stricter than MERGE, deliberately --+//! MERGE silently double-inserts non-matching duplicates).+//! - Tables with deletion vectors or column mapping (including the legacy+//! `minReaderVersion=2/minWriterVersion=5` form) are refused.+//!+//! This crate is pure Rust; the Python bindings live in the sibling `deltalite-python`+//! crate (built with maturin, imported as `deltalite`).++pub mod errors;+pub mod limits;+pub mod pkset;+pub mod schema;+pub mod store;+pub mod table;+pub mod upsert;++pub use errors::{Error, Result};+pub use limits::ProcessLimits;+pub use table::{open_table, open_table_multipart, MultipartConfig};+pub use upsert::{upsert, PruneStrategy, UpsertOptions, UpsertStats};diff --git a/rust/deltalite/core/src/limits.rs b/rust/deltalite/core/src/limits.rsnew file mode 100644index 000000000000..b4f49ca1c92d--- /dev/null+++ b/rust/deltalite/core/src/limits.rs@@ -0,0 +1,268 @@+//! Process-global concurrency limits and the source-size guard.+//!+//! The per-call semaphores (`max_parallel_partitions`, `max_parallel_files`,+//! `max_buffered_bytes`) are constructed inside `upsert()`, so alone they bound one+//! *call*.+//! Production runs ~15 concurrent upserts as Temporal activity threads inside ONE worker+//! process, so a "global" 64 MB byte budget was really 15 x 64 MB, and the process could+//! host `15 x mpp x mpf` concurrent file readers on the shared tokio runtime.+//!+//! Every acquisition therefore goes through BOTH a per-call semaphore (preserving the+//! per-call knobs) and a process-global one from this module, so the process-level bound+//! means what it says regardless of how many upserts run concurrently. Acquisition order+//! is fixed everywhere -- partition -> file -> bytes, local before global at each level+//! -- so the two layers cannot deadlock against each other.+//!+//! Limits are injected as an [`Arc<ProcessLimits>`] rather than read from a hidden+//! static, so tests can build isolated instances; the binding crate passes+//! [`ProcessLimits::global()`], a lazily-initialised process-wide singleton configured+//! from environment variables.++use std::sync::{Arc, OnceLock};++use tokio::sync::{OwnedSemaphorePermit, Semaphore};++use crate::errors::{Error, Result};++/// Default process-wide cap on concurrently rewriting partitions.+pub const DEFAULT_PROCESS_MAX_PARALLEL_PARTITIONS: usize = 8;+/// Default process-wide cap on concurrently streaming file readers.+pub const DEFAULT_PROCESS_MAX_PARALLEL_FILES: usize = 16;+/// Default process-wide cap on decompressed survivor bytes in flight.+pub const DEFAULT_PROCESS_MAX_BUFFERED_BYTES: usize = 256 * 1024 * 1024;+/// Default ceiling for the source-size guard (resident source + estimated PK set).+pub const DEFAULT_MAX_SOURCE_BYTES: usize = 2 * 1024 * 1024 * 1024;++/// Process-wide concurrency budgets shared by every concurrent `upsert` call.+pub struct ProcessLimits {+ partitions: Arc<Semaphore>,+ files: Arc<Semaphore>,+ buffer: Arc<Semaphore>,+ /// Capacity of `buffer` in KiB (tokio permits are u32-denominated).+ buffer_cap_kb: u32,+}++pub(crate) fn env_usize(name: &str, default: usize) -> usize {+ match std::env::var(name) {+ Ok(v) => match v.trim().parse::<usize>() {+ Ok(n) if n > 0 => n,+ _ => {+ tracing::warn!(var = name, value = %v, "invalid value, using default");+ default+ }+ },+ Err(_) => default,+ }+}++impl ProcessLimits {+ /// Build limits with explicit capacities. Zero capacities are clamped to 1 (a+ /// zero-permit semaphore would deadlock every upsert forever).+ pub fn new(max_partitions: usize, max_files: usize, max_buffered_bytes: usize) -> Self {+ let cap_kb = (max_buffered_bytes / 1024).clamp(1, u32::MAX as usize) as u32;+ Self {+ partitions: Arc::new(Semaphore::new(max_partitions.max(1))),+ files: Arc::new(Semaphore::new(max_files.max(1))),+ buffer: Arc::new(Semaphore::new(cap_kb as usize)),+ buffer_cap_kb: cap_kb,+ }+ }++ /// Capacities from `DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS`,+ /// `DELTALITE_PROCESS_MAX_PARALLEL_FILES` and+ /// `DELTALITE_PROCESS_MAX_BUFFERED_BYTES`, with the module defaults as fallback.+ pub fn from_env() -> Self {+ Self::new(+ env_usize(+ "DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS",+ DEFAULT_PROCESS_MAX_PARALLEL_PARTITIONS,+ ),+ env_usize(+ "DELTALITE_PROCESS_MAX_PARALLEL_FILES",+ DEFAULT_PROCESS_MAX_PARALLEL_FILES,+ ),+ env_usize(+ "DELTALITE_PROCESS_MAX_BUFFERED_BYTES",+ DEFAULT_PROCESS_MAX_BUFFERED_BYTES,+ ),+ )+ }++ /// The process-wide singleton, initialised from the environment on first use.+ pub fn global() -> &'static Arc<ProcessLimits> {+ static GLOBAL: OnceLock<Arc<ProcessLimits>> = OnceLock::new();+ GLOBAL.get_or_init(|| Arc::new(ProcessLimits::from_env()))+ }++ /// Acquire one process-global partition permit.+ pub async fn acquire_partition(&self) -> Result<OwnedSemaphorePermit> {+ self.partitions+ .clone()+ .acquire_owned()+ .await+ .map_err(|_| Error::Generic("process partition semaphore closed".into()))+ }++ /// Acquire one process-global file-reader permit.+ pub async fn acquire_file(&self) -> Result<OwnedSemaphorePermit> {+ self.files+ .clone()+ .acquire_owned()+ .await+ .map_err(|_| Error::Generic("process file semaphore closed".into()))+ }++ /// Acquire `kb` KiB of the process-global byte budget; requests larger than the+ /// whole budget are capped so an oversized batch still makes progress.+ pub async fn acquire_buffer_kb(&self, kb: u32) -> Result<OwnedSemaphorePermit> {+ self.buffer+ .clone()+ .acquire_many_owned(kb.min(self.buffer_cap_kb).max(1))+ .await+ .map_err(|_| Error::Generic("process byte-budget semaphore closed".into()))+ }++ /// Capacity of the byte budget in KiB.+ pub fn buffer_cap_kb(&self) -> u32 {+ self.buffer_cap_kb+ }+}++/// Estimate of what an upsert will keep resident for the whole rewrite: the cast source+/// batches (shared with the caller, but counted -- deltalite holds them alive) plus the+/// row-encoded PK hash set (~key bytes + per-entry overhead).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct SourceFootprint {+ /// Total Arrow buffer bytes across the cast source batches.+ pub source_bytes: usize,+ /// Estimated resident bytes of the PK hash set once built.+ pub pk_set_bytes: usize,+}++impl SourceFootprint {+ /// Combined estimate compared against the guard ceiling.+ pub fn total(&self) -> usize {+ self.source_bytes.saturating_add(self.pk_set_bytes)+ }+}++/// Per-`HashSet`-entry overhead: `Vec<u8>` header (24) + hash-table slot bookkeeping.+const PK_ENTRY_OVERHEAD: usize = 48;++/// Estimate the PK-set size from the source's PK columns: encoded key width is+/// approximated by the columns' in-memory bytes per row, which upper-bounds the+/// row-encoding for fixed-width types and tracks it closely for strings.+pub fn estimate_pk_set_bytes(pk_bytes: usize, rows: usize) -> usize {+ pk_bytes.saturating_add(rows.saturating_mul(PK_ENTRY_OVERHEAD))+}++/// Resolve the guard ceiling: explicit argument > `DELTALITE_MAX_SOURCE_BYTES` env >+/// [`DEFAULT_MAX_SOURCE_BYTES`]. An explicit `Some(0)` disables the guard.+pub fn resolve_max_source_bytes(explicit: Option<usize>) -> Option<usize> {+ let v = match explicit {+ Some(v) => v,+ None => env_usize("DELTALITE_MAX_SOURCE_BYTES", DEFAULT_MAX_SOURCE_BYTES),+ };+ (v > 0).then_some(v)+}++/// Reject a source whose estimated footprint exceeds the ceiling. This is the clean+/// front-door failure that replaces "RSS grows until the pod OOMs": the target side of+/// an upsert is memory-bounded by construction, the source side is linear in the+/// caller's batch, and nothing else refuses an oversized one.+pub fn check_source_size(footprint: &SourceFootprint, ceiling: Option<usize>) -> Result<()> {+ let Some(max) = ceiling else { return Ok(()) };+ if footprint.total() > max {+ return Err(Error::SourceTooLarge(format!(+ "source batch is too large for this upsert: ~{} MB resident ({} MB of \+ source data + ~{} MB of primary-key set) exceeds the {} MB ceiling. \+ Split the batch into smaller pieces, or raise the ceiling via the \+ max_source_bytes argument / DELTALITE_MAX_SOURCE_BYTES.",+ footprint.total() / (1024 * 1024),+ footprint.source_bytes / (1024 * 1024),+ footprint.pk_set_bytes / (1024 * 1024),+ max / (1024 * 1024),+ )));+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn total_saturates_instead_of_overflowing() {+ let f = SourceFootprint {+ source_bytes: usize::MAX,+ pk_set_bytes: 10,+ };+ assert_eq!(f.total(), usize::MAX);+ }++ #[test]+ fn guard_rejects_only_above_the_ceiling() {+ let small = SourceFootprint {+ source_bytes: 100,+ pk_set_bytes: 50,+ };+ assert!(check_source_size(&small, Some(150)).is_ok());+ let err = check_source_size(&small, Some(149)).unwrap_err();+ assert!(matches!(err, Error::SourceTooLarge(_)), "{err}");+ assert_eq!(err.kind(), "source_too_large");+ }++ #[test]+ fn guard_disabled_by_none_ceiling() {+ let huge = SourceFootprint {+ source_bytes: usize::MAX,+ pk_set_bytes: 0,+ };+ assert!(check_source_size(&huge, None).is_ok());+ }++ #[test]+ fn explicit_zero_disables_and_explicit_value_wins() {+ assert_eq!(resolve_max_source_bytes(Some(0)), None);+ assert_eq!(resolve_max_source_bytes(Some(123)), Some(123));+ // No env var set in tests: default applies.+ assert_eq!(+ resolve_max_source_bytes(None),+ Some(DEFAULT_MAX_SOURCE_BYTES)+ );+ }++ #[test]+ fn pk_estimate_includes_per_entry_overhead() {+ assert_eq!(estimate_pk_set_bytes(1000, 10), 1000 + 480);+ assert_eq!(estimate_pk_set_bytes(0, 0), 0);+ }++ #[tokio::test]+ async fn buffer_requests_are_capped_at_capacity() {+ let limits = ProcessLimits::new(1, 1, 64 * 1024); // 64 KiB+ // A request far larger than the budget still succeeds (capped), so an+ // oversized batch can make progress instead of deadlocking.+ let permit = limits.acquire_buffer_kb(u32::MAX).await.unwrap();+ drop(permit);+ let p1 = limits.acquire_buffer_kb(32).await.unwrap();+ let p2 = limits.acquire_buffer_kb(32).await.unwrap();+ // Budget exhausted: a third acquire must not be immediately ready.+ let pending = tokio::time::timeout(+ std::time::Duration::from_millis(50),+ limits.acquire_buffer_kb(1),+ )+ .await;+ assert!(pending.is_err(), "budget should be exhausted");+ drop(p1);+ drop(p2);+ }++ #[tokio::test]+ async fn zero_capacities_are_clamped_to_one() {+ let limits = ProcessLimits::new(0, 0, 0);+ let _p = limits.acquire_partition().await.unwrap();+ let _f = limits.acquire_file().await.unwrap();+ let _b = limits.acquire_buffer_kb(1).await.unwrap();+ }+}diff --git a/rust/deltalite/core/src/pkset.rs b/rust/deltalite/core/src/pkset.rsnew file mode 100644index 000000000000..84750ee3647b--- /dev/null+++ b/rust/deltalite/core/src/pkset.rs@@ -0,0 +1,279 @@+//! Multi-column primary-key hash set with SQL NULL semantics.+//!+//! Keys are encoded with arrow-row's `RowConverter`, which gives a byte-comparable,+//! type-aware encoding of a tuple of arrays. Equality on the encoded bytes is exactly+//! equality on the tuple values, provided both sides were encoded with the same+//! converter (hence the same data types) -- which is why callers must cast both the+//! source batch and every existing row group to the table schema first.+//!+//! SQL semantics that matter here: `NULL = NULL` is *not* true. A source row with a NULL+//! in any PK column can therefore never match a target row, so it must be excluded from+//! the set; and a target row with a NULL in any PK column can never be matched, so it is+//! never probed. Getting this wrong silently corrupts tables, so it is handled+//! explicitly on both sides rather than left to the encoding.++use std::collections::HashSet;+use std::sync::Arc;++use arrow_array::{Array, RecordBatch};+use arrow_row::{RowConverter, SortField};+use arrow_schema::SchemaRef;++use crate::errors::{Error, Result};++/// A hash set of primary-key tuples with SQL NULL semantics (NULL never matches).+pub struct PkSet {+ converter: RowConverter,+ keys: HashSet<Vec<u8>>,+ pk_indices: Vec<usize>,+ /// Number of source rows skipped because they carry a NULL PK component.+ pub null_pk_rows: usize,+}++/// True where the row has no NULL in any of `cols` (i.e. the row is matchable).+fn matchable_mask(cols: &[Arc<dyn Array>], num_rows: usize) -> Vec<bool> {+ let mut mask = vec![true; num_rows];+ for c in cols {+ if c.null_count() == 0 {+ continue;+ }+ for (i, m) in mask.iter_mut().enumerate() {+ if c.is_null(i) {+ *m = false;+ }+ }+ }+ mask+}++impl PkSet {+ /// Build an empty set keyed on `primary_keys`, whose types are taken from `schema`.+ pub fn new(schema: &SchemaRef, primary_keys: &[String]) -> Result<Self> {+ if primary_keys.is_empty() {+ return Err(Error::Generic("primary_keys must not be empty".into()));+ }+ let mut pk_indices = Vec::with_capacity(primary_keys.len());+ let mut fields = Vec::with_capacity(primary_keys.len());+ for pk in primary_keys {+ let idx = schema.index_of(pk).map_err(|_| {+ Error::SchemaMismatch(format!(+ "primary key column '{pk}' not found in table schema"+ ))+ })?;+ pk_indices.push(idx);+ fields.push(SortField::new(schema.field(idx).data_type().clone()));+ }+ let converter =+ RowConverter::new(fields).map_err(|e| Error::Generic(format!("row converter: {e}")))?;+ Ok(Self {+ converter,+ keys: HashSet::new(),+ pk_indices,+ null_pk_rows: 0,+ })+ }++ fn pk_columns(&self, batch: &RecordBatch) -> Vec<Arc<dyn Array>> {+ self.pk_indices+ .iter()+ .map(|i| batch.column(*i).clone())+ .collect()+ }++ /// Insert every matchable row of the given PK columns, returning how many were+ /// already present (duplicates). `cols` must be the PK columns in primary-key+ /// order, with the table schema's PK types (see `contains_any_columns`). Lets+ /// callers feed the set from narrow column selections without materialising a+ /// full-width batch; the set persists across calls, so duplicates spanning calls+ /// are still counted.+ pub fn insert_columns(&mut self, cols: &[Arc<dyn Array>], num_rows: usize) -> Result<usize> {+ let mask = matchable_mask(cols, num_rows);+ let rows = self+ .converter+ .convert_columns(cols)+ .map_err(|e| Error::Generic(format!("row encode: {e}")))?;++ let mut duplicates = 0;+ for (i, matchable) in mask.iter().enumerate() {+ if !matchable {+ self.null_pk_rows += 1;+ continue;+ }+ if !self.keys.insert(rows.row(i).as_ref().to_vec()) {+ duplicates += 1;+ }+ }+ Ok(duplicates)+ }++ /// Whether *any* row of the given PK columns is present in the set.+ ///+ /// `cols` must be the PK columns in primary-key order, already cast to the same+ /// data types this set was built with (the table schema's PK types) -- otherwise the+ /// row encodings would not be comparable. Used by the per-file probe, which reads+ /// only the PK columns of a candidate file and therefore has no full-schema batch.+ pub fn contains_any_columns(&self, cols: &[Arc<dyn Array>], num_rows: usize) -> Result<bool> {+ if self.keys.is_empty() || num_rows == 0 {+ return Ok(false);+ }+ let mask = matchable_mask(cols, num_rows);+ let rows = self+ .converter+ .convert_columns(cols)+ .map_err(|e| Error::Generic(format!("row encode: {e}")))?;+ Ok((0..num_rows).any(|i| mask[i] && self.keys.contains(rows.row(i).as_ref())))+ }++ /// For each row of `batch`, whether it is replaced by a source row.+ pub fn contains_rows(&self, batch: &RecordBatch) -> Result<Vec<bool>> {+ let cols = self.pk_columns(batch);+ let mask = matchable_mask(&cols, batch.num_rows());+ let rows = self+ .converter+ .convert_columns(&cols)+ .map_err(|e| Error::Generic(format!("row encode: {e}")))?;++ Ok((0..batch.num_rows())+ .map(|i| mask[i] && self.keys.contains(rows.row(i).as_ref()))+ .collect())+ }++ /// Number of matchable keys in the set.+ pub fn len(&self) -> usize {+ self.keys.len()+ }++ /// True when the set holds no matchable key (e.g. every source row had a NULL PK).+ pub fn is_empty(&self) -> bool {+ self.keys.is_empty()+ }++ /// Resident bytes of the encoded key set (keys only, excluding `HashSet` overhead).+ /// Used by the source-size guard to report how large a rejected set was.+ pub fn approx_bytes(&self) -> usize {+ self.keys.iter().map(|k| k.len() + 48).sum()+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use arrow_array::{Int64Array, StringArray};+ use arrow_schema::{DataType, Field, Schema};++ fn schema() -> SchemaRef {+ Arc::new(Schema::new(vec![+ Field::new("id", DataType::Utf8, true),+ Field::new("tenant", DataType::Int64, true),+ Field::new("payload", DataType::Utf8, true),+ ]))+ }++ fn batch(ids: Vec<Option<&str>>, tenants: Vec<Option<i64>>) -> RecordBatch {+ let n = ids.len();+ RecordBatch::try_new(+ schema(),+ vec![+ Arc::new(StringArray::from(ids)),+ Arc::new(Int64Array::from(tenants)),+ Arc::new(StringArray::from(vec![Some("x"); n])),+ ],+ )+ .unwrap()+ }++ fn cols(b: &RecordBatch, names: &[&str]) -> Vec<Arc<dyn Array>> {+ names+ .iter()+ .map(|n| b.column_by_name(n).unwrap().clone())+ .collect()+ }++ #[test]+ fn null_pk_rows_are_never_inserted_and_never_match() {+ let s = schema();+ let mut set = PkSet::new(&s, &["id".to_string()]).unwrap();+ let src = batch(vec![Some("a"), None, None], vec![Some(1), Some(2), Some(3)]);+ let dup = set.insert_columns(&cols(&src, &["id"]), 3).unwrap();+ // Two NULL-keyed rows: not duplicates of each other (NULL != NULL), not inserted.+ assert_eq!(dup, 0);+ assert_eq!(set.null_pk_rows, 2);+ assert_eq!(set.len(), 1);++ // A NULL-keyed target row never matches, even though the set contains keys.+ let target = batch(vec![Some("a"), None], vec![Some(9), Some(9)]);+ assert_eq!(set.contains_rows(&target).unwrap(), vec![true, false]);+ }++ #[test]+ fn null_in_any_composite_component_excludes_the_row() {+ let s = schema();+ let pks = vec!["id".to_string(), "tenant".to_string()];+ let mut set = PkSet::new(&s, &pks).unwrap();+ let src = batch(+ vec![Some("a"), Some("b"), None],+ vec![Some(1), None, Some(3)],+ );+ set.insert_columns(&cols(&src, &["id", "tenant"]), 3)+ .unwrap();+ assert_eq!(set.len(), 1); // only ("a", 1)+ assert_eq!(set.null_pk_rows, 2);++ // Only the exact tuple matches.+ let target = batch(+ vec![Some("a"), Some("a"), Some("b")],+ vec![Some(1), Some(2), None],+ );+ assert_eq!(+ set.contains_rows(&target).unwrap(),+ vec![true, false, false]+ );+ }++ #[test]+ fn duplicates_are_counted_within_and_across_insert_calls() {+ let s = schema();+ let mut set = PkSet::new(&s, &["id".to_string()]).unwrap();+ let b1 = batch(vec![Some("a"), Some("a")], vec![Some(1), Some(2)]);+ assert_eq!(set.insert_columns(&cols(&b1, &["id"]), 2).unwrap(), 1);+ // The same key arriving in a later call is still a duplicate.+ let b2 = batch(vec![Some("a"), Some("b")], vec![Some(3), Some(4)]);+ assert_eq!(set.insert_columns(&cols(&b2, &["id"]), 2).unwrap(), 1);+ assert_eq!(set.len(), 2);+ }++ #[test]+ fn contains_any_columns_short_circuits_and_respects_nulls() {+ let s = schema();+ let mut set = PkSet::new(&s, &["id".to_string()]).unwrap();+ let src = batch(vec![Some("hit")], vec![Some(1)]);+ set.insert_columns(&cols(&src, &["id"]), 1).unwrap();++ let miss = batch(vec![Some("x"), None], vec![Some(1), Some(2)]);+ assert!(!set.contains_any_columns(&cols(&miss, &["id"]), 2).unwrap());+ let hit = batch(vec![Some("x"), Some("hit")], vec![Some(1), Some(2)]);+ assert!(set.contains_any_columns(&cols(&hit, &["id"]), 2).unwrap());+ }++ #[test]+ fn empty_set_matches_nothing() {+ let s = schema();+ let set = PkSet::new(&s, &["id".to_string()]).unwrap();+ assert!(set.is_empty());+ let target = batch(vec![Some("a")], vec![Some(1)]);+ assert_eq!(set.contains_rows(&target).unwrap(), vec![false]);+ assert!(!set+ .contains_any_columns(&cols(&target, &["id"]), 1)+ .unwrap());+ }++ #[test]+ fn missing_pk_column_is_a_schema_mismatch() {+ let s = schema();+ let err = match PkSet::new(&s, &["nope".to_string()]) {+ Err(e) => e,+ Ok(_) => panic!("expected an error for a missing PK column"),+ };+ assert!(matches!(err, Error::SchemaMismatch(_)));+ }+}diff --git a/rust/deltalite/core/src/schema.rs b/rust/deltalite/core/src/schema.rsnew file mode 100644index 000000000000..4b0e4e806edc--- /dev/null+++ b/rust/deltalite/core/src/schema.rs@@ -0,0 +1,306 @@+//! Decimal buffer realignment and schema casting.+//!+//! The pyarrow-facing half of ingest (the C Data Interface import) lives in the+//! `deltalite-python` binding crate; everything here is pure arrow-rs so it can be+//! unit-tested without a Python runtime.++use std::sync::Arc;++use arrow_array::{make_array, new_null_array, Array, RecordBatch};+use arrow_buffer::Buffer;+use arrow_cast::{cast_with_options, CastOptions};+use arrow_data::ArrayData;+use arrow_schema::{DataType, Schema, SchemaRef};++use crate::errors::{Error, Result};++/// Copy any decimal value buffer that is not aligned to its native type's alignment into+/// a freshly allocated (and therefore correctly aligned) buffer. Recurses into children+/// so nested decimals are covered too.+///+/// This is the fix for delta-io/delta-rs#3884: arrow-rs asserts 16-byte alignment while+/// constructing the *typed* decimal array, and buffers arriving over the C Data+/// Interface from pyarrow are only guaranteed 8-byte aligned (an Arrow IPC round-trip+/// reliably produces one). The assert fires *inside* a `RecordBatch`-level import,+/// before any batch exists to repair -- so ingest must go column by column as+/// `ArrayData` (which carries untyped buffers) and pass through here before+/// `make_array` builds the typed array.+pub fn realign_array_data(data: ArrayData) -> Result<ArrayData> {+ Ok(realign_inner(data)?.0)+}++/// Realign `data`, returning it alongside whether anything in the subtree was repaired.+/// The `changed` flag is threaded up from the recursion rather than inferred from a+/// buffer-pointer comparison: a Struct carries no buffers of its own and a List/Map's+/// first buffer is its (unchanged) offsets, so a repaired decimal nested two or more+/// levels deep (e.g. `map<string, decimal>`) would otherwise look unchanged to its+/// parent and be silently discarded, leaving the delta-rs#3884 panic to still fire.+fn realign_inner(data: ArrayData) -> Result<(ArrayData, bool)> {+ // arrow-rs represents Decimal256 as `i256`, a `#[repr(C)]` pair of 128-bit lanes, so+ // both decimal widths require 16-byte alignment.+ let align = match data.data_type() {+ DataType::Decimal128(_, _) | DataType::Decimal256(_, _) => {+ Some(std::mem::align_of::<i128>())+ }+ _ => None,+ };++ let mut children = Vec::with_capacity(data.child_data().len());+ let mut child_changed = false;+ for c in data.child_data() {+ let (fixed, changed) = realign_inner(c.clone())?;+ child_changed |= changed;+ children.push(fixed);+ }++ let needs_fix = align+ .map(|a| {+ data.buffers()+ .iter()+ .any(|b| !(b.as_ptr() as usize).is_multiple_of(a))+ })+ .unwrap_or(false);++ if !needs_fix && !child_changed {+ return Ok((data, false));+ }++ let buffers = if needs_fix {+ data.buffers()+ .iter()+ .map(|b| realign_buffer(b, align.unwrap_or(16)))+ .collect()+ } else {+ data.buffers().to_vec()+ };++ let builder = data.into_builder().buffers(buffers).child_data(children);+ // Only buffers were replaced, with byte-identical copies, so the layout the+ // original data was validated against still holds.+ let built = builder+ .build()+ .map_err(|e| Error::Generic(format!("rebuilding realigned array: {e}")))?;+ Ok((built, true))+}++/// Byte-identical copy of `buf` into a `Vec<i128>` allocation, which the allocator+/// guarantees is 16-byte aligned.+fn realign_buffer(buf: &Buffer, align: usize) -> Buffer {+ if (buf.as_ptr() as usize).is_multiple_of(align) {+ return buf.clone();+ }+ let bytes = buf.as_slice();+ // Copy through `i128` lanes so the fresh allocation is 16-byte aligned; the final+ // partial chunk is zero-padded and sliced back off below.+ let v: Vec<i128> = bytes+ .chunks(16)+ .map(|chunk| {+ let mut lane = [0u8; 16];+ lane[..chunk.len()].copy_from_slice(chunk);+ i128::from_ne_bytes(lane)+ })+ .collect();+ Buffer::from_vec(v).slice_with_length(0, bytes.len())+}++/// Cast `batch` to `target`, padding columns absent from the batch with nulls.+///+/// This is the equivalent of delta-rs's `schema_mode="merge"` for the additive-evolution+/// case: old Parquet files predating an `add_columns` are read up to the current schema,+/// and incoming batches missing a recently added column get nulls for it.+pub fn cast_to_schema(batch: &RecordBatch, target: &SchemaRef) -> Result<RecordBatch> {+ let opts = CastOptions {+ safe: false,+ ..Default::default()+ };+ let mut cols = Vec::with_capacity(target.fields().len());++ for field in target.fields() {+ match batch.schema().index_of(field.name()) {+ Ok(idx) => {+ let col = batch.column(idx);+ if col.data_type() == field.data_type() {+ cols.push(col.clone());+ } else {+ cols.push(+ cast_with_options(col, field.data_type(), &opts).map_err(|e| {+ Error::SchemaMismatch(format!(+ "cannot cast column '{}' from {:?} to {:?}: {e}",+ field.name(),+ col.data_type(),+ field.data_type()+ ))+ })?,+ );+ }+ }+ Err(_) => cols.push(new_null_array(field.data_type(), batch.num_rows())),+ }+ }++ Ok(RecordBatch::try_new(target.clone(), cols)?)+}++/// Columns present in `source` but absent from the table schema. Schema evolution is+/// expected to have run before `upsert`, so these are a genuine mismatch.+pub fn unknown_columns(source: &Schema, target: &Schema) -> Vec<String> {+ source+ .fields()+ .iter()+ .filter(|f| target.index_of(f.name()).is_err())+ .map(|f| f.name().clone())+ .collect()+}++/// Import helper shared with the binding crate: realign a freshly imported column and+/// build the typed array. Split out so the alignment-sensitive step is testable here.+pub fn import_column(data: ArrayData) -> Result<Arc<dyn Array>> {+ Ok(make_array(realign_array_data(data)?))+}++#[cfg(test)]+mod tests {+ use super::*;+ use arrow_array::cast::AsArray;+ use arrow_array::types::Decimal128Type;+ use arrow_array::{Decimal128Array, Int64Array, StringArray};+ use arrow_schema::Field;++ /// Build a Decimal128 `ArrayData` whose value buffer is deliberately NOT 16-byte+ /// aligned, the exact shape a pyarrow IPC round-trip hands us over FFI.+ fn misaligned_decimal_data(values: &[i128]) -> ArrayData {+ let mut bytes: Vec<u8> = vec![0u8; 8]; // 8-byte prefix forces misalignment+ for v in values {+ bytes.extend_from_slice(&v.to_le_bytes());+ }+ let buf = Buffer::from_vec(bytes).slice(8);+ assert_ne!(+ (buf.as_ptr() as usize) % 16,+ 0,+ "test setup failed to produce a misaligned buffer"+ );+ let builder = ArrayData::builder(DataType::Decimal128(38, 10))+ .len(values.len())+ .add_buffer(buf);+ // SAFETY: length/buffer layout are valid by construction; the only invariant+ // violated is 16-byte alignment, which is exactly the (real, FFI-produced)+ // condition this test exists to reproduce -- validated `build()` would reject+ // the input before the repair under test could run.+ // nosemgrep: rust.lang.security.unsafe-usage.unsafe-usage+ unsafe { builder.build_unchecked() }+ }++ #[test]+ fn realigns_misaligned_decimal_buffer() {+ let values = [1_i128, -2, 3_000_000_000];+ let data = misaligned_decimal_data(&values);+ let fixed = realign_array_data(data).unwrap();+ assert_eq!(+ (fixed.buffers()[0].as_ptr() as usize) % 16,+ 0,+ "buffer must be 16-byte aligned after realignment"+ );+ // And the typed array constructs (this is where #3884 aborts) with equal values.+ let arr = make_array(fixed);+ let arr = arr.as_primitive::<Decimal128Type>();+ assert_eq!(arr.values(), &values[..]);+ }++ /// Wrap `child` in a single-field, non-nullable Struct via `build_unchecked` (a+ /// validated `build()` would reject the deliberately misaligned decimal leaf before+ /// the repair under test could run).+ fn wrap_in_struct(child: ArrayData, field_name: &str) -> ArrayData {+ let len = child.len();+ let field = Field::new(field_name, child.data_type().clone(), true);+ let ty = DataType::Struct(vec![field].into());+ let builder = ArrayData::builder(ty).len(len).add_child_data(child);+ // SAFETY: layout is valid by construction; only the leaf's 16-byte alignment is+ // violated, which is the FFI-produced condition under repair here.+ // nosemgrep: rust.lang.security.unsafe-usage.unsafe-usage+ unsafe { builder.build_unchecked() }+ }++ #[test]+ fn realigns_decimal_nested_two_levels_deep() {+ // struct<struct<decimal>>: the intermediate structs carry no buffers of their+ // own, so the old first-buffer-pointer heuristic saw "no change" at the top and+ // discarded the repair -- reproducing delta-rs#3884 for depth >= 2 decimals.+ let values = [1_i128, -2, 3_000_000_000];+ let leaf = misaligned_decimal_data(&values);+ let nested = wrap_in_struct(wrap_in_struct(leaf, "d"), "s");+ let fixed = realign_array_data(nested).unwrap();++ let leaf = &fixed.child_data()[0].child_data()[0];+ assert_eq!(+ (leaf.buffers()[0].as_ptr() as usize) % 16,+ 0,+ "nested decimal buffer must be realigned"+ );+ // And the typed leaf array constructs (this is where #3884 aborts).+ let arr = make_array(leaf.clone());+ let arr = arr.as_primitive::<Decimal128Type>();+ assert_eq!(arr.values(), &values[..]);+ }++ #[test]+ fn aligned_buffers_are_left_untouched() {+ let arr = Decimal128Array::from(vec![1_i128, 2, 3]);+ let data = arr.to_data();+ let before = data.buffers()[0].as_ptr();+ let fixed = realign_array_data(data).unwrap();+ assert_eq!(fixed.buffers()[0].as_ptr(), before, "no copy expected");+ }++ #[test]+ fn cast_pads_missing_columns_with_nulls_and_casts_types() {+ let target: SchemaRef = Arc::new(Schema::new(vec![+ Field::new("id", DataType::Utf8, true),+ Field::new("n", DataType::Int64, true),+ Field::new("added_later", DataType::Utf8, true),+ ]));+ let batch = RecordBatch::try_new(+ Arc::new(Schema::new(vec![+ Field::new("id", DataType::Utf8, true),+ Field::new("n", DataType::Int32, true),+ ])),+ vec![+ Arc::new(StringArray::from(vec!["a", "b"])),+ Arc::new(arrow_array::Int32Array::from(vec![1, 2])),+ ],+ )+ .unwrap();++ let out = cast_to_schema(&batch, &target).unwrap();+ assert_eq!(out.schema(), target);+ let n = out.column_by_name("n").unwrap();+ assert_eq!(n.data_type(), &DataType::Int64);+ assert_eq!(+ n.as_any().downcast_ref::<Int64Array>().unwrap().values(),+ &[1, 2]+ );+ assert_eq!(out.column_by_name("added_later").unwrap().null_count(), 2);+ }++ #[test]+ fn uncastable_column_is_a_schema_mismatch() {+ let target: SchemaRef = Arc::new(Schema::new(vec![Field::new("n", DataType::Int64, true)]));+ let batch = RecordBatch::try_new(+ Arc::new(Schema::new(vec![Field::new("n", DataType::Utf8, true)])),+ vec![Arc::new(StringArray::from(vec!["not a number"]))],+ )+ .unwrap();+ let err = cast_to_schema(&batch, &target).unwrap_err();+ assert!(matches!(err, Error::SchemaMismatch(_)), "{err}");+ }++ #[test]+ fn unknown_columns_reports_only_extras() {+ let target = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);+ let source = Schema::new(vec![+ Field::new("a", DataType::Utf8, true),+ Field::new("b", DataType::Utf8, true),+ ]);+ assert_eq!(unknown_columns(&source, &target), vec!["b".to_string()]);+ assert!(unknown_columns(&target, &source).is_empty());+ }+}diff --git a/rust/deltalite/core/src/store.rs b/rust/deltalite/core/src/store.rsnew file mode 100644index 000000000000..0462436b96aa--- /dev/null+++ b/rust/deltalite/core/src/store.rs@@ -0,0 +1,367 @@+//! Multipart upload for large data files.+//!+//! `RecordBatchWriter::flush()` uploads each finished Parquet file through+//! `ObjectStore::put` -- a single PUT (~`target_file_size` bytes, 100 MB by default).+//! On real S3 that serialises the whole file on one connection and re-uploads+//! everything on a connection reset; measured under injected per-request latency it+//! cost deltalite ~4x more wall-clock than MERGE. delta-rs's own DataFusion writer+//! uses ~5 MB multipart parts for the same reason.+//!+//! The writer offers no hook to change this, but the store it writes through does:+//! `RecordBatchWriter::for_table` takes `table.object_store()`, which comes from the+//! table's `LogStore`. [`MultipartPutStore`] wraps an object store so that plain+//! overwrite `put`s above a size threshold become multipart uploads, and+//! [`MultipartLogStore`] wraps a log store to hand that store to the writer.+//!+//! Commit safety is deliberately untouched: log-store commit writes go through+//! `write_commit_entry` (delegated verbatim to the inner log store, preserving the+//! conditional-put `If-None-Match` behaviour), and any `put_opts` with a non-Overwrite+//! mode or a preconditioned option set is forwarded unmodified.++use std::sync::Arc;++use async_trait::async_trait;+use bytes::Bytes;+use deltalake::kernel::transaction::TransactionError;+use deltalake::logstore::{CommitOrBytes, LogStore, LogStoreConfig};+use futures::stream::BoxStream;+use object_store::path::Path;+use object_store::{+ GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, PutMode,+ PutMultipartOptions, PutOptions, PutPayload, PutResult,+};+use uuid::Uuid;++/// Default size above which a single `put` becomes a multipart upload.+pub const DEFAULT_MULTIPART_THRESHOLD: usize = 64 * 1024 * 1024;+/// Part size for multipart uploads. Must be >= 5 MiB for S3; 16 MiB balances request+/// count against retry granularity.+pub const DEFAULT_MULTIPART_PART_SIZE: usize = 16 * 1024 * 1024;++/// An [`ObjectStore`] wrapper that turns large plain-overwrite `put`s into multipart+/// uploads and delegates everything else.+#[derive(Debug)]+pub struct MultipartPutStore {+ inner: Arc<dyn ObjectStore>,+ threshold: usize,+ part_size: usize,+}++impl MultipartPutStore {+ /// Wrap `inner`; `threshold` of 0 disables the rewrite (pure delegation).+ pub fn new(inner: Arc<dyn ObjectStore>, threshold: usize, part_size: usize) -> Self {+ Self {+ inner,+ threshold,+ part_size: part_size.max(5 * 1024 * 1024),+ }+ }++ /// Split `payload` into parts of at most `part_size` bytes, zero-copy (`Bytes`+ /// slices share the underlying allocation).+ fn split_parts(&self, payload: &PutPayload) -> Vec<PutPayload> {+ let mut parts: Vec<PutPayload> = Vec::new();+ let mut current: Vec<Bytes> = Vec::new();+ let mut current_len = 0usize;+ for chunk in payload.as_ref() {+ let mut offset = 0usize;+ while offset < chunk.len() {+ let room = self.part_size - current_len;+ let take = room.min(chunk.len() - offset);+ current.push(chunk.slice(offset..offset + take));+ current_len += take;+ offset += take;+ if current_len == self.part_size {+ parts.push(PutPayload::from_iter(current.drain(..)));+ current_len = 0;+ }+ }+ }+ if current_len > 0 {+ parts.push(PutPayload::from_iter(current.drain(..)));+ }+ parts+ }+}++impl std::fmt::Display for MultipartPutStore {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "MultipartPutStore({})", self.inner)+ }+}++#[async_trait]+impl ObjectStore for MultipartPutStore {+ async fn put_opts(+ &self,+ location: &Path,+ payload: PutPayload,+ opts: PutOptions,+ ) -> object_store::Result<PutResult> {+ // Only rewrite the plain overwrite path (data-file uploads). Conditional puts+ // (PutMode::Create -- Delta log commits -- or Update) must keep their exact+ // semantics, so they are forwarded untouched.+ if self.threshold == 0+ || !matches!(opts.mode, PutMode::Overwrite)+ || payload.content_length() < self.threshold+ {+ return self.inner.put_opts(location, payload, opts).await;+ }++ let multipart_opts = PutMultipartOptions {+ tags: opts.tags,+ attributes: opts.attributes,+ extensions: opts.extensions,+ };+ let mut upload = self+ .inner+ .put_multipart_opts(location, multipart_opts)+ .await?;+ for part in self.split_parts(&payload) {+ if let Err(e) = upload.put_part(part).await {+ // Best-effort cleanup of the incomplete upload; the original error is+ // what the caller needs to see.+ drop(upload.abort().await);+ return Err(e);+ }+ }+ match upload.complete().await {+ Ok(result) => Ok(result),+ Err(e) => {+ drop(upload.abort().await);+ Err(e)+ }+ }+ }++ async fn put_multipart_opts(+ &self,+ location: &Path,+ opts: PutMultipartOptions,+ ) -> object_store::Result<Box<dyn MultipartUpload>> {+ self.inner.put_multipart_opts(location, opts).await+ }++ async fn get_opts(+ &self,+ location: &Path,+ options: GetOptions,+ ) -> object_store::Result<GetResult> {+ self.inner.get_opts(location, options).await+ }++ async fn get_ranges(+ &self,+ location: &Path,+ ranges: &[std::ops::Range<u64>],+ ) -> object_store::Result<Vec<Bytes>> {+ self.inner.get_ranges(location, ranges).await+ }++ fn delete_stream(+ &self,+ locations: BoxStream<'static, object_store::Result<Path>>,+ ) -> BoxStream<'static, object_store::Result<Path>> {+ self.inner.delete_stream(locations)+ }++ fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ self.inner.list(prefix)+ }++ fn list_with_offset(+ &self,+ prefix: Option<&Path>,+ offset: &Path,+ ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {+ self.inner.list_with_offset(prefix, offset)+ }++ async fn list_with_delimiter(&self, prefix: Option<&Path>) -> object_store::Result<ListResult> {+ self.inner.list_with_delimiter(prefix).await+ }++ async fn copy_opts(+ &self,+ from: &Path,+ to: &Path,+ options: object_store::CopyOptions,+ ) -> object_store::Result<()> {+ self.inner.copy_opts(from, to, options).await+ }++ async fn rename_opts(+ &self,+ from: &Path,+ to: &Path,+ options: object_store::RenameOptions,+ ) -> object_store::Result<()> {+ self.inner.rename_opts(from, to, options).await+ }+}++/// A [`LogStore`] wrapper whose `object_store()` returns a [`MultipartPutStore`] over+/// the inner store, so data files written by `RecordBatchWriter` (and read by the+/// probe/rewrite) go through the multipart-aware store while commit-entry writes stay+/// on the inner log store's own path.+pub struct MultipartLogStore {+ inner: Arc<dyn LogStore>,+ threshold: usize,+ part_size: usize,+}++impl MultipartLogStore {+ /// Wrap `inner` with the given multipart threshold and part size.+ pub fn new(inner: Arc<dyn LogStore>, threshold: usize, part_size: usize) -> Self {+ Self {+ inner,+ threshold,+ part_size,+ }+ }+}++impl std::fmt::Debug for MultipartLogStore {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "MultipartLogStore({})", self.inner.name())+ }+}++#[async_trait]+impl LogStore for MultipartLogStore {+ fn name(&self) -> String {+ // Delegated VERBATIM, not decorated: delta-rs's transaction layer string-matches+ // `log_store.name()` (`["LakeFSLogStore", "DefaultLogStore"]`) to decide between+ // the conditional-put commit path (LogBytes) and the tmp-commit + rename path.+ // A decorated name silently switched every commit onto the tmp-commit path,+ // which `DefaultLogStore::write_commit_entry` rejects with `unreachable!()`.+ // The wrapper changes nothing about commit behaviour, so it must present the+ // inner store's identity.+ self.inner.name()+ }++ async fn refresh(&self) -> deltalake::DeltaResult<()> {+ self.inner.refresh().await+ }++ async fn read_commit_entry(&self, version: u64) -> deltalake::DeltaResult<Option<Bytes>> {+ self.inner.read_commit_entry(version).await+ }++ async fn write_commit_entry(+ &self,+ version: u64,+ commit_or_bytes: CommitOrBytes,+ operation_id: Uuid,+ ) -> Result<(), TransactionError> {+ self.inner+ .write_commit_entry(version, commit_or_bytes, operation_id)+ .await+ }++ async fn abort_commit_entry(+ &self,+ version: u64,+ commit_or_bytes: CommitOrBytes,+ operation_id: Uuid,+ ) -> Result<(), TransactionError> {+ self.inner+ .abort_commit_entry(version, commit_or_bytes, operation_id)+ .await+ }++ async fn get_latest_version(&self, start_version: u64) -> deltalake::DeltaResult<u64> {+ self.inner.get_latest_version(start_version).await+ }++ fn object_store(&self, operation_id: Option<Uuid>) -> Arc<dyn ObjectStore> {+ Arc::new(MultipartPutStore::new(+ self.inner.object_store(operation_id),+ self.threshold,+ self.part_size,+ ))+ }++ fn root_object_store(&self, operation_id: Option<Uuid>) -> Arc<dyn ObjectStore> {+ Arc::new(MultipartPutStore::new(+ self.inner.root_object_store(operation_id),+ self.threshold,+ self.part_size,+ ))+ }++ fn config(&self) -> &LogStoreConfig {+ self.inner.config()+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use object_store::memory::InMemory;+ use object_store::ObjectStoreExt;++ fn payload_of(len: usize) -> PutPayload {+ PutPayload::from_bytes(Bytes::from(vec![7u8; len]))+ }++ #[tokio::test]+ async fn small_put_is_delegated_and_readable() {+ let inner = Arc::new(InMemory::new());+ let store = MultipartPutStore::new(inner.clone(), 1024, 5 * 1024 * 1024);+ let path = Path::from("small");+ store.put(&path, payload_of(100)).await.unwrap();+ let got = inner.get(&path).await.unwrap().bytes().await.unwrap();+ assert_eq!(got.len(), 100);+ }++ #[tokio::test]+ async fn large_put_goes_multipart_and_content_is_identical() {+ let inner = Arc::new(InMemory::new());+ // Force multipart with a tiny threshold; part size is clamped to >= 5 MiB, so+ // use a payload bigger than one part to exercise splitting.+ let store = MultipartPutStore::new(inner.clone(), 1024, 5 * 1024 * 1024);+ let path = Path::from("large");+ let len = 11 * 1024 * 1024; // 3 parts at 5 MiB+ let mut data = Vec::with_capacity(len);+ for i in 0..len {+ data.push((i % 251) as u8);+ }+ let payload = PutPayload::from_bytes(Bytes::from(data.clone()));+ store.put(&path, payload).await.unwrap();+ let got = inner.get(&path).await.unwrap().bytes().await.unwrap();+ assert_eq!(got.as_ref(), data.as_slice(), "content must round-trip");+ }++ #[tokio::test]+ async fn conditional_puts_are_never_rewritten() {+ let inner = Arc::new(InMemory::new());+ let store = MultipartPutStore::new(inner.clone(), 1, 5 * 1024 * 1024);+ let path = Path::from("commit");+ let opts = PutOptions::from(PutMode::Create);+ store+ .put_opts(&path, payload_of(10_000), opts.clone())+ .await+ .unwrap();+ // Second Create on the same path must fail exactly as the inner store would --+ // this is the conditional-put semantics Delta commits rely on.+ let err = store.put_opts(&path, payload_of(10_000), opts).await;+ assert!(+ matches!(err, Err(object_store::Error::AlreadyExists { .. })),+ "{err:?}"+ );+ }++ #[test]+ fn split_parts_respects_part_size_and_preserves_bytes() {+ let store = MultipartPutStore::new(Arc::new(InMemory::new()), 1, 5 * 1024 * 1024);+ let a = Bytes::from(vec![1u8; 3 * 1024 * 1024]);+ let b = Bytes::from(vec![2u8; 9 * 1024 * 1024]);+ let payload = PutPayload::from_iter(vec![a, b]);+ let parts = store.split_parts(&payload);+ assert_eq!(parts.len(), 3); // 12 MiB at 5 MiB parts+ assert!(parts.iter().all(|p| p.content_length() <= 5 * 1024 * 1024));+ let total: usize = parts.iter().map(|p| p.content_length()).sum();+ assert_eq!(total, 12 * 1024 * 1024);+ }+}diff --git a/rust/deltalite/core/src/table.rs b/rust/deltalite/core/src/table.rsnew file mode 100644index 000000000000..47daf8cb55ce--- /dev/null+++ b/rust/deltalite/core/src/table.rs@@ -0,0 +1,77 @@+//! Table opening helpers.++use std::collections::HashMap;+use std::sync::Arc;++use deltalake::{DeltaTable, DeltaTableBuilder};++use crate::errors::{Error, Result};+use crate::store::MultipartLogStore;++/// How data-file uploads are performed.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct MultipartConfig {+ /// Files at or above this size upload as multipart; 0 disables the rewrite.+ pub threshold: usize,+ /// Part size for multipart uploads (clamped to >= 5 MiB by the store wrapper).+ pub part_size: usize,+}++impl Default for MultipartConfig {+ fn default() -> Self {+ Self {+ threshold: crate::store::DEFAULT_MULTIPART_THRESHOLD,+ part_size: crate::store::DEFAULT_MULTIPART_PART_SIZE,+ }+ }+}++impl MultipartConfig {+ /// Resolve from explicit arguments, then `DELTALITE_MULTIPART_THRESHOLD_BYTES` /+ /// `DELTALITE_MULTIPART_PART_SIZE_BYTES`, then the defaults. An explicit+ /// `Some(0)` threshold disables multipart entirely.+ pub fn resolve(threshold: Option<usize>, part_size: Option<usize>) -> Self {+ let d = Self::default();+ Self {+ threshold: threshold.unwrap_or_else(|| {+ crate::limits::env_usize("DELTALITE_MULTIPART_THRESHOLD_BYTES", d.threshold)+ }),+ part_size: part_size.unwrap_or_else(|| {+ crate::limits::env_usize("DELTALITE_MULTIPART_PART_SIZE_BYTES", d.part_size)+ }),+ }+ }+}++/// Open and load a Delta table from `uri` with the given delta-rs `storage_options`+/// (the same keys the Python package accepts; the dict passes through unchanged).+pub async fn open_table(uri: &str, storage_options: HashMap<String, String>) -> Result<DeltaTable> {+ let url = deltalake::ensure_table_uri(uri)+ .map_err(|e| Error::NotFound(format!("invalid table uri {uri}: {e}")))?;+ Ok(DeltaTableBuilder::from_url(url)?+ .with_storage_options(storage_options)+ .load()+ .await?)+}++/// Open a table whose data-file uploads go through the multipart-aware store wrapper+/// (see [`crate::store`]). Commit-entry writes keep the inner log store's conditional+/// -put path untouched.+pub async fn open_table_multipart(+ uri: &str,+ storage_options: HashMap<String, String>,+ multipart: MultipartConfig,+) -> Result<DeltaTable> {+ let table = open_table(uri, storage_options).await?;+ if multipart.threshold == 0 {+ return Ok(table);+ }+ let wrapped = Arc::new(MultipartLogStore::new(+ table.log_store(),+ multipart.threshold,+ multipart.part_size,+ ));+ let mut wrapped_table = DeltaTable::new(wrapped, Default::default());+ wrapped_table.load().await.map_err(Error::from)?;+ Ok(wrapped_table)+}diff --git a/rust/deltalite/core/src/upsert.rs b/rust/deltalite/core/src/upsert.rsnew file mode 100644index 000000000000..7ddef11bb308--- /dev/null+++ b/rust/deltalite/core/src/upsert.rs@@ -0,0 +1,2108 @@+//! Streaming partition-level upsert.+//!+//! For each affected partition: build a PK hash set over the incoming rows, stream the+//! partition's existing Parquet files a row group at a time, drop rows whose PK is being+//! replaced, write survivors plus the new rows through a stats-producing writer, and+//! collect Add/Remove actions. All partitions land in a single `CommitBuilder` commit.+//!+//! No DataFusion, no join, no spill. Within a partition, files are read and filtered by+//! up to `max_parallel_files` concurrent readers feeding one writer task through a+//! channel; every surviving batch holds byte-budget permits from decode until it has+//! been handed to the write buffer, so decompressed survivor data in flight never+//! exceeds the budget no matter what the product of the parallelism knobs is. All three+//! budgets are enforced twice: per call (the `UpsertOptions` knobs) and per process+//! ([`ProcessLimits`]), because production runs many upserts concurrently as threads in+//! one worker process.+//!+//! The source is held exactly once: partition membership is planned as row selections+//! (`RowSel`) into the caller's cast batches, and a partition's rows are materialised+//! only inside its worker -- transiently for the PK set (narrow columns) and the final+//! write. Peak memory is bounded by `source (1x, shared with the caller)+//! + max_parallel_partitions * (one partition's slice + PK set + write buffer)+//! + max_buffered_bytes + in-flight read batches`, and the source term is guarded by+//! [`crate::limits::check_source_size`].++use std::collections::{HashMap, HashSet};+use std::sync::Arc;+use std::time::Instant;++use arrow_array::{Array, RecordBatch, StringArray, UInt32Array};+use arrow_cast::{cast_with_options, CastOptions};+use arrow_schema::{DataType, Field, Schema, SchemaRef};+use arrow_select::filter::filter_record_batch;+use arrow_select::take::{take, take_record_batch};+use deltalake::kernel::transaction::{CommitBuilder, CommitProperties};+use deltalake::kernel::{Action, Remove};+use deltalake::protocol::{DeltaOperation, SaveMode};+use deltalake::table::config::TablePropertiesExt;+use deltalake::writer::{DeltaWriter, RecordBatchWriter};+use deltalake::{DeltaTable, ObjectStore, PartitionFilter, PartitionValue, Path};+use futures::{StreamExt, TryStreamExt};+use metrics::{counter, histogram};+use parquet::arrow::async_reader::ParquetObjectReader;+use parquet::arrow::ParquetRecordBatchStreamBuilder;+use parquet::arrow::ProjectionMask;+use parquet::file::metadata::ParquetMetaData;+use serde_json::Value;+use tokio::sync::{mpsc, OwnedSemaphorePermit, Semaphore};+use tracing::{debug, info, instrument};++use crate::errors::{Error, Result};+use crate::limits::{+ check_source_size, estimate_pk_set_bytes, resolve_max_source_bytes, ProcessLimits,+ SourceFootprint,+};+use crate::pkset::PkSet;+use crate::schema::{cast_to_schema, unknown_columns};++/// One logical group of work: a partition value (or the whole table when unpartitioned).+const WHOLE_TABLE: &str = "__deltalite_whole_table__";++/// First-iteration pre-decode budget reservation for full-width row groups; adapts to+/// the observed batch size after the first decode.+const INITIAL_DECODE_ESTIMATE_BYTES: usize = 4 * 1024 * 1024;+/// First-iteration pre-decode reservation for narrow PK-column probe batches.+const INITIAL_PROBE_ESTIMATE_BYTES: usize = 256 * 1024;++/// Read batch size (in rows) that keeps a decoded batch near `target_bytes`, derived from+/// the widest row group's average *uncompressed* bytes/row.+///+/// A batch never spans more than one row group, so `total_byte_size / num_rows` upper-bounds+/// the per-row content a batch decodes. Sizing the read by this bounds a batch's resident+/// footprint by content rather than by a fixed row count, so a tenant syncing wide or highly+/// compressible rows can't inflate a single decoded batch far past the pre-decode reservation+/// (which would otherwise sit unaccounted while the reader tops its permit up). Clamped to+/// `[1, cap]`; falls back to `cap` when metadata carries no usable sizes.+fn byte_bounded_batch_rows(meta: &ParquetMetaData, target_bytes: usize, cap: usize) -> usize {+ let max_bytes_per_row = meta+ .row_groups()+ .iter()+ .filter(|rg| rg.num_rows() > 0)+ .map(|rg| (rg.total_byte_size().max(0) as usize).div_ceil(rg.num_rows() as usize))+ .max()+ .unwrap_or(0);+ batch_rows_for_bytes_per_row(max_bytes_per_row, target_bytes, cap)+}++/// Rows that fit `target_bytes` at `max_bytes_per_row`, clamped to `[1, cap]`. Split out+/// from `byte_bounded_batch_rows` so the sizing arithmetic is unit-testable without a+/// `ParquetMetaData`. A zero bytes/row (no usable metadata) falls back to the full `cap`.+fn batch_rows_for_bytes_per_row(+ max_bytes_per_row: usize,+ target_bytes: usize,+ cap: usize,+) -> usize {+ let cap = cap.max(1);+ if max_bytes_per_row == 0 {+ return cap;+ }+ (target_bytes / max_bytes_per_row).clamp(1, cap)+}++/// How the set of existing files to rewrite is chosen within each affected partition.+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]+pub enum PruneStrategy {+ /// Rewrite every live file in the partition.+ None,+ /// Skip files whose Add-action statistics *prove* they hold no match: min/max+ /// disjointness on the first PK column, or a PK column that is entirely NULL+ /// (`nullCount == numRecords`; SQL NULL never matches). Zero extra I/O, but+ /// approximate-conservative: with random UUID keys min/max excludes nothing.+ Stats,+ /// `Stats` first, then read ONLY the PK column(s) of each surviving file (Parquet+ /// projection pushdown) and probe them against the source PK set, skipping files+ /// with zero matches. Exact, like MERGE's join-based file selection, at the cost of+ /// one streamed pass over one narrow column per candidate file. With random UUID+ /// keys (whose min/max stats prune nothing), this is what keeps bytes written+ /// identical to MERGE instead of rewriting every candidate file.+ #[default]+ Probe,+}++impl PruneStrategy {+ /// Static label for metrics; never allocate for metric labels (rust/CLAUDE.md).+ pub fn as_str(&self) -> &'static str {+ match self {+ PruneStrategy::None => "none",+ PruneStrategy::Stats => "stats",+ PruneStrategy::Probe => "probe",+ }+ }+}++impl std::str::FromStr for PruneStrategy {+ type Err = Error;++ fn from_str(s: &str) -> Result<Self> {+ match s.to_ascii_lowercase().as_str() {+ "none" => Ok(Self::None),+ "stats" => Ok(Self::Stats),+ "probe" => Ok(Self::Probe),+ other => Err(Error::Generic(format!(+ "unknown prune_strategy '{other}' (expected 'none', 'stats' or 'probe')"+ ))),+ }+ }+}++/// Options controlling a single `upsert` call.+pub struct UpsertOptions {+ /// Column names forming the primary key, in order.+ pub primary_keys: Vec<String>,+ /// The partition column the caller believes the table uses; the table's own+ /// metadata remains the source of truth.+ pub partition_key: Option<String>,+ /// Extra `commitInfo` metadata (e.g. `run_uuid` / `batch_index` idempotency tags).+ pub commit_metadata: Option<HashMap<String, Value>>,+ /// Concurrent partition workers within this call.+ pub max_parallel_partitions: usize,+ /// How the rewrite set is chosen. See [`PruneStrategy`].+ pub prune_strategy: PruneStrategy,+ /// How many files a partition worker probes concurrently. Each in-flight probe+ /// holds only a Parquet footer plus one decoded batch of the PK column(s), so the+ /// memory bound is `max_parallel_partitions * probe_concurrency * O(batch of PKs)`+ /// -- a few MB, independent of table size.+ pub probe_concurrency: usize,+ /// Concurrent file readers *within* one partition. Files are independent for the+ /// read->probe->filter stage; a single writer task per partition consumes their+ /// output, so file count and output-file sizing are unchanged by this knob.+ pub max_parallel_files: usize,+ /// Per-call cap (bytes) on decompressed survivor batches in flight across this+ /// call's partition workers and file readers. The process-wide cap in+ /// [`ProcessLimits`] applies on top.+ pub max_buffered_bytes: usize,+ /// Commit retry budget handed to `CommitBuilder`.+ pub commit_max_retries: usize,+ /// Row-count granularity for Parquet reads and source-slice writes.+ pub read_batch_size: usize,+ /// Flush the write buffer once it exceeds this many bytes, bounding resident memory+ /// at the cost of more (smaller) output files.+ ///+ /// `None` means "use the table's own `delta.targetFileSize`", falling back to+ /// delta-rs's `DEFAULT_TARGET_FILE_SIZE` (100 MiB) when the table does not set it --+ /// which is what every other delta-rs operation (optimize, merge, delete, update,+ /// write) does. Hardcoding a value here would make `upsert` the one writer that+ /// ignores a table explicitly configured with a different target.+ ///+ /// Note this knob does double duty in deltalite: it shapes output file size *and*+ /// is the write-buffer flush threshold, so it is also a memory knob worth+ /// `max_parallel_partitions x target_file_size` of exposure.+ pub target_file_size: Option<usize>,+ /// Ceiling for the source-size guard; `None` resolves from the environment,+ /// `Some(0)` disables. See [`crate::limits::resolve_max_source_bytes`].+ pub max_source_bytes: Option<usize>,+ /// Process-wide concurrency budgets shared with every other concurrent upsert.+ pub limits: Arc<ProcessLimits>,+}++impl Default for UpsertOptions {+ fn default() -> Self {+ Self {+ primary_keys: Vec::new(),+ partition_key: None,+ commit_metadata: None,+ max_parallel_partitions: 2,+ prune_strategy: PruneStrategy::Probe,+ probe_concurrency: 8,+ max_parallel_files: 4,+ max_buffered_bytes: 64 * 1024 * 1024,+ commit_max_retries: 15,+ read_batch_size: 8192,+ target_file_size: None,+ max_source_bytes: None,+ limits: ProcessLimits::global().clone(),+ }+ }+}++/// Counters describing what one `upsert` did.+#[derive(Default, Debug, Clone)]+pub struct UpsertStats {+ /// The committed table version.+ pub version: i64,+ /// Distinct partitions the batch touched.+ pub partitions_touched: usize,+ /// Existing files tombstoned (rewritten).+ pub files_removed: usize,+ /// New files written.+ pub files_added: usize,+ /// Live files proven match-free and left untouched.+ pub files_carried_over: usize,+ /// Files whose PK column(s) were actually read by the probe (prune_strategy=probe).+ pub files_probed: usize,+ /// Existing rows dropped in favour of an incoming row.+ pub rows_updated: usize,+ /// Incoming rows with no existing match.+ pub rows_inserted: usize,+ /// Unchanged rows rewritten into new files.+ pub rows_copied: usize,+ /// Rows in the (deduped) source batch.+ pub source_rows: usize,+ /// Source rows carrying a NULL PK component (always inserted, never matched).+ pub null_pk_rows: usize,+}++/// A file selected for rewrite, with the metadata needed to tombstone it.+struct TargetFile {+ path: String,+ size: u64,+ stats: Option<String>,+ remove: Remove,+}++/// Which rows of one source batch belong to a partition. Chosen so the common shapes+/// are zero-copy: a batch wholly inside one partition is `All`, a partition-sorted+/// batch yields `Range`s (Arc-sharing slices), and only genuinely interleaved input+/// pays for a `take` copy -- and even then only inside the partition's worker, while+/// it runs, never all partitions at once.+#[derive(Debug)]+enum RowSel {+ /// Every row of the batch.+ All,+ /// A contiguous run of rows: `batch.slice(offset, len)`, zero-copy.+ Range { offset: usize, len: usize },+ /// Arbitrary row indices, materialised with `take` when the worker needs them.+ Indices(UInt32Array),+}++impl RowSel {+ /// `idx` must be strictly ascending (rows are scanned in order).+ fn from_indices(idx: Vec<u32>, batch_rows: usize) -> Self {+ if idx.len() == batch_rows {+ return RowSel::All;+ }+ match (idx.first(), idx.last()) {+ (Some(&first), Some(&last)) if idx.len() == (last - first) as usize + 1 => {+ // Ascending with span == count => consecutive.+ RowSel::Range {+ offset: first as usize,+ len: idx.len(),+ }+ }+ _ => RowSel::Indices(UInt32Array::from(idx)),+ }+ }++ fn len(&self, batch_rows: usize) -> usize {+ match self {+ RowSel::All => batch_rows,+ RowSel::Range { len, .. } => *len,+ RowSel::Indices(idx) => idx.len(),+ }+ }++ /// Materialise the selected rows of one column. `All`/`Range` are O(1) Arc clones.+ fn select_array(&self, col: &Arc<dyn Array>) -> Result<Arc<dyn Array>> {+ Ok(match self {+ RowSel::All => col.clone(),+ RowSel::Range { offset, len } => col.slice(*offset, *len),+ RowSel::Indices(idx) => take(col.as_ref(), idx, None)?,+ })+ }++ /// Materialise the selected rows of a whole batch. `All`/`Range` are O(1).+ fn select_batch(&self, batch: &RecordBatch) -> Result<RecordBatch> {+ Ok(match self {+ RowSel::All => batch.clone(),+ RowSel::Range { offset, len } => batch.slice(*offset, *len),+ RowSel::Indices(idx) => take_record_batch(batch, idx)?,+ })+ }+}++/// A partition's source rows, described by row selections into the shared cast batches+/// instead of a materialised slice. Holding this costs O(rows) u32 indices at worst and+/// nothing at best -- the data itself is materialised only inside the partition's+/// worker, bounded by `max_parallel_partitions`.+#[derive(Debug)]+struct PartitionSource {+ batches: Arc<Vec<RecordBatch>>,+ /// Selections for the batches that contribute rows, as (batch index, selection)+ /// in batch order. Sparse on purpose: a dense per-batch vector would make the+ /// planning structures O(distinct partitions x batches), which a highly chunked+ /// source with many partition values could blow up regardless of its Arrow size.+ sel: Vec<(usize, RowSel)>,+ /// Total selected rows across all batches.+ rows: usize,+}++impl PartitionSource {+ /// The contributing (batch, selection) pairs, in batch order.+ fn parts(&self) -> impl Iterator<Item = (&RecordBatch, &RowSel)> {+ self.sel.iter().map(|(bi, sel)| (&self.batches[*bi], sel))+ }++ /// The selected rows of one column (by table-schema index), per contributing+ /// batch. Narrow: used for PK columns only.+ fn select_column(&self, col_idx: usize) -> Result<Vec<Arc<dyn Array>>> {+ let mut out = Vec::new();+ for (b, sel) in self.parts() {+ if sel.len(b.num_rows()) == 0 {+ continue;+ }+ out.push(sel.select_array(b.column(col_idx))?);+ }+ Ok(out)+ }+}++struct PartitionWork {+ value: String,+ source: PartitionSource,+ rewrite: Vec<TargetFile>,+ carried: usize,+}++struct PartitionOutcome {+ actions: Vec<Action>,+ files_added: usize,+ files_removed: usize,+ files_probed: usize,+ rows_updated: usize,+ rows_copied: usize,+ rows_inserted: usize,+ null_pk_rows: usize,+ carried: usize,+}++/// A unit of byte budget: one permit from the per-call budget and one from the+/// process-global budget. Both ride with a batch from decode until the writer has+/// copied it into its buffer.+struct BudgetPermit {+ /// `None` only transiently inside `top_up`, while the estimate's permits have been+ /// released and the grown permits are being re-acquired.+ local: Option<OwnedSemaphorePermit>,+ global: Option<OwnedSemaphorePermit>,+ /// KiB currently held against the per-call budget (capped at its capacity).+ held_local_kb: u32,+ /// KiB currently held against the process-global budget (capped at its capacity).+ held_global_kb: u32,+}++/// Per-call view of the budget semaphores plus their process-global counterparts.+#[derive(Clone)]+struct Budgets {+ local: Arc<Semaphore>,+ local_cap_kb: u32,+ limits: Arc<ProcessLimits>,+}++impl Budgets {+ fn kb(bytes: usize) -> u64 {+ (bytes / 1024).max(1) as u64+ }++ /// Acquire byte budget for `bytes`, capped at both budgets' capacities so a batch+ /// larger than either budget still makes progress. Local before global, the fixed+ /// order used everywhere (see `crate::limits` module docs).+ async fn acquire_bytes(&self, bytes: usize) -> Result<BudgetPermit> {+ let want = Self::kb(bytes);+ let local_kb = want.min(self.local_cap_kb as u64) as u32;+ let global_kb = want.min(self.limits.buffer_cap_kb() as u64) as u32;+ let local = self+ .local+ .clone()+ .acquire_many_owned(local_kb)+ .await+ .map_err(|_| Error::Generic("byte-budget semaphore closed".into()))?;+ let global = self.limits.acquire_buffer_kb(global_kb).await?;+ Ok(BudgetPermit {+ local: Some(local),+ global: Some(global),+ held_local_kb: local_kb,+ held_global_kb: global_kb,+ })+ }++ /// Grow `permit` so it covers `total_bytes` (used after a decode turns out larger+ /// than the pre-decode estimate). Total held stays capped at each budget's capacity,+ /// preserving the oversized-batch progress guarantee; a decode smaller than the+ /// estimate keeps the estimate's permits, which only errs conservative.+ ///+ /// Growth *releases the estimate's permits before re-acquiring the larger amount*+ /// rather than acquiring the extra while still holding them. Acquiring-while-holding+ /// wedges the worker: concurrent readers that each reserved an estimate and then block+ /// for more form a hold-and-wait cycle -- their estimates can pin the whole budget with+ /// no holder able to release. Releasing first means a reader never waits on the budget+ /// while holding any of it, so some waiter can always make progress. The decoded batch+ /// stays resident during the brief re-acquire gap, but it is already allocated and the+ /// wait is bounded by the budget draining as writers flush.+ async fn top_up(&self, permit: &mut BudgetPermit, total_bytes: usize) -> Result<()> {+ let want = Self::kb(total_bytes);+ let want_local = want.min(self.local_cap_kb as u64) as u32;+ let want_global = want.min(self.limits.buffer_cap_kb() as u64) as u32;+ if want_local <= permit.held_local_kb && want_global <= permit.held_global_kb {+ return Ok(());+ }+ // Release both budgets before re-acquiring either, so no growth ever waits while+ // holding budget (holding one semaphore while waiting on the other would deadlock+ // just as surely as holding an estimate while waiting to grow it).+ permit.local = None;+ permit.global = None;+ permit.held_local_kb = 0;+ permit.held_global_kb = 0;+ // Local before global, the fixed order used everywhere (see `crate::limits`).+ let local = self+ .local+ .clone()+ .acquire_many_owned(want_local)+ .await+ .map_err(|_| Error::Generic("byte-budget semaphore closed".into()))?;+ let global = self.limits.acquire_buffer_kb(want_global).await?;+ permit.local = Some(local);+ permit.global = Some(global);+ permit.held_local_kb = want_local;+ permit.held_global_kb = want_global;+ Ok(())+ }+}++/// Run one streaming partition upsert against `table` and commit the result.+///+/// This is the replacement for `DeltaTable.merge(...).when_matched_update_all()+/// .when_not_matched_insert_all().execute()`: identity is `(primary_keys, partition)`,+/// matched target rows are replaced wholesale by the source row, unmatched source rows+/// insert, unmatched target rows survive verbatim, and SQL NULL semantics apply to the+/// primary keys (a NULL component never matches). The whole batch lands in ONE commit+/// carrying `opts.commit_metadata` in flat `commitInfo`.+#[instrument(+ level = "info",+ skip_all,+ fields(+ prune_strategy = opts.prune_strategy.as_str(),+ source_rows = tracing::field::Empty,+ partitions = tracing::field::Empty,+ version = tracing::field::Empty,+ )+)]+pub async fn upsert(+ table: &DeltaTable,+ source_batches: Vec<RecordBatch>,+ source_schema: SchemaRef,+ opts: UpsertOptions,+) -> Result<UpsertStats> {+ let started = Instant::now();+ let strategy = opts.prune_strategy.as_str();+ let result = upsert_inner(table, source_batches, source_schema, opts).await;++ // Static label values only -- no per-call allocation (rust/CLAUDE.md).+ histogram!("deltalite_upsert_duration_seconds").record(started.elapsed().as_secs_f64());+ match &result {+ Ok(stats) => {+ counter!("deltalite_upserts_total", "outcome" => "ok", "prune_strategy" => strategy)+ .increment(1);+ counter!("deltalite_files_added_total").increment(stats.files_added as u64);+ counter!("deltalite_files_removed_total").increment(stats.files_removed as u64);+ counter!("deltalite_files_carried_over_total")+ .increment(stats.files_carried_over as u64);+ counter!("deltalite_files_probed_total").increment(stats.files_probed as u64);+ counter!("deltalite_rows_updated_total").increment(stats.rows_updated as u64);+ counter!("deltalite_rows_inserted_total").increment(stats.rows_inserted as u64);+ counter!("deltalite_rows_copied_total").increment(stats.rows_copied as u64);+ }+ Err(e) => {+ counter!(+ "deltalite_upserts_total",+ "outcome" => "error",+ "prune_strategy" => strategy,+ "error_kind" => e.kind()+ )+ .increment(1);+ }+ }+ result+}++async fn upsert_inner(+ table: &DeltaTable,+ mut source_batches: Vec<RecordBatch>,+ source_schema: SchemaRef,+ opts: UpsertOptions,+) -> Result<UpsertStats> {+ if opts.primary_keys.is_empty() {+ return Err(Error::Generic(+ "primary_keys must not be empty for an upsert".into(),+ ));+ }++ let snapshot = table.snapshot()?;+ ensure_supported_table(table)?;++ // Explicit argument wins; otherwise honour the table's own `delta.targetFileSize`,+ // exactly as delta-rs's own operations do.+ let effective_target_file_size = resolve_target_file_size(+ opts.target_file_size,+ snapshot.table_config().target_file_size().get() as usize,+ );++ // Take the arrow schema from a writer built for this table: it is by construction+ // exactly the schema the writer will expect on the way back in, so casting to it+ // cannot drift from what `RecordBatchWriter` accepts.+ let table_schema: SchemaRef = RecordBatchWriter::for_table(table)?.arrow_schema();++ let extra = unknown_columns(&source_schema, &table_schema);+ if !extra.is_empty() {+ return Err(Error::SchemaMismatch(format!(+ "source has columns not present in the table schema: {extra:?}. \+ Additive schema evolution must run before upsert."+ )));+ }++ // The table's own metadata is the source of truth for partitioning, not the caller's+ // hint: a table created unpartitioned must be treated as unpartitioned even if a+ // partition_key is passed (this mirrors the helper's partition-downgrade check).+ let partition_columns: Vec<String> = snapshot.metadata().partition_columns().to_vec();+ if partition_columns.len() > 1 {+ return Err(Error::Unsupported(format!(+ "deltalite supports at most one partition column, table has {partition_columns:?}"+ )));+ }+ let partition_col: Option<String> = partition_columns.first().cloned();+ if let (Some(tbl), Some(req)) = (&partition_col, &opts.partition_key) {+ if tbl != req {+ return Err(Error::Generic(format!(+ "table is partitioned by '{tbl}' but upsert was called with partition_key '{req}'"+ )));+ }+ }++ // --- Ingest: cast each source batch to the table schema, and stop there. ---------+ //+ // The source is the one memory term that scales with caller-supplied size rather+ // than being bounded by a knob, so it is held exactly once. The batches are never+ // concatenated and never split eagerly: partition membership is planned as row+ // selections (`RowSel`, O(rows) u32 indices at worst), and each partition's worker+ // materialises its own rows only when it runs. The previous concat-then-split form+ // held the concatenated batch and every partition's slice simultaneously --+ // measured at ~3x the source; now at most `max_parallel_partitions` slices exist+ // at any moment on top of the single shared copy.+ let mut cast: Vec<RecordBatch> = Vec::with_capacity(source_batches.len());+ for b in source_batches.drain(..) {+ // `b` is dropped each iteration; when no cast is needed `cast_to_schema`+ // returns Arc-shared columns, so this does not duplicate buffers.+ cast.push(cast_to_schema(&b, &table_schema)?);+ }+ let source_rows: usize = cast.iter().map(RecordBatch::num_rows).sum();++ // --- Source-size guard: fail at the front door, not as an OOM mid-rewrite. -------+ let footprint = source_footprint(&cast, &table_schema, &opts.primary_keys)?;+ check_source_size(&footprint, resolve_max_source_bytes(opts.max_source_bytes))?;++ let batches = Arc::new(cast);+ let groups = plan_partition_sources(&batches, partition_col.as_deref())?;++ tracing::Span::current().record("source_rows", source_rows);+ tracing::Span::current().record("partitions", groups.len());+ debug!(+ source_rows,+ source_bytes = footprint.source_bytes,+ partitions = groups.len(),+ target_file_size = effective_target_file_size,+ "planned partition groups"+ );++ // Index of the first PK column in the table schema, for stats-based pruning.+ let pk0_idx = table_schema.index_of(&opts.primary_keys[0]).ok();++ let mut work = Vec::new();+ for (value, source) in groups {+ let files = list_partition_files(table, partition_col.as_deref(), &value).await?;+ // Stats-based pruning is free (the Add-action stats are already in memory), so+ // both `Stats` and `Probe` apply it; `Probe` then verifies the survivors by+ // reading their PK columns inside the partition worker.+ let (rewrite, carried) = match opts.prune_strategy {+ PruneStrategy::None => (files, 0usize),+ PruneStrategy::Stats | PruneStrategy::Probe => {+ let src_range = match pk0_idx {+ Some(idx) => source_pk_range(&source, idx)?,+ None => None,+ };+ prune_by_pk_stats(files, src_range.as_ref(), &opts.primary_keys)+ }+ };+ work.push(PartitionWork {+ value,+ source,+ rewrite,+ carried,+ });+ }++ // --- Rewrite (parallel across partitions) ----------------------------------------+ let partitions_touched = work.len();+ let semaphore = Arc::new(Semaphore::new(opts.max_parallel_partitions.max(1)));+ // Per-call byte budget in KiB units (tokio's acquire_many takes u32); the+ // process-global budget in `opts.limits` applies on top of it.+ let local_cap_kb: u32 = (opts.max_buffered_bytes / 1024).clamp(1, u32::MAX as usize) as u32;+ let budgets = Budgets {+ local: Arc::new(Semaphore::new(local_cap_kb as usize)),+ local_cap_kb,+ limits: opts.limits.clone(),+ };+ let opts = Arc::new(opts);+ let mut handles = Vec::new();++ for w in work {+ // Fixed acquisition order everywhere: local partition permit, then the+ // process-global one. Consistent ordering is what makes the two semaphore+ // layers deadlock-free against each other.+ let local_permit = semaphore+ .clone()+ .acquire_owned()+ .await+ .map_err(|_| Error::Generic("partition semaphore closed".into()))?;+ let global_permit = opts.limits.acquire_partition().await?;+ let table = table.clone();+ let schema = table_schema.clone();+ let opts = opts.clone();+ let pcol = partition_col.clone();+ let budgets = budgets.clone();+ handles.push(tokio::spawn(async move {+ let r = rewrite_partition(+ &table,+ w,+ schema,+ pcol,+ &opts,+ budgets,+ effective_target_file_size,+ )+ .await;+ drop(local_permit);+ drop(global_permit);+ r+ }));+ }++ let mut stats = UpsertStats {+ partitions_touched,+ source_rows,+ ..Default::default()+ };+ let mut actions: Vec<Action> = Vec::new();++ for h in handles {+ let outcome = h+ .await+ .map_err(|e| Error::Generic(format!("partition worker panicked: {e}")))??;+ stats.files_added += outcome.files_added;+ stats.files_removed += outcome.files_removed;+ stats.files_probed += outcome.files_probed;+ stats.files_carried_over += outcome.carried;+ stats.rows_updated += outcome.rows_updated;+ stats.rows_copied += outcome.rows_copied;+ stats.rows_inserted += outcome.rows_inserted;+ stats.null_pk_rows += outcome.null_pk_rows;+ actions.extend(outcome.actions);+ }++ // --- Commit ----------------------------------------------------------------------+ let predicate = partition_col.as_ref().map(|c| {+ let vals: Vec<String> = actions+ .iter()+ .filter_map(|a| match a {+ Action::Add(add) => add.partition_values.get(c).cloned().flatten(),+ _ => None,+ })+ .collect::<HashSet<_>>()+ .into_iter()+ .map(|v| format!("'{}'", v.replace('\'', "''")))+ .collect();+ format!("{c} IN ({})", vals.join(", "))+ });++ let operation = DeltaOperation::Write {+ mode: SaveMode::Overwrite,+ partition_by: if partition_columns.is_empty() {+ None+ } else {+ Some(partition_columns.clone())+ },+ predicate,+ };++ let mut props = CommitProperties::default().with_max_retries(opts.commit_max_retries);+ if let Some(md) = opts.commit_metadata.clone() {+ props = props.with_metadata(md);+ }++ let finalized = CommitBuilder::from(props)+ .with_actions(actions)+ .build(Some(snapshot), table.log_store(), operation)+ .await?;++ stats.version = i64::try_from(finalized.version())+ .map_err(|_| Error::Generic("committed version overflows i64".into()))?;+ tracing::Span::current().record("version", stats.version);+ info!(+ version = stats.version,+ partitions = stats.partitions_touched,+ files_added = stats.files_added,+ files_removed = stats.files_removed,+ files_carried_over = stats.files_carried_over,+ rows_updated = stats.rows_updated,+ rows_inserted = stats.rows_inserted,+ rows_copied = stats.rows_copied,+ "upsert committed"+ );+ Ok(stats)+}++/// Explicit argument > table property (already folded with delta-rs's default by the+/// caller). Zero/absent explicit values fall through to the table's value.+fn resolve_target_file_size(explicit: Option<usize>, table_value: usize) -> usize {+ match explicit {+ Some(v) if v > 0 => v,+ _ => table_value,+ }+}++/// Estimate what this upsert keeps resident: the cast source batches plus the PK set+/// that will be built over them.+fn source_footprint(+ batches: &[RecordBatch],+ table_schema: &SchemaRef,+ primary_keys: &[String],+) -> Result<SourceFootprint> {+ let source_bytes: usize = batches.iter().map(RecordBatch::get_array_memory_size).sum();+ let rows: usize = batches.iter().map(RecordBatch::num_rows).sum();+ let mut pk_bytes = 0usize;+ for pk in primary_keys {+ let idx = table_schema.index_of(pk).map_err(|_| {+ Error::SchemaMismatch(format!(+ "primary key column '{pk}' not found in table schema"+ ))+ })?;+ pk_bytes += batches+ .iter()+ .map(|b| b.column(idx).get_array_memory_size())+ .sum::<usize>();+ }+ Ok(SourceFootprint {+ source_bytes,+ pk_set_bytes: estimate_pk_set_bytes(pk_bytes, rows),+ })+}++/// Refuse tables whose features would make a blind file rewrite unsafe.+fn ensure_supported_table(table: &DeltaTable) -> Result<()> {+ let snapshot = table.snapshot()?;+ let protocol = snapshot.protocol();++ let has = |feats: Option<&[String]>, name: &str| {+ feats.map(|f| f.iter().any(|x| x == name)).unwrap_or(false)+ };+ let reader: Option<Vec<String>> = protocol+ .reader_features()+ .map(|f| f.iter().map(|x| x.to_string()).collect());+ let writer: Option<Vec<String>> = protocol+ .writer_features()+ .map(|f| f.iter().map(|x| x.to_string()).collect());++ for (kind, feats) in [("reader", &reader), ("writer", &writer)] {+ let slice = feats.as_deref();+ for bad in ["deletionVectors", "columnMapping"] {+ if has(slice, bad) {+ return Err(Error::Unsupported(format!(+ "table declares {kind} feature '{bad}', which deltalite cannot safely \+ rewrite (a blind file rewrite would resurrect deleted rows or write \+ wrongly-named columns)"+ )));+ }+ }+ }++ // `invariants` / `checkConstraints` as declared writer features (writer protocol v7):+ // deltalite's raw `RecordBatchWriter` evaluates neither, so a rewrite that inserts+ // source rows could persist ones that violate them. The legacy pre-v7 CHECK-constraint+ // form is caught below via `delta.constraints.*` config.+ for bad in ["invariants", "checkConstraints"] {+ if has(writer.as_deref(), bad) {+ return Err(Error::Unsupported(format!(+ "table declares writer feature '{bad}', which deltalite's writer does not \+ enforce and could persist violating rows"+ )));+ }+ }++ let metadata = snapshot.metadata();+ let config = metadata.configuration();+ let is_true = |key: &str| {+ config+ .get(key)+ .map(|v| v.eq_ignore_ascii_case("true"))+ .unwrap_or(false)+ };++ if is_true("delta.enableDeletionVectors") {+ return Err(Error::Unsupported(+ "table has delta.enableDeletionVectors=true; deltalite cannot safely rewrite it".into(),+ ));+ }++ // A full file rewrite emits no `_change_data`, so the CDF a reader replays would be+ // wrong; deltalite must not silently corrupt it.+ if is_true("delta.enableChangeDataFeed") {+ return Err(Error::Unsupported(+ "table has delta.enableChangeDataFeed=true; deltalite's blind file rewrite would \+ not emit change-data-feed entries and would corrupt the feed"+ .into(),+ ));+ }++ // Upsert tombstones and rewrites files, which an append-only table forbids.+ if is_true("delta.appendOnly") {+ return Err(Error::Unsupported(+ "table has delta.appendOnly=true; deltalite rewrites and removes files, which an \+ append-only table forbids"+ .into(),+ ));+ }++ // CHECK constraints (`delta.constraints.<name>`) and column invariants are enforced by+ // delta-rs's merge/write path, not by the raw `RecordBatchWriter` deltalite uses, so a+ // rewrite could persist rows violating them. Refuse rather than write unchecked data.+ if let Some(name) = config+ .keys()+ .find_map(|k| k.strip_prefix("delta.constraints."))+ {+ return Err(Error::Unsupported(format!(+ "table declares CHECK constraint '{name}'; deltalite's writer does not enforce \+ constraints and could persist violating rows"+ )));+ }++ // Legacy column mapping (minReaderVersion=2/minWriterVersion=5, as Spark writes it)+ // carries no reader/writer *feature* list, so the check above cannot see it. Without+ // this, such a table only fails later inside `RecordBatchWriter::for_table` with a+ // generic error -- safe, but by luck rather than by design.+ if let Some(mode) = config.get("delta.columnMapping.mode") {+ if !mode.eq_ignore_ascii_case("none") {+ return Err(Error::Unsupported(format!(+ "table has delta.columnMapping.mode={mode}; deltalite cannot safely rewrite \+ it (physical column names differ from logical ones)"+ )));+ }+ }+ Ok(())+}++/// Plan which rows of which source batches belong to each distinct partition value,+/// without copying any row data. Returns groups in first-seen order (scanning batches+/// in order, rows in order), the same deterministic order the eager split produced.+///+/// Partition values are compared as their Delta string representation, which is what the+/// log stores and what the writer uses to build the Hive path. NULL partition values are+/// rejected here, before any worker starts.+fn plan_partition_sources(+ batches: &Arc<Vec<RecordBatch>>,+ partition_col: Option<&str>,+) -> Result<Vec<(String, PartitionSource)>> {+ let n_batches = batches.len();+ let total_rows: usize = batches.iter().map(RecordBatch::num_rows).sum();++ let Some(col) = partition_col else {+ // Unpartitioned: one group covering every row of every batch, zero-copy.+ return Ok(vec![(+ WHOLE_TABLE.to_string(),+ PartitionSource {+ batches: batches.clone(),+ sel: (0..n_batches).map(|bi| (bi, RowSel::All)).collect(),+ rows: total_rows,+ },+ )]);+ };++ // Preserve first-seen order for deterministic behaviour.+ let mut order: Vec<String> = Vec::new();+ // partition value -> (batch index, ascending row indices) for contributing+ // batches only. Sparse: cost is O(total rows + contributing pairs), never+ // O(partitions x batches).+ let mut indices: HashMap<String, Vec<(usize, Vec<u32>)>> = HashMap::new();+ let mut row_base = 0usize;++ for (bi, batch) in batches.iter().enumerate() {+ if batch.num_rows() > u32::MAX as usize {+ return Err(Error::Generic(format!(+ "source batch has {} rows, more than a single batch supports",+ batch.num_rows()+ )));+ }+ let idx = batch.schema().index_of(col).map_err(|_| {+ Error::SchemaMismatch(format!(+ "partition column '{col}' is missing from the incoming batch"+ ))+ })?;+ let as_str = arrow_cast::cast(batch.column(idx), &DataType::Utf8)?;+ let as_str = as_str+ .as_any()+ .downcast_ref::<StringArray>()+ .ok_or_else(|| Error::Generic("partition column did not cast to Utf8".into()))?;++ for i in 0..batch.num_rows() {+ if as_str.is_null(i) {+ return Err(Error::Generic(format!(+ "partition column '{col}' contains NULL at row {}; \+ Delta partition values must not be null",+ row_base + i+ )));+ }+ let v = as_str.value(i);+ if !indices.contains_key(v) {+ order.push(v.to_string());+ indices.insert(v.to_string(), Vec::new());+ }+ // The key was just inserted if absent, so this lookup cannot fail.+ if let Some(parts) = indices.get_mut(v) {+ match parts.last_mut() {+ Some((last_bi, rows)) if *last_bi == bi => rows.push(i as u32),+ _ => parts.push((bi, vec![i as u32])),+ }+ }+ }+ row_base += batch.num_rows();+ }++ let mut out = Vec::with_capacity(order.len());+ for v in order {+ let parts = indices.remove(&v).ok_or_else(|| {+ Error::Generic("internal: partition index vanished during planning".into())+ })?;+ let rows: usize = parts.iter().map(|(_, idx)| idx.len()).sum();+ let sel: Vec<(usize, RowSel)> = parts+ .into_iter()+ .map(|(bi, idx)| {+ let n = batches[bi].num_rows();+ (bi, RowSel::from_indices(idx, n))+ })+ .collect();+ out.push((+ v,+ PartitionSource {+ batches: batches.clone(),+ sel,+ rows,+ },+ ));+ }+ Ok(out)+}++/// Min/max of the partition's selected rows of one column, as JSON values comparable+/// against Add-action stats. Only the selected rows of the (narrow) PK column are ever+/// materialised, and only transiently.+fn source_pk_range(source: &PartitionSource, col_idx: usize) -> Result<Option<(Value, Value)>> {+ let mut acc: Option<(Value, Value)> = None;+ for chunk in source.select_column(col_idx)? {+ if let Some((mn, mx)) = min_max_json(chunk.as_ref()) {+ acc = Some(match acc {+ None => (mn, mx),+ Some((amn, amx)) => (+ if matches!(json_cmp(&mn, &amn), Some(std::cmp::Ordering::Less)) {+ mn+ } else {+ amn+ },+ if matches!(json_cmp(&mx, &amx), Some(std::cmp::Ordering::Greater)) {+ mx+ } else {+ amx+ },+ ),+ });+ }+ }+ Ok(acc)+}++async fn list_partition_files(+ table: &DeltaTable,+ partition_col: Option<&str>,+ value: &str,+) -> Result<Vec<TargetFile>> {+ let filters = match partition_col {+ Some(c) => vec![PartitionFilter {+ key: c.to_string(),+ value: PartitionValue::Equal(value.to_string()),+ }],+ None => vec![],+ };++ let views: Vec<_> = table+ .get_active_add_actions_by_partitions(&filters)+ .try_collect()+ .await?;++ Ok(views+ .into_iter()+ .map(|v| TargetFile {+ path: v.path().to_string(),+ size: v.size() as u64,+ stats: v.stats(),+ remove: v.remove_action(true),+ })+ .collect())+}++/// Drop files whose Add-action stats prove they hold no match: min/max disjointness on+/// the first PK column, or a PK column that is entirely NULL in the file (SQL NULL never+/// matches, so such a file cannot contain a matched row). Both checks are exact+/// negatives; anything unprovable stays in the rewrite set. Returns (files to rewrite,+/// count carried over untouched).+fn prune_by_pk_stats(+ files: Vec<TargetFile>,+ src_range: Option<&(Value, Value)>,+ primary_keys: &[String],+) -> (Vec<TargetFile>, usize) {+ let mut rewrite = Vec::with_capacity(files.len());+ let mut carried = 0usize;+ for f in files {+ if file_cannot_match(&f, primary_keys, src_range) {+ carried += 1;+ } else {+ rewrite.push(f);+ }+ }+ (rewrite, carried)+}++fn file_cannot_match(+ f: &TargetFile,+ primary_keys: &[String],+ src_range: Option<&(Value, Value)>,+) -> bool {+ let Some(stats) = &f.stats else { return false };+ let Ok(parsed): std::result::Result<Value, _> = serde_json::from_str(stats) else {+ return false;+ };++ // A PK column that is NULL in every row of the file (e.g. it was added by schema+ // evolution after the file was written) means no row of the file can match.+ if let Some(n) = parsed.get("numRecords").and_then(Value::as_i64) {+ if n == 0 {+ return true;+ }+ if let Some(nulls) = parsed.get("nullCount") {+ for pk in primary_keys {+ if nulls.get(pk).and_then(Value::as_i64) == Some(n) {+ return true;+ }+ }+ }+ }++ let pk0 = &primary_keys[0];+ let Some((src_min, src_max)) = src_range else {+ return false;+ };+ let fmin = parsed.get("minValues").and_then(|m| m.get(pk0));+ let fmax = parsed.get("maxValues").and_then(|m| m.get(pk0));+ let (Some(fmin), Some(fmax)) = (fmin, fmax) else {+ return false;+ };+ // file_max < src_min || file_min > src_max+ matches!(json_cmp(fmax, src_min), Some(std::cmp::Ordering::Less))+ || matches!(json_cmp(fmin, src_max), Some(std::cmp::Ordering::Greater))+}++fn json_cmp(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {+ match (a, b) {+ (Value::String(x), Value::String(y)) => Some(x.cmp(y)),+ (Value::Number(x), Value::Number(y)) => x.as_f64()?.partial_cmp(&y.as_f64()?),+ _ => None,+ }+}++fn min_max_json(col: &dyn Array) -> Option<(Value, Value)> {+ use arrow_array::cast::AsArray;+ use arrow_array::types::*;++ macro_rules! num {+ ($t:ty) => {{+ let a = col.as_primitive::<$t>();+ let mut mn = None;+ let mut mx = None;+ for i in 0..a.len() {+ if a.is_null(i) {+ continue;+ }+ let v = a.value(i);+ mn = Some(mn.map_or(+ v,+ |m: <$t as ArrowPrimitiveType>::Native| {+ if v < m {+ v+ } else {+ m+ }+ },+ ));+ mx = Some(mx.map_or(+ v,+ |m: <$t as ArrowPrimitiveType>::Native| {+ if v > m {+ v+ } else {+ m+ }+ },+ ));+ }+ match (mn, mx) {+ (Some(a), Some(b)) => Some((+ Value::Number(serde_json::Number::from(i64::from(a))),+ Value::Number(serde_json::Number::from(i64::from(b))),+ )),+ _ => None,+ }+ }};+ }++ match col.data_type() {+ DataType::Utf8 => {+ let a = col.as_string::<i32>();+ let mut mn: Option<&str> = None;+ let mut mx: Option<&str> = None;+ for i in 0..a.len() {+ if a.is_null(i) {+ continue;+ }+ let v = a.value(i);+ mn = Some(mn.map_or(v, |m| if v < m { v } else { m }));+ mx = Some(mx.map_or(v, |m| if v > m { v } else { m }));+ }+ match (mn, mx) {+ (Some(a), Some(b)) => {+ Some((Value::String(a.to_string()), Value::String(b.to_string())))+ }+ _ => None,+ }+ }+ DataType::Int64 => num!(Int64Type),+ DataType::Int32 => num!(Int32Type),+ DataType::Int16 => num!(Int16Type),+ DataType::Int8 => num!(Int8Type),+ _ => None,+ }+}++/// Append a constant partition column to a batch read from a data file.+///+/// Delta stores partition columns in the path, not in the Parquet file, so a row group+/// read back from storage is missing the column that the writer needs in order to route+/// the rows back to the same partition. Getting this wrong would silently misroute+/// rewritten rows.+fn add_partition_column(batch: &RecordBatch, name: &str, value: &str) -> Result<RecordBatch> {+ let n = batch.num_rows();+ let arr: Arc<dyn Array> = Arc::new(StringArray::from(vec![value; n]));+ let mut fields: Vec<Field> = batch+ .schema()+ .fields()+ .iter()+ .map(|f| f.as_ref().clone())+ .collect();+ fields.push(Field::new(name, DataType::Utf8, false));+ let mut cols = batch.columns().to_vec();+ cols.push(arr);+ Ok(RecordBatch::try_new(Arc::new(Schema::new(fields)), cols)?)+}++/// Where one PK column of a candidate file comes from during the probe.+enum PkSource {+ /// Physically present in the Parquet file; read via projection pushdown.+ Physical,+ /// The partition column: not stored in the data file, constant for every row.+ PartitionConst,+}++/// Assemble the PK columns (in PK order, cast to the table schema's PK types) for a+/// probe batch. `batch` is `None` only in the all-`PartitionConst` case.+fn build_pk_columns(+ primary_keys: &[String],+ sources: &[PkSource],+ batch: Option<&RecordBatch>,+ num_rows: usize,+ partition_value: &str,+ pk_types: &[DataType],+) -> Result<Vec<Arc<dyn Array>>> {+ let cast_opts = CastOptions {+ safe: false,+ ..Default::default()+ };+ let mut cols: Vec<Arc<dyn Array>> = Vec::with_capacity(primary_keys.len());+ for (i, src) in sources.iter().enumerate() {+ let raw: Arc<dyn Array> = match src {+ PkSource::Physical => batch+ .and_then(|b| b.column_by_name(&primary_keys[i]))+ .cloned()+ .ok_or_else(|| {+ Error::Generic(format!(+ "probe projection lost PK column '{}'",+ primary_keys[i]+ ))+ })?,+ PkSource::PartitionConst => {+ Arc::new(StringArray::from(vec![partition_value; num_rows]))+ }+ };+ cols.push(if raw.data_type() == &pk_types[i] {+ raw+ } else {+ cast_with_options(&raw, &pk_types[i], &cast_opts)?+ });+ }+ Ok(cols)+}++/// Read ONLY the PK column(s) of `f` and return whether any row matches the source PK+/// set. Streams one projected batch at a time and short-circuits on the first hit, so+/// resident memory is a Parquet footer plus one narrow batch.+///+/// Exactness of the negative answer is what licenses skipping the file: a PK column+/// absent from the file reads as all-NULL, and SQL NULL never matches, so such a file+/// is an exact negative without any I/O beyond the footer.+#[allow(clippy::too_many_arguments)]+async fn probe_file(+ store: &Arc<dyn ObjectStore>,+ f: &TargetFile,+ pkset: &PkSet,+ table_schema: &SchemaRef,+ partition_col: &Option<String>,+ partition_value: &str,+ opts: &UpsertOptions,+ budgets: &Budgets,+) -> Result<bool> {+ let path = Path::parse(&f.path)+ .map_err(|e| Error::Generic(format!("bad data file path {:?}: {e}", f.path)))?;+ let reader = ParquetObjectReader::new(store.clone(), path).with_file_size(f.size);+ let builder = ParquetRecordBatchStreamBuilder::new(reader).await?;+ let file_schema = builder.schema().clone();++ let mut pk_types: Vec<DataType> = Vec::with_capacity(opts.primary_keys.len());+ for pk in &opts.primary_keys {+ pk_types.push(+ table_schema+ .field_with_name(pk)+ .map_err(|e| Error::Generic(format!("PK column lookup: {e}")))?+ .data_type()+ .clone(),+ );+ }++ let mut sources: Vec<PkSource> = Vec::with_capacity(opts.primary_keys.len());+ let mut projection: Vec<usize> = Vec::new();+ for pk in &opts.primary_keys {+ if let Ok(idx) = file_schema.index_of(pk) {+ projection.push(idx);+ sources.push(PkSource::Physical);+ } else if partition_col.as_deref() == Some(pk.as_str()) {+ sources.push(PkSource::PartitionConst);+ } else {+ // The column is physically absent (file predates schema evolution): every+ // row has NULL for this PK component, and NULL never matches.+ return Ok(false);+ }+ }++ if projection.is_empty() {+ // Every PK component is the partition constant: all rows share one PK tuple, so+ // one synthetic row decides the whole file.+ let cols = build_pk_columns(+ &opts.primary_keys,+ &sources,+ None,+ 1,+ partition_value,+ &pk_types,+ )?;+ return pkset.contains_any_columns(&cols, 1);+ }++ let mask = ProjectionMask::roots(builder.parquet_schema(), projection);+ let batch_rows = byte_bounded_batch_rows(+ builder.metadata(),+ INITIAL_PROBE_ESTIMATE_BYTES,+ opts.read_batch_size,+ );+ let mut stream = builder+ .with_projection(mask)+ .with_batch_size(batch_rows)+ .build()?;++ // Probe batches are narrow (PK columns only) but still decoded data; budget them+ // like the rewrite path so `probe_concurrency x partitions x upserts` cannot hold+ // unaccounted memory. Estimate-then-top-up, same as `filter_file`.+ let mut estimate_bytes = INITIAL_PROBE_ESTIMATE_BYTES;+ loop {+ let mut permit = budgets.acquire_bytes(estimate_bytes).await?;+ let Some(batch) = stream.try_next().await? else {+ break;+ };+ let actual = batch.get_array_memory_size();+ budgets.top_up(&mut permit, actual).await?;+ estimate_bytes = actual.max(16 * 1024);+ let cols = build_pk_columns(+ &opts.primary_keys,+ &sources,+ Some(&batch),+ batch.num_rows(),+ partition_value,+ &pk_types,+ )?;+ let hit = pkset.contains_any_columns(&cols, batch.num_rows())?;+ drop(permit);+ if hit {+ return Ok(true);+ }+ }+ Ok(false)+}++/// Probe `files` with bounded concurrency, splitting them into (files that contain at+/// least one match, count of files proven match-free). Order is preserved.+#[allow(clippy::too_many_arguments)]+async fn probe_files(+ store: &Arc<dyn ObjectStore>,+ files: Vec<TargetFile>,+ pkset: &PkSet,+ table_schema: &SchemaRef,+ partition_col: &Option<String>,+ partition_value: &str,+ opts: &UpsertOptions,+ budgets: &Budgets,+) -> Result<(Vec<TargetFile>, usize)> {+ let results: Vec<(TargetFile, bool)> = futures::stream::iter(files.into_iter().map(|f| {+ let store = store.clone();+ async move {+ let hit = probe_file(+ &store,+ &f,+ pkset,+ table_schema,+ partition_col,+ partition_value,+ opts,+ budgets,+ )+ .await?;+ Ok::<_, Error>((f, hit))+ }+ }))+ .buffered(opts.probe_concurrency.max(1))+ .try_collect()+ .await?;++ let mut keep = Vec::new();+ let mut skipped = 0usize;+ for (f, hit) in results {+ if hit {+ keep.push(f);+ } else {+ skipped += 1;+ }+ }+ Ok((keep, skipped))+}++/// Per-file result from a reader task.+struct FileOutcome {+ rows_updated: usize,+ rows_copied: usize,+ remove: Action,+}++/// Stream one existing file, drop replaced rows, and send surviving batches to the+/// partition's writer task. Every batch sent carries byte-budget permits acquired+/// *before* the send; the writer releases them only after `write()` has copied the+/// batch into its buffer, so queued + in-write survivor data across the whole process+/// never exceeds the budgets.+#[allow(clippy::too_many_arguments)]+async fn filter_file(+ store: Arc<dyn ObjectStore>,+ f: TargetFile,+ pkset: Arc<PkSet>,+ table_schema: SchemaRef,+ partition_col: Option<String>,+ partition_value: String,+ opts: Arc<UpsertOptions>,+ budgets: Budgets,+ tx: mpsc::UnboundedSender<(RecordBatch, BudgetPermit)>,+) -> Result<FileOutcome> {+ let path = Path::parse(&f.path)+ .map_err(|e| Error::Generic(format!("bad data file path {:?}: {e}", f.path)))?;+ let reader = ParquetObjectReader::new(store, path).with_file_size(f.size);+ let builder = ParquetRecordBatchStreamBuilder::new(reader).await?;+ let batch_rows = byte_bounded_batch_rows(+ builder.metadata(),+ INITIAL_DECODE_ESTIMATE_BYTES,+ opts.read_batch_size,+ );+ let mut stream = builder.with_batch_size(batch_rows).build()?;++ let mut rows_updated = 0usize;+ let mut rows_copied = 0usize;+ // Pre-decode budget estimate, adapted to the last decoded batch so steady state+ // reserves roughly the right amount up front.+ let mut estimate_bytes = INITIAL_DECODE_ESTIMATE_BYTES;++ loop {+ // Budget BEFORE decoding: `try_next()` fully materialises a batch, so+ // acquiring afterwards would let every concurrent reader hold one unaccounted+ // decoded batch and the knob product (partitions x files x concurrent+ // upserts) would multiply resident memory. Reserve the estimate first, decode,+ // then top the permit up if the batch came out larger. The permits ride with+ // the data through filter and the writer queue, and are released by the+ // writer only after write().+ let mut permit = budgets.acquire_bytes(estimate_bytes).await?;+ let Some(batch) = stream.try_next().await? else {+ break;+ };+ let actual = batch.get_array_memory_size();+ budgets.top_up(&mut permit, actual).await?;+ estimate_bytes = actual.max(64 * 1024);++ // Old files may predate a column addition, and never carry the partition+ // column; restore both before probing so PK encodings line up.+ let batch = match (&partition_col, partition_value.as_str()) {+ (Some(c), v) => add_partition_column(&batch, c, v)?,+ _ => batch,+ };+ let batch = cast_to_schema(&batch, &table_schema)?;++ let hits = pkset.contains_rows(&batch)?;+ let n_hits = hits.iter().filter(|h| **h).count();+ rows_updated += n_hits;++ if n_hits == batch.num_rows() {+ continue; // every row replaced; permits drop here and free their budget+ }+ let keep: arrow_array::BooleanArray = hits.iter().map(|h| Some(!*h)).collect();+ let survivors = filter_record_batch(&batch, &keep)?;+ rows_copied += survivors.num_rows();++ tx.send((survivors, permit))+ .map_err(|_| Error::Generic("writer task ended before its readers".into()))?;+ }++ Ok(FileOutcome {+ rows_updated,+ rows_copied,+ remove: Action::Remove(f.remove),+ })+}++async fn rewrite_partition(+ table: &DeltaTable,+ work: PartitionWork,+ table_schema: SchemaRef,+ partition_col: Option<String>,+ opts: &Arc<UpsertOptions>,+ budgets: Budgets,+ target_file_size: usize,+) -> Result<PartitionOutcome> {+ let PartitionWork {+ value,+ source,+ mut rewrite,+ mut carried,+ } = work;++ // Build the PK set from the partition's source rows without materialising the+ // full-width slice: only the (narrow) PK columns are selected, per source batch,+ // and dropped as soon as they are encoded into the set. Duplicate detection is+ // unchanged -- the set persists across sub-batches, so a duplicate anywhere in the+ // partition's rows still fires.+ let mut pkset = PkSet::new(&table_schema, &opts.primary_keys)?;+ {+ let mut pk_idx: Vec<usize> = Vec::with_capacity(opts.primary_keys.len());+ for pk in &opts.primary_keys {+ pk_idx.push(table_schema.index_of(pk).map_err(|_| {+ Error::SchemaMismatch(format!(+ "primary key column '{pk}' not found in table schema"+ ))+ })?);+ }+ let mut duplicates = 0usize;+ for (b, sel) in source.parts() {+ let n = sel.len(b.num_rows());+ if n == 0 {+ continue;+ }+ let mut cols: Vec<Arc<dyn Array>> = Vec::with_capacity(pk_idx.len());+ for &ci in &pk_idx {+ cols.push(sel.select_array(b.column(ci))?);+ }+ duplicates += pkset.insert_columns(&cols, n)?;+ }+ if duplicates > 0 {+ // Stricter than MERGE on purpose: MERGE errors on duplicates that match an+ // existing row but silently double-inserts ones that do not, breaking PK+ // uniqueness. Refusing here leaves the table byte-identical.+ return Err(Error::Generic(format!(+ "source batch contains {duplicates} duplicate primary-key tuple(s) in partition \+ '{value}'; the batch must be deduped keep-last before upsert"+ )));+ }+ }+ let null_pk_rows = pkset.null_pk_rows;+ // Insert phase done; from here the set is read-only and shared by every reader.+ let pkset = Arc::new(pkset);++ let writer = RecordBatchWriter::for_table(table)?;+ let store: Arc<dyn ObjectStore> = table.object_store();++ // Content-based file selection: keep only files that actually contain a matched+ // row, exactly as MERGE's join does. Files proven match-free are carried over --+ // neither read again, rewritten, nor tombstoned.+ let mut files_probed = 0usize;+ if opts.prune_strategy == PruneStrategy::Probe && !rewrite.is_empty() {+ if pkset.is_empty() {+ // Every source row has a NULL PK component: nothing can match, so every+ // file is an exact negative without reading anything.+ carried += rewrite.len();+ rewrite = Vec::new();+ } else {+ files_probed = rewrite.len();+ let (keep, skipped) = probe_files(+ &store,+ rewrite,+ &pkset,+ &table_schema,+ &partition_col,+ &value,+ opts,+ &budgets,+ )+ .await?;+ rewrite = keep;+ carried += skipped;+ }+ }++ // Single writer task per partition: file count and output sizing behave exactly as+ // in the sequential implementation. The channel is unbounded; memory is bounded by+ // the byte-budget permits attached to every message, not by message count.+ let (tx, mut rx) = mpsc::unbounded_channel::<(RecordBatch, BudgetPermit)>();+ let writer_task = tokio::spawn(async move {+ let mut writer = writer;+ let mut adds = Vec::new();+ while let Some((batch, permit)) = rx.recv().await {+ writer.write(batch).await?;+ // The batch now lives (compressed) in the write buffer; release its budget.+ drop(permit);++ // Bound resident memory: RecordBatchWriter buffers the whole partition as+ // compressed Parquet until flushed, so flush on a size threshold instead of+ // once at the end. Each flush yields Add actions and resets the buffer.+ if writer.buffer_len() >= target_file_size {+ adds.extend(writer.flush().await?);+ }+ }+ Ok::<_, Error>((writer, adds))+ });++ // Reader tasks: up to max_parallel_files files stream concurrently (per call AND+ // per process). Each task takes its concurrency permits *inside* the task so+ // spawning never blocks this function.+ let file_sem = Arc::new(Semaphore::new(opts.max_parallel_files.max(1)));+ let mut readers = Vec::with_capacity(rewrite.len());+ for f in rewrite {+ let sem = file_sem.clone();+ let store = store.clone();+ let pkset = pkset.clone();+ let schema = table_schema.clone();+ let pcol = partition_col.clone();+ let value = value.clone();+ let opts = opts.clone();+ let budgets = budgets.clone();+ let tx = tx.clone();+ readers.push(tokio::spawn(async move {+ // Local before global, matching the fixed order used for partitions.+ let _local = sem+ .acquire_owned()+ .await+ .map_err(|_| Error::Generic("file semaphore closed".into()))?;+ let _global = opts.limits.acquire_file().await?;+ filter_file(store, f, pkset, schema, pcol, value, opts, budgets, tx).await+ }));+ }+ // Drop the parent's sender so the writer task ends when the readers do.+ drop(tx);++ let mut rows_updated = 0usize;+ let mut rows_copied = 0usize;+ let mut removes: Vec<Action> = Vec::new();+ let mut reader_err: Option<Error> = None;+ for h in readers {+ match h+ .await+ .map_err(|e| Error::Generic(format!("file worker panicked: {e}")))?+ {+ Ok(o) => {+ rows_updated += o.rows_updated;+ rows_copied += o.rows_copied;+ removes.push(o.remove);+ }+ // Keep the first reader error, but keep draining so the writer terminates.+ Err(e) => reader_err = reader_err.or(Some(e)),+ }+ }++ // Writer errors take precedence: when the writer dies, readers fail secondarily on+ // send, and reporting those would mask the root cause.+ let (mut writer, mut adds) = writer_task+ .await+ .map_err(|e| Error::Generic(format!("writer task panicked: {e}")))??;+ if let Some(e) = reader_err {+ return Err(e);+ }++ // Source rows are written LAST: an updated row therefore carries the source values,+ // which is exactly `when_matched_update_all`. The ordering is semantic, not+ // stylistic. Each sub-batch's slice is materialised here, inside the worker (so at+ // most `max_parallel_partitions` slices exist at once), and dropped as soon as+ // `write` has copied it into the compressed buffer. Sub-batches are written in+ // batch order and rows in ascending order within each, preserving exactly the row+ // order the eager concat-then-split produced.+ for (b, sel) in source.parts() {+ if sel.len(b.num_rows()) == 0 {+ continue;+ }+ // Written in row slices (zero-copy) rather than one call, so the threshold can+ // be checked *between* slices. The survivor loop above only ever sees survivors,+ // so a batch matching every target row never passes through it; without this a+ // large source produced one oversized file and an unbounded write buffer.+ // Flushing mid-source is order-safe: it closes the current file and opens+ // another, and every source row still lands after every survivor.+ let selected = sel.select_batch(b)?;+ let mut offset = 0usize;+ while offset < selected.num_rows() {+ let n = (selected.num_rows() - offset).min(opts.read_batch_size.max(1));+ writer.write(selected.slice(offset, n)).await?;+ offset += n;+ if writer.buffer_len() >= target_file_size {+ adds.extend(writer.flush().await?);+ }+ }+ }+ adds.extend(writer.flush().await?);++ // Every source row is written, but a source row that replaced an existing one is an+ // update, not an insert -- the batch is deduped, so each match consumes exactly one+ // source row. Counting the whole slice here double-counted matches as both.+ let rows_inserted = source.rows.saturating_sub(rows_updated);+ let files_added = adds.len();+ let files_removed = removes.len();++ let mut actions: Vec<Action> = removes;+ actions.extend(adds.into_iter().map(Action::Add));++ Ok(PartitionOutcome {+ actions,+ files_added,+ files_removed,+ files_probed,+ rows_updated,+ rows_copied,+ rows_inserted,+ null_pk_rows,+ carried,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ // ---- PruneStrategy parsing -------------------------------------------------------++ #[test]+ fn prune_strategy_parses_case_insensitively_and_rejects_unknown() {+ assert_eq!(+ "none".parse::<PruneStrategy>().unwrap(),+ PruneStrategy::None+ );+ assert_eq!(+ "STATS".parse::<PruneStrategy>().unwrap(),+ PruneStrategy::Stats+ );+ assert_eq!(+ "Probe".parse::<PruneStrategy>().unwrap(),+ PruneStrategy::Probe+ );+ assert!("join".parse::<PruneStrategy>().is_err());+ assert_eq!(PruneStrategy::default(), PruneStrategy::Probe);+ }++ // ---- target_file_size resolution -------------------------------------------------++ #[test]+ fn explicit_target_file_size_wins_and_zero_falls_through() {+ assert_eq!(resolve_target_file_size(Some(42), 100), 42);+ assert_eq!(resolve_target_file_size(Some(0), 100), 100);+ assert_eq!(resolve_target_file_size(None, 100), 100);+ }++ // ---- RowSel ----------------------------------------------------------------------++ use arrow_array::Int64Array;+ use arrow_schema::Field as AField;++ fn int_batch(vals: &[i64]) -> RecordBatch {+ RecordBatch::try_new(+ Arc::new(Schema::new(vec![AField::new("v", DataType::Int64, false)])),+ vec![Arc::new(Int64Array::from(vals.to_vec()))],+ )+ .unwrap()+ }++ #[test]+ fn rowsel_all_range_and_indices_are_detected() {+ assert!(matches!(+ RowSel::from_indices(vec![0, 1, 2], 3),+ RowSel::All+ ));+ assert!(matches!(+ RowSel::from_indices(vec![2, 3, 4], 6),+ RowSel::Range { offset: 2, len: 3 }+ ));+ assert!(matches!(+ RowSel::from_indices(vec![0, 2], 3),+ RowSel::Indices(_)+ ));+ assert!(matches!(+ RowSel::from_indices(vec![], 3),+ RowSel::Indices(_)+ ));+ }++ #[test]+ fn rowsel_select_batch_matches_selection() {+ let b = int_batch(&[10, 20, 30, 40]);+ let all = RowSel::from_indices(vec![0, 1, 2, 3], 4)+ .select_batch(&b)+ .unwrap();+ assert_eq!(all.num_rows(), 4);+ let range = RowSel::from_indices(vec![1, 2], 4)+ .select_batch(&b)+ .unwrap();+ let col = range+ .column(0)+ .as_any()+ .downcast_ref::<Int64Array>()+ .unwrap();+ assert_eq!(col.values(), &[20, 30]);+ let scattered = RowSel::from_indices(vec![0, 3], 4)+ .select_batch(&b)+ .unwrap();+ let col = scattered+ .column(0)+ .as_any()+ .downcast_ref::<Int64Array>()+ .unwrap();+ assert_eq!(col.values(), &[10, 40]);+ }++ // ---- partition planning ----------------------------------------------------------++ fn part_batch(parts: &[&str]) -> RecordBatch {+ RecordBatch::try_new(+ Arc::new(Schema::new(vec![+ AField::new("p", DataType::Utf8, true),+ AField::new("v", DataType::Int64, false),+ ])),+ vec![+ Arc::new(StringArray::from(parts.to_vec())),+ Arc::new(Int64Array::from(+ (0..parts.len() as i64).collect::<Vec<_>>(),+ )),+ ],+ )+ .unwrap()+ }++ #[test]+ fn plan_groups_in_first_seen_order_with_correct_rows() {+ let batches = Arc::new(vec![part_batch(&["b", "a", "b"]), part_batch(&["a"])]);+ let groups = plan_partition_sources(&batches, Some("p")).unwrap();+ let names: Vec<_> = groups.iter().map(|(v, _)| v.as_str()).collect();+ assert_eq!(names, vec!["b", "a"]);+ let rows: Vec<_> = groups.iter().map(|(_, s)| s.rows).collect();+ assert_eq!(rows, vec![2, 2]);+ }++ #[test]+ fn plan_unpartitioned_is_one_zero_copy_group() {+ let batches = Arc::new(vec![part_batch(&["x", "y"])]);+ let groups = plan_partition_sources(&batches, None).unwrap();+ assert_eq!(groups.len(), 1);+ assert_eq!(groups[0].0, WHOLE_TABLE);+ assert_eq!(groups[0].1.rows, 2);+ assert!(matches!(groups[0].1.sel[0], (0, RowSel::All)));+ }++ #[test]+ fn plan_rejects_null_partition_values() {+ let b = RecordBatch::try_new(+ Arc::new(Schema::new(vec![AField::new("p", DataType::Utf8, true)])),+ vec![Arc::new(StringArray::from(vec![Some("a"), None]))],+ )+ .unwrap();+ let err = plan_partition_sources(&Arc::new(vec![b]), Some("p")).unwrap_err();+ assert!(err.to_string().contains("NULL"), "{err}");+ }++ #[test]+ fn plan_stores_selections_sparsely_per_contributing_batch() {+ // 3 batches, each contributing to exactly one of 3 partitions: the dense+ // representation would hold 9 selections, the sparse one holds 3.+ let batches = Arc::new(vec![+ part_batch(&["a", "a"]),+ part_batch(&["b"]),+ part_batch(&["c", "c"]),+ ]);+ let groups = plan_partition_sources(&batches, Some("p")).unwrap();+ assert_eq!(groups.len(), 3);+ for (_, source) in &groups {+ assert_eq!(source.sel.len(), 1, "only contributing batches are stored");+ }+ // And the sparse pairs point at the right batches.+ let sel_batches: Vec<usize> = groups.iter().map(|(_, s)| s.sel[0].0).collect();+ assert_eq!(sel_batches, vec![0, 1, 2]);+ }++ #[test]+ fn plan_merges_contiguous_rows_of_one_batch_into_one_selection() {+ let batches = Arc::new(vec![part_batch(&["a", "b", "a", "a"])]);+ let groups = plan_partition_sources(&batches, Some("p")).unwrap();+ let a = &groups[0].1;+ assert_eq!(a.sel.len(), 1, "one (batch, selection) pair per batch");+ assert_eq!(a.rows, 3);+ }++ #[tokio::test]+ async fn budget_permit_tops_up_and_caps_at_capacity() {+ let limits = Arc::new(crate::limits::ProcessLimits::new(1, 1, 1024 * 1024));+ let budgets = Budgets {+ local: Arc::new(Semaphore::new(512)), // 512 KiB per-call budget+ local_cap_kb: 512,+ limits: limits.clone(),+ };+ // Pre-acquire a small estimate, then top up to something bigger.+ let mut p = budgets.acquire_bytes(64 * 1024).await.unwrap();+ assert_eq!(p.held_local_kb, 64);+ budgets.top_up(&mut p, 256 * 1024).await.unwrap();+ assert_eq!(p.held_local_kb, 256);+ // Topping up beyond both capacities caps instead of deadlocking.+ budgets.top_up(&mut p, usize::MAX).await.unwrap();+ assert_eq!(p.held_local_kb, 512);+ assert_eq!(p.held_global_kb, 1024);+ // A smaller "total" never shrinks or over-releases.+ budgets.top_up(&mut p, 1).await.unwrap();+ assert_eq!(p.held_local_kb, 512);+ drop(p);+ // Everything was released exactly once: the full budget is available again.+ let q = budgets.acquire_bytes(512 * 1024).await.unwrap();+ assert_eq!(q.held_local_kb, 512);+ }++ #[test]+ fn batch_rows_bounds_decoded_size_by_bytes_per_row() {+ // Narrow rows: read the full cap.+ assert_eq!(+ batch_rows_for_bytes_per_row(100, 4 * 1024 * 1024, 8192),+ 8192+ );+ // Wide/compressible rows: shrink the batch so its decoded size stays near target.+ assert_eq!(+ batch_rows_for_bytes_per_row(1024 * 1024, 4 * 1024 * 1024, 8192),+ 4+ );+ // Pathologically wide rows never drop below one row.+ assert_eq!(+ batch_rows_for_bytes_per_row(64 * 1024 * 1024, 4 * 1024 * 1024, 8192),+ 1+ );+ // No usable metadata falls back to the cap (but at least one row).+ assert_eq!(batch_rows_for_bytes_per_row(0, 4 * 1024 * 1024, 8192), 8192);+ assert_eq!(batch_rows_for_bytes_per_row(0, 4 * 1024 * 1024, 0), 1);+ }++ #[tokio::test]+ async fn concurrent_top_ups_beyond_estimate_do_not_wedge() {+ // Budget fits roughly one grown batch, far less than all readers' grown batches at+ // once. Under the old acquire-while-holding scheme the readers would each pin their+ // estimate and none could grow -- a permanent wedge. Release-and-reacquire makes+ // them serialize instead, so every reader completes.+ let limits = Arc::new(crate::limits::ProcessLimits::new(1, 1, 100 * 1024));+ let budgets = Budgets {+ local: Arc::new(Semaphore::new(100)), // 100 KiB per-call budget+ local_cap_kb: 100,+ limits,+ };+ let tasks: Vec<_> = (0..8)+ .map(|_| {+ let budgets = budgets.clone();+ tokio::spawn(async move {+ // Reserve a small estimate, then "decode" a batch far larger than it.+ let mut p = budgets.acquire_bytes(4 * 1024).await.unwrap();+ budgets.top_up(&mut p, 80 * 1024).await.unwrap();+ // Hold the grown permit briefly, as a reader does before it sends.+ tokio::task::yield_now().await;+ drop(p);+ })+ })+ .collect();+ let run = async {+ for t in tasks {+ t.await.unwrap();+ }+ };+ tokio::time::timeout(std::time::Duration::from_secs(10), run)+ .await+ .expect("readers wedged topping up past their estimate");+ // Budget fully released: the whole capacity is available again.+ let all = budgets.acquire_bytes(100 * 1024).await.unwrap();+ assert_eq!(all.held_local_kb, 100);+ }++ #[test]+ fn plan_rejects_missing_partition_column() {+ let batches = Arc::new(vec![int_batch(&[1])]);+ let err = plan_partition_sources(&batches, Some("p")).unwrap_err();+ assert!(matches!(err, Error::SchemaMismatch(_)), "{err}");+ }++ // ---- stats-based pruning ---------------------------------------------------------++ fn target_file(stats: Option<&str>) -> TargetFile {+ TargetFile {+ path: "part-0.parquet".into(),+ size: 1,+ stats: stats.map(|s| s.to_string()),+ remove: Remove::default(),+ }+ }++ fn pk() -> Vec<String> {+ vec!["id".to_string()]+ }++ #[test]+ fn file_without_stats_is_never_pruned() {+ let range = (Value::String("a".into()), Value::String("z".into()));+ assert!(!file_cannot_match(&target_file(None), &pk(), Some(&range)));+ }++ #[test]+ fn disjoint_minmax_range_is_pruned_overlap_is_not() {+ let stats = r#"{"numRecords": 5, "minValues": {"id": "a"}, "maxValues": {"id": "c"}}"#;+ let f = target_file(Some(stats));+ let disjoint = (Value::String("d".into()), Value::String("f".into()));+ assert!(file_cannot_match(&f, &pk(), Some(&disjoint)));+ let overlap = (Value::String("b".into()), Value::String("f".into()));+ assert!(!file_cannot_match(&f, &pk(), Some(&overlap)));+ // No source range at all: cannot prove anything.+ assert!(!file_cannot_match(&f, &pk(), None));+ }++ #[test]+ fn all_null_pk_column_is_an_exact_negative() {+ // PK column added by schema evolution after this file was written: every row+ // reads NULL, and SQL NULL never matches.+ let stats = r#"{"numRecords": 7, "nullCount": {"id": 7}}"#;+ let f = target_file(Some(stats));+ let range = (Value::String("a".into()), Value::String("z".into()));+ assert!(file_cannot_match(&f, &pk(), Some(&range)));+ // Partially-null PK column proves nothing.+ let stats = r#"{"numRecords": 7, "nullCount": {"id": 6}}"#;+ assert!(!file_cannot_match(+ &target_file(Some(stats)),+ &pk(),+ Some(&range)+ ));+ }++ #[test]+ fn empty_file_is_pruned_and_malformed_stats_are_kept() {+ let range = (Value::String("a".into()), Value::String("z".into()));+ let empty = target_file(Some(r#"{"numRecords": 0}"#));+ assert!(file_cannot_match(&empty, &pk(), Some(&range)));+ let broken = target_file(Some("not json"));+ assert!(!file_cannot_match(&broken, &pk(), Some(&range)));+ }++ #[test]+ fn numeric_stats_compare_numerically_not_lexically() {+ let stats = r#"{"numRecords": 2, "minValues": {"id": 9}, "maxValues": {"id": 11}}"#;+ let f = target_file(Some(stats));+ // Lexically "11" < "9"; numerically the file range [9, 11] overlaps [10, 10].+ let range = (Value::Number(10.into()), Value::Number(10.into()));+ assert!(!file_cannot_match(&f, &pk(), Some(&range)));+ let range = (Value::Number(12.into()), Value::Number(20.into()));+ assert!(file_cannot_match(&f, &pk(), Some(&range)));+ }++ #[test]+ fn prune_by_pk_stats_partitions_files() {+ let range = (Value::String("a".into()), Value::String("b".into()));+ let keep = target_file(Some(+ r#"{"numRecords": 5, "minValues": {"id": "a"}, "maxValues": {"id": "z"}}"#,+ ));+ let skip = target_file(Some(+ r#"{"numRecords": 5, "minValues": {"id": "x"}, "maxValues": {"id": "z"}}"#,+ ));+ let (rewrite, carried) = prune_by_pk_stats(vec![keep, skip], Some(&range), &pk());+ assert_eq!(rewrite.len(), 1);+ assert_eq!(carried, 1);+ }++ // ---- source PK range across chunks ----------------------------------------------++ #[test]+ fn source_pk_range_spans_all_selected_chunks() {+ let batches = Arc::new(vec![part_batch(&["a", "a"]), part_batch(&["a"])]);+ let source = PartitionSource {+ batches: batches.clone(),+ sel: vec![(0, RowSel::All), (1, RowSel::All)],+ rows: 3,+ };+ // Column 1 is v: [0, 1] and [0].+ let (mn, mx) = source_pk_range(&source, 1).unwrap().unwrap();+ assert_eq!(mn, Value::Number(0.into()));+ assert_eq!(mx, Value::Number(1.into()));+ }++ // ---- partition column re-adding --------------------------------------------------++ #[test]+ fn add_partition_column_appends_constant_column() {+ let b = int_batch(&[1, 2]);+ let out = add_partition_column(&b, "p", "2026-01-01").unwrap();+ assert_eq!(out.num_columns(), 2);+ let col = out+ .column_by_name("p")+ .unwrap()+ .as_any()+ .downcast_ref::<StringArray>()+ .unwrap();+ assert_eq!(col.value(0), "2026-01-01");+ assert_eq!(col.value(1), "2026-01-01");+ }++ // ---- footprint estimation --------------------------------------------------------++ #[test]+ fn source_footprint_counts_pk_columns_only_once() {+ let schema: SchemaRef = Arc::new(Schema::new(vec![+ AField::new("p", DataType::Utf8, true),+ AField::new("v", DataType::Int64, false),+ ]));+ let b = part_batch(&["a", "b"]);+ let fp = source_footprint(std::slice::from_ref(&b), &schema, &["v".to_string()]).unwrap();+ assert_eq!(fp.source_bytes, b.get_array_memory_size());+ assert!(fp.pk_set_bytes >= b.column(1).get_array_memory_size());+ // Unknown PK column errors.+ assert!(source_footprint(&[b], &schema, &["nope".to_string()]).is_err());+ }+}diff --git a/rust/deltalite/python/Cargo.toml b/rust/deltalite/python/Cargo.tomlnew file mode 100644index 000000000000..97503b4feb3b--- /dev/null+++ b/rust/deltalite/python/Cargo.toml@@ -0,0 +1,41 @@+[package]+name = "deltalite-python"+# Mirrors pyproject.toml in this directory (always identical); bump both together.+version = "0.1.0"+edition = "2021"+# CI compiles with this exact toolchain; cargo's MSRV-aware resolver uses it to+# avoid picking dependency versions CI cannot build (aws-* crates move MSRV often).+rust-version = "1.91.1"+publish = false++[lib]+name = "deltalite_python"+# `cdylib` for the Python wheel that maturin builds; `rlib` so other Rust crates could+# depend on the binding layer if useful later -- `cdylib` alone would break that. Same+# shape as `rust/hogql/parser`.+#+# NOTE: keep Rust unit tests OUT of this crate. `extension-module` (below) suppresses+# the libpython link, so a `cargo test` harness binary for this crate cannot link on+# Linux. All Rust tests live in `deltalite-core`, which has no pyo3 dependency.+crate-type = ["cdylib", "rlib"]++[lints]+workspace = true++[dependencies]+deltalite-core = { path = "../core" }++# `abi3-py312` matches the repo convention (`rust/hogql/parser`): one wheel works on+# every Python 3.12+ via the stable CPython ABI, including the pinned prod 3.13.+#+# pyo3 0.28 is dictated by arrow 58's `pyarrow` feature (arrow major fixed by+# `deltalake` 0.32). Cargo allows one pyo3 version per workspace (`links = "python"`),+# so this must stay in lockstep with `rust/hogql/parser`.+pyo3 = { version = "0.28", features = ["extension-module", "abi3-py312"] }+arrow = { version = "58", features = ["pyarrow"] }+arrow-array = { version = "58" }+arrow-schema = { version = "58" }++deltalake = { version = "=0.32.4", default-features = false, features = ["s3", "rustls"] }+serde_json = { workspace = true }+tokio = { workspace = true }diff --git a/rust/deltalite/python/README.md b/rust/deltalite/python/README.mdnew file mode 100644index 000000000000..75714c8e5bdd--- /dev/null+++ b/rust/deltalite/python/README.md@@ -0,0 +1,15 @@+# deltalite (Python package)++Thin pyo3 binding over `deltalite-core`, built with maturin and imported as+`deltalite`. See [`../README.md`](../README.md) for what deltalite is, why the+crate is split in two, how the wheel is built and consumed, the operational+knobs, and the pre-rollout conditions.++- `src/lib.rs` — the pyo3 module: `DeltaLiteTable.open(...).upsert(...)`,+ `UpsertStats`, and the `DeltaLiteError` exception hierarchy.+- `tests/` — the differential parity suite (delta-rs MERGE vs deltalite upsert)+ plus probe/operations/types/crash-redelivery/interop/planner tests.+- `harness/` — the two write paths and logical-content comparison the tests use.+- `deltalite_planner.py` — rough knob-tuning helper (concurrent upserts + pod+ memory in, suggested mpp/mpf/byte-budget out).+- `bench/` — test-data generation helpers shared by the tests.diff --git a/rust/deltalite/python/bench/__init__.py b/rust/deltalite/python/bench/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/rust/deltalite/python/bench/gen.py b/rust/deltalite/python/bench/gen.pynew file mode 100644index 000000000000..b0749bfa5681--- /dev/null+++ b/rust/deltalite/python/bench/gen.py@@ -0,0 +1,256 @@+"""Fast generation of wide-row Delta tables that model the production workload.++Rows carry a UUID-shaped string PK, a couple of ints, two timestamps, a decimal, and a+large JSON-ish string column. Payloads are cut from a big random pool with a unique+per-row prefix so Parquet cannot dictionary-encode them away -- otherwise the benchmark+would understate both file size and decompressed memory.+"""++from __future__ import annotations++import json+import random+import shutil+import string+import datetime as dt+from pathlib import Path++import pyarrow as pa+import deltalake++PARTITION_KEY = "_ph_partition_key"++_POOL: str | None = None+++def _pool(size: int = 1 << 20) -> str:+ global _POOL+ if _POOL is None or len(_POOL) < size:+ rng = random.Random(1234)+ _POOL = "".join(rng.choices(string.ascii_letters + string.digits, k=size))+ return _POOL+++def schema() -> pa.Schema:+ return pa.schema(+ [+ pa.field("id", pa.string()),+ pa.field("tenant", pa.int64()),+ pa.field("counter", pa.int32()),+ pa.field("created_at", pa.timestamp("us")),+ pa.field("updated_at", pa.timestamp("us")),+ pa.field("amount", pa.decimal128(38, 10)),+ pa.field("payload", pa.string()),+ pa.field(PARTITION_KEY, pa.string()),+ ]+ )+++def pk(i: int) -> str:+ return f"{i:08x}-0000-4000-8000-{i:012x}"+++def make_batch(+ start: int,+ n: int,+ partition: str,+ payload_size: int = 4500,+ version: int = 1,+) -> pa.Table:+ import decimal++ pool = _pool()+ plen = len(pool)+ base = dt.datetime(2026, 1, 1)++ ids = [pk(i) for i in range(start, start + n)]+ payloads = []+ for i in range(start, start + n):+ off = (i * 7919) % (plen - payload_size - 1)+ payloads.append(f'{{"row":{i},"v":{version},"d":"' + pool[off : off + payload_size] + '"}')++ return pa.table(+ {+ "id": pa.array(ids, pa.string()),+ "tenant": pa.array([(i % 50) + 1 for i in range(start, start + n)], pa.int64()),+ "counter": pa.array([version] * n, pa.int32()),+ "created_at": pa.array([base] * n, pa.timestamp("us")),+ "updated_at": pa.array([base + dt.timedelta(seconds=version)] * n, pa.timestamp("us")),+ "amount": pa.array(+ [decimal.Decimal(f"{i % 1000000}.{(i * 37) % 10**9:09d}") for i in range(start, start + n)],+ pa.decimal128(38, 10),+ ),+ "payload": pa.array(payloads, pa.string()),+ PARTITION_KEY: pa.array([partition] * n, pa.string()),+ },+ schema=schema(),+ )+++def build_table(+ uri: str,+ partitions: dict[str, int],+ payload_size: int = 4500,+ partitioned: bool = True,+ chunk: int = 25_000,+ files_per_partition: int | None = None,+) -> None:+ """Create a table with `partitions` mapping partition value -> row count.++ `files_per_partition` forces fragmentation by splitting each partition's rows across+ that many separate append commits.+ """+ p = Path(uri)+ if p.exists():+ shutil.rmtree(p)++ offset = 0+ first = True+ for part, rows in partitions.items():+ if files_per_partition:+ per = max(1, rows // files_per_partition)+ steps = [per] * files_per_partition+ steps[-1] += rows - per * files_per_partition+ else:+ steps = []+ remaining = rows+ while remaining > 0:+ steps.append(min(chunk, remaining))+ remaining -= chunk++ for step in steps:+ if step <= 0:+ continue+ batch = make_batch(offset, step, part, payload_size=payload_size)+ deltalake.write_deltalake(+ uri,+ batch,+ partition_by=[PARTITION_KEY] if partitioned else None,+ mode="overwrite" if first else "append",+ schema_mode="overwrite" if first else None,+ )+ first = False+ offset += step+++def make_upsert_batch(+ n_updates: int,+ n_inserts: int,+ partition: str,+ existing_rows: int,+ payload_size: int = 4500,+ version: int = 2,+) -> pa.Table:+ """Mostly-updates batch: `n_updates` existing PKs plus `n_inserts` brand-new ones."""+ step = max(1, existing_rows // max(1, n_updates))+ upd_ids = [i * step for i in range(n_updates) if i * step < existing_rows]++ parts = []+ if upd_ids:+ pool = _pool()+ plen = len(pool)+ import decimal++ base = dt.datetime(2026, 1, 1)+ payloads = []+ for i in upd_ids:+ off = (i * 104729) % (plen - payload_size - 1)+ payloads.append(f'{{"row":{i},"v":{version},"d":"' + pool[off : off + payload_size] + '"}')+ parts.append(+ pa.table(+ {+ "id": pa.array([pk(i) for i in upd_ids], pa.string()),+ "tenant": pa.array([(i % 50) + 1 for i in upd_ids], pa.int64()),+ "counter": pa.array([version] * len(upd_ids), pa.int32()),+ "created_at": pa.array([base] * len(upd_ids), pa.timestamp("us")),+ "updated_at": pa.array(+ [base + dt.timedelta(seconds=version)] * len(upd_ids),+ pa.timestamp("us"),+ ),+ "amount": pa.array(+ [decimal.Decimal(f"{i % 1000000}.{(i * 41) % 10**9:09d}") for i in upd_ids],+ pa.decimal128(38, 10),+ ),+ "payload": pa.array(payloads, pa.string()),+ PARTITION_KEY: pa.array([partition] * len(upd_ids), pa.string()),+ },+ schema=schema(),+ )+ )+ if n_inserts:+ parts.append(make_batch(10_000_000, n_inserts, partition, payload_size, version=version))+ return pa.concat_tables(parts)+++# --------------------------------------------------------------------------------------+# Log inspection: write amplification accounting+# --------------------------------------------------------------------------------------+++def commit_io(uri: str, version: int) -> dict:+ """Bytes/files added and removed by a single commit, read from the Delta log."""+ path = Path(uri) / "_delta_log" / f"{version:020d}.json"+ added_bytes = removed_bytes = 0+ added = removed = 0+ for line in path.read_text().splitlines():+ a = json.loads(line)+ if "add" in a:+ added += 1+ added_bytes += a["add"].get("size", 0)+ elif "remove" in a:+ removed += 1+ removed_bytes += a["remove"].get("size", 0) or 0+ return {+ "files_added": added,+ "files_removed": removed,+ "bytes_added": added_bytes,+ "bytes_removed": removed_bytes,+ }+++def table_bytes(uri: str) -> int:+ return sum(Path(f.replace("file://", "")).stat().st_size for f in deltalake.DeltaTable(uri).file_uris())+++def table_files(uri: str) -> int:+ return len(deltalake.DeltaTable(uri).file_uris())+++def make_clustered_upsert_batch(+ n_updates: int,+ partition: str,+ existing_rows: int,+ payload_size: int = 4500,+ version: int = 2,+ fraction: float = 0.02,+) -> pa.Table:+ """Updates confined to a contiguous slice at the end of the key space.++ The uniform-spread batch touches every file, so MERGE gets no file-pruning benefit+ and the write-amplification comparison degenerates. Real syncs of a monotonic key+ (and any table whose files have disjoint key ranges) look like this instead: a few+ files hold every match. This is the shape where MERGE should win on bytes written,+ and where deltalite's PK-stats pruning has to earn its keep.+ """+ start = max(0, existing_rows - int(existing_rows * fraction))+ ids = list(range(start, min(start + n_updates, existing_rows)))+ return make_batch(ids[0], len(ids), partition, payload_size=payload_size, version=version)+++def commit_io_range(uri: str, first_version: int, last_version: int) -> dict:+ """Sum commit_io over an inclusive version range.++ MERGE commits once per affected partition, so reading only the final version+ undercounts its write volume by the number of partitions touched. Any comparison of+ bytes/files written between the two paths must use this, not `commit_io`.+ """+ total = {"files_added": 0, "files_removed": 0, "bytes_added": 0, "bytes_removed": 0}+ for v in range(first_version, last_version + 1):+ try:+ one = commit_io(uri, v)+ except FileNotFoundError:+ continue+ for k in total:+ total[k] += one[k]+ total["commits"] = last_version - first_version + 1+ return totaldiff --git a/rust/deltalite/python/build.rs b/rust/deltalite/python/build.rsnew file mode 100644index 000000000000..3ef3335f9457--- /dev/null+++ b/rust/deltalite/python/build.rs@@ -0,0 +1,13 @@+// Tell macOS's linker to defer libpython symbols to load time. PyO3's+// `extension-module` feature suppresses the libpython link, but on macOS the+// linker still needs `-undefined dynamic_lookup` to accept the unresolved+// symbols when producing a `cdylib`. `maturin` adds this implicitly when it+// builds the wheel, but a plain `cargo build -p deltalite-python` on macOS+// doesn't go through maturin, so we add it here too. (Same as+// rust/hogql/parser/build.rs.)+fn main() {+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {+ println!("cargo:rustc-link-arg=-undefined");+ println!("cargo:rustc-link-arg=dynamic_lookup");+ }+}diff --git a/rust/deltalite/python/deltalite_planner.py b/rust/deltalite/python/deltalite_planner.pynew file mode 100644index 000000000000..c27cbeadab10--- /dev/null+++ b/rust/deltalite/python/deltalite_planner.py@@ -0,0 +1,171 @@+"""Rough knob tuning for deltalite: "we run N concurrent upserts on a pod with M MB+of memory -- what should mpp / mpf be?"++This is deliberately a heuristic, not a capacity model. The measurements behind it+established the *shape* of deltalite's memory behaviour, and the shape is all this+module relies on:++* Peak memory never tracks target-table size. It tracks the resident source batch,+ the number of concurrent partition workers (`max_parallel_partitions`, "mpp"), and+ the write-buffer / byte-budget knobs.+* `max_parallel_partitions` is the memory dial. Each concurrent partition worker+ costs roughly its write buffer (`target_file_size`, 100 MB by default) plus+ in-flight row groups.+* `max_parallel_files` ("mpf") is a wall-clock dial with little memory effect of its+ own -- decoded data in flight is capped by the byte budget, not by mpf.+* Upserts running as threads in one process share the interpreter/runtime overhead+ and do not peak simultaneously, so a process fits noticeably more than+ N x (single-upsert peak).++Absolute numbers vary with row width, Parquet row-group sizing and hardware, so treat+the output as a starting point and validate under real load. The process-global+ceilings in `deltalite_core::limits` (DELTALITE_PROCESS_* env vars) are the hard+backstop either way.+"""++from __future__ import annotations++from dataclasses import dataclass, field++MB = 1024 * 1024++#: Keep this fraction of pod memory for everything that is not deltalite (interpreter,+#: pyarrow buffers in flight, allocator slack).+_SAFETY = 0.8++#: One-off process overhead (interpreter, imports, tokio runtime, object-store pools).+_PROCESS_OVERHEAD_MB = 500++#: Rough marginal cost of one in-flight upsert before any partition worker spins up+#: (snapshot/log state, plan, channels). Staggered peaks are already baked in.+_PER_UPSERT_FLOOR_MB = 300++#: Rough cost of one concurrent partition worker on top of its write buffer+#: (in-flight row groups, PK set, transient source slice).+_PER_WORKER_OVERHEAD_MB = 150+++@dataclass(frozen=True)+class Knobs:+ """A suggested starting configuration, plus how it was arrived at."""++ max_parallel_partitions: int+ max_parallel_files: int+ max_buffered_bytes: int+ #: Memory this plan roughly assumes one in-flight upsert may use.+ per_upsert_budget_mb: float+ #: False when even the most conservative knobs look too big for the pod.+ fits: bool+ #: Suggested process-global ceilings (the env vars `deltalite_core` reads).+ env: dict[str, str] = field(default_factory=dict)+ notes: list[str] = field(default_factory=list)++ def as_upsert_kwargs(self) -> dict:+ """Keyword arguments for `DeltaLiteTable.upsert`."""+ return {+ "max_parallel_partitions": self.max_parallel_partitions,+ "max_parallel_files": self.max_parallel_files,+ "max_buffered_bytes": self.max_buffered_bytes,+ }+++def plan(+ concurrent_upserts: int,+ pod_memory_mb: float,+ *,+ source_mb: float | None = None,+ target_file_size_mb: float = 100.0,+) -> Knobs:+ """Suggest mpp / mpf / byte-budget knobs for `concurrent_upserts` upsert threads+ in one process on a pod with `pod_memory_mb` of memory.++ `source_mb` is the typical resident size of one upsert's source batch; when not+ given, a note reminds you that the source is the term nothing else bounds.+ """+ if concurrent_upserts < 1:+ raise ValueError("concurrent_upserts must be >= 1")+ if pod_memory_mb <= 0:+ raise ValueError("pod_memory_mb must be positive")+ if target_file_size_mb <= 0:+ raise ValueError("target_file_size_mb must be positive")++ notes: list[str] = []++ usable_mb = pod_memory_mb * _SAFETY - _PROCESS_OVERHEAD_MB+ per_upsert_mb = usable_mb / concurrent_upserts++ # The floor one upsert needs before any partition worker: bookkeeping plus the+ # resident source (held for the whole upsert; roughly doubled while interleaved+ # sources are sliced per partition).+ floor_mb = _PER_UPSERT_FLOOR_MB + (2.0 * source_mb if source_mb is not None else 0.0)+ if source_mb is None:+ notes.append(+ "source size not given: the resident source batch is the one memory term "+ "no knob bounds, so re-check against your largest batches"+ )++ worker_mb = target_file_size_mb + _PER_WORKER_OVERHEAD_MB+ headroom_mb = per_upsert_mb - floor_mb++ # mpp: however many partition workers fit in the headroom, kept between 1 and 4+ # (beyond 4 the measured wall-clock gains vanish while memory keeps climbing).+ mpp = max(1, min(4, int(headroom_mb // worker_mb)))+ tight = headroom_mb < worker_mb++ # mpf is a wall-clock knob; 4 is the measured sweet spot, halved when tight so+ # fewer decoded batches sit waiting for budget.+ mpf = 2 if tight else 4+ buffered = 32 * MB if tight else 64 * MB++ fits = headroom_mb >= worker_mb * 0.75 # allow a modest squeeze at mpp=1+ if not fits:+ notes.append(+ f"~{per_upsert_mb:.0f} MB per upsert is below the ~{floor_mb + worker_mb:.0f} MB "+ "a single-worker upsert wants: reduce concurrent upserts, shrink source "+ "batches, or use a bigger pod"+ )+ if tight and fits:+ notes.append("memory is tight: knobs reduced to their most conservative settings")++ # Process-global ceilings: cap total in-flight work at roughly four upserts' worth+ # of per-call knobs -- threads do not peak together, so this holds the process+ # bound without serialising everything.+ burst = min(concurrent_upserts, 4)+ env = {+ "DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS": str(mpp * burst),+ "DELTALITE_PROCESS_MAX_PARALLEL_FILES": str(mpf * burst),+ "DELTALITE_PROCESS_MAX_BUFFERED_BYTES": str(buffered * burst),+ }++ return Knobs(+ max_parallel_partitions=mpp,+ max_parallel_files=mpf,+ max_buffered_bytes=buffered,+ per_upsert_budget_mb=round(per_upsert_mb, 1),+ fits=fits,+ env=env,+ notes=notes,+ )+++if __name__ == "__main__":+ import argparse++ ap = argparse.ArgumentParser(description="Suggest deltalite knobs for a pod")+ ap.add_argument("concurrent_upserts", type=int)+ ap.add_argument("pod_memory_mb", type=float)+ ap.add_argument("--source-mb", type=float, default=None)+ ap.add_argument("--target-file-size-mb", type=float, default=100.0)+ args = ap.parse_args()+ k = plan(+ args.concurrent_upserts,+ args.pod_memory_mb,+ source_mb=args.source_mb,+ target_file_size_mb=args.target_file_size_mb,+ )+ print(f"fits={k.fits} per-upsert budget ~{k.per_upsert_budget_mb} MB")+ print(f"upsert kwargs: {k.as_upsert_kwargs()}")+ for kk, v in k.env.items():+ print(f"env: {kk}={v}")+ for n in k.notes:+ print(f"note: {n}")diff --git a/rust/deltalite/python/harness/__init__.py b/rust/deltalite/python/harness/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/rust/deltalite/python/harness/common.py b/rust/deltalite/python/harness/common.pynew file mode 100644index 000000000000..ccb4a4a47e8e--- /dev/null+++ b/rust/deltalite/python/harness/common.py@@ -0,0 +1,348 @@+"""Shared harness: data generation, the two write paths, and logical comparison.++The `merge_path` function is a faithful transcription of the production incremental+branch of `DeltaTableHelper.write_to_deltalake` (per-partition merge loop with+`streamed_exec=True`, single merge with `streamed_exec=False` when unpartitioned, only+the final commit tagged), so parity assertions compare against what actually ships.+"""++from __future__ import annotations++import random+import shutil+import string+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import pyarrow as pa+import deltalake+import pyarrow.compute as pc++PARTITION_KEY = "_ph_partition_key"+++# --------------------------------------------------------------------------------------+# Source-batch preparation (must be identical for both paths)+# --------------------------------------------------------------------------------------+++def dedupe_keep_last(table: pa.Table, primary_keys: list[str], partition_key: str | None) -> pa.Table:+ """Intra-batch keep-last dedup per (PKs, partition), mirroring+ `_dedupe_incremental_batch`.++ Rows carrying a NULL in any PK column are exempt: SQL `NULL != NULL` means they can+ never collide with anything, so they must all survive rather than collapse into one.+ """+ if table.num_rows == 0:+ return table+ keys = list(primary_keys) + ([partition_key] if partition_key else [])++ null_mask = None+ for k in primary_keys:+ m = pc.is_null(table[k])+ null_mask = m if null_mask is None else pc.or_(null_mask, m)++ idx = pa.array(range(table.num_rows), pa.int64())+ with_idx = table.append_column("__idx", idx)++ nullable_rows = with_idx.filter(null_mask)+ keyed_rows = with_idx.filter(pc.invert(null_mask))++ if keyed_rows.num_rows:+ grouped = keyed_rows.group_by(keys).aggregate([("__idx", "max")])+ keep = set(grouped["__idx_max"].to_pylist())+ mask = pa.array([i in keep for i in keyed_rows["__idx"].to_pylist()])+ keyed_rows = keyed_rows.filter(mask)++ out = pa.concat_tables([keyed_rows, nullable_rows])+ out = out.sort_by([("__idx", "ascending")])+ return out.drop(["__idx"])+++# --------------------------------------------------------------------------------------+# The two write paths+# --------------------------------------------------------------------------------------+++def evolve_schema(uri: str, batch: pa.Table, storage_options: dict[str, str] | None = None) -> None:+ """Additive schema evolution, mirroring `_evolve_delta_schema`."""+ dt = deltalake.DeltaTable(uri, storage_options=storage_options)+ existing = {f.name for f in dt.schema().fields}+ new_fields = [deltalake.Field.from_arrow(batch.schema.field(n)) for n in batch.schema.names if n not in existing]+ if new_fields:+ dt.alter.add_columns(new_fields)+++def merge_path(+ uri: str,+ batch: pa.Table,+ primary_keys: list[str],+ partition_key: str | None,+ commit_metadata: dict[str, str] | None = None,+ storage_options: dict[str, str] | None = None,+) -> None:+ """delta-rs SQL MERGE, exactly as the production helper drives it."""+ evolve_schema(uri, batch, storage_options)+ dt = deltalake.DeltaTable(uri, storage_options=storage_options)++ props = deltalake.CommitProperties(custom_metadata=commit_metadata) if commit_metadata else None++ if partition_key:+ partitions = sorted(set(batch[partition_key].to_pylist()))+ if not partitions:+ return+ for i, p in enumerate(partitions):+ part_batch = batch.filter(pc.equal(batch[partition_key], p))+ pred = " AND ".join(+ [f"source.{k} = target.{k}" for k in primary_keys]+ + [f"source.{partition_key} = target.{partition_key}"]+ + [f"target.{partition_key} = '{p}'"]+ )+ # Only the terminal commit of the batch carries the idempotency tag.+ is_last = i == len(partitions) - 1+ (+ dt.merge(+ source=part_batch,+ source_alias="source",+ target_alias="target",+ predicate=pred,+ streamed_exec=True,+ commit_properties=props if (is_last and props) else None,+ )+ .when_matched_update_all()+ .when_not_matched_insert_all()+ .execute()+ )+ dt = deltalake.DeltaTable(uri, storage_options=storage_options)+ else:+ pred = " AND ".join(f"source.{k} = target.{k}" for k in primary_keys)+ (+ dt.merge(+ source=batch,+ source_alias="source",+ target_alias="target",+ predicate=pred,+ streamed_exec=False,+ commit_properties=props,+ )+ .when_matched_update_all()+ .when_not_matched_insert_all()+ .execute()+ )+++def upsert_path(+ uri: str,+ batch: pa.Table,+ primary_keys: list[str],+ partition_key: str | None,+ commit_metadata: dict[str, str] | None = None,+ storage_options: dict[str, str] | None = None,+ **kwargs: Any,+) -> Any:+ """deltalite streaming partition upsert."""+ import deltalite++ evolve_schema(uri, batch, storage_options)+ t = deltalite.DeltaLiteTable.open(uri, storage_options)+ return t.upsert(+ batch,+ primary_keys,+ partition_key,+ commit_metadata=commit_metadata,+ **kwargs,+ )+++# --------------------------------------------------------------------------------------+# Comparison+# --------------------------------------------------------------------------------------+++def read_sorted(uri: str, storage_options: dict[str, str] | None = None) -> tuple[list[tuple], list[tuple[str, str]]]:+ """Full logical content as a sorted list of row tuples, plus the schema."""+ dt = deltalake.DeltaTable(uri, storage_options=storage_options)+ tbl = dt.to_pyarrow_table()+ names = sorted(tbl.schema.names)+ tbl = tbl.select(names)+ cols = [tbl.column(n).to_pylist() for n in names]+ rows = list(zip(*cols)) if cols else []+ # Sort on a total order that tolerates NULLs and mixed types.+ rows.sort(key=lambda r: tuple((v is None, str(v)) for v in r))+ schema = [(f.name, str(f.type)) for f in tbl.schema]+ return rows, sorted(schema)+++def assert_parity(+ uri_merge: str,+ uri_upsert: str,+ label: str,+ storage_options: dict[str, str] | None = None,+) -> None:+ rows_m, schema_m = read_sorted(uri_merge, storage_options)+ rows_u, schema_u = read_sorted(uri_upsert, storage_options)++ assert schema_m == schema_u, f"[{label}] schema mismatch\n merge : {schema_m}\n upsert: {schema_u}"+ if rows_m != rows_u:+ only_m = [r for r in rows_m if r not in rows_u][:5]+ only_u = [r for r in rows_u if r not in rows_m][:5]+ raise AssertionError(+ f"[{label}] content mismatch: merge has {len(rows_m)} rows, "+ f"upsert has {len(rows_u)}\n"+ f" only in merge : {only_m}\n"+ f" only in upsert: {only_u}"+ )+++# --------------------------------------------------------------------------------------+# Scenario driver+# --------------------------------------------------------------------------------------+++@dataclass+class Scenario:+ name: str+ initial: pa.Table+ batches: list[pa.Table]+ primary_keys: list[str]+ partitioned: bool = True++ @property+ def partition_key(self) -> str | None:+ return PARTITION_KEY if self.partitioned else None+++def create_table(+ uri: str,+ data: pa.Table,+ partitioned: bool,+ storage_options: dict[str, str] | None = None,+) -> None:+ if "://" not in uri and Path(uri).exists():+ shutil.rmtree(uri)+ deltalake.write_deltalake(+ uri,+ data,+ partition_by=[PARTITION_KEY] if partitioned else None,+ mode="overwrite",+ storage_options=storage_options,+ )+++def run_scenario(+ scenario: Scenario,+ tmp: Path | str,+ storage_options: dict[str, str] | None = None,+) -> tuple[str, str]:+ """Apply the same batch sequence to two fresh tables via the two paths.++ `tmp` may be a local directory Path or a remote base URI string (e.g.+ ``s3://bucket/prefix``); table URIs are appended to it either way.+ """+ if isinstance(tmp, Path):+ uri_m = str(tmp / f"{scenario.name}_merge")+ uri_u = str(tmp / f"{scenario.name}_upsert")+ else:+ uri_m = f"{tmp.rstrip('/')}/{scenario.name}_merge"+ uri_u = f"{tmp.rstrip('/')}/{scenario.name}_upsert"+ create_table(uri_m, scenario.initial, scenario.partitioned, storage_options)+ create_table(uri_u, scenario.initial, scenario.partitioned, storage_options)++ for i, raw in enumerate(scenario.batches):+ batch = dedupe_keep_last(raw, scenario.primary_keys, scenario.partition_key)+ md = {"run_uuid": "run-1", "batch_index": str(i)}+ merge_path(+ uri_m,+ batch,+ scenario.primary_keys,+ scenario.partition_key,+ md,+ storage_options=storage_options,+ )+ upsert_path(+ uri_u,+ batch,+ scenario.primary_keys,+ scenario.partition_key,+ md,+ storage_options=storage_options,+ )++ return uri_m, uri_u+++# --------------------------------------------------------------------------------------+# Data generation+# --------------------------------------------------------------------------------------++_WORDS = ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta"]+++def big_string(rng: random.Random, size: int = 4500) -> str:+ """A JSON-ish blob, so rows land around the ~5 KB the real workload sees."""+ parts = []+ n = 0+ while n < size:+ k = rng.choice(_WORDS)+ v = "".join(rng.choices(string.ascii_letters + string.digits, k=24))+ chunk = f'"{k}_{rng.randint(0, 9999)}": "{v}"'+ parts.append(chunk)+ n += len(chunk) + 2+ return "{" + ", ".join(parts) + "}"+++def wide_schema() -> pa.Schema:+ return pa.schema(+ [+ pa.field("id", pa.string()),+ pa.field("tenant", pa.int64()),+ pa.field("counter", pa.int32()),+ pa.field("created_at", pa.timestamp("us")),+ pa.field("updated_at", pa.timestamp("us")),+ pa.field("amount", pa.decimal128(38, 10)),+ pa.field("payload", pa.string()),+ pa.field(PARTITION_KEY, pa.string()),+ ]+ )+++def gen_wide(+ ids: list[str],+ partition: str,+ seed: int = 0,+ payload_size: int = 4500,+ version: int = 1,+) -> pa.Table:+ """Wide ~5 KB rows: string PK, ints, timestamps, a decimal, a large JSON-ish string."""+ import datetime as _dt++ rng = random.Random(seed)+ n = len(ids)+ base = _dt.datetime(2026, 1, 1)+ return pa.table(+ {+ "id": pa.array(ids, pa.string()),+ "tenant": pa.array([rng.randint(1, 50) for _ in range(n)], pa.int64()),+ "counter": pa.array([version] * n, pa.int32()),+ "created_at": pa.array([base] * n, pa.timestamp("us")),+ "updated_at": pa.array([base + _dt.timedelta(seconds=version)] * n, pa.timestamp("us")),+ "amount": pa.array(+ [+ __import__("decimal").Decimal(f"{rng.randint(0, 10**6)}.{rng.randint(0, 10**9):09d}")+ for _ in range(n)+ ],+ pa.decimal128(38, 10),+ ),+ "payload": pa.array([big_string(rng, payload_size) for _ in range(n)], pa.string()),+ PARTITION_KEY: pa.array([partition] * n, pa.string()),+ },+ schema=wide_schema(),+ )+++def uuid_ids(n: int, offset: int = 0, seed: int = 0) -> list[str]:+ """Deterministic UUID-shaped primary keys."""+ rng = random.Random(seed)+ _ = rng+ return [f"{i:08x}-0000-4000-8000-{i:012x}" for i in range(offset, offset + n)]diff --git a/rust/deltalite/python/pyproject.toml b/rust/deltalite/python/pyproject.tomlnew file mode 100644index 000000000000..f427577e7760--- /dev/null+++ b/rust/deltalite/python/pyproject.toml@@ -0,0 +1,36 @@+[build-system]+# `maturin` is fetched into an isolated PEP-517 build environment, so no+# system install (or `cargo install maturin`) is required to build the wheel+# in CI or on a contributor's machine. The only host requirements are a+# Python interpreter, `uv` / `pip`, and a Rust toolchain. (Same arrangement+# as rust/hogql/parser.)+requires = ["maturin>=1.7,<2.0"]+build-backend = "maturin"++[project]+name = "deltalite"+# Mirrors `rust/deltalite/python/Cargo.toml` (always identical); bump both together.+version = "0.1.0"+description = "Streaming partition upsert for Delta tables, replacing delta-rs SQL MERGE"+readme = "README.md"+requires-python = ">=3.12"+authors = [{ name = "PostHog" }]+license = "MIT"+classifiers = [+ "Development Status :: 4 - Beta",+ "Operating System :: OS Independent",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.12",+ "Programming Language :: Python :: 3.13",+ "Programming Language :: Rust",+]++[project.urls]+Repository = "https://github.com/PostHog/posthog"+Issues = "https://github.com/PostHog/posthog/issues"++[tool.maturin]+module-name = "deltalite"+# Build using the workspace at `rust/Cargo.toml`. Maturin walks up from the+# crate's `Cargo.toml` to find it automatically.+features = ["pyo3/extension-module"]diff --git a/rust/deltalite/python/pytest.ini b/rust/deltalite/python/pytest.ininew file mode 100644index 000000000000..cb6c0a14a771--- /dev/null+++ b/rust/deltalite/python/pytest.ini@@ -0,0 +1,4 @@+# Standalone pytest root: keeps pytest from ascending to the repo pyproject.toml+# (whose ini_options assume the Django test environment and its plugins).+[pytest]+testpaths = testsdiff --git a/rust/deltalite/python/src/lib.rs b/rust/deltalite/python/src/lib.rsnew file mode 100644index 000000000000..a7282aefa38f--- /dev/null+++ b/rust/deltalite/python/src/lib.rs@@ -0,0 +1,451 @@+//! Python bindings for `deltalite-core` (imported as `deltalite`).+//!+//! Every entry point releases the GIL for the I/O-heavy work and runs it on a+//! process-wide tokio runtime. Errors surface as a typed exception hierarchy rooted at+//! `DeltaLiteError`, so the caller can branch on kind instead of sniffing error text.++use std::collections::HashMap;+use std::sync::{Arc, OnceLock};++use arrow::array::ArrayData;+use arrow::pyarrow::{FromPyArrow, ToPyArrow};+use arrow_array::{new_empty_array, Array, RecordBatch};+use arrow_schema::SchemaRef;+use deltalake::writer::RecordBatchWriter;+use deltalake::DeltaTable;+use deltalite_core::errors::Error;+use deltalite_core::limits::ProcessLimits;+use deltalite_core::schema::import_column;+use deltalite_core::table::{open_table, open_table_multipart, MultipartConfig};+use deltalite_core::upsert::{PruneStrategy, UpsertOptions};+use pyo3::create_exception;+use pyo3::exceptions::PyException;+use pyo3::prelude::*;+use pyo3::types::{PyDict, PyList};+use serde_json::Value;++create_exception!(deltalite, DeltaLiteError, PyException);+create_exception!(deltalite, DeltaLiteCommitConflictError, DeltaLiteError);+create_exception!(deltalite, DeltaLiteSchemaMismatchError, DeltaLiteError);+create_exception!(deltalite, DeltaLiteTableNotFoundError, DeltaLiteError);+create_exception!(deltalite, DeltaLiteUnsupportedTableError, DeltaLiteError);+create_exception!(deltalite, DeltaLiteSourceTooLargeError, DeltaLiteError);++/// Map a core error onto the matching Python exception class.+fn to_py_err(e: Error) -> PyErr {+ let msg = e.to_string();+ match e {+ Error::SchemaMismatch(_) => DeltaLiteSchemaMismatchError::new_err(msg),+ Error::NotFound(_) => DeltaLiteTableNotFoundError::new_err(msg),+ Error::Unsupported(_) => DeltaLiteUnsupportedTableError::new_err(msg),+ Error::Conflict(_) => DeltaLiteCommitConflictError::new_err(msg),+ Error::SourceTooLarge(_) => DeltaLiteSourceTooLargeError::new_err(msg),+ Error::Generic(_) => DeltaLiteError::new_err(msg),+ }+}++fn runtime() -> &'static tokio::runtime::Runtime {+ static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();+ RT.get_or_init(|| {+ tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .build()+ // Unreachable outside of catastrophic resource exhaustion at import time;+ // there is no Python-visible fallible path to surface it on.+ .expect("failed to build tokio runtime")+ })+}++/// Ingest a pyarrow object (`pa.Table`, `pa.RecordBatch`, `pa.RecordBatchReader`).+///+/// Deliberately imported **column by column as `ArrayData`** rather than straight to a+/// `RecordBatch`. arrow-rs asserts that a `Decimal128` value buffer is 16-byte aligned+/// while constructing the *typed* array, and buffers arriving over the C Data Interface+/// from pyarrow are only guaranteed 8-byte aligned (an Arrow IPC round-trip reliably+/// produces one) -- that assert is delta-io/delta-rs#3884, and it fires *inside* the+/// import, before any `RecordBatch` exists to repair. `ArrayData` carries untyped+/// buffers and skips the assert, giving `deltalite_core::schema::realign_array_data` a+/// chance to copy-realign first.+///+/// The table's chunks are deliberately NOT combined: `combine_chunks` copies the whole+/// source into fresh contiguous buffers, and upsert consumes multiple batches natively.+/// `to_batches()` re-chunks to aligned boundaries by zero-copy slicing, so this import+/// shares the caller's buffers instead of duplicating them.+fn read_pyarrow(obj: &Bound<'_, PyAny>) -> PyResult<(SchemaRef, Vec<RecordBatch>)> {+ let py = obj.py();+ let err = |e: PyErr| DeltaLiteError::new_err(format!("pyarrow ingest: {e}"));++ // Normalise whatever we were handed into a pa.Table.+ let mut obj = obj.clone();+ if obj.hasattr("read_all").map_err(err)? {+ obj = obj.call_method0("read_all").map_err(err)?;+ }+ if !obj.hasattr("to_batches").map_err(err)? {+ let pa = py.import("pyarrow").map_err(err)?;+ obj = pa+ .getattr("Table")+ .map_err(err)?+ .call_method1("from_batches", (vec![obj.clone()],))+ .map_err(err)?;+ }+ let table = obj;++ let schema: SchemaRef = Arc::new(+ arrow_schema::Schema::from_pyarrow_bound(&table.getattr("schema").map_err(err)?)+ .map_err(err)?,+ );++ let py_batches: Vec<Bound<'_, PyAny>> = table+ .call_method0("to_batches")+ .map_err(err)?+ .extract()+ .map_err(err)?;++ let mut batches: Vec<RecordBatch> = Vec::with_capacity(py_batches.len());+ for pyb in py_batches {+ let num_rows: usize = pyb+ .getattr("num_rows")+ .map_err(err)?+ .extract()+ .map_err(err)?;++ let mut columns: Vec<Arc<dyn Array>> = Vec::with_capacity(schema.fields().len());+ for (i, field) in schema.fields().iter().enumerate() {+ let col = pyb.call_method1("column", (i,)).map_err(err)?;+ let array: Arc<dyn Array> = if num_rows == 0 {+ new_empty_array(field.data_type())+ } else {+ let data = ArrayData::from_pyarrow_bound(&col).map_err(err)?;+ import_column(data).map_err(to_py_err)?+ };+ columns.push(array);+ }+ batches.push(+ RecordBatch::try_new(schema.clone(), columns)+ .map_err(|e| DeltaLiteError::new_err(format!("assembling imported batch: {e}")))?,+ );+ }++ if batches.is_empty() {+ // A zero-chunk table produces no batches; keep the empty-source path alive+ // (an empty upsert must still land a tagged commit).+ batches.push(RecordBatch::new_empty(schema.clone()));+ }++ Ok((schema, batches))+}++/// Counters describing what one `upsert` did.+#[pyclass(module = "deltalite", skip_from_py_object)]+#[derive(Clone, Debug, Default)]+pub struct UpsertStats {+ #[pyo3(get)]+ pub version: i64,+ #[pyo3(get)]+ pub partitions_touched: usize,+ #[pyo3(get)]+ pub files_removed: usize,+ #[pyo3(get)]+ pub files_added: usize,+ #[pyo3(get)]+ pub files_carried_over: usize,+ #[pyo3(get)]+ pub files_probed: usize,+ #[pyo3(get)]+ pub rows_updated: usize,+ #[pyo3(get)]+ pub rows_inserted: usize,+ #[pyo3(get)]+ pub rows_copied: usize,+ #[pyo3(get)]+ pub source_rows: usize,+ #[pyo3(get)]+ pub null_pk_rows: usize,+}++#[pymethods]+impl UpsertStats {+ fn __repr__(&self) -> String {+ format!(+ "UpsertStats(version={}, partitions_touched={}, files_added={}, files_removed={}, \+ files_carried_over={}, files_probed={}, rows_updated={}, rows_inserted={}, \+ rows_copied={})",+ self.version,+ self.partitions_touched,+ self.files_added,+ self.files_removed,+ self.files_carried_over,+ self.files_probed,+ self.rows_updated,+ self.rows_inserted,+ self.rows_copied+ )+ }+}++impl From<deltalite_core::upsert::UpsertStats> for UpsertStats {+ fn from(s: deltalite_core::upsert::UpsertStats) -> Self {+ Self {+ version: s.version,+ partitions_touched: s.partitions_touched,+ files_removed: s.files_removed,+ files_added: s.files_added,+ files_carried_over: s.files_carried_over,+ files_probed: s.files_probed,+ rows_updated: s.rows_updated,+ rows_inserted: s.rows_inserted,+ rows_copied: s.rows_copied,+ source_rows: s.source_rows,+ null_pk_rows: s.null_pk_rows,+ }+ }+}++/// A handle on a Delta table for deltalite writes. Reads (schema, history, file+/// listing) exist for parity tooling; production read paths stay on the Python+/// `deltalake` package -- both address the same `_delta_log`.+#[pyclass(module = "deltalite")]+pub struct DeltaLiteTable {+ uri: String,+ storage_options: HashMap<String, String>,+ table: DeltaTable,+}++#[pymethods]+impl DeltaLiteTable {+ /// Open an existing Delta table.+ #[staticmethod]+ #[pyo3(signature = (uri, storage_options = None))]+ fn open(+ py: Python<'_>,+ uri: String,+ storage_options: Option<HashMap<String, String>>,+ ) -> PyResult<Self> {+ let so = storage_options.unwrap_or_default();+ let so2 = so.clone();+ let table = py+ .detach(|| runtime().block_on(open_table(&uri, so2)))+ .map_err(to_py_err)?;+ Ok(Self {+ uri,+ storage_options: so,+ table,+ })+ }++ /// Whether `uri` points at a loadable Delta table.+ #[staticmethod]+ #[pyo3(signature = (uri, storage_options = None))]+ fn is_deltatable(+ py: Python<'_>,+ uri: String,+ storage_options: Option<HashMap<String, String>>,+ ) -> PyResult<bool> {+ let so = storage_options.unwrap_or_default();+ Ok(py+ .detach(|| runtime().block_on(open_table(&uri, so)))+ .is_ok())+ }++ /// The table version this handle currently observes (-1 before any load).+ fn version(&self) -> i64 {+ self.table+ .version()+ .and_then(|v| i64::try_from(v).ok())+ .unwrap_or(-1)+ }++ /// Re-read the log so this handle observes commits made elsewhere.+ fn reload(&mut self, py: Python<'_>) -> PyResult<()> {+ let uri = self.uri.clone();+ let so = self.storage_options.clone();+ self.table = py+ .detach(|| runtime().block_on(open_table(&uri, so)))+ .map_err(to_py_err)?;+ Ok(())+ }++ /// The table's Arrow schema, as the write path will expect it.+ fn schema_arrow(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {+ let schema = RecordBatchWriter::for_table(&self.table)+ .map_err(|e| to_py_err(Error::from(e)))?+ .arrow_schema();+ Ok(schema.to_pyarrow(py)?.into())+ }++ /// The table's partition columns (possibly empty).+ fn partition_columns(&self) -> PyResult<Vec<String>> {+ let snapshot = self.table.snapshot().map_err(|e| to_py_err(e.into()))?;+ Ok(snapshot.metadata().partition_columns().to_vec())+ }++ /// URIs of the live data files.+ fn file_uris(&self) -> PyResult<Vec<String>> {+ Ok(self+ .table+ .get_file_uris()+ .map_err(|e| to_py_err(e.into()))?+ .collect::<Vec<_>>())+ }++ /// The core replacement for `DeltaTable.merge(...).when_matched_update_all()+ /// .when_not_matched_insert_all().execute()`.+ ///+ /// `prune_strategy` selects how the rewrite set is chosen per partition:+ /// - `"none"`: rewrite every live file.+ /// - `"stats"`: skip files whose Add-action stats prove no match (min/max on the+ /// first PK column, all-NULL PK columns).+ /// - `"probe"` (default): stats first, then read only the PK column(s) of each+ /// surviving file and skip those that contain no matched row. Exact, like MERGE.+ ///+ /// When `prune_strategy` is not given, `skip_unmatched_files=False` maps to+ /// `"none"` and the default `True` maps to `"probe"`.+ ///+ /// `max_source_bytes` guards against oversized batches (resident source + estimated+ /// PK set); `0` disables the guard, `None` uses `DELTALITE_MAX_SOURCE_BYTES` or the+ /// built-in 2 GiB default. `multipart_threshold` / `multipart_part_size` control+ /// multipart upload of output files (`0` threshold disables).+ #[pyo3(signature = (+ data,+ primary_keys,+ partition_key = None,+ *,+ commit_metadata = None,+ max_parallel_partitions = 2,+ max_parallel_files = 4,+ max_buffered_bytes = 67108864,+ skip_unmatched_files = true,+ prune_strategy = None,+ probe_concurrency = 8,+ commit_max_retries = 15,+ read_batch_size = 8192,+ target_file_size = None,+ max_source_bytes = None,+ multipart_threshold = None,+ multipart_part_size = None,+ ))]+ #[allow(clippy::too_many_arguments)]+ fn upsert(+ &mut self,+ py: Python<'_>,+ data: &Bound<'_, PyAny>,+ primary_keys: Vec<String>,+ partition_key: Option<String>,+ commit_metadata: Option<HashMap<String, String>>,+ max_parallel_partitions: usize,+ max_parallel_files: usize,+ max_buffered_bytes: usize,+ skip_unmatched_files: bool,+ prune_strategy: Option<String>,+ probe_concurrency: usize,+ commit_max_retries: usize,+ read_batch_size: usize,+ target_file_size: Option<usize>,+ max_source_bytes: Option<usize>,+ multipart_threshold: Option<usize>,+ multipart_part_size: Option<usize>,+ ) -> PyResult<UpsertStats> {+ // Import while holding the GIL (it reads a Python object), then release it for+ // all the I/O.+ let (schema, batches) = read_pyarrow(data)?;++ let prune_strategy = match prune_strategy.as_deref() {+ Some(s) => s.parse::<PruneStrategy>().map_err(to_py_err)?,+ None if skip_unmatched_files => PruneStrategy::Probe,+ None => PruneStrategy::None,+ };++ let opts = UpsertOptions {+ primary_keys,+ partition_key,+ commit_metadata: commit_metadata.map(|m| {+ m.into_iter()+ .map(|(k, v)| (k, Value::String(v)))+ .collect::<HashMap<String, Value>>()+ }),+ max_parallel_partitions,+ prune_strategy,+ probe_concurrency,+ max_parallel_files,+ max_buffered_bytes,+ commit_max_retries,+ read_batch_size,+ target_file_size,+ max_source_bytes,+ // Shared with every other concurrent upsert in this process, so the+ // process-level memory bound holds regardless of thread count.+ limits: ProcessLimits::global().clone(),+ };+ let multipart = MultipartConfig::resolve(multipart_threshold, multipart_part_size);++ let uri = self.uri.clone();+ let so = self.storage_options.clone();+ let stats = py+ .detach(|| {+ runtime().block_on(async move {+ // Take a fresh snapshot for the upsert so a retried batch never+ // plans against stale state.+ let table = open_table_multipart(&uri, so, multipart).await?;+ deltalite_core::upsert::upsert(&table, batches, schema, opts).await+ })+ })+ .map_err(to_py_err)?;++ self.reload(py)?;+ Ok(stats.into())+ }++ /// Commit metadata of the most recent `limit` commits, oldest first.+ fn history(&self, py: Python<'_>, limit: usize) -> PyResult<Py<PyAny>> {+ let table = self.table.clone();+ let infos = py+ .detach(|| {+ runtime().block_on(async move {+ let h: Vec<_> = table.history(Some(limit)).await?.collect();+ Ok::<_, Error>(h)+ })+ })+ .map_err(to_py_err)?;++ let out = PyList::empty(py);+ for info in infos {+ let d = PyDict::new(py);+ d.set_item("operation", info.operation.clone())?;+ let flat = PyDict::new(py);+ for (k, v) in &info.info {+ flat.set_item(k, v.to_string())?;+ }+ d.set_item("info", flat)?;+ out.append(d)?;+ }+ Ok(out.into())+ }+}++#[pymodule]+fn deltalite(m: &Bound<'_, PyModule>) -> PyResult<()> {+ m.add_class::<DeltaLiteTable>()?;+ m.add_class::<UpsertStats>()?;+ m.add("DeltaLiteError", m.py().get_type::<DeltaLiteError>())?;+ m.add(+ "DeltaLiteCommitConflictError",+ m.py().get_type::<DeltaLiteCommitConflictError>(),+ )?;+ m.add(+ "DeltaLiteSchemaMismatchError",+ m.py().get_type::<DeltaLiteSchemaMismatchError>(),+ )?;+ m.add(+ "DeltaLiteTableNotFoundError",+ m.py().get_type::<DeltaLiteTableNotFoundError>(),+ )?;+ m.add(+ "DeltaLiteUnsupportedTableError",+ m.py().get_type::<DeltaLiteUnsupportedTableError>(),+ )?;+ m.add(+ "DeltaLiteSourceTooLargeError",+ m.py().get_type::<DeltaLiteSourceTooLargeError>(),+ )?;+ Ok(())+}diff --git a/rust/deltalite/python/tests/test_crash_redelivery.py b/rust/deltalite/python/tests/test_crash_redelivery.pynew file mode 100644index 000000000000..5e695eecf578--- /dev/null+++ b/rust/deltalite/python/tests/test_crash_redelivery.py@@ -0,0 +1,592 @@+"""Crash-safety and redelivery.++Production runs these batches under Temporal with Kafka-style redelivery, so a batch can+be SIGKILLed at any point and re-run. These tests verify:++1. A kill between the parquet rewrite and the `CommitBuilder` commit leaves the table+ logically unchanged (orphaned data files are fine; the log, version, live file set,+ and contents must be untouched and the table must not be corrupted).+2. The idempotency tag (`run_uuid` + `batch_index` in commitInfo) supports the+ redelivery decision: discoverable after a successful commit (skip), absent after a+ pre-commit crash (re-run).+3. Re-running a whole batch is idempotent by construction -- with the documented+ exception of NULL-PK rows, which always insert and therefore duplicate on redelivery+ on BOTH paths (a genuine trap; pinned explicitly below).+4. deltalite makes ONE commit per batch, so a mid-batch kill never exposes a partial+ (some-partitions-updated) table -- unlike today's per-partition MERGE loop, whose+ partial visibility is also demonstrated here for contrast.++Kill mechanics: the upsert runs in a subprocess; the parent polls the table directory+every ~1 ms and SIGKILLs on a phase trigger (new data files appearing before the log+gains a commit). Every kill asserts on *observed* state -- the worker must die without+printing its COMMITTED sentinel and without a new log entry -- so a kill that missed its+phase fails (or retries) rather than silently passing.+"""++from __future__ import annotations++import os+import re+import sys+import time+import shutil+import signal+import textwrap+import subprocess+from pathlib import Path++import pytest++import pyarrow as pa+import deltalake+import pyarrow.parquet as pq++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+from harness.common import ( # noqa: E402+ PARTITION_KEY,+ create_table,+ gen_wide,+ merge_path,+ read_sorted,+ upsert_path,+ uuid_ids,+)++# Crash-table shape: 4 partitions x 8000 wide rows (~27 MB total). With+# max_parallel_partitions=1 each partition's rewritten parquet file appears ~50 ms after+# the previous one and the commit lands ~2 ms after the last, so killing on the first+# new file leaves ~150 ms of margin before the commit could possibly land.+N_PARTITIONS = 4+ROWS_PER_PARTITION = 8_000+BATCH_ROWS_PER_PARTITION = 1_000+PAYLOAD_SIZE = 1_000+CRASH_PARTITIONS = [f"2026-07-{d:02d}" for d in range(20, 20 + N_PARTITIONS)]++POLL_S = 0.001+WORKER_TIMEOUT_S = 120+KILL_ATTEMPTS = 3 # re-try a lost race (commit beat the kill) up to this many times++COMMIT_RE = re.compile(r"^\d{20}\.json$")+CRASH_MD = {"run_uuid": "crash-run", "batch_index": "0"}++WORKER_SRC = textwrap.dedent(+ """+ import sys+ sys.path.insert(0, {root!r})+ import pyarrow.parquet as pq+ from harness.common import merge_path, upsert_path++ mode, uri, batch_path = sys.argv[1], sys.argv[2], sys.argv[3]+ batch = pq.read_table(batch_path)+ md = {md!r}+ if mode == "merge":+ merge_path(uri, batch, ["id"], {pk!r}, md)+ else:+ upsert_path(uri, batch, ["id"], {pk!r}, md, max_parallel_partitions=1)+ print("COMMITTED", flush=True)+ """+).format(root=str(ROOT), md=CRASH_MD, pk=PARTITION_KEY)+++# --------------------------------------------------------------------------------------+# Observation helpers+# --------------------------------------------------------------------------------------+++def data_files(uri: str) -> set[str]:+ root = Path(uri)+ return {str(f.relative_to(root)) for f in root.rglob("*.parquet") if "_delta_log" not in f.parts}+++def commit_entries(uri: str) -> set[str]:+ log = Path(uri) / "_delta_log"+ if not log.exists():+ return set()+ return {f.name for f in log.iterdir() if COMMIT_RE.match(f.name)}+++def table_state(uri: str):+ """The full logically-visible state: version, live files, content, schema."""+ dt = deltalake.DeltaTable(uri)+ rows, schema = read_sorted(uri)+ return {+ "version": dt.version(),+ "file_uris": sorted(dt.file_uris()),+ "rows": rows,+ "schema": schema,+ }+++def batch_already_committed(uri: str, md: dict[str, str], limit: int = 10) -> bool:+ """The production redelivery decision: `has_commit_with_metadata`'s matcher+ (accepts both the flat 1.x commitInfo layout and nested userMetadata)."""+ for commit in deltalake.DeltaTable(uri).history(limit):+ flat = all(commit.get(k) == v for k, v in md.items())+ nested = commit.get("userMetadata")+ if flat or (isinstance(nested, dict) and all(nested.get(k) == v for k, v in md.items())):+ return True+ return False+++def updated_partitions(uri: str) -> list[str]:+ """Partitions in which the batch's rows (counter == 2) are visible."""+ tbl = deltalake.DeltaTable(uri).to_pyarrow_table(columns=["counter", PARTITION_KEY])+ return sorted({p for c, p in zip(tbl["counter"].to_pylist(), tbl[PARTITION_KEY].to_pylist()) if c == 2})+++# --------------------------------------------------------------------------------------+# Crash fixture: one base table template per session, copied per attempt+# --------------------------------------------------------------------------------------++[email protected](scope="session")+def crash_template(tmp_path_factory):+ tmp = tmp_path_factory.mktemp("crash_template")+ uri = str(tmp / "base")+ initial = pa.concat_tables(+ gen_wide(+ uuid_ids(ROWS_PER_PARTITION, offset=i * ROWS_PER_PARTITION),+ p,+ seed=i,+ payload_size=PAYLOAD_SIZE,+ version=1,+ )+ for i, p in enumerate(CRASH_PARTITIONS)+ )+ create_table(uri, initial, True)++ # The redelivered batch: 1000 updated rows in every partition (version/counter=2).+ batch = pa.concat_tables(+ gen_wide(+ uuid_ids(BATCH_ROWS_PER_PARTITION, offset=i * ROWS_PER_PARTITION),+ p,+ seed=100 + i,+ payload_size=PAYLOAD_SIZE,+ version=2,+ )+ for i, p in enumerate(CRASH_PARTITIONS)+ )+ batch_path = tmp / "batch.parquet"+ pq.write_table(batch, batch_path)++ worker = tmp / "worker.py"+ worker.write_text(WORKER_SRC)++ # Expected content after the batch is applied exactly once (either path).+ control = str(tmp / "control")+ shutil.copytree(uri, control)+ upsert_path(control, batch, ["id"], PARTITION_KEY, CRASH_MD)+ expected_rows, expected_schema = read_sorted(control)++ yield {+ "base": uri,+ "batch": batch,+ "batch_path": str(batch_path),+ "worker": str(worker),+ "expected_rows": expected_rows,+ "expected_schema": expected_schema,+ }+ shutil.rmtree(tmp, ignore_errors=True)+++def fresh_copy(template, tmp_path: Path, name: str) -> str:+ dst = tmp_path / name+ shutil.copytree(template["base"], dst)+ return str(dst)+++def run_and_kill(uri: str, template, mode: str, trigger):+ """Run one write in a subprocess; SIGKILL when `trigger(new_files, new_commits)`+ fires. Returns observed state; caller decides whether the attempt landed."""+ before_files = data_files(uri)+ before_commits = commit_entries(uri)++ proc = subprocess.Popen(+ [sys.executable, template["worker"], mode, uri, template["batch_path"]],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ )+ killed = False+ kill_snapshot = None+ t0 = time.perf_counter()+ try:+ while proc.poll() is None:+ if time.perf_counter() - t0 > WORKER_TIMEOUT_S:+ raise AssertionError("crash worker hung")+ new_files = data_files(uri) - before_files+ new_commits = commit_entries(uri) - before_commits+ if trigger(new_files, new_commits):+ kill_snapshot = {"files": set(new_files), "commits": set(new_commits)}+ proc.send_signal(signal.SIGKILL)+ killed = True+ break+ time.sleep(POLL_S)+ finally:+ if proc.poll() is None and not killed:+ proc.kill()+ out, err = proc.communicate(timeout=WORKER_TIMEOUT_S)++ return {+ "killed": killed,+ "returncode": proc.returncode,+ "stdout": out,+ "stderr": err,+ "kill_snapshot": kill_snapshot,+ "new_files": data_files(uri) - before_files,+ "new_commits": commit_entries(uri) - before_commits,+ }+++def kill_upsert_mid_rewrite(uri: str, template, min_new_files: int):+ """Kill the upsert worker once >= min_new_files rewritten parquet files exist on+ disk but before any commit. Asserts the kill verifiably landed pre-commit."""+ res = run_and_kill(+ uri,+ template,+ "upsert",+ lambda files, commits: len(files) >= min_new_files and not commits,+ )+ if not res["killed"] or res["new_commits"]:+ return None # commit won the race; caller retries on a fresh copy++ # Prove the kill landed in the intended phase.+ assert res["returncode"] == -signal.SIGKILL+ assert "COMMITTED" not in res["stdout"]+ assert len(res["new_files"]) >= min_new_files, f"expected >= {min_new_files} orphaned files, saw {res['new_files']}"+ assert not res["new_commits"], "kill was supposed to land before the commit"+ return res+++# --------------------------------------------------------------------------------------+# 1. Kill between rewrite and commit -> nothing visible+# --------------------------------------------------------------------------------------+++ "min_new_files",+ [1, N_PARTITIONS - 1],+ ids=["early_in_rewrite", "after_most_partitions_rewritten"],+)+def test_kill_before_commit_leaves_table_logically_unchanged(tmp_path, crash_template, min_new_files):+ """New parquet files are on disk (verified) but the commit never happened: the+ table's version, live file set, contents, and schema must all be untouched."""+ for attempt in range(KILL_ATTEMPTS):+ uri = fresh_copy(crash_template, tmp_path, f"kill_{min_new_files}_{attempt}")+ before = table_state(uri)+ before_commits = commit_entries(uri)++ res = kill_upsert_mid_rewrite(uri, crash_template, min_new_files)+ if res is None:+ shutil.rmtree(uri)+ continue++ after = table_state(uri)+ assert after == before, "a pre-commit kill changed the logically-visible table"+ assert commit_entries(uri) == before_commits++ # The orphans really exist and really are invisible.+ live = {Path(u).name for u in after["file_uris"]}+ orphans = {Path(f).name for f in res["new_files"]}+ assert orphans and not (orphans & live)++ # Not corrupted: the standard corruption probe passes.+ assert deltalake.DeltaTable.is_deltatable(uri)+ deltalake.DeltaTable(uri).to_pyarrow_table(columns=["id"])+ shutil.rmtree(uri)+ return+ pytest.fail(f"kill never landed mid-rewrite in {KILL_ATTEMPTS} attempts")+++def test_crash_orphans_survive_default_vacuum_and_need_full_mode(tmp_path, crash_template):+ """The design says orphaned pre-commit files are 'reclaimed by vacuum'. That is+ only true of vacuum(full=True): a never-committed file has no Remove tombstone, and+ delta-rs 1.x vacuum defaults to lite mode (tombstones only) -- which is exactly how+ production's `vacuum_table` calls it (retention_hours=24, enforce off, no full=).+ Crash orphans therefore accumulate until a full vacuum runs. Pinned here so the+ operational requirement is a documented fact."""+ for attempt in range(KILL_ATTEMPTS):+ uri = fresh_copy(crash_template, tmp_path, f"vacuum_{attempt}")+ res = kill_upsert_mid_rewrite(uri, crash_template, 1)+ if res is None:+ shutil.rmtree(uri)+ continue++ orphans = [Path(uri) / f for f in res["new_files"]]+ assert orphans and all(f.exists() for f in orphans)+ # Pretend the crash happened 2 days ago so the 24 h retention cannot excuse+ # vacuum from considering the files.+ old = time.time() - 48 * 3600+ for f in orphans:+ os.utime(f, (old, old))++ dt = deltalake.DeltaTable(uri)+ # Production's exact invocation (lite mode): orphans are NOT reclaimed.+ dt.vacuum(retention_hours=24, enforce_retention_duration=False, dry_run=False)+ assert all(f.exists() for f in orphans), (+ "unexpectedly reclaimed by lite vacuum -- the full-mode requirement no longer holds"+ )++ # Only full mode reclaims them, and doing so does not harm the table.+ dt.vacuum(+ retention_hours=24,+ enforce_retention_duration=False,+ dry_run=False,+ full=True,+ )+ assert not any(f.exists() for f in orphans)+ rows, _ = read_sorted(uri)+ assert len(rows) == N_PARTITIONS * ROWS_PER_PARTITION+ shutil.rmtree(uri)+ return+ pytest.fail(f"kill never landed mid-rewrite in {KILL_ATTEMPTS} attempts")+++# --------------------------------------------------------------------------------------+# 4. Single atomic commit: no partial batch is ever visible; redelivery converges+# --------------------------------------------------------------------------------------+++def test_no_partial_batch_after_kill_and_redelivery_converges(tmp_path, crash_template):+ """Kill after 3 of 4 partitions were fully rewritten on disk. Because deltalite+ commits once per batch, ZERO partitions may be visibly updated. The tag must be+ absent (decision: re-run), and re-running the whole batch must converge to exactly+ the single-application result with one new commit."""+ for attempt in range(KILL_ATTEMPTS):+ uri = fresh_copy(crash_template, tmp_path, f"partial_{attempt}")+ before = table_state(uri)++ res = kill_upsert_mid_rewrite(uri, crash_template, N_PARTITIONS - 1)+ if res is None:+ shutil.rmtree(uri)+ continue++ # >= 3 partitions' worth of rewritten data sits on disk, yet none is visible.+ assert updated_partitions(uri) == [], "partial batch visible after mid-batch kill -- atomicity broken"+ assert table_state(uri) == before++ # Redelivery decision: the tag must NOT be discoverable -> re-run the batch.+ assert not batch_already_committed(uri, CRASH_MD)++ # Re-run the identical batch (the Temporal redelivery), in spite of orphans.+ stats = upsert_path(uri, crash_template["batch"], ["id"], PARTITION_KEY, CRASH_MD)+ assert stats.version == before["version"] + 1 # exactly one commit+ rows, schema = read_sorted(uri)+ assert rows == crash_template["expected_rows"]+ assert schema == crash_template["expected_schema"]+ assert updated_partitions(uri) == CRASH_PARTITIONS+ assert batch_already_committed(uri, CRASH_MD)+ shutil.rmtree(uri)+ return+ pytest.fail(f"kill never landed mid-rewrite in {KILL_ATTEMPTS} attempts")+++def test_merge_path_kill_exposes_partial_batch(tmp_path, crash_template):+ """Contrast: today's per-partition MERGE loop commits N times, so a mid-batch kill+ leaves some partitions updated and others not -- the failure mode deltalite's+ single commit removes. Recovery still works (intermediate commits are untagged, so+ the redelivery decision is re-run, and MERGE re-application converges)."""+ for attempt in range(KILL_ATTEMPTS):+ uri = fresh_copy(crash_template, tmp_path, f"merge_partial_{attempt}")++ res = run_and_kill(+ uri,+ crash_template,+ "merge",+ lambda files, commits: len(commits) >= 1,+ )+ n_commits = len(res["new_commits"])+ if not res["killed"] or not (1 <= n_commits < N_PARTITIONS):+ shutil.rmtree(uri)+ continue # worker finished all partitions before the kill; retry++ assert res["returncode"] == -signal.SIGKILL+ assert "COMMITTED" not in res["stdout"]++ # Partial state IS visible: the first n_commits partitions (merge_path walks+ # them in sorted order) show the new rows, the rest do not.+ assert updated_partitions(uri) == CRASH_PARTITIONS[:n_commits], (+ "expected exactly the committed partitions to be visibly updated"+ )++ # Only the terminal commit carries the tag, so redelivery correctly re-runs.+ assert not batch_already_committed(uri, CRASH_MD)+ merge_path(uri, crash_template["batch"], ["id"], PARTITION_KEY, CRASH_MD)+ rows, schema = read_sorted(uri)+ assert rows == crash_template["expected_rows"]+ assert schema == crash_template["expected_schema"]+ assert batch_already_committed(uri, CRASH_MD)+ shutil.rmtree(uri)+ return+ pytest.fail(f"never caught MERGE between its per-partition commits in {KILL_ATTEMPTS} attempts")+++# --------------------------------------------------------------------------------------+# 2. Redelivery after a successful commit is detected+# --------------------------------------------------------------------------------------+++def simple(ids, part, v):+ n = len(ids)+ return pa.table(+ {+ "id": pa.array(ids, pa.string()),+ "v": pa.array([v] * n if isinstance(v, int) else v, pa.int64()),+ PARTITION_KEY: pa.array(part if isinstance(part, list) else [part] * n, pa.string()),+ }+ )+++def test_redelivery_after_successful_commit_is_detected(tmp_path):+ """The full redelivery decision: tag absent before the batch -> run; present after+ -> skip; a *different* batch of the same run is not confused with it."""+ uri = str(tmp_path / "redelivery")+ create_table(uri, simple(["a", "b"], "2026-07-23", 1), True)+ md0 = {"run_uuid": "run-r", "batch_index": "0"}+ md1 = {"run_uuid": "run-r", "batch_index": "1"}++ assert not batch_already_committed(uri, md0)++ upsert_path(uri, simple(["a", "c"], "2026-07-23", 2), ["id"], PARTITION_KEY, md0)++ assert batch_already_committed(uri, md0), "redelivered batch would NOT be skipped"+ assert not batch_already_committed(uri, md1), "unrelated batch would be skipped"+ assert not batch_already_committed(uri, {"run_uuid": "other-run", "batch_index": "0"})++ # An empty batch's action-less commit must also register for redelivery detection.+ upsert_path(uri, simple([], "2026-07-23", []), ["id"], PARTITION_KEY, md1)+ assert batch_already_committed(uri, md1)+++# --------------------------------------------------------------------------------------+# 3. Re-running a whole batch is idempotent by construction (except NULL PKs)+# --------------------------------------------------------------------------------------++[email protected]("path_name", ["merge", "upsert"])+def test_rerun_of_committed_batch_is_idempotent(tmp_path, path_name):+ """Apply the identical (NULL-free) batch twice; the table must equal a single+ application -- no duplicated rows, same schema, and on the upsert path the second+ run reports pure updates (nothing inserted)."""+ path = merge_path if path_name == "merge" else upsert_path+ parts = ["2026-07-23", "2026-07-24"]+ batch = simple(["a", "b", "x"], [parts[0], parts[0], parts[1]], 2)++ uri_once = str(tmp_path / f"once_{path_name}")+ uri_twice = str(tmp_path / f"twice_{path_name}")+ initial = simple(["a", "b", "c"], parts[0], 1)+ create_table(uri_once, initial, True)+ create_table(uri_twice, initial, True)++ path(uri_once, batch, ["id"], PARTITION_KEY, {"run_uuid": "r", "batch_index": "0"})+ path(uri_twice, batch, ["id"], PARTITION_KEY, {"run_uuid": "r", "batch_index": "0"})+ stats = path(uri_twice, batch, ["id"], PARTITION_KEY, {"run_uuid": "r", "batch_index": "0"})++ rows_once, schema_once = read_sorted(uri_once)+ rows_twice, schema_twice = read_sorted(uri_twice)+ assert rows_twice == rows_once, f"[{path_name}] re-applying the batch changed the table"+ assert schema_twice == schema_once+ assert len(rows_twice) == 4 # a, b updated; c untouched; x inserted -- exactly once++ if path_name == "upsert":+ # Every row of the re-applied batch matched an existing row, so nothing is new.+ assert stats.rows_updated == batch.num_rows+ assert stats.rows_inserted == 0+++def test_upsert_stats_do_not_double_count_updated_rows_as_inserts(tmp_path):+ """A 3-row batch with 2 matches must report rows_updated=2, rows_inserted=1.++ Regression test for a fixed bug: `rewrite_partition` used to set+ `rows_inserted = source.num_rows()` (the whole slice), counting every matched row+ as both an update and an insert. Table content was never affected.+ """+ uri = str(tmp_path / "stats_counts")+ create_table(uri, simple(["a", "b", "c"], "2026-07-23", 1), True)+ batch = simple(["a", "b", "x"], "2026-07-23", 2)++ stats = upsert_path(uri, batch, ["id"], PARTITION_KEY)+ assert stats.rows_updated == 2+ assert stats.rows_inserted == batch.num_rows - stats.rows_updated # 1, not 3+++def test_null_pk_batch_redelivery_is_not_idempotent_on_either_path(tmp_path):+ """The correctness trap: NULL-PK rows never match (SQL NULL != NULL), so they+ INSERT on every application. Re-running a batch containing NULL PKs therefore+ legitimately duplicates those rows -- on BOTH paths, identically. The commit tag is+ the ONLY thing standing between an after-commit redelivery and duplicated data.++ This pins the behavior so the divergence-from-idempotency is a documented fact,+ not a latent surprise."""+ batch = simple([None, None, "a"], "2026-07-23", 2)+ results = {}+ for path_name, path in (("merge", merge_path), ("upsert", upsert_path)):+ uri = str(tmp_path / f"nullpk_{path_name}")+ create_table(uri, simple(["a", "b"], "2026-07-23", 1), True)++ path(uri, batch, ["id"], PARTITION_KEY, {"run_uuid": "r", "batch_index": "0"})+ rows_after_first, _ = read_sorted(uri)+ # First application: 2 NULL rows inserted, 'a' updated.+ assert len(rows_after_first) == 4++ # The redelivery (same batch, same tag -- as if the tag check were skipped).+ path(uri, batch, ["id"], PARTITION_KEY, {"run_uuid": "r", "batch_index": "0"})+ rows_after_second, _ = read_sorted(uri)+ results[path_name] = rows_after_second++ # NOT idempotent: the two NULL rows inserted again.+ assert len(rows_after_second) == 6, (+ f"[{path_name}] expected NULL-PK rows to duplicate on redelivery (got {len(rows_after_second)} rows)"+ )++ # ...and both paths land on the identical (duplicated) state: no divergence.+ assert results["merge"] == results["upsert"]+++def test_null_pk_redelivery_is_safe_when_tag_is_honored(tmp_path):+ """The mitigation for the trap above: the production flow checks the tag BEFORE+ re-applying. After a successful commit, the skip decision protects even NULL-PK+ batches; only a tag-check bypass (or history truncation) can duplicate them."""+ uri = str(tmp_path / "nullpk_guard")+ create_table(uri, simple(["a", "b"], "2026-07-23", 1), True)+ md = {"run_uuid": "r", "batch_index": "0"}+ batch = simple([None, "a"], "2026-07-23", 2)++ if not batch_already_committed(uri, md):+ upsert_path(uri, batch, ["id"], PARTITION_KEY, md)+ rows_first, _ = read_sorted(uri)++ # Redelivery, this time driving the decision the way production does.+ if not batch_already_committed(uri, md): # -> True, so skipped+ upsert_path(uri, batch, ["id"], PARTITION_KEY, md)+ rows_second, _ = read_sorted(uri)++ assert batch_already_committed(uri, md)+ assert rows_second == rows_first, "tag-guarded redelivery must be a no-op"+ assert len(rows_first) == 3 # a updated, one NULL insert, b untouched+++# --------------------------------------------------------------------------------------+# Single-commit-per-batch happy path (the property the crash tests rely on)+# --------------------------------------------------------------------------------------+++def test_upsert_is_one_commit_per_batch_where_merge_is_n(tmp_path):+ parts = ["2026-07-21", "2026-07-22", "2026-07-23"]+ initial = simple(["a", "b", "c"], parts, 1)+ batch = simple(["a", "b", "c", "d"], [*parts, parts[0]], 2)++ uri_m = str(tmp_path / "ncommits_merge")+ uri_u = str(tmp_path / "ncommits_upsert")+ create_table(uri_m, initial, True)+ create_table(uri_u, initial, True)++ v0_m = deltalake.DeltaTable(uri_m).version()+ v0_u = deltalake.DeltaTable(uri_u).version()++ merge_path(uri_m, batch, ["id"], PARTITION_KEY, {"run_uuid": "r", "batch_index": "0"})+ upsert_path(uri_u, batch, ["id"], PARTITION_KEY, {"run_uuid": "r", "batch_index": "0"})++ assert deltalake.DeltaTable(uri_m).version() == v0_m + len(parts) # N commits+ assert deltalake.DeltaTable(uri_u).version() == v0_u + 1 # ONE commitdiff --git a/rust/deltalite/python/tests/test_guards.py b/rust/deltalite/python/tests/test_guards.pynew file mode 100644index 000000000000..6472d9591ef3--- /dev/null+++ b/rust/deltalite/python/tests/test_guards.py@@ -0,0 +1,116 @@+"""Production hardening added on top of the spike: the source-size guard and the+multipart upload path.++The guard turns "RSS grows until the pod OOMs" into a clean typed error at the front+door; multipart replaces single ~100 MB PUTs of output files. Both must leave upsert+semantics byte-identical, so the multipart test is a full differential parity run with+the threshold forced to minimum.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++import pyarrow as pa+import deltalake++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from harness.common import PARTITION_KEY, Scenario, assert_parity, create_table, upsert_path+++def simple(ids, part, v):+ return pa.table(+ {+ "id": pa.array(ids, pa.string()),+ "value": pa.array([v] * len(ids), pa.int64()),+ PARTITION_KEY: pa.array([part] * len(ids), pa.string()),+ }+ )+++def test_source_guard_rejects_oversized_batch_and_leaves_table_untouched(tmp_path):+ import deltalite++ uri = str(tmp_path / "guarded")+ create_table(uri, simple(["a", "b"], "p1", 1), partitioned=True)+ before = deltalake.DeltaTable(uri)+ version_before = before.version()++ with pytest.raises(deltalite.DeltaLiteSourceTooLargeError) as ei:+ upsert_path(uri, simple(["a", "c"], "p1", 2), ["id"], PARTITION_KEY, max_source_bytes=1)+ assert "ceiling" in str(ei.value)++ after = deltalake.DeltaTable(uri)+ assert after.version() == version_before, "a rejected batch must not commit anything"+++def test_source_guard_zero_disables_the_ceiling(tmp_path):+ uri = str(tmp_path / "unguarded")+ create_table(uri, simple(["a"], "p1", 1), partitioned=True)+ stats = upsert_path(uri, simple(["a", "b"], "p1", 2), ["id"], PARTITION_KEY, max_source_bytes=0)+ assert stats.rows_updated == 1+ assert stats.rows_inserted == 1+++def test_source_guard_error_is_a_deltalite_error_subclass():+ import deltalite++ assert issubclass(deltalite.DeltaLiteSourceTooLargeError, deltalite.DeltaLiteError)+++def test_multipart_forced_upsert_has_merge_parity(tmp_path):+ """Force every output file through the multipart path (threshold=1 byte) and assert+ full differential parity against the real delta-rs MERGE. Proves the multipart+ store wrapper changes nothing about logical content or the commit protocol."""+ scenario = Scenario(+ name="multipart_forced",+ initial=pa.concat_tables([simple([f"k{i}" for i in range(50)], p, 1) for p in ("p1", "p2")]),+ batches=[+ pa.concat_tables(+ [+ simple([f"k{i}" for i in range(0, 30)], "p1", 2),+ simple([f"n{i}" for i in range(5)], "p2", 2),+ ]+ )+ ],+ primary_keys=["id"],+ partitioned=True,+ )+ # run_scenario drives the upsert arm through upsert_path(**kwargs).+ uri_m, uri_u = run_scenario_with_multipart(scenario, tmp_path)+ assert_parity(uri_m, uri_u, "multipart_forced")+++def run_scenario_with_multipart(scenario, tmp_path):+ from harness.common import dedupe_keep_last, merge_path++ uri_m = str(tmp_path / f"{scenario.name}_merge")+ uri_u = str(tmp_path / f"{scenario.name}_upsert")+ create_table(uri_m, scenario.initial, scenario.partitioned)+ create_table(uri_u, scenario.initial, scenario.partitioned)+ for i, raw in enumerate(scenario.batches):+ batch = dedupe_keep_last(raw, scenario.primary_keys, scenario.partition_key)+ md = {"run_uuid": "run-mp", "batch_index": str(i)}+ merge_path(uri_m, batch, scenario.primary_keys, scenario.partition_key, md)+ upsert_path(+ uri_u,+ batch,+ scenario.primary_keys,+ scenario.partition_key,+ md,+ multipart_threshold=1,+ multipart_part_size=5 * 1024 * 1024,+ )+ return uri_m, uri_u+++def test_invalid_prune_strategy_raises_typed_error(tmp_path):+ import deltalite++ uri = str(tmp_path / "badstrategy")+ create_table(uri, simple(["a"], "p1", 1), partitioned=True)+ with pytest.raises(deltalite.DeltaLiteError):+ upsert_path(uri, simple(["a"], "p1", 2), ["id"], PARTITION_KEY, prune_strategy="join")diff --git a/rust/deltalite/python/tests/test_interop.py b/rust/deltalite/python/tests/test_interop.pynew file mode 100644index 000000000000..2c4577c373ca--- /dev/null+++ b/rust/deltalite/python/tests/test_interop.py@@ -0,0 +1,137 @@+"""Interop: do external readers see spec-compliant commits after a deltalite upsert?++Covers the Python `deltalake` package (which is what the rest of the pipeline uses) and+DuckDB's native `delta_scan` (a stand-in for the chdb/ClickHouse and Trino/Spark readers+that consume these tables in production).+"""++from __future__ import annotations++import sys+import json+from pathlib import Path++import pytest++import duckdb+import pyarrow as pa+import deltalake++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from harness.common import PARTITION_KEY, create_table, upsert_path # noqa: E402+++def simple(ids, part, v):+ n = len(ids)+ return pa.table(+ {+ "id": pa.array(ids, pa.string()),+ "v": pa.array([v] * n if isinstance(v, int) else v, pa.int64()),+ PARTITION_KEY: pa.array(part if isinstance(part, list) else [part] * n, pa.string()),+ }+ )+++def upserted(tmp_path):+ uri = str(tmp_path / "interop")+ create_table(uri, simple(["a", "b", "c"], "2026-07-23", 1), True)+ stats = upsert_path(+ uri,+ simple(["b", "d", "e"], ["2026-07-23", "2026-07-23", "2026-07-24"], 2),+ ["id"],+ PARTITION_KEY,+ {"run_uuid": "r", "batch_index": "0"},+ )+ return uri, stats+++def test_python_deltalake_agrees_on_version_files_schema(upserted):+ import deltalite++ uri, stats = upserted+ py = deltalake.DeltaTable(uri)+ rs = deltalite.DeltaLiteTable.open(uri)++ assert py.version() == rs.version() == stats.version+ assert sorted(py.file_uris()) == sorted(rs.file_uris())+ assert py.schema().to_arrow() == rs.schema_arrow()+ assert py.metadata().partition_columns == rs.partition_columns()+++def test_add_actions_carry_statistics(upserted):+ """Data skipping in external engines depends on Add-action stats being present."""+ uri, _ = upserted+ log_dir = Path(uri) / "_delta_log"+ latest = sorted(log_dir.glob("*.json"))[-1]++ adds = []+ for line in latest.read_text().splitlines():+ action = json.loads(line)+ if "add" in action:+ adds.append(action["add"])++ assert adds, "commit contained no Add actions"+ for add in adds:+ assert add.get("stats"), f"Add action missing stats: {add['path']}"+ stats = json.loads(add["stats"])+ assert stats["numRecords"] > 0+ assert "minValues" in stats and "maxValues" in stats+ assert "id" in stats["minValues"], "PK column missing from min/max stats"+ # Partition columns live in the path, not in the file stats.+ assert PARTITION_KEY not in stats["minValues"]+++def test_duckdb_delta_scan_reads_the_table(upserted):+ """DuckDB reads the Delta log itself -- proves the commit is spec-compliant."""+ uri, _ = upserted+ con = duckdb.connect()+ con.execute("INSTALL delta; LOAD delta;")++ rows = con.execute(f"SELECT id, v, {PARTITION_KEY} FROM delta_scan('{uri}') ORDER BY id").fetchall()++ assert rows == [+ ("a", 1, "2026-07-23"),+ ("b", 2, "2026-07-23"),+ ("c", 1, "2026-07-23"),+ ("d", 2, "2026-07-23"),+ ("e", 2, "2026-07-24"),+ ]+++def test_duckdb_sees_partition_pruning_metadata(upserted):+ uri, _ = upserted+ con = duckdb.connect()+ con.execute("INSTALL delta; LOAD delta;")+ n = con.execute(f"SELECT count(*) FROM delta_scan('{uri}') WHERE {PARTITION_KEY} = '2026-07-24'").fetchone()[0]+ assert n == 1+++def test_tombstoned_files_are_not_read(upserted):+ """The rewritten file must be tombstoned, not merely superseded."""+ uri, stats = upserted+ assert stats.files_removed >= 1++ log_dir = Path(uri) / "_delta_log"+ latest = sorted(log_dir.glob("*.json"))[-1]+ removes = [json.loads(line)["remove"] for line in latest.read_text().splitlines() if "remove" in json.loads(line)]+ assert removes, "no Remove actions in the commit"+ for r in removes:+ assert r["dataChange"] is True+ assert r.get("deletionTimestamp")++ live = {Path(u).name for u in deltalake.DeltaTable(uri).file_uris()}+ for r in removes:+ assert Path(r["path"]).name not in live+++def test_optimize_and_vacuum_still_work_after_upsert(upserted):+ """Maintenance stays on the Python package; it must accept deltalite's commits."""+ uri, _ = upserted+ dt = deltalake.DeltaTable(uri)+ dt.optimize.compact()+ dt = deltalake.DeltaTable(uri)+ dt.vacuum(retention_hours=0, enforce_retention_duration=False, dry_run=False)++ rows = deltalake.DeltaTable(uri).to_pyarrow_table().sort_by("id")["v"].to_pylist()+ assert rows == [1, 2, 1, 2, 2]diff --git a/rust/deltalite/python/tests/test_operations.py b/rust/deltalite/python/tests/test_operations.pynew file mode 100644index 000000000000..52a7649df286--- /dev/null+++ b/rust/deltalite/python/tests/test_operations.py@@ -0,0 +1,811 @@+"""Mixed-writer operation sequences: everything EXCEPT the upsert stays on the Python+`deltalake` package. These tests interleave the two writers against the same table and+assert correct contents and a valid, readable log at every step.++Covers: create/append/overwrite via Python + upsert via deltalite, optimize.compact,+vacuum, alter.add_columns, history/idempotency metadata interleaving, the+partition-downgrade rule, and refusal of deletion-vector / column-mapping tables.+"""++from __future__ import annotations++import sys+import json+from pathlib import Path++import pytest++import duckdb+import pyarrow as pa+import deltalake++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from harness.common import PARTITION_KEY, create_table, merge_path, read_sorted, upsert_path # noqa: E402+++def simple(ids, part, v, extra="ABSENT"):+ n = len(ids)+ d = {+ "id": pa.array(ids, pa.string()),+ "v": pa.array([v] * n if isinstance(v, int) else v, pa.int64()),+ PARTITION_KEY: pa.array(part if isinstance(part, list) else [part] * n, pa.string()),+ }+ if extra != "ABSENT":+ d["new_col"] = pa.array(extra, pa.string())+ return pa.table(d)+++def content(uri) -> dict[tuple[str | None, str], int]:+ """{(id, partition): v} via the Python package -- also proves the log is readable."""+ tbl = deltalake.DeltaTable(uri).to_pyarrow_table()+ return dict(+ zip(+ zip(tbl["id"].to_pylist(), tbl[PARTITION_KEY].to_pylist()),+ tbl["v"].to_pylist(),+ )+ )+++def duckdb_content(uri) -> dict[tuple[str | None, str], int]:+ con = duckdb.connect()+ con.execute("INSTALL delta; LOAD delta;")+ rows = con.execute(f"SELECT id, {PARTITION_KEY}, v FROM delta_scan('{uri}')").fetchall()+ con.close()+ return {(r[0], r[1]): r[2] for r in rows}+++def assert_valid_log(uri, expected: dict) -> None:+ """Content matches via the Python reader AND the version chain is contiguous."""+ assert content(uri) == expected+ log_dir = Path(uri) / "_delta_log"+ versions = sorted(int(p.stem) for p in log_dir.glob("*.json"))+ assert versions == list(range(versions[0], versions[-1] + 1))+ assert deltalake.DeltaTable(uri).version() == versions[-1]+++# --------------------------------------------------------------------------------------+# 1. Interleaved sequences+# --------------------------------------------------------------------------------------+++def test_interleaved_create_append_upsert_optimize_vacuum(tmp_path):+ """create (py) -> append (py) -> upsert -> append (py) -> upsert -> compact (py)+ -> upsert -> vacuum (py) -> upsert, asserting contents + valid log at every step."""+ uri = str(tmp_path / "lifecycle")+ p = "2026-07-23"++ # create (python) -- empty partitioned table, as the helper's first-sync path does+ deltalake.DeltaTable.create(+ uri,+ deltalake.Schema.from_arrow(simple([], p, [])[:0].schema),+ partition_by=[PARTITION_KEY],+ )+ expected: dict = {}+ assert_valid_log(uri, expected)++ # append (python)+ deltalake.write_deltalake(uri, simple(["a", "b"], p, 1), mode="append")+ expected = {("a", p): 1, ("b", p): 1}+ assert_valid_log(uri, expected)++ # upsert (deltalite) into a table whose only files were written by python+ upsert_path(uri, simple(["b", "c"], p, 2), ["id"], PARTITION_KEY)+ expected.update({("b", p): 2, ("c", p): 2})+ assert_valid_log(uri, expected)++ # append (python) on top of deltalite's files+ deltalake.write_deltalake(uri, simple(["d"], p, 3), mode="append")+ expected[("d", p)] = 3+ assert_valid_log(uri, expected)++ # upsert must replace rows living in BOTH writers' files in one pass+ upsert_path(uri, simple(["a", "d", "e"], p, 4), ["id"], PARTITION_KEY)+ expected.update({("a", p): 4, ("d", p): 4, ("e", p): 4})+ assert_valid_log(uri, expected)++ # a second small file, so compaction has real work to do+ deltalake.write_deltalake(uri, simple(["f0"], p, 3), mode="append")+ expected[("f0", p)] = 3+ assert len(deltalake.DeltaTable(uri).file_uris()) >= 2++ # compact (python)+ metrics = deltalake.DeltaTable(uri).optimize.compact()+ assert metrics["numFilesRemoved"] > 0, "expected real compaction work"+ assert_valid_log(uri, expected)++ # upsert after compact+ upsert_path(uri, simple(["e", "f"], p, 5), ["id"], PARTITION_KEY)+ expected.update({("e", p): 5, ("f", p): 5})+ assert_valid_log(uri, expected)++ # vacuum (python), production settings+ deltalake.DeltaTable(uri).vacuum(retention_hours=0, enforce_retention_duration=False, dry_run=False)+ assert_valid_log(uri, expected)++ # upsert after vacuum+ upsert_path(uri, simple(["a", "g"], p, 6), ["id"], PARTITION_KEY)+ expected.update({("a", p): 6, ("g", p): 6})+ assert_valid_log(uri, expected)++ # an external reader agrees with the final state+ assert duckdb_content(uri) == expected+++def test_full_refresh_overwrite_then_upsert_then_overwrite(tmp_path):+ """The full-refresh path (`mode="overwrite", schema_mode="overwrite"`) must wipe+ deltalite's rows, and upsert must work on the overwritten table -- both ways round."""+ uri = str(tmp_path / "refresh")+ p = "2026-07-23"+ create_table(uri, simple(["a", "b"], p, 1), True)++ upsert_path(uri, simple(["b", "c"], p, 2), ["id"], PARTITION_KEY)+ assert content(uri) == {("a", p): 1, ("b", p): 2, ("c", p): 2}++ # full refresh: overwrite replaces everything, including deltalite-written files+ deltalake.write_deltalake(+ uri,+ simple(["x", "y"], p, 10),+ partition_by=[PARTITION_KEY],+ mode="overwrite",+ schema_mode="overwrite",+ )+ assert content(uri) == {("x", p): 10, ("y", p): 10}++ # upsert on the overwritten table+ upsert_path(uri, simple(["y", "z"], p, 11), ["id"], PARTITION_KEY)+ expected = {("x", p): 10, ("y", p): 11, ("z", p): 11}+ assert_valid_log(uri, expected)++ # and overwrite again on top of that+ deltalake.write_deltalake(+ uri,+ simple(["q"], p, 20),+ partition_by=[PARTITION_KEY],+ mode="overwrite",+ schema_mode="overwrite",+ )+ assert_valid_log(uri, {("q", p): 20})+++def test_overwrite_with_changed_schema_then_upsert(tmp_path):+ """schema_mode="overwrite" may change the column set; upsert must follow the new+ schema, not the one deltalite last wrote."""+ uri = str(tmp_path / "reschema")+ p = "2026-07-23"+ create_table(uri, simple(["a"], p, 1), True)+ upsert_path(uri, simple(["b"], p, 2), ["id"], PARTITION_KEY)++ replaced = pa.table(+ {+ "id": pa.array(["m"], pa.string()),+ "brand_new": pa.array([7], pa.int64()),+ PARTITION_KEY: pa.array([p], pa.string()),+ }+ )+ deltalake.write_deltalake(uri, replaced, partition_by=[PARTITION_KEY], mode="overwrite", schema_mode="overwrite")++ batch = pa.table(+ {+ "id": pa.array(["m", "n"], pa.string()),+ "brand_new": pa.array([8, 9], pa.int64()),+ PARTITION_KEY: pa.array([p, p], pa.string()),+ }+ )+ upsert_path(uri, batch, ["id"], PARTITION_KEY)++ tbl = deltalake.DeltaTable(uri).to_pyarrow_table().sort_by("id")+ assert tbl.schema.names == ["id", "brand_new", PARTITION_KEY]+ assert tbl["brand_new"].to_pylist() == [8, 9]+++def test_upsert_add_columns_upsert_with_and_without_new_column(tmp_path):+ """upsert -> alter.add_columns (py) -> upsert WITH the new column -> upsert WITHOUT+ it. Pins deltalite's behavior on the last step (missing column -> NULL on updated+ rows); the divergence from raw MERGE is documented in the test below."""+ uri = str(tmp_path / "evolve")+ p = "2026-07-23"+ create_table(uri, simple(["a", "b"], p, 1), True)++ upsert_path(uri, simple(["b", "c"], p, 2), ["id"], PARTITION_KEY)++ # additive evolution via the python package (upsert_path's evolve_schema does the+ # same alter.add_columns call the production helper does)+ upsert_path(uri, simple(["c", "d"], p, 3, extra=["C", "D"]), ["id"], PARTITION_KEY)+ tbl = deltalake.DeltaTable(uri).to_pyarrow_table().sort_by("id")+ assert tbl["new_col"].to_pylist() == [None, None, "C", "D"]++ # batch WITHOUT the new column: the updated row's new_col becomes NULL (wholesale+ # row replacement with a null-padded source), inserted rows get NULL too+ upsert_path(uri, simple(["d", "e"], p, 4), ["id"], PARTITION_KEY)+ tbl = deltalake.DeltaTable(uri).to_pyarrow_table().sort_by("id")+ assert tbl["id"].to_pylist() == ["a", "b", "c", "d", "e"]+ assert tbl["v"].to_pylist() == [1, 2, 3, 4, 4]+ assert tbl["new_col"].to_pylist() == [None, None, "C", None, None]+++def test_missing_column_after_evolution_diverges_from_raw_merge(tmp_path):+ """FINDING (executable): for a source batch MISSING a recently-added column,+ `when_matched_update_all` only assigns columns present in the source, so raw MERGE+ PRESERVES the target's existing value -- while deltalite null-pads the source and+ replaces the row wholesale, WIPING it to NULL.++ Production pads batches to the table schema (`evolve_pyarrow_schema`) before+ writing, and against a null-PADDED source the two paths agree (asserted below), so+ the divergence is only reachable if a caller bypasses the padding preamble.+ """+ p = "2026-07-23"++ def run(path, uri, pad_missing):+ create_table(uri, simple(["a"], p, 1), True)+ path(uri, simple(["a"], p, 2, extra=["A"]), ["id"], PARTITION_KEY)+ missing = (+ simple(["a"], p, 3, extra=[None]) # padded, as production does+ if pad_missing+ else simple(["a"], p, 3) # column absent+ )+ path(uri, missing, ["id"], PARTITION_KEY)+ return deltalake.DeltaTable(uri).to_pyarrow_table()["new_col"].to_pylist()++ # column absent: raw MERGE keeps 'A', deltalite wipes to NULL -- the divergence+ assert run(merge_path, str(tmp_path / "m_absent"), False) == ["A"]+ assert run(upsert_path, str(tmp_path / "u_absent"), False) == [None]++ # column present-but-null (the production shape): both wipe to NULL -- parity+ assert run(merge_path, str(tmp_path / "m_padded"), True) == [None]+ assert run(upsert_path, str(tmp_path / "u_padded"), True) == [None]+++def test_merge_then_upsert_then_merge_same_table(tmp_path):+ """The rollout is flag-gated: a table may see MERGE and deltalite commits+ interleaved. Both must read each other's files correctly."""+ uri = str(tmp_path / "mixed_writers")+ p = "2026-07-23"+ create_table(uri, simple(["a", "b"], p, 1), True)++ merge_path(uri, simple(["b", "c"], p, 2), ["id"], PARTITION_KEY)+ upsert_path(uri, simple(["c", "d"], p, 3), ["id"], PARTITION_KEY)+ merge_path(uri, simple(["d", "e"], p, 4), ["id"], PARTITION_KEY)+ upsert_path(uri, simple(["a", "e"], p, 5), ["id"], PARTITION_KEY)++ expected = {("a", p): 5, ("b", p): 2, ("c", p): 3, ("d", p): 4, ("e", p): 5}+ assert_valid_log(uri, expected)+ assert duckdb_content(uri) == expected+++# --------------------------------------------------------------------------------------+# 2. optimize.compact() specifically+# --------------------------------------------------------------------------------------+++def fragmented(tmp_path):+ """A partition holding files from BOTH writers, small enough to be compacted."""+ uri = str(tmp_path / "frag")+ p = "2026-07-23"+ create_table(uri, simple(["a", "b"], p, 1), True)+ upsert_path(uri, simple(["b", "c"], p, 2), ["id"], PARTITION_KEY)+ deltalake.write_deltalake(uri, simple(["d"], p, 3), mode="append")+ deltalake.write_deltalake(uri, simple(["e"], p, 3), mode="append")+ expected = {("a", p): 1, ("b", p): 2, ("c", p): 2, ("d", p): 3, ("e", p): 3}+ assert content(uri) == expected+ assert len(deltalake.DeltaTable(uri).file_uris()) >= 3+ return uri, p, expected+++def test_compact_after_upsert_preserves_contents_exactly(fragmented):+ uri, _, expected = fragmented+ before_rows = read_sorted(uri)++ metrics = deltalake.DeltaTable(uri).optimize.compact()+ assert metrics["numFilesRemoved"] >= 3+ assert metrics["numFilesAdded"] >= 1++ assert read_sorted(uri) == before_rows+ assert_valid_log(uri, expected)+++def test_compacted_files_carry_statistics(fragmented):+ """External readers depend on Add-action stats; the files compaction writes when it+ rewrites deltalite's output must still carry them, PK column included."""+ uri, _, _ = fragmented+ deltalake.DeltaTable(uri).optimize.compact()++ log_dir = Path(uri) / "_delta_log"+ latest = sorted(log_dir.glob("*.json"))[-1]+ adds = [json.loads(line)["add"] for line in latest.read_text().splitlines() if "add" in json.loads(line)]+ assert adds, "compaction commit contained no Add actions"+ for add in adds:+ assert add.get("stats"), f"post-compact Add missing stats: {add['path']}"+ stats = json.loads(add["stats"])+ assert stats["numRecords"] > 0+ assert "id" in stats["minValues"] and "id" in stats["maxValues"]+ assert PARTITION_KEY not in stats["minValues"]+++def test_upsert_after_compact(fragmented):+ """Compaction rewrote files and tombstoned the originals; the next upsert must plan+ against the compacted file set, and its stats must reflect real work."""+ uri, p, expected = fragmented+ deltalake.DeltaTable(uri).optimize.compact()++ stats = upsert_path(uri, simple(["a", "z"], p, 9), ["id"], PARTITION_KEY)+ assert stats.rows_updated == 1 # 'a' lived in the compacted file+ assert stats.files_removed >= 1++ expected.update({("a", p): 9, ("z", p): 9})+ assert_valid_log(uri, expected)+++def test_compact_between_every_upsert(tmp_path):+ """Alternate upsert/compact repeatedly -- neither writer may corrupt the other."""+ uri = str(tmp_path / "alternate")+ p = "2026-07-23"+ create_table(uri, simple(["a"], p, 0), True)+ expected = {("a", p): 0}++ for i in range(1, 4):+ upsert_path(uri, simple(["a", f"k{i}"], p, i), ["id"], PARTITION_KEY)+ expected.update({("a", p): i, (f"k{i}", p): i})+ deltalake.DeltaTable(uri).optimize.compact()+ assert_valid_log(uri, expected)+++# --------------------------------------------------------------------------------------+# 3. vacuum+# --------------------------------------------------------------------------------------+++def test_vacuum_reclaims_deltalite_tombstones_and_keeps_live_files(tmp_path):+ uri = str(tmp_path / "vac")+ p = "2026-07-23"+ create_table(uri, simple(["a", "b"], p, 1), True)++ # this upsert tombstones the original file and writes a fresh one+ stats = upsert_path(uri, simple(["b", "c"], p, 2), ["id"], PARTITION_KEY)+ assert stats.files_removed >= 1++ on_disk = {f.name for f in Path(uri).rglob("*.parquet")}+ live = {Path(u).name for u in deltalake.DeltaTable(uri).file_uris()}+ dead = on_disk - live+ assert dead, "expected at least one tombstoned physical file before vacuum"++ deltalake.DeltaTable(uri).vacuum(retention_hours=0, enforce_retention_duration=False, dry_run=False)++ after = {f.name for f in Path(uri).rglob("*.parquet")}+ assert dead.isdisjoint(after), "vacuum failed to reclaim deltalite's tombstones"+ assert live <= after, "vacuum deleted files deltalite just wrote"++ expected = {("a", p): 1, ("b", p): 2, ("c", p): 2}+ assert_valid_log(uri, expected)+++def test_upsert_immediately_after_vacuum(tmp_path):+ uri = str(tmp_path / "vac_then_upsert")+ p = "2026-07-23"+ create_table(uri, simple(["a", "b"], p, 1), True)+ upsert_path(uri, simple(["b"], p, 2), ["id"], PARTITION_KEY)+ deltalake.DeltaTable(uri).vacuum(retention_hours=0, enforce_retention_duration=False, dry_run=False)++ upsert_path(uri, simple(["a", "c"], p, 3), ["id"], PARTITION_KEY)+ assert_valid_log(uri, {("a", p): 3, ("b", p): 2, ("c", p): 3})+++def test_vacuum_after_compact_after_upsert(tmp_path):+ """The production maintenance order: compact then vacuum, over deltalite commits."""+ uri = str(tmp_path / "maintenance")+ p = "2026-07-23"+ create_table(uri, simple(["a", "b"], p, 1), True)+ upsert_path(uri, simple(["b", "c"], p, 2), ["id"], PARTITION_KEY)+ deltalake.write_deltalake(uri, simple(["d"], p, 3), mode="append")++ dt = deltalake.DeltaTable(uri)+ dt.optimize.compact()+ deltalake.DeltaTable(uri).vacuum(retention_hours=0, enforce_retention_duration=False, dry_run=False)++ live = [Path(u) for u in deltalake.DeltaTable(uri).file_uris()]+ on_disk = list(Path(uri).rglob("*.parquet"))+ assert sorted(f.name for f in on_disk) == sorted(f.name for f in live), (+ "after compact+vacuum only the live file set should remain on disk"+ )+ expected = {("a", p): 1, ("b", p): 2, ("c", p): 2, ("d", p): 3}+ assert_valid_log(uri, expected)+ assert duckdb_content(uri) == expected+++# --------------------------------------------------------------------------------------+# 5. history() / idempotency metadata interleaving+# --------------------------------------------------------------------------------------+++def _has_commit_with_metadata(history_entries, md: dict) -> bool:+ """The production matcher: flat 1.x layout or nested userMetadata both accepted."""++ def matches(commit):+ flat = all(commit.get(k) == v for k, v in md.items())+ nested = commit.get("userMetadata")+ return flat or (isinstance(nested, dict) and all(nested.get(k) == v for k, v in md.items()))++ return any(matches(c) for c in history_entries)+++def test_history_interleaved_writers_tags_all_discoverable(tmp_path):+ """Tagged commits from python append, MERGE, and deltalite must all be discoverable+ through `history()` on either handle after interleaving."""+ import deltalite++ uri = str(tmp_path / "hist")+ p = "2026-07-23"+ create_table(uri, simple(["a"], p, 1), True)++ deltalake.write_deltalake(+ uri,+ simple(["b"], p, 1),+ mode="append",+ commit_properties=deltalake.CommitProperties(custom_metadata={"run_uuid": "run-append", "batch_index": "0"}),+ )+ merge_path(+ uri,+ simple(["a"], p, 2),+ ["id"],+ PARTITION_KEY,+ {"run_uuid": "run-merge", "batch_index": "1"},+ )+ upsert_path(+ uri,+ simple(["b"], p, 3),+ ["id"],+ PARTITION_KEY,+ {"run_uuid": "run-lite", "batch_index": "2"},+ )+ merge_path(+ uri,+ simple(["c"], p, 4),+ ["id"],+ PARTITION_KEY,+ {"run_uuid": "run-merge", "batch_index": "3"},+ )+ upsert_path(+ uri,+ simple(["d"], p, 5),+ ["id"],+ PARTITION_KEY,+ {"run_uuid": "run-lite", "batch_index": "4"},+ )++ history = deltalake.DeltaTable(uri).history(20)+ for md in [+ {"run_uuid": "run-append", "batch_index": "0"},+ {"run_uuid": "run-merge", "batch_index": "1"},+ {"run_uuid": "run-lite", "batch_index": "2"},+ {"run_uuid": "run-merge", "batch_index": "3"},+ {"run_uuid": "run-lite", "batch_index": "4"},+ ]:+ assert _has_commit_with_metadata(history, md), f"tag not found: {md}"+ # a batch that never ran must NOT be found+ assert not _has_commit_with_metadata(history, {"run_uuid": "run-lite", "batch_index": "99"})++ # deltalite's own history() sees the python-written tags too+ lite_hist = deltalite.DeltaLiteTable.open(uri).history(20)+ infos = [h["info"] for h in lite_hist]+ assert any('"run-append"' in str(i.get("run_uuid")) for i in infos)+ assert any('"run-merge"' in str(i.get("run_uuid")) for i in infos)+++def test_history_survives_compact_and_vacuum(tmp_path):+ """Maintenance commits interleave with tagged writes; earlier tags must remain+ discoverable within the helper's lookback window."""+ uri = str(tmp_path / "hist_maint")+ p = "2026-07-23"+ create_table(uri, simple(["a", "b"], p, 1), True)+ upsert_path(+ uri,+ simple(["b"], p, 2),+ ["id"],+ PARTITION_KEY,+ {"run_uuid": "run-x", "batch_index": "0"},+ )+ # a second file so compact does real work and actually commits+ deltalake.write_deltalake(uri, simple(["x"], p, 9), mode="append")+ deltalake.DeltaTable(uri).optimize.compact()+ deltalake.DeltaTable(uri).vacuum(retention_hours=0, enforce_retention_duration=False, dry_run=False)+ upsert_path(+ uri,+ simple(["c"], p, 3),+ ["id"],+ PARTITION_KEY,+ {"run_uuid": "run-x", "batch_index": "1"},+ )++ history = deltalake.DeltaTable(uri).history(20)+ assert _has_commit_with_metadata(history, {"run_uuid": "run-x", "batch_index": "0"})+ assert _has_commit_with_metadata(history, {"run_uuid": "run-x", "batch_index": "1"})+ ops = [c.get("operation") for c in history]+ assert "OPTIMIZE" in ops and "VACUUM END" in ops+++# --------------------------------------------------------------------------------------+# 6. Partition downgrade + unsupported-table refusal+# --------------------------------------------------------------------------------------+++def test_unpartitioned_table_downgraded_even_with_partition_hint(tmp_path):+ """The table's own metadata, not the caller's hint, decides partitioning: an+ unpartitioned table upserted WITH partition_key must behave exactly like the+ unpartitioned MERGE (identity = PKs only, whole-table handling)."""+ uri_m = str(tmp_path / "down_m")+ uri_u = str(tmp_path / "down_u")+ p1, p2 = "2026-07-23", "2026-07-24"+ initial = simple(["a", "b"], p1, 1)+ create_table(uri_m, initial, False) # NOT partitioned+ create_table(uri_u, initial, False)++ # same PK arriving under a DIFFERENT partition value: unpartitioned identity is PK+ # only, so this must UPDATE 'a' (a partitioned table would insert a second row)+ batch = simple(["a", "c"], p2, 2)+ merge_path(uri_m, batch, ["id"], None) # production downgrades to no partition key+ stats = upsert_path(uri_u, batch, ["id"], PARTITION_KEY) # hint passed anyway++ assert stats.partitions_touched == 1 # one whole-table group, not per-value groups+ assert read_sorted(uri_m) == read_sorted(uri_u)+ assert content(uri_u) == {("a", p2): 2, ("b", p1): 1, ("c", p2): 2}+++def test_table_partitioned_by_other_column_with_hint_is_refused(tmp_path):+ """A table partitioned by something other than the hinted key must be refused+ cleanly, not silently treated as either partitioning."""+ import deltalite++ uri = str(tmp_path / "otherpart")+ tb = pa.table(+ {+ "id": pa.array(["a", "b"], pa.string()),+ "v": pa.array([1, 1], pa.int64()),+ "region": pa.array(["eu", "us"], pa.string()),+ }+ )+ deltalake.write_deltalake(uri, tb, partition_by=["region"], mode="overwrite")++ t = deltalite.DeltaLiteTable.open(uri)+ with pytest.raises(deltalite.DeltaLiteError, match="partitioned by 'region'"):+ t.upsert(+ pa.table(+ {+ "id": pa.array(["a"], pa.string()),+ "v": pa.array([2], pa.int64()),+ "region": pa.array(["eu"], pa.string()),+ }+ ),+ ["id"],+ PARTITION_KEY,+ )+ # and the failed call must not have committed anything+ assert deltalake.DeltaTable(uri).version() == 0+++def test_deletion_vector_table_is_refused_cleanly(tmp_path):+ """A table created (via the python package) with deletion vectors enabled must be+ refused with the typed error, before any commit."""+ import deltalite++ uri = str(tmp_path / "dv")+ schema = simple([], "p", [])[:0].schema+ deltalake.DeltaTable.create(+ uri,+ deltalake.Schema.from_arrow(schema),+ partition_by=[PARTITION_KEY],+ configuration={"delta.enableDeletionVectors": "true"},+ )+ proto = deltalake.DeltaTable(uri).protocol()+ assert "deletionVectors" in (proto.writer_features or [])++ t = deltalite.DeltaLiteTable.open(uri)+ with pytest.raises(deltalite.DeltaLiteUnsupportedTableError, match="deletionVectors"):+ t.upsert(simple(["a"], "p", 1), ["id"], PARTITION_KEY)+ assert deltalake.DeltaTable(uri).version() == 0+++ "config_key",+ ["delta.appendOnly", "delta.enableChangeDataFeed"],+)+def test_unsupported_table_property_is_refused_cleanly(tmp_path, config_key):+ import deltalite++ uri = str(tmp_path / "prop")+ schema = simple([], "p", [])[:0].schema+ deltalake.DeltaTable.create(+ uri,+ deltalake.Schema.from_arrow(schema),+ partition_by=[PARTITION_KEY],+ configuration={config_key: "true"},+ )++ t = deltalite.DeltaLiteTable.open(uri)+ feature = config_key.removeprefix("delta.")+ with pytest.raises(deltalite.DeltaLiteUnsupportedTableError, match=feature):+ t.upsert(simple(["a"], "p", 1), ["id"], PARTITION_KEY)+ assert deltalake.DeltaTable(uri).version() == 0+++def test_legacy_column_mapping_table_is_refused(tmp_path):+ """A LEGACY-protocol column-mapping table (minReaderVersion=2/minWriterVersion=5,+ no feature lists) -- the python package cannot create one, but they exist in the+ wild, so the log is crafted by hand.++ FINDING: `ensure_supported_table` (src/upsert.rs) does NOT catch this shape -- its+ feature-list check only fires for protocol v3/v7 feature tables, and its+ configuration check only looks at delta.enableDeletionVectors, not+ delta.columnMapping.mode. The refusal below actually comes from+ `RecordBatchWriter::for_table` ("column mapping writes are not supported"), so it+ is safe today but surfaces as a generic DeltaLiteError instead of+ DeltaLiteUnsupportedTableError. This test pins that the table is refused at all;+ if it ever starts succeeding, that is silent corruption.+ """+ import deltalite++ uri = str(tmp_path / "cm_legacy")+ log = Path(uri) / "_delta_log"+ log.mkdir(parents=True)+ schema_str = json.dumps(+ {+ "type": "struct",+ "fields": [+ {+ "name": "id",+ "type": "string",+ "nullable": True,+ "metadata": {+ "delta.columnMapping.id": 1,+ "delta.columnMapping.physicalName": "col-1",+ },+ },+ {+ "name": "v",+ "type": "long",+ "nullable": True,+ "metadata": {+ "delta.columnMapping.id": 2,+ "delta.columnMapping.physicalName": "col-2",+ },+ },+ ],+ }+ )+ with open(log / "00000000000000000000.json", "w") as f:+ f.write(json.dumps({"protocol": {"minReaderVersion": 2, "minWriterVersion": 5}}) + "\n")+ f.write(+ json.dumps(+ {+ "metaData": {+ "id": "11111111-1111-1111-1111-111111111111",+ "format": {"provider": "parquet", "options": {}},+ "schemaString": schema_str,+ "partitionColumns": [],+ "configuration": {+ "delta.columnMapping.mode": "name",+ "delta.columnMapping.maxColumnId": "2",+ },+ "createdTime": 1700000000000,+ }+ }+ )+ + "\n"+ )++ # the python package opens it fine+ assert deltalake.DeltaTable(uri).metadata().configuration["delta.columnMapping.mode"] == "name"++ t = deltalite.DeltaLiteTable.open(uri)+ with pytest.raises(deltalite.DeltaLiteError):+ t.upsert(+ pa.table({"id": pa.array(["a"]), "v": pa.array([1], pa.int64())}),+ ["id"],+ None,+ )+ assert deltalake.DeltaTable(uri).version() == 0+++def test_is_deltatable_agrees_after_mixed_writers(tmp_path):+ import deltalite++ uri = str(tmp_path / "exists")+ assert deltalake.DeltaTable.is_deltatable(uri) is False+ assert deltalite.DeltaLiteTable.is_deltatable(uri) is False++ p = "2026-07-23"+ create_table(uri, simple(["a"], p, 1), True)+ upsert_path(uri, simple(["b"], p, 2), ["id"], PARTITION_KEY)++ assert deltalake.DeltaTable.is_deltatable(uri) is True+ assert deltalite.DeltaLiteTable.is_deltatable(uri) is True+ assert sorted(deltalake.DeltaTable(uri).file_uris()) == sorted(deltalite.DeltaLiteTable.open(uri).file_uris())+++# --------------------------------------------------------------------------------------+# `delta.targetFileSize` must be honoured, as it is by every other delta-rs operation+# --------------------------------------------------------------------------------------+++def _tfs_table(uri, rows, target_file_size=None, payload=2000, update_rows=None):+ """Build a table, and return a batch that updates only part of it.++ The updated fraction matters: rows that are REPLACED never reach the writer, so a+ batch matching everything produces no survivors and the periodic flush never runs.+ """+ import sys as _sys+ from pathlib import Path as _Path++ _sys.path.insert(0, str(_Path(__file__).resolve().parents[1]))+ from bench import gen++ batch = gen.make_batch(0, rows, "2026-07-23", payload)+ cfg = {"delta.targetFileSize": str(target_file_size)} if target_file_size else None+ deltalake.write_deltalake(uri, batch, partition_by=[PARTITION_KEY], mode="overwrite", configuration=cfg)+ return gen.make_batch(0, update_rows or (rows // 10), "2026-07-23", payload, version=2)+++def _added_file_sizes(uri, version):+ log = Path(uri) / "_delta_log" / f"{version:020d}.json"+ return [json.loads(line)["add"]["size"] for line in log.read_text().splitlines() if "add" in json.loads(line)]+++def test_upsert_honours_delta_target_file_size(tmp_path):+ """A table configured with a small target must get small files from upsert too.++ Every other delta-rs operation reads `delta.targetFileSize`; upsert hardcoding its+ own default would make it the odd one out on a table that sets the property.+ """+ import deltalite++ uri = str(tmp_path / "tfs_small")+ batch = _tfs_table(uri, 40_000, target_file_size=4 * 1024 * 1024) # 4 MiB+ stats = deltalite.DeltaLiteTable.open(uri).upsert(batch, ["id"], PARTITION_KEY, prune_strategy="none")++ sizes = _added_file_sizes(uri, stats.version)+ assert stats.files_added > 1, f"a 4 MiB target should split the survivors into several files, got {stats}"+ assert max(sizes) < 32 * 1024 * 1024, f"file far larger than the 4 MiB target: {sizes}"+++def test_upsert_uses_the_delta_rs_default_when_unset(tmp_path):+ """No property set -> one ~85 MB partition fits in delta-rs's 100 MiB default."""+ import deltalite++ uri = str(tmp_path / "tfs_default")+ batch = _tfs_table(uri, 40_000)+ stats = deltalite.DeltaLiteTable.open(uri).upsert(batch, ["id"], PARTITION_KEY, prune_strategy="none")+ assert stats.files_added == 1, "should not split below the 100 MiB default"+++def test_explicit_argument_overrides_the_table_property(tmp_path):+ import deltalite++ uri = str(tmp_path / "tfs_override")+ batch = _tfs_table(uri, 40_000, target_file_size=4 * 1024 * 1024)+ stats = deltalite.DeltaLiteTable.open(uri).upsert(+ batch,+ ["id"],+ PARTITION_KEY,+ target_file_size=100 * 1024 * 1024,+ prune_strategy="none",+ )+ assert stats.files_added == 1, "explicit argument must win over the table property"+++def test_large_source_is_also_split_by_the_target(tmp_path):+ """The source write must respect the threshold too, not just the survivor stream.++ The periodic flush lives in the loop that consumes *survivors*, so a batch that+ matches every target row never passes through it. Without a check on the source+ path, such a batch produced one oversized file and an unbounded write buffer.+ """+ import deltalite++ uri = str(tmp_path / "tfs_source")+ # Every row matches, so there are zero survivors and only the source is written.+ batch = _tfs_table(uri, 40_000, target_file_size=4 * 1024 * 1024, update_rows=40_000)+ stats = deltalite.DeltaLiteTable.open(uri).upsert(batch, ["id"], PARTITION_KEY, prune_strategy="none")++ assert stats.rows_copied == 0, "test intends a full-match batch (no survivors)"+ sizes = _added_file_sizes(uri, stats.version)+ assert stats.files_added > 1, f"source write ignored the 4 MiB target: {stats}"+ assert max(sizes) < 32 * 1024 * 1024, f"file far larger than the target: {sizes}"diff --git a/rust/deltalite/python/tests/test_parity.py b/rust/deltalite/python/tests/test_parity.pynew file mode 100644index 000000000000..88a5ed318127--- /dev/null+++ b/rust/deltalite/python/tests/test_parity.py@@ -0,0 +1,543 @@+"""Differential parity: delta-rs SQL MERGE vs deltalite streaming partition upsert.++Every scenario applies the *same* batch sequence to two fresh tables, one through each+path, and asserts the resulting logical content is identical. A single mismatch here is a+NO-GO signal.+"""++from __future__ import annotations++import io+import sys+import decimal+from pathlib import Path++import pytest++import pyarrow as pa+import deltalake+import pyarrow.ipc as ipc++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from harness.common import ( # noqa: E402+ PARTITION_KEY,+ Scenario,+ assert_parity,+ create_table,+ dedupe_keep_last,+ gen_wide,+ merge_path,+ read_sorted,+ run_scenario,+ upsert_path,+ uuid_ids,+)++# --------------------------------------------------------------------------------------+# Small helpers for building scenario data+# --------------------------------------------------------------------------------------+++def simple(ids, part, v, tenant=None):+ """id (string PK) + v (int) + partition key."""+ n = len(ids)+ return pa.table(+ {+ "id": pa.array(ids, pa.string()),+ "tenant": pa.array(tenant if tenant is not None else [1] * n, pa.int64()),+ "v": pa.array([v] * n if isinstance(v, int) else v, pa.int64()),+ PARTITION_KEY: pa.array(part if isinstance(part, list) else [part] * n, pa.string()),+ }+ )+++# --------------------------------------------------------------------------------------+# Scenarios+# --------------------------------------------------------------------------------------+++def sc_partitioned_basic():+ return Scenario(+ name="partitioned_basic",+ initial=simple(["a", "b", "c", "d"], "2026-07-23", 1),+ batches=[+ simple(["b", "c", "e"], "2026-07-23", 2), # 2 updates, 1 insert+ simple(["a", "f"], "2026-07-23", 3),+ ],+ primary_keys=["id"],+ )+++def sc_unpartitioned_basic():+ return Scenario(+ name="unpartitioned_basic",+ initial=simple(["a", "b", "c", "d"], "2026-07-23", 1),+ batches=[+ simple(["b", "c", "e"], "2026-07-23", 2),+ simple(["a", "f"], "2026-07-23", 3),+ ],+ primary_keys=["id"],+ partitioned=False,+ )+++def sc_composite_pk():+ return Scenario(+ name="composite_pk",+ initial=simple(["a", "a", "b"], "2026-07-23", 1, tenant=[1, 2, 1]),+ batches=[+ # (a,2) updates; (a,3) inserts; (b,1) updates+ simple(["a", "a", "b"], "2026-07-23", 5, tenant=[2, 3, 1]),+ ],+ primary_keys=["id", "tenant"],+ )+++def sc_composite_pk_unpartitioned():+ s = sc_composite_pk()+ s.name = "composite_pk_unpartitioned"+ s.partitioned = False+ return s+++def sc_null_pk_single():+ """NULL PKs must always insert and never match -- SQL NULL != NULL."""+ return Scenario(+ name="null_pk_single",+ initial=simple(["a", None, "c"], "2026-07-23", 1),+ batches=[+ simple([None, "a"], "2026-07-23", 2), # NULL must insert, not update+ simple([None], "2026-07-23", 3), # another distinct NULL row+ ],+ primary_keys=["id"],+ )+++def sc_null_pk_composite():+ """NULL in *any* PK component makes the whole tuple unmatchable."""+ return Scenario(+ name="null_pk_composite",+ initial=pa.table(+ {+ "id": pa.array(["a", "b", None], pa.string()),+ "tenant": pa.array([1, None, 3], pa.int64()),+ "v": pa.array([1, 1, 1], pa.int64()),+ PARTITION_KEY: pa.array(["2026-07-23"] * 3, pa.string()),+ }+ ),+ batches=[+ pa.table(+ {+ "id": pa.array(["a", "b", None], pa.string()),+ "tenant": pa.array([1, None, 3], pa.int64()),+ "v": pa.array([9, 9, 9], pa.int64()),+ PARTITION_KEY: pa.array(["2026-07-23"] * 3, pa.string()),+ }+ )+ ],+ primary_keys=["id", "tenant"],+ )+++def sc_null_pk_unpartitioned():+ s = sc_null_pk_single()+ s.name = "null_pk_unpartitioned"+ s.partitioned = False+ return s+++def sc_intra_batch_duplicates():+ return Scenario(+ name="intra_batch_duplicates",+ initial=simple(["a", "b"], "2026-07-23", 1),+ batches=[+ # 'a' appears three times: keep-last must win (v=30)+ simple(["a", "a", "a", "c"], "2026-07-23", [10, 20, 30, 40]),+ ],+ primary_keys=["id"],+ )+++def sc_pk_changes_partition():+ """A PK that moves partition: the old row is deliberately left behind."""+ return Scenario(+ name="pk_changes_partition",+ initial=simple(["a", "b"], "2026-07-23", 1),+ batches=[simple(["a"], "2026-07-24", 2)],+ primary_keys=["id"],+ )+++def sc_new_partition():+ return Scenario(+ name="new_partition",+ initial=simple(["a", "b"], "2026-07-23", 1),+ batches=[+ simple(["x", "y"], "2026-07-25", 2),+ simple(["a", "z"], ["2026-07-23", "2026-07-26"], 3),+ ],+ primary_keys=["id"],+ )+++def sc_empty_batch():+ return Scenario(+ name="empty_batch",+ initial=simple(["a", "b"], "2026-07-23", 1),+ batches=[+ simple([], "2026-07-23", []),+ simple(["a"], "2026-07-23", 5),+ ],+ primary_keys=["id"],+ )+++# Partition values that are hostile but that MERGE can still express. The+# single-quote case cannot be expressed by the current code at all and is covered+# separately in `test_single_quote_partition_value_*` below.+HOSTILE_QUOTE_FREE = ["2026-07-23", 'quote"dq', "üñîçødé", "sp ace", "back\\slash", "a,b"]+HOSTILE_WITH_QUOTE = "o'brien"+++def sc_hostile_partition_values():+ """Unicode / quote-adjacent partition values that MERGE can still express."""+ vals = HOSTILE_QUOTE_FREE+ return Scenario(+ name="hostile_partition_values",+ initial=simple([f"i{i}" for i in range(len(vals))], vals, 1),+ batches=[simple([f"i{i}" for i in range(len(vals))], vals, 2)],+ primary_keys=["id"],+ )+++def sc_all_rows_replaced():+ return Scenario(+ name="all_rows_replaced",+ initial=simple(["a", "b", "c"], "2026-07-23", 1),+ batches=[simple(["a", "b", "c"], "2026-07-23", 2)],+ primary_keys=["id"],+ )+++def sc_many_partitions():+ parts = [f"2026-07-{d:02d}" for d in range(1, 13)]+ ids = [f"k{i}" for i in range(len(parts))]+ return Scenario(+ name="many_partitions",+ initial=simple(ids, parts, 1),+ batches=[simple(ids, parts, 2), simple(ids[:5], parts[:5], 3)],+ primary_keys=["id"],+ )+++def sc_decimal_wide():+ ids = uuid_ids(40)+ return Scenario(+ name="decimal_wide",+ initial=gen_wide(ids, "2026-07-23", seed=1, payload_size=600, version=1),+ batches=[+ gen_wide(ids[10:30], "2026-07-23", seed=2, payload_size=600, version=2),+ gen_wide(uuid_ids(10, offset=100), "2026-07-24", seed=3, payload_size=600, version=3),+ ],+ primary_keys=["id"],+ )+++SCENARIOS = [+ sc_partitioned_basic,+ sc_unpartitioned_basic,+ sc_composite_pk,+ sc_composite_pk_unpartitioned,+ sc_null_pk_single,+ sc_null_pk_composite,+ sc_null_pk_unpartitioned,+ sc_intra_batch_duplicates,+ sc_pk_changes_partition,+ sc_new_partition,+ sc_empty_batch,+ sc_hostile_partition_values,+ sc_all_rows_replaced,+ sc_many_partitions,+ sc_decimal_wide,+]++[email protected]("builder", SCENARIOS, ids=[f.__name__[3:] for f in SCENARIOS])+def test_parity(builder, tmp_path):+ scenario = builder()+ uri_m, uri_u = run_scenario(scenario, tmp_path)+ assert_parity(uri_m, uri_u, scenario.name)+++# --------------------------------------------------------------------------------------+# Cases that need bespoke driving rather than the generic scenario runner+# --------------------------------------------------------------------------------------+++def test_schema_evolution_midsequence(tmp_path):+ """An additive column appears mid-sequence; old files must read up as NULL."""+ uri_m = str(tmp_path / "evo_merge")+ uri_u = str(tmp_path / "evo_upsert")+ initial = simple(["a", "b", "c"], "2026-07-23", 1)+ create_table(uri_m, initial, True)+ create_table(uri_u, initial, True)++ b1 = simple(["b"], "2026-07-23", 2)+ evolved = pa.table(+ {+ "id": pa.array(["c", "d"], pa.string()),+ "tenant": pa.array([1, 1], pa.int64()),+ "v": pa.array([7, 8], pa.int64()),+ "new_col": pa.array(["x", "y"], pa.string()),+ PARTITION_KEY: pa.array(["2026-07-23"] * 2, pa.string()),+ }+ )++ for uri, path in ((uri_m, merge_path), (uri_u, upsert_path)):+ path(uri, b1, ["id"], PARTITION_KEY, {"run_uuid": "r", "batch_index": "0"})+ path(uri, evolved, ["id"], PARTITION_KEY, {"run_uuid": "r", "batch_index": "1"})++ assert_parity(uri_m, uri_u, "schema_evolution")+ rows, _ = read_sorted(uri_u)+ assert len(rows) == 4+++def test_decimal_misaligned_buffer(tmp_path):+ """delta-rs#3884: a Decimal128 buffer that is 8- but not 16-byte aligned.++ An Arrow IPC round-trip reliably produces one. The crate must realign on ingest+ rather than aborting.+ """+ uri_m = str(tmp_path / "dec_merge")+ uri_u = str(tmp_path / "dec_upsert")++ def mk(ids, vals):+ return pa.table(+ {+ "id": pa.array(ids, pa.string()),+ "amount": pa.array([decimal.Decimal(v) for v in vals], pa.decimal128(38, 10)),+ PARTITION_KEY: pa.array(["2026-07-23"] * len(ids), pa.string()),+ }+ )++ initial = mk(["a", "b", "c"], ["1.5", "2.5", "3.5"])+ create_table(uri_m, initial, True)+ create_table(uri_u, initial, True)++ src = mk(["b", "d"], ["99.5", "7.25"])+ sink = io.BytesIO()+ w = ipc.new_stream(sink, src.schema)+ w.write_table(src)+ w.close()+ misaligned = ipc.open_stream(io.BytesIO(sink.getvalue())).read_all()++ addr = misaligned.column("amount").chunk(0).buffers()[1].address+ assert addr % 16 == 8, "expected an 8-but-not-16 byte aligned decimal buffer"++ merge_path(uri_m, misaligned, ["id"], PARTITION_KEY, None)+ upsert_path(uri_u, misaligned, ["id"], PARTITION_KEY, None)+ assert_parity(uri_m, uri_u, "decimal_misaligned")+++def test_batch_spans_multiple_row_groups(tmp_path):+ """Existing files with several row groups must stream correctly."""+ uri_m = str(tmp_path / "rg_merge")+ uri_u = str(tmp_path / "rg_upsert")++ n = 20_000+ ids = uuid_ids(n)+ initial = simple(ids, "2026-07-23", 1)+ props = deltalake.WriterProperties(max_row_group_size=1000) # ~20 row groups+ for uri in (uri_m, uri_u):+ deltalake.write_deltalake(+ uri,+ initial,+ partition_by=[PARTITION_KEY],+ mode="overwrite",+ writer_properties=props,+ )++ # Update half the rows, insert 5k new ones.+ batch = simple(ids[::2] + uuid_ids(5000, offset=n), "2026-07-23", 2)+ merge_path(uri_m, batch, ["id"], PARTITION_KEY, None)+ stats = upsert_path(uri_u, batch, ["id"], PARTITION_KEY, None)++ assert_parity(uri_m, uri_u, "multi_row_group")+ rows, _ = read_sorted(uri_u)+ assert len(rows) == n + 5000+ assert stats.rows_updated == n // 2+++def test_idempotency_tag_is_discoverable(tmp_path):+ """`has_commit_with_metadata` must find deltalite's tag exactly as it finds merge's."""+ uri = str(tmp_path / "idem")+ create_table(uri, simple(["a", "b"], "2026-07-23", 1), True)+ upsert_path(+ uri,+ simple(["a", "c"], "2026-07-23", 2),+ ["id"],+ PARTITION_KEY,+ {"run_uuid": "run-xyz", "batch_index": "7"},+ )++ history = deltalake.DeltaTable(uri).history(5)++ def matches(commit, md):+ flat = all(commit.get(k) == v for k, v in md.items())+ nested = commit.get("userMetadata")+ return flat or (isinstance(nested, dict) and all(nested.get(k) == v for k, v in md.items()))++ assert any(matches(c, {"run_uuid": "run-xyz", "batch_index": "7"}) for c in history), (+ f"idempotency tag not discoverable in history: {history}"+ )+++def test_empty_batch_still_tags_the_commit(tmp_path):+ """Open question from the design: does an action-less commit land?"""+ uri = str(tmp_path / "empty_tag")+ create_table(uri, simple(["a", "b"], "2026-07-23", 1), True)+ before = deltalake.DeltaTable(uri).version()++ stats = upsert_path(+ uri,+ simple([], "2026-07-23", []),+ ["id"],+ PARTITION_KEY,+ {"run_uuid": "run-empty", "batch_index": "0"},+ )++ after = deltalake.DeltaTable(uri).version()+ assert after == before + 1, "empty batch did not produce a commit"+ assert stats.files_added == 0 and stats.files_removed == 0+ history = deltalake.DeltaTable(uri).history(3)+ assert any(c.get("run_uuid") == "run-empty" for c in history)+++def test_duplicate_pks_in_source_are_rejected(tmp_path):+ """The crate must refuse an un-deduped batch rather than double-insert."""+ import deltalite++ uri = str(tmp_path / "dupe")+ create_table(uri, simple(["a"], "2026-07-23", 1), True)+ raw = simple(["b", "b"], "2026-07-23", [1, 2]) # deliberately NOT deduped++ t = deltalite.DeltaLiteTable.open(uri)+ with pytest.raises(deltalite.DeltaLiteError, match="duplicate primary-key"):+ t.upsert(raw, ["id"], PARTITION_KEY)+++def test_dedupe_helper_keeps_last(tmp_path):+ batch = simple(["a", "a", "b"], "2026-07-23", [1, 2, 3])+ out = dedupe_keep_last(batch, ["id"], PARTITION_KEY)+ d = dict(zip(out["id"].to_pylist(), out["v"].to_pylist()))+ assert d == {"a": 2, "b": 3}+++# --------------------------------------------------------------------------------------+# The single-quote partition value: a pre-existing MERGE defect, not a deltalite one+# --------------------------------------------------------------------------------------+++def _quote_scenario_tables(tmp_path, name):+ uri = str(tmp_path / name)+ initial = simple(["i0", "i1"], [HOSTILE_WITH_QUOTE, "2026-07-23"], 1)+ create_table(uri, initial, True)+ return uri, simple(["i0", "i1"], [HOSTILE_WITH_QUOTE, "2026-07-23"], 2)+++def test_single_quote_partition_value_breaks_merge(tmp_path):+ """Documents the current production sharp edge.++ `DeltaTableHelper` interpolates the partition value straight into a SQL predicate+ (`target._ph_partition_key = '{partition}'`), so a value containing a single quote+ produces invalid SQL. This is a live bug on the existing code path.+ """+ uri, batch = _quote_scenario_tables(tmp_path, "quote_merge")+ with pytest.raises(Exception) as exc:+ merge_path(uri, batch, ["id"], PARTITION_KEY, None)+ assert "Unterminated string literal" in str(exc.value) or "SQL" in str(exc.value)+++def test_single_quote_partition_value_works_in_deltalite(tmp_path):+ """deltalite never builds a SQL predicate, so the same value is handled."""+ uri, batch = _quote_scenario_tables(tmp_path, "quote_upsert")+ upsert_path(uri, batch, ["id"], PARTITION_KEY, None)++ rows, _ = read_sorted(uri)+ assert len(rows) == 2+ tbl = deltalake.DeltaTable(uri).to_pyarrow_table().sort_by("id")+ assert tbl["v"].to_pylist() == [2, 2]+ assert set(tbl[PARTITION_KEY].to_pylist()) == {HOSTILE_WITH_QUOTE, "2026-07-23"}+++# --------------------------------------------------------------------------------------+# Absolute expectations. Cross-path equality cannot catch both paths being wrong in the+# same way, so the semantically load-bearing cases are also pinned to explicit content.+# --------------------------------------------------------------------------------------+++def _content(uri):+ tbl = deltalake.DeltaTable(uri).to_pyarrow_table()+ return sorted(+ zip(tbl["id"].to_pylist(), tbl["v"].to_pylist(), tbl[PARTITION_KEY].to_pylist()),+ key=lambda r: (r[0] is None, str(r[0]), r[1]),+ )++[email protected]("path_name", ["merge", "upsert"])+def test_null_pk_absolute_semantics(tmp_path, path_name):+ """A NULL PK must never match: every NULL-keyed source row inserts a new row."""+ path = merge_path if path_name == "merge" else upsert_path+ uri = str(tmp_path / f"nullabs_{path_name}")+ create_table(uri, simple(["a", None, "c"], "2026-07-23", 1), True)++ path(uri, simple([None, "a"], "2026-07-23", 2), ["id"], PARTITION_KEY, None)+ path(uri, simple([None], "2026-07-23", 3), ["id"], PARTITION_KEY, None)++ assert _content(uri) == [+ ("a", 2, "2026-07-23"), # matched and updated+ ("c", 1, "2026-07-23"), # untouched+ (None, 1, "2026-07-23"), # original NULL row survives+ (None, 2, "2026-07-23"), # first NULL insert+ (None, 3, "2026-07-23"), # second NULL insert+ ]++[email protected]("path_name", ["merge", "upsert"])+def test_pk_changing_partition_absolute_semantics(tmp_path, path_name):+ """Identity is (PK, partition): a moved PK inserts and leaves the old row behind."""+ path = merge_path if path_name == "merge" else upsert_path+ uri = str(tmp_path / f"moveabs_{path_name}")+ create_table(uri, simple(["a", "b"], "2026-07-23", 1), True)++ path(uri, simple(["a"], "2026-07-24", 2), ["id"], PARTITION_KEY, None)++ assert _content(uri) == [+ ("a", 1, "2026-07-23"), # stale row deliberately NOT deleted+ ("a", 2, "2026-07-24"), # new partition gets the new row+ ("b", 1, "2026-07-23"),+ ]++[email protected]("path_name", ["merge", "upsert"])+def test_composite_pk_absolute_semantics(tmp_path, path_name):+ path = merge_path if path_name == "merge" else upsert_path+ uri = str(tmp_path / f"compabs_{path_name}")+ create_table(uri, simple(["a", "a", "b"], "2026-07-23", 1, tenant=[1, 2, 1]), True)++ path(+ uri,+ simple(["a", "a"], "2026-07-23", 5, tenant=[2, 3]),+ ["id", "tenant"],+ PARTITION_KEY,+ None,+ )++ tbl = deltalake.DeltaTable(uri).to_pyarrow_table()+ got = sorted(zip(tbl["id"].to_pylist(), tbl["tenant"].to_pylist(), tbl["v"].to_pylist()))+ assert got == [+ ("a", 1, 1), # untouched: only (a,2) matched+ ("a", 2, 5), # updated+ ("a", 3, 5), # inserted+ ("b", 1, 1),+ ]diff --git a/rust/deltalite/python/tests/test_planner.py b/rust/deltalite/python/tests/test_planner.pynew file mode 100644index 000000000000..8e4a3152f42d--- /dev/null+++ b/rust/deltalite/python/tests/test_planner.py@@ -0,0 +1,159 @@+"""Tests for the knob-tuning heuristic (deltalite_planner).++The planner is deliberately rough -- these tests pin its *shape* (monotonicity,+clamps, the honest "does not fit" answer, and agreement with the env-var names the+Rust crate reads), not any absolute MB figure.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from deltalite_planner import MB, Knobs, plan+++def test_production_shape_gives_usable_knobs():+ # The stated production shape: ~15 concurrent upserts on an 8 GB pod.+ k = plan(15, 8_000, source_mb=250)+ assert 1 <= k.max_parallel_partitions <= 4+ assert k.max_parallel_files in (2, 4)+ assert k.max_buffered_bytes in (32 * MB, 64 * MB)+ assert k.per_upsert_budget_mb > 0+++def test_generous_pod_reaches_but_never_exceeds_the_mpp_cap():+ k = plan(1, 64_000, source_mb=100)+ assert k.max_parallel_partitions == 4+ assert k.fits+++def test_more_memory_never_reduces_mpp():+ prev = 0+ for pod_mb in (2_000, 4_000, 8_000, 16_000, 32_000):+ mpp = plan(10, pod_mb, source_mb=100).max_parallel_partitions+ assert mpp >= prev+ prev = mpp+++def test_more_concurrency_never_increases_mpp():+ prev = 5+ for n in (1, 2, 4, 8, 16, 32):+ mpp = plan(n, 16_000, source_mb=100).max_parallel_partitions+ assert mpp <= prev+ prev = mpp+++def test_overloaded_pod_says_no_rather_than_pretending():+ k = plan(50, 4_000, source_mb=500)+ assert not k.fits+ assert k.max_parallel_partitions == 1 # still returns the most conservative knobs+ assert any("below" in n for n in k.notes)+++def test_bigger_sources_reduce_headroom():+ small = plan(10, 16_000, source_mb=50)+ large = plan(10, 16_000, source_mb=600)+ assert large.max_parallel_partitions <= small.max_parallel_partitions+++def test_missing_source_size_is_flagged():+ k = plan(4, 16_000)+ assert any("source size not given" in n for n in k.notes)+ assert not any("source size not given" in n for n in plan(4, 16_000, source_mb=100).notes)+++def test_tight_budget_halves_the_wall_clock_knobs():+ tight = plan(30, 8_000, source_mb=200)+ assert tight.max_parallel_files == 2+ assert tight.max_buffered_bytes == 32 * MB+ roomy = plan(2, 32_000, source_mb=200)+ assert roomy.max_parallel_files == 4+ assert roomy.max_buffered_bytes == 64 * MB+++def test_env_suggestions_match_the_rust_crate_names_and_scale():+ k = plan(15, 16_000, source_mb=100)+ assert set(k.env) == {+ "DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS",+ "DELTALITE_PROCESS_MAX_PARALLEL_FILES",+ "DELTALITE_PROCESS_MAX_BUFFERED_BYTES",+ }+ # Ceilings are per-call knobs x a bounded burst factor, never per-call x N upserts.+ assert int(k.env["DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS"]) <= k.max_parallel_partitions * 4+ assert int(k.env["DELTALITE_PROCESS_MAX_PARALLEL_FILES"]) <= k.max_parallel_files * 4+ assert int(k.env["DELTALITE_PROCESS_MAX_BUFFERED_BYTES"]) <= k.max_buffered_bytes * 4+++def test_single_upsert_env_does_not_over_provision():+ k = plan(1, 16_000, source_mb=100)+ assert int(k.env["DELTALITE_PROCESS_MAX_PARALLEL_PARTITIONS"]) == k.max_parallel_partitions+ assert int(k.env["DELTALITE_PROCESS_MAX_BUFFERED_BYTES"]) == k.max_buffered_bytes+++def test_as_upsert_kwargs_round_trips_into_upsert_signature():+ k = plan(4, 8_000, source_mb=100)+ kwargs = k.as_upsert_kwargs()+ assert set(kwargs) == {+ "max_parallel_partitions",+ "max_parallel_files",+ "max_buffered_bytes",+ }+ assert isinstance(k, Knobs)+++ "args",+ [+ (0, 8_000),+ (-1, 8_000),+ (4, 0),+ (4, -100),+ ],+)+def test_invalid_inputs_raise(args):+ with pytest.raises(ValueError):+ plan(*args)+++def test_invalid_target_file_size_raises():+ with pytest.raises(ValueError):+ plan(4, 8_000, target_file_size_mb=0)+++def test_smaller_target_file_size_frees_room_for_workers():+ big = plan(10, 8_000, source_mb=100, target_file_size_mb=200)+ small = plan(10, 8_000, source_mb=100, target_file_size_mb=25)+ assert small.max_parallel_partitions >= big.max_parallel_partitions+++def test_knob_kwargs_are_accepted_by_a_real_upsert(tmp_path):+ """The suggested kwargs must remain valid arguments of DeltaLiteTable.upsert."""+ import pyarrow as pa+ import deltalake+ from harness.common import PARTITION_KEY, upsert_path++ uri = str(tmp_path / "planned")+ table = pa.table(+ {+ "id": pa.array(["a", "b"], pa.string()),+ "v": pa.array([1, 2], pa.int64()),+ PARTITION_KEY: pa.array(["p1", "p1"], pa.string()),+ }+ )+ deltalake.write_deltalake(uri, table, partition_by=[PARTITION_KEY], mode="overwrite")++ knobs = plan(15, 8_000, source_mb=1)+ batch = pa.table(+ {+ "id": pa.array(["a", "c"], pa.string()),+ "v": pa.array([10, 3], pa.int64()),+ PARTITION_KEY: pa.array(["p1", "p1"], pa.string()),+ }+ )+ stats = upsert_path(uri, batch, ["id"], PARTITION_KEY, **knobs.as_upsert_kwargs())+ assert stats.rows_updated == 1+ assert stats.rows_inserted == 1diff --git a/rust/deltalite/python/tests/test_probe.py b/rust/deltalite/python/tests/test_probe.pynew file mode 100644index 000000000000..af7bfa6abe5c--- /dev/null+++ b/rust/deltalite/python/tests/test_probe.py@@ -0,0 +1,466 @@+"""Content-based file selection (`prune_strategy="probe"`).++The probe reads only the PK column(s) of each candidate file and skips files with zero+matches, recovering MERGE's exact join-based rewrite set without a join. The tests here+weight the silent-corruption risk heaviest: a file that DOES contain a match must never+be skipped, under random UUID keys (where min/max stats prune nothing), NULL PKs,+composite PKs, schema evolution, and partitioned layouts. Parity against the real+delta-rs MERGE is the oracle throughout.+"""++from __future__ import annotations++import sys+import uuid+import random+import shutil+from pathlib import Path++import pytest++import pyarrow as pa+import deltalake++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from harness.common import ( # noqa: E402+ PARTITION_KEY,+ assert_parity,+ dedupe_keep_last,+ merge_path,+ read_sorted,+ upsert_path,+)++N_FILES = 6+ROWS_PER_FILE = 300+++def rand_ids(rng: random.Random, n: int) -> list[str]:+ return [str(uuid.UUID(int=rng.getrandbits(128), version=4)) for _ in range(n)]+++def rows(ids, v, part="p1", tenant=None):+ n = len(ids)+ return pa.table(+ {+ "id": pa.array(ids, pa.string()),+ "tenant": pa.array(tenant if tenant is not None else [1] * n, pa.int64()),+ "v": pa.array([v] * n if isinstance(v, int) else v, pa.int64()),+ PARTITION_KEY: pa.array(part if isinstance(part, list) else [part] * n, pa.string()),+ }+ )+++def build_multifile_table(+ uri: str,+ partitioned: bool = False,+ n_files: int = N_FILES,+ rows_per_file: int = ROWS_PER_FILE,+ partitions: list[str] | None = None,+ seed: int = 20260724,+) -> dict[str, list[list[str]]]:+ """One append per file, random UUID PKs, so min/max stats can prune nothing and we+ know exactly which ids live in which file. Returns partition -> per-file id lists."""+ rng = random.Random(seed)+ parts = partitions or ["p1"]+ per_file: dict[str, list[list[str]]] = {p: [] for p in parts}+ first = True+ for p in parts:+ for _ in range(n_files):+ ids = rand_ids(rng, rows_per_file)+ per_file[p].append(ids)+ deltalake.write_deltalake(+ uri,+ rows(ids, 1, part=p),+ partition_by=[PARTITION_KEY] if partitioned else None,+ mode="overwrite" if first else "append",+ schema_mode="overwrite" if first else None,+ )+ first = False+ return per_file+++# --------------------------------------------------------------------------------------+# Exactness: rewrite exactly the matching files, never more, NEVER less+# --------------------------------------------------------------------------------------+++def test_temporal_locality_rewrites_only_the_matching_file(tmp_path):+ """The production shape: random UUID keys, updates re-touching recently written+ rows. min/max stats prune nothing; the probe must find the single matching file."""+ base = tmp_path / "base"+ ids = build_multifile_table(str(base))["p1"]+ # updates all live in the newest file+ batch_ids = random.Random(7).sample(ids[-1], 50)++ uri_m, uri_u = str(tmp_path / "m"), str(tmp_path / "u")+ for uri in (uri_m, uri_u):+ shutil.copytree(base, uri)+ batch = rows(batch_ids, 2)+ merge_path(uri_m, batch, ["id"], None)+ stats = upsert_path(uri_u, batch, ["id"], None, prune_strategy="probe")+ assert_parity(uri_m, uri_u, "temporal_locality")++ assert stats.files_removed == 1+ assert stats.files_carried_over == N_FILES - 1+ assert stats.files_probed == N_FILES+ assert stats.rows_updated == 50++[email protected]("target_file", range(N_FILES))+def test_never_skips_a_file_containing_a_match(tmp_path, target_file):+ """The silent-corruption case: a single update whose row lives in file+ `target_file` must always cause exactly that file to be rewritten."""+ ids: list[list[str]] = []++ def build(uri):+ nonlocal ids+ ids = build_multifile_table(uri)["p1"]++ base = tmp_path / "base"+ build(str(base))+ victim = ids[target_file][ROWS_PER_FILE // 2]++ uri_m, uri_u = str(tmp_path / "m"), str(tmp_path / "u")+ for uri in (uri_m, uri_u):+ shutil.copytree(base, uri)+ batch = rows([victim], 99)+ merge_path(uri_m, batch, ["id"], None)+ stats = upsert_path(uri_u, batch, ["id"], None, prune_strategy="probe")+ assert_parity(uri_m, uri_u, f"single_hit_file_{target_file}")++ assert stats.files_removed == 1+ assert stats.files_carried_over == N_FILES - 1+ assert stats.rows_updated == 1++ # Belt and braces beyond parity: the updated value is actually visible.+ content, _ = read_sorted(uri_u)+ assert sum(1 for r in content if victim in r and 99 in r) == 1++[email protected]("seed", [1, 2, 3])+def test_fuzz_random_file_subsets(tmp_path, seed):+ """Random subsets of files receive updates; parity with MERGE is the oracle and the+ probe must rewrite exactly the touched files."""+ ids: list[list[str]] = []++ def build(uri):+ nonlocal ids+ ids = build_multifile_table(uri, seed=1000 + seed)["p1"]++ base = tmp_path / "base"+ build(str(base))+ rng = random.Random(seed)+ touched = sorted(rng.sample(range(N_FILES), rng.randint(1, N_FILES)))+ upd = [i for f in touched for i in rng.sample(ids[f], rng.randint(1, 40))]+ new = rand_ids(rng, 10)++ uri_m, uri_u = str(tmp_path / "m"), str(tmp_path / "u")+ for uri in (uri_m, uri_u):+ shutil.copytree(base, uri)+ batch = rows(upd + new, 2)+ merge_path(uri_m, batch, ["id"], None)+ stats = upsert_path(uri_u, batch, ["id"], None, prune_strategy="probe")+ assert_parity(uri_m, uri_u, f"fuzz_{seed}")++ assert stats.files_removed == len(touched)+ assert stats.files_carried_over == N_FILES - len(touched)+ assert stats.rows_updated == len(upd)+ assert stats.rows_inserted == len(new)+++def test_scattered_updates_rewrite_everything(tmp_path):+ """No locality: every file holds a match, so nothing may be skipped."""+ base = tmp_path / "base"+ ids = build_multifile_table(str(base))["p1"]+ rng = random.Random(11)+ upd = [i for f in ids for i in rng.sample(f, 5)]+ uri_m, uri_u = str(tmp_path / "m"), str(tmp_path / "u")+ for uri in (uri_m, uri_u):+ shutil.copytree(base, uri)+ batch = rows(upd, 2)+ merge_path(uri_m, batch, ["id"], None)+ stats = upsert_path(uri_u, batch, ["id"], None, prune_strategy="probe")+ assert_parity(uri_m, uri_u, "scattered")++ assert stats.files_removed == N_FILES+ assert stats.files_carried_over == 0+++def test_match_only_in_last_row_group_is_found(tmp_path):+ """The probe streams a file batch by batch and short-circuits on the first hit. A+ match living in the LAST row group of a multi-row-group file must still be found --+ and a small read_batch_size forces many probe batches per row group too."""+ props = deltalake.WriterProperties(max_row_group_size=500) # 8 row groups of 500+ rng = random.Random(42)+ ids = rand_ids(rng, 4000)+ other = rand_ids(rng, 100)++ def build(uri):+ deltalake.write_deltalake(uri, rows(ids, 1), mode="overwrite", writer_properties=props)+ deltalake.write_deltalake(uri, rows(other, 1), mode="append", writer_properties=props)++ base = tmp_path / "base"+ build(str(base))+ uri_m, uri_u = str(tmp_path / "m"), str(tmp_path / "u")+ for uri in (uri_m, uri_u):+ shutil.copytree(base, uri)++ victim = ids[-1] # physically in the final row group of file 1+ batch = rows([victim], 99)+ merge_path(uri_m, batch, ["id"], None)+ stats = upsert_path(uri_u, batch, ["id"], None, prune_strategy="probe", read_batch_size=100)+ assert_parity(uri_m, uri_u, "late_row_group")++ assert stats.files_removed == 1+ assert stats.files_carried_over == 1+ assert stats.rows_updated == 1+ content, _ = read_sorted(uri_u)+ assert sum(1 for r in content if victim in r and 99 in r) == 1+++# --------------------------------------------------------------------------------------+# NULL PK semantics under the probe+# --------------------------------------------------------------------------------------+++def test_null_pk_rows_never_match_and_all_files_skip(tmp_path):+ """An all-NULL-PK source can match nothing: every file must be carried over without+ even being probed, and the NULL rows must append."""+ ids: list[list[str]] = []++ def build(uri):+ nonlocal ids+ ids = build_multifile_table(uri)["p1"]++ base = tmp_path / "base"+ build(str(base))+ uri_m, uri_u = str(tmp_path / "m"), str(tmp_path / "u")+ for uri in (uri_m, uri_u):+ shutil.copytree(base, uri)++ batch = rows([None, None, None], 7)+ batch = dedupe_keep_last(batch, ["id"], None)+ merge_path(uri_m, batch, ["id"], None)+ stats = upsert_path(uri_u, batch, ["id"], None, prune_strategy="probe")+ assert_parity(uri_m, uri_u, "all_null_pk")++ assert stats.files_removed == 0+ assert stats.files_carried_over == N_FILES+ assert stats.files_probed == 0 # short-circuit: empty PK set needs no I/O+ assert stats.rows_inserted == 3+++def test_null_pks_in_target_files_are_not_matched(tmp_path):+ """Target rows with NULL PKs must survive every rewrite and never be 'updated' by a+ NULL source row, while real updates in the same files still land."""++ def build(uri):+ deltalake.write_deltalake(uri, rows(["a", None, "b"], 1), mode="overwrite")+ deltalake.write_deltalake(uri, rows([None, "c"], 1), mode="append")++ base = tmp_path / "base"+ build(str(base))+ uri_m, uri_u = str(tmp_path / "m"), str(tmp_path / "u")+ for uri in (uri_m, uri_u):+ shutil.copytree(base, uri)++ batch = dedupe_keep_last(rows(["c", None, "x"], 2), ["id"], None)+ merge_path(uri_m, batch, ["id"], None)+ stats = upsert_path(uri_u, batch, ["id"], None, prune_strategy="probe")+ assert_parity(uri_m, uri_u, "null_pk_target")++ # 'c' lives in file 2 -> file 1 is match-free and must be carried over.+ assert stats.files_removed == 1+ assert stats.files_carried_over == 1+ assert stats.rows_updated == 1+++# --------------------------------------------------------------------------------------+# Composite PKs+# --------------------------------------------------------------------------------------+++def test_composite_pk_only_full_tuple_matches(tmp_path):+ """(id, tenant) PK: a file holding (X, 1) is match-free for source (X, 2)."""++ def build(uri):+ deltalake.write_deltalake(uri, rows(["x", "y"], 1, tenant=[1, 1]), mode="overwrite")+ deltalake.write_deltalake(uri, rows(["z"], 1, tenant=[1]), mode="append")++ base = tmp_path / "base"+ build(str(base))+ uri_m, uri_u = str(tmp_path / "m"), str(tmp_path / "u")+ for uri in (uri_m, uri_u):+ shutil.copytree(base, uri)++ # (x,2) matches nothing anywhere; (z,1) matches file 2 only.+ batch = dedupe_keep_last(rows(["x", "z"], 5, tenant=[2, 1]), ["id", "tenant"], None)+ merge_path(uri_m, batch, ["id", "tenant"], None)+ stats = upsert_path(uri_u, batch, ["id", "tenant"], None, prune_strategy="probe")+ assert_parity(uri_m, uri_u, "composite_pk")++ assert stats.files_removed == 1+ assert stats.files_carried_over == 1+ assert stats.rows_updated == 1+++# --------------------------------------------------------------------------------------+# Schema evolution: PK column physically absent from old files+# --------------------------------------------------------------------------------------+++def test_pk_column_added_by_evolution_skips_old_files(tmp_path):+ """Old files predate a PK column: it reads as all-NULL there, so those files are+ exact negatives and must be skipped without corruption."""++ def build(uri):+ deltalake.write_deltalake(uri, rows(["a", "b"], 1), mode="overwrite")+ deltalake.write_deltalake(uri, rows(["c", "d"], 1), mode="append")++ base = tmp_path / "base"+ build(str(base))+ uri_m, uri_u = str(tmp_path / "m"), str(tmp_path / "u")+ for uri in (uri_m, uri_u):+ shutil.copytree(base, uri)++ batch = rows(["a", "c"], 2).append_column("k2", pa.array(["k", "k"], pa.string()))+ batch = dedupe_keep_last(batch, ["id", "k2"], None)+ # merge_path/upsert_path both evolve the schema (add k2) before writing.+ merge_path(uri_m, batch, ["id", "k2"], None)+ stats = upsert_path(uri_u, batch, ["id", "k2"], None, prune_strategy="probe")+ assert_parity(uri_m, uri_u, "evolved_pk")++ # No old row can match a (id, k2) tuple -> everything carried, rows appended.+ assert stats.files_removed == 0+ assert stats.files_carried_over == 2+ assert stats.rows_updated == 0+ assert stats.rows_inserted == 2+++# --------------------------------------------------------------------------------------+# Partitioned tables+# --------------------------------------------------------------------------------------+++def test_partitioned_probe_prunes_within_each_partition(tmp_path):+ per_file: dict[str, list[list[str]]] = {}++ def build(uri):+ per_file.update(build_multifile_table(uri, partitioned=True, n_files=3, partitions=["p1", "p2"]))++ base = tmp_path / "base"+ build(str(base))+ rng = random.Random(3)+ upd = rng.sample(per_file["p1"][2], 10) + rng.sample(per_file["p2"][0], 10)+ parts = ["p1"] * 10 + ["p2"] * 10++ uri_m, uri_u = str(tmp_path / "m"), str(tmp_path / "u")+ for uri in (uri_m, uri_u):+ shutil.copytree(base, uri)+ batch = dedupe_keep_last(rows(upd, 2, part=parts), ["id"], PARTITION_KEY)+ merge_path(uri_m, batch, ["id"], PARTITION_KEY)+ stats = upsert_path(uri_u, batch, ["id"], PARTITION_KEY, prune_strategy="probe")+ assert_parity(uri_m, uri_u, "partitioned_probe")++ assert stats.partitions_touched == 2+ assert stats.files_removed == 2 # one matching file per partition+ assert stats.files_carried_over == 4+ assert stats.rows_updated == 20+++def test_pk_equal_to_partition_column_is_conservative(tmp_path):+ """Degenerate PK = the partition column (all-constant probe): probe and none must+ produce identical content -- probing may only skip provably match-free files."""++ def build(uri):+ deltalake.write_deltalake(+ uri,+ rows(["a", "b"], 1, part=["p1", "p1"]),+ partition_by=[PARTITION_KEY],+ mode="overwrite",+ )+ deltalake.write_deltalake(+ uri,+ rows(["c"], 1, part=["p2"]),+ partition_by=[PARTITION_KEY],+ mode="append",+ )++ base = tmp_path / "base"+ build(str(base))+ uri_p, uri_n = str(tmp_path / "p"), str(tmp_path / "n")+ for uri in (uri_p, uri_n):+ shutil.copytree(base, uri)++ batch = rows(["z"], 9, part=["p1"])+ s_probe = upsert_path(uri_p, batch, [PARTITION_KEY], PARTITION_KEY, prune_strategy="probe")+ s_none = upsert_path(uri_n, batch, [PARTITION_KEY], PARTITION_KEY, prune_strategy="none")+ assert read_sorted(uri_p) == read_sorted(uri_n)+ # Every p1 row shares the source's PK tuple -> the p1 file must be rewritten.+ assert s_probe.files_removed == s_none.files_removed == 1+++# --------------------------------------------------------------------------------------+# The knob itself+# --------------------------------------------------------------------------------------++[email protected]("strategy", ["none", "stats", "probe"])+def test_every_strategy_is_merge_equivalent(tmp_path, strategy):+ ids: list[list[str]] = []++ def build(uri):+ nonlocal ids+ ids = build_multifile_table(uri, n_files=3)["p1"]++ base = tmp_path / "base"+ build(str(base))+ rng = random.Random(5)+ upd = rng.sample(ids[1], 20)++ uri_m, uri_u = str(tmp_path / "m"), str(tmp_path / "u")+ for uri in (uri_m, uri_u):+ shutil.copytree(base, uri)+ batch = rows(upd, 2)+ merge_path(uri_m, batch, ["id"], None)+ stats = upsert_path(uri_u, batch, ["id"], None, prune_strategy=strategy)+ assert_parity(uri_m, uri_u, f"strategy_{strategy}")++ if strategy == "probe":+ assert stats.files_removed == 1 and stats.files_carried_over == 2+ else:+ # Random UUID ranges overlap: stats pruning cannot exclude anything here.+ assert stats.files_removed == 3 and stats.files_carried_over == 0+ assert stats.files_probed == 0+++def test_skip_unmatched_files_false_maps_to_none(tmp_path):+ ids: list[list[str]] = []++ def build(uri):+ nonlocal ids+ ids = build_multifile_table(uri, n_files=3)["p1"]++ base = tmp_path / "base"+ build(str(base))+ uri_u = str(tmp_path / "u")+ shutil.copytree(base, uri_u)++ batch = rows([ids[0][0]], 2)+ stats = upsert_path(uri_u, batch, ["id"], None, skip_unmatched_files=False)+ assert stats.files_removed == 3+ assert stats.files_carried_over == 0+ assert stats.files_probed == 0+++def test_invalid_prune_strategy_is_rejected(tmp_path):+ def build(uri):+ deltalake.write_deltalake(uri, rows(["a"], 1), mode="overwrite")++ uri = str(tmp_path / "t")+ build(uri)+ import deltalite++ with pytest.raises(deltalite.DeltaLiteError, match="unknown prune_strategy"):+ upsert_path(uri, rows(["a"], 2), ["id"], None, prune_strategy="bogus")diff --git a/rust/deltalite/python/tests/test_types.py b/rust/deltalite/python/tests/test_types.pynew file mode 100644index 000000000000..56144a238071--- /dev/null+++ b/rust/deltalite/python/tests/test_types.py@@ -0,0 +1,356 @@+"""Type-surface parity: deltalite vs delta-rs SQL MERGE across the arrow types a+warehouse sync actually produces.++Two axes:+ * value columns -- every type must survive the streaming rewrite (write, read back,+ cast, filter, re-write) with content identical to MERGE's;+ * primary-key columns -- every type that could legitimately be a PK must produce the+ same match/insert decisions in deltalite's RowConverter-encoded hash set+ (src/pkset.rs) as in MERGE's join, including the float -0.0/NaN sharp edges.++Any case where the two paths disagree, or where deltalite errors and MERGE succeeds,+is a NO-GO finding, not a skip.+"""++from __future__ import annotations++import sys+import decimal+import datetime+from pathlib import Path++import pytest++import pyarrow as pa+import deltalake++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from harness.common import PARTITION_KEY, create_table, merge_path, read_sorted, upsert_path # noqa: E402++TS = datetime.datetime(2026, 1, 1)+UTC = datetime.UTC+D = decimal.Decimal+++def _dual(tmp_path, name, initial):+ uri_m = str(tmp_path / f"{name}_m")+ uri_u = str(tmp_path / f"{name}_u")+ create_table(uri_m, initial, True)+ create_table(uri_u, initial, True)+ return uri_m, uri_u+++def _assert_type_parity(uri_m, uri_u, batches, primary_keys, label):+ """Drive both paths with the same batches, then compare logical content."""+ for batch in batches:+ merge_path(uri_m, batch, primary_keys, PARTITION_KEY)+ upsert_path(uri_u, batch, primary_keys, PARTITION_KEY)+ rows_m, schema_m = read_sorted(uri_m)+ rows_u, schema_u = read_sorted(uri_u)+ assert schema_m == schema_u, f"[{label}] schema: {schema_m} != {schema_u}"+ # Compare via str(): NaN != NaN under tuple equality, but str() is stable and also+ # distinguishes -0.0 from 0.0.+ norm_m = [tuple(str(v) for v in r) for r in rows_m]+ norm_u = [tuple(str(v) for v in r) for r in rows_u]+ assert norm_m == norm_u, f"[{label}] content mismatch:\n merge : {rows_m}\n upsert: {rows_u}"+++# --------------------------------------------------------------------------------------+# Value columns: string PK, the type under test as a payload column.+# Three batches so the second/third upserts must stream back and cast the nested+# Parquet files the first upsert wrote.+# --------------------------------------------------------------------------------------+++def _val_table(ids, col):+ return pa.table(+ {+ "id": pa.array(ids, pa.string()),+ "x": col,+ PARTITION_KEY: pa.array(["2026-07-23"] * len(ids), pa.string()),+ }+ )+++STRUCT_T = pa.struct([("a", pa.int64()), ("b", pa.string())])+DEEP_T = pa.struct(+ [+ ("inner", pa.struct([("n", pa.int64()), ("s", pa.string())])),+ ("tags", pa.list_(pa.string())),+ ]+)++VALUE_CASES = {+ "bool": (+ pa.array([True, False, None], pa.bool_()),+ pa.array([False, None], pa.bool_()),+ pa.array([True, True], pa.bool_()),+ ),+ "float32": (+ pa.array([1.5, -2.5, None], pa.float32()),+ pa.array([9.5, None], pa.float32()),+ pa.array([0.0, -0.0], pa.float32()),+ ),+ "float64": (+ pa.array([1.5, float("nan"), None], pa.float64()),+ pa.array([float("inf"), None], pa.float64()),+ pa.array([float("nan"), -0.0], pa.float64()),+ ),+ "binary": (+ pa.array([b"\x00\x01", b"", None], pa.binary()),+ pa.array([b"\xff" * 8, None], pa.binary()),+ pa.array([b"q", b"\x00"], pa.binary()),+ ),+ "fixed_size_binary": (+ pa.array([b"aaaa", b"bbbb", None], pa.binary(4)),+ pa.array([b"cccc", None], pa.binary(4)),+ pa.array([b"dddd", b"\x00\x00\x00\x00"], pa.binary(4)),+ ),+ "large_binary": (+ pa.array([b"a", b"b", None], pa.large_binary()),+ pa.array([b"c", None], pa.large_binary()),+ pa.array([b"d", b"e"], pa.large_binary()),+ ),+ "date32": (+ pa.array([datetime.date(2026, 1, 1), datetime.date(1970, 1, 1), None], pa.date32()),+ pa.array([datetime.date(2026, 2, 2), None], pa.date32()),+ pa.array([datetime.date(1900, 1, 1), datetime.date(2100, 12, 31)], pa.date32()),+ ),+ "timestamp_tz": (+ pa.array([TS.replace(tzinfo=UTC)] * 2 + [None], pa.timestamp("us", tz="UTC")),+ pa.array([TS.replace(tzinfo=UTC) + datetime.timedelta(days=1), None], pa.timestamp("us", tz="UTC")),+ pa.array([TS.replace(tzinfo=UTC)] * 2, pa.timestamp("us", tz="UTC")),+ ),+ "timestamp_tz_offset": (+ pa.array([1, 2, None], pa.timestamp("s", tz="+02:00")),+ pa.array([3, None], pa.timestamp("s", tz="+02:00")),+ pa.array([4, 5], pa.timestamp("s", tz="+02:00")),+ ),+ "timestamp_ns": (+ pa.array([1, 2, None], pa.timestamp("ns")),+ pa.array([3, None], pa.timestamp("ns")),+ pa.array([4, 5], pa.timestamp("ns")),+ ),+ "large_string": (+ pa.array(["x" * 100, "", None], pa.large_string()),+ pa.array(["y", None], pa.large_string()),+ pa.array(["z", "w"], pa.large_string()),+ ),+ "dictionary": (+ pa.array(["red", "blue", "red"]).dictionary_encode(),+ pa.array(["green", "red"]).dictionary_encode(),+ pa.array(["blue", "blue"]).dictionary_encode(),+ ),+ # NOTE: delta stores uint32 as signed int32, so values must fit in i32; a uint32+ # value >= 2**31 fails at CREATE time for both writers equally (not a deltalite gap).+ "uint32": (+ pa.array([1, 2**31 - 1, None], pa.uint32()),+ pa.array([7, None], pa.uint32()),+ pa.array([0, 3], pa.uint32()),+ ),+ "list_int": (+ pa.array([[1, 2], [], None], pa.list_(pa.int64())),+ pa.array([[9, None], None], pa.list_(pa.int64())),+ pa.array([[0], [1, 2, 3]], pa.list_(pa.int64())),+ ),+ "struct": (+ pa.array([{"a": 1, "b": "s"}, {"a": None, "b": None}, None], STRUCT_T),+ pa.array([{"a": 9, "b": "t"}, None], STRUCT_T),+ pa.array([{"a": 2, "b": None}, {"a": None, "b": "u"}], STRUCT_T),+ ),+ "map": (+ pa.array([[("k", 1)], [], None], pa.map_(pa.string(), pa.int64())),+ pa.array([[("z", 9), ("y", None)], None], pa.map_(pa.string(), pa.int64())),+ pa.array([[("a", 0)], [("b", 1)]], pa.map_(pa.string(), pa.int64())),+ ),+ "list_of_struct": (+ pa.array([[{"a": 1, "b": "x"}], [], None], pa.list_(STRUCT_T)),+ pa.array([[{"a": 9, "b": None}, None], None], pa.list_(STRUCT_T)),+ pa.array([[{"a": 2, "b": "y"}], [{"a": None, "b": None}]], pa.list_(STRUCT_T)),+ ),+ "deeply_nullable_nested": (+ pa.array(+ [+ {"inner": {"n": 1, "s": "a"}, "tags": ["t1", None]},+ {"inner": None, "tags": None},+ None,+ ],+ DEEP_T,+ ),+ pa.array([{"inner": {"n": None, "s": None}, "tags": []}, None], DEEP_T),+ pa.array([None, {"inner": None, "tags": [None]}], DEEP_T),+ ),+}++[email protected]("case", VALUE_CASES, ids=list(VALUE_CASES))+def test_value_column_type_parity(case, tmp_path):+ init, upd1, upd2 = VALUE_CASES[case]+ uri_m, uri_u = _dual(tmp_path, case, _val_table(["a", "b", "c"], init))+ batches = [+ _val_table(["b", "d"], upd1), # update one existing + insert one+ _val_table(["a", "d"], upd2), # forces reading back deltalite-written files+ ]+ _assert_type_parity(uri_m, uri_u, batches, ["id"], case)+++def test_null_typed_column_deltalite_errors_where_merge_succeeds(tmp_path):+ """FINDING (executable): a `pa.null()` column becomes Delta type 'void' at create+ time. MERGE handles the table; deltalite fails to open a writer for it+ ("Kernel error: Unsupported Delta table type: 'void'", surfaced from+ `RecordBatchWriter::for_table` in src/upsert.rs). Pinned so a fix is loud.+ """+ import deltalite++ init = _val_table(["a", "b"], pa.array([None, None], pa.null()))+ uri_m, uri_u = _dual(tmp_path, "null_typed", init)+ batch = _val_table(["b", "c"], pa.array([None, None], pa.null()))++ merge_path(uri_m, batch, ["id"], PARTITION_KEY) # MERGE is fine with it+ assert len(read_sorted(uri_m)[0]) == 3++ with pytest.raises(deltalite.DeltaLiteError, match="void"):+ upsert_path(uri_u, batch, ["id"], PARTITION_KEY)+ assert deltalake.DeltaTable(uri_u).version() == 0 # nothing committed+++# --------------------------------------------------------------------------------------+# Primary-key columns: the type under test IS the PK.+# --------------------------------------------------------------------------------------+++def _pk_table(keys, key_type, v):+ n = len(keys)+ return pa.table(+ {+ "k": pa.array(keys, key_type) if key_type is not None else keys,+ "v": pa.array([v] * n, pa.int64()),+ PARTITION_KEY: pa.array(["2026-07-23"] * n, pa.string()),+ }+ )+++# (type, initial keys, batch keys) -- batch overlaps initial so both a match and an+# insert are exercised; a NULL key is included where the type admits one, pinning the+# NULL-never-matches rule per type.+PK_CASES = {+ "int8": (pa.int8(), [1, 2, None], [2, 3, None]),+ "int16": (pa.int16(), [1, -2, None], [-2, 3, None]),+ "int32": (pa.int32(), [1, 2, None], [2, 3, None]),+ "int64": (pa.int64(), [2**40, -(2**40), None], [2**40, 3, None]),+ "bool": (pa.bool_(), [True, False], [True]),+ "float32": (pa.float32(), [1.5, 2.5, None], [2.5, 3.5, None]),+ "float64": (pa.float64(), [1.5, 2.5, None], [2.5, 3.5, None]),+ "binary": (pa.binary(), [b"\x00a", b"b", None], [b"b", b"c", None]),+ "large_string": (pa.large_string(), ["a", "b", None], ["b", "c", None]),+ "date32": (+ pa.date32(),+ [datetime.date(2026, 1, 1), datetime.date(2026, 1, 2), None],+ [datetime.date(2026, 1, 2), datetime.date(2026, 1, 3), None],+ ),+ "timestamp": (+ pa.timestamp("us"),+ [TS, TS + datetime.timedelta(seconds=1), None],+ [TS, TS + datetime.timedelta(days=1), None],+ ),+ "timestamp_tz": (+ pa.timestamp("us", tz="UTC"),+ [TS.replace(tzinfo=UTC), None],+ [TS.replace(tzinfo=UTC), TS.replace(tzinfo=UTC) + datetime.timedelta(days=1), None],+ ),+ "decimal128": (+ pa.decimal128(10, 2),+ [D("1.10"), D("2.20"), None],+ [D("2.20"), D("-3.30"), None],+ ),+ "decimal_wide": (+ pa.decimal128(38, 10),+ [D("12345678901234567890.0123456789"), None],+ [D("12345678901234567890.0123456789"), D("1.5"), None],+ ),+}++[email protected]("case", PK_CASES, ids=list(PK_CASES))+def test_pk_type_parity(case, tmp_path):+ key_type, init_keys, batch_keys = PK_CASES[case]+ uri_m, uri_u = _dual(tmp_path, case, _pk_table(init_keys, key_type, 1))+ _assert_type_parity(uri_m, uri_u, [_pk_table(batch_keys, key_type, 2)], ["k"], case)+++def test_pk_dictionary_encoded_parity(tmp_path):+ """A dictionary-encoded PK column must probe against plain-encoded target files."""+ init = _pk_table(pa.array(["a", "b"]).dictionary_encode(), None, 1)+ uri_m, uri_u = _dual(tmp_path, "pk_dict", init)+ batch = _pk_table(pa.array(["b", "c"]).dictionary_encode(), None, 2)+ _assert_type_parity(uri_m, uri_u, [batch], ["k"], "pk_dict")+++def test_composite_pk_mixed_types_parity(tmp_path):+ """Composite PK across (string, int64, timestamp) with a NULL in each component."""++ def mk(rows, v):+ return pa.table(+ {+ "s": pa.array([r[0] for r in rows], pa.string()),+ "n": pa.array([r[1] for r in rows], pa.int64()),+ "t": pa.array([r[2] for r in rows], pa.timestamp("us")),+ "v": pa.array([v] * len(rows), pa.int64()),+ PARTITION_KEY: pa.array(["2026-07-23"] * len(rows), pa.string()),+ }+ )++ init = mk([("a", 1, TS), ("a", 2, TS), (None, 1, TS), ("b", None, TS), ("c", 1, None)], 1)+ batch = mk([("a", 2, TS), ("a", 3, TS), (None, 1, TS), ("b", None, TS), ("c", 1, None)], 2)+ uri_m, uri_u = _dual(tmp_path, "mixed_composite", init)+ _assert_type_parity(uri_m, uri_u, [batch], ["s", "n", "t"], "mixed_composite")+++# --------------------------------------------------------------------------------------+# Float PK sharp edges, pinned ABSOLUTELY on both paths (cross-path equality alone+# cannot catch both being wrong the same way). The design flagged these as a risk;+# measured behavior is that the two paths agree:+# * -0.0 does NOT match 0.0 (both treat them as distinct keys -> insert);+# * NaN DOES match NaN (both treat NaN as equal to itself -> update).+# --------------------------------------------------------------------------------------+++def _float_content(uri):+ tbl = deltalake.DeltaTable(uri).to_pyarrow_table()+ ks = [str(k) for k in tbl["k"].to_pylist()] # str() distinguishes -0.0 from 0.0+ return sorted(zip(ks, tbl["v"].to_pylist()))++[email protected]("path_name", ["merge", "upsert"])+def test_float_pk_negative_zero_absolute(tmp_path, path_name):+ path = merge_path if path_name == "merge" else upsert_path+ uri = str(tmp_path / f"negzero_{path_name}")+ create_table(uri, _pk_table([0.0, 1.5], pa.float64(), 1), True)++ path(uri, _pk_table([-0.0], pa.float64(), 2), ["k"], PARTITION_KEY)++ # -0.0 is a DISTINCT key: it inserts, and the 0.0 row is untouched+ assert _float_content(uri) == [("-0.0", 2), ("0.0", 1), ("1.5", 1)]++[email protected]("path_name", ["merge", "upsert"])+def test_float_pk_nan_absolute(tmp_path, path_name):+ path = merge_path if path_name == "merge" else upsert_path+ uri = str(tmp_path / f"nan_{path_name}")+ create_table(uri, _pk_table([float("nan"), 1.5], pa.float64(), 1), True)++ path(uri, _pk_table([float("nan")], pa.float64(), 2), ["k"], PARTITION_KEY)++ # NaN MATCHES the existing NaN row: update, no duplicate NaN row+ assert _float_content(uri) == [("1.5", 1), ("nan", 2)]++[email protected]("path_name", ["merge", "upsert"])+def test_float_pk_infinities_absolute(tmp_path, path_name):+ path = merge_path if path_name == "merge" else upsert_path+ uri = str(tmp_path / f"inf_{path_name}")+ create_table(uri, _pk_table([float("inf"), float("-inf")], pa.float64(), 1), True)++ path(uri, _pk_table([float("inf"), 0.5], pa.float64(), 2), ["k"], PARTITION_KEY)++ assert _float_content(uri) == [("-inf", 1), ("0.5", 2), ("inf", 2)]