From 8bd4d3a6ca25be470b2aa3ec2c66f0b378d1d4f3 Mon Sep 17 00:00:00 2001 From: Annie Liang Date: Mon, 15 Jun 2026 09:42:24 -0700 Subject: [PATCH 1/5] perf(cosmos): strip unused fields when constructing PartitionKeyRange from ObjectNode Reduce per-instance memory footprint of every PartitionKeyRange the SDK deserializes from a service response by removing fields the SDK does not need to retain in heap. Implementation moved into PartitionKeyRange(ObjectNode) -- the universal constructor funnel used by JsonSerializable#instantiateFromObjectNodeAndType for every FeedResponse page (and the change-feed deserialization path). All ingress paths that matter to memory pressure flow through this ctor, so the strip happens once at the boundary and the RxPartitionKeyRangeCache requires no change. Dropped fields are kept identical to the equivalent Python optimization in https://github.com/Azure/azure-sdk-for-python/pull/46297 to keep cross-SDK behaviour aligned: Dropped: _rid, _etag, ridPrefix, _self, ownedArchivalPKRangeIds, _ts, lsn Kept: id, minInclusive, maxExclusive, parents, throughputFraction, status, _lsn, and any future field the service starts returning (deny-list, not allow-list). Cross-SDK consistency matters here: a field that Java does not consume today may become useful tomorrow, and aligning with Python's audited deny-list ensures both SDKs make the same memory-vs-future-flexibility trade-off in one place. The ObjectNode argument is mutated in place rather than deep-copied because every production caller obtains it fresh from Jackson deserialization and does not retain another reference. Tests that need to preserve a fully-populated source object can use ObjectNode#deepCopy before handing it to the constructor. The (String) ctor is intentionally untouched -- it is used only by tests/samples that may want full-fidelity round-trip JSON, and a unit test pins that behaviour. PartitionKeyRange#equals / #hashCode already key on id/min/max only, so slim instances remain value-equal to manually-constructed ones. No public-API or wire change. PartitionKeyRange itself is in the com.azure.cosmos.implementation package. New unit tests in PartitionKeyRangeTest cover: - all 7 deny-listed fields are removed via the ObjectNode ctor - throughputFraction, status, _lsn, parents all preserved - unknown future field passes through (deny-list semantics) - non-empty parents preserved (split-merge bookkeeping) - equals / hashCode / toRange behaviour unchanged - null ObjectNode is tolerated (pre-existing contract) - String ctor retains full fidelity - JsonSerializable.instantiateFromObjectNodeAndType (FeedResponse funnel) routes through the stripped ctor Full mvn -P unit verify on azure-cosmos-tests: 2536 tests, 0 failures. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../implementation/PartitionKeyRangeTest.java | 174 ++++++++++++++++++ sdk/cosmos/azure-cosmos/CHANGELOG.md | 3 + .../implementation/PartitionKeyRange.java | 49 ++++- 3 files changed, 223 insertions(+), 3 deletions(-) create mode 100644 sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java new file mode 100644 index 000000000000..07e67fe29b3f --- /dev/null +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java @@ -0,0 +1,174 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.cosmos.implementation; + +import com.azure.cosmos.implementation.routing.Range; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.testng.annotations.Test; + +import java.util.Arrays; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +/** + * Tests for {@link PartitionKeyRange}, focused on the memory-saving "strip unused fields" behavior + * applied when constructing from a Jackson {@link ObjectNode}. + * + *

The strip set is intentionally kept aligned with + * azure-sdk-for-python#46297. + * These tests pin that contract.

+ */ +public class PartitionKeyRangeTest { + + private static final ObjectMapper MAPPER = Utils.getSimpleObjectMapper(); + + /** Mirrors the JSON shape the Cosmos DB service returns for a partition key range. */ + private static final String FULL_PK_RANGE_JSON = + "{" + + "\"_rid\":\"90t-ALzvP44CAAAAAAAAUA==\"," + + "\"id\":\"0\"," + + "\"_etag\":\"\\\"00001e02-0000-0800-0000-6a2c41690000\\\"\"," + + "\"minInclusive\":\"\"," + + "\"maxExclusive\":\"FF\"," + + "\"ridPrefix\":0," + + "\"_self\":\"dbs/90t-AA==/colls/90t-ALzvP44=/pkranges/90t-ALzvP44CAAAAAAAAUA==/\"," + + "\"throughputFraction\":1," + + "\"status\":\"online\"," + + "\"parents\":[]," + + "\"ownedArchivalPKRangeIds\":[]," + + "\"_ts\":1781285225," + + "\"lsn\":87," + + "\"_lsn\":87" + + "}"; + + private static ObjectNode fullPkRangeNode() throws Exception { + return (ObjectNode) MAPPER.readTree(FULL_PK_RANGE_JSON); + } + + @Test(groups = "unit") + public void objectNodeConstructor_stripsPythonAlignedFieldSet() throws Exception { + // Pin the deny-list to the exact set agreed across SDKs (Python PR 46297). + ObjectNode node = fullPkRangeNode(); + PartitionKeyRange range = new PartitionKeyRange(node); + + // Fields that MUST be dropped. + assertEquals(range.has("_rid"), false, "_rid must be stripped"); + assertEquals(range.has("_etag"), false, "_etag must be stripped"); + assertEquals(range.has("ridPrefix"), false, "ridPrefix must be stripped"); + assertEquals(range.has("_self"), false, "_self must be stripped"); + assertEquals(range.has("ownedArchivalPKRangeIds"), false, "ownedArchivalPKRangeIds must be stripped"); + assertEquals(range.has("_ts"), false, "_ts must be stripped"); + assertEquals(range.has("lsn"), false, "lsn must be stripped"); + } + + @Test(groups = "unit") + public void objectNodeConstructor_preservesFieldsNotOnDropList() throws Exception { + // Forward-compat: fields not on the deny-list pass through even if the Java SDK + // does not currently consume them. This matches Python's choice and protects + // future usage. + ObjectNode node = fullPkRangeNode(); + PartitionKeyRange range = new PartitionKeyRange(node); + + // Routing-map essentials. + assertEquals(range.getId(), "0"); + assertEquals(range.getMinInclusive(), ""); + assertEquals(range.getMaxExclusive(), "FF"); + assertNotNull(range.getParents()); + assertEquals(range.getParents().size(), 0); + + // Not currently consumed but kept (mirrors Python). + assertTrue(range.has("throughputFraction"), "throughputFraction should be preserved"); + assertTrue(range.has("status"), "status should be preserved"); + assertTrue(range.has("_lsn"), "_lsn should be preserved"); + assertTrue(range.has("parents"), "parents should be preserved"); + } + + @Test(groups = "unit") + public void objectNodeConstructor_passesThroughUnknownFutureField() throws Exception { + // Deny-list (not allow-list) semantics: a new server-side field tomorrow is preserved + // automatically with zero SDK change. + String json = "{" + + "\"id\":\"0\",\"minInclusive\":\"\",\"maxExclusive\":\"FF\"," + + "\"_rid\":\"X==\"," // dropped + + "\"futureFieldA\":\"hello\"," // not on drop list -> kept + + "\"futureFieldB\":{\"nested\":42}" // not on drop list -> kept + + "}"; + ObjectNode node = (ObjectNode) MAPPER.readTree(json); + PartitionKeyRange range = new PartitionKeyRange(node); + + assertEquals(range.has("_rid"), false); + assertTrue(range.has("futureFieldA"), "unknown future field must pass through"); + assertTrue(range.has("futureFieldB"), "unknown future nested field must pass through"); + } + + @Test(groups = "unit") + public void objectNodeConstructor_preservesNonEmptyParents() throws Exception { + // Split-merge bookkeeping uses parents; verify it survives the strip. + String json = "{" + + "\"_rid\":\"X==\",\"id\":\"1\",\"_etag\":\"\\\"e\\\"\"," + + "\"minInclusive\":\"\",\"maxExclusive\":\"FF\"," + + "\"_self\":\"x/\",\"parents\":[\"0\"],\"_ts\":1,\"lsn\":1" + + "}"; + ObjectNode node = (ObjectNode) MAPPER.readTree(json); + PartitionKeyRange range = new PartitionKeyRange(node); + + assertNotNull(range.getParents()); + assertEquals(range.getParents().size(), 1); + assertEquals(range.getParents().get(0), "0"); + // Dropped fields still gone. + assertEquals(range.has("_rid"), false); + assertEquals(range.has("_self"), false); + assertEquals(range.has("lsn"), false); + } + + @Test(groups = "unit") + public void objectNodeConstructor_equalsAndHashCodeUnchanged() throws Exception { + // PartitionKeyRange#equals / #hashCode use id/min/max only -- the slim instance must + // remain value-equal to a manually-constructed instance with the same identity fields. + ObjectNode node = fullPkRangeNode(); + PartitionKeyRange slim = new PartitionKeyRange(node); + PartitionKeyRange handBuilt = new PartitionKeyRange("0", "", "FF"); + + assertEquals(slim, handBuilt); + assertEquals(slim.hashCode(), handBuilt.hashCode()); + assertEquals(slim.toRange(), new Range<>("", "FF", true, false)); + } + + @Test(groups = "unit") + public void objectNodeConstructor_handlesNull() { + // Defensive: a null ObjectNode argument must not throw; super(null) is the existing + // pre-PR contract and must be preserved. + new PartitionKeyRange((ObjectNode) null); + } + + @Test(groups = "unit") + public void stringConstructor_isUnaffectedByStrip() { + // The (String) ctor goes through a different superclass path (JsonSerializable(String)) + // and is used by tests/samples that may want full fidelity for round-trip JSON. It is + // intentionally NOT touched by the strip optimization; this test pins that. + PartitionKeyRange range = new PartitionKeyRange(FULL_PK_RANGE_JSON); + assertEquals(range.has("_rid"), true, "string-ctor PKR retains full fidelity"); + assertEquals(range.has("_self"), true, "string-ctor PKR retains full fidelity"); + } + + @Test(groups = "unit") + public void deserializationFunnelStripsForFeedResponsePath() throws Exception { + // JsonSerializable.instantiateFromObjectNodeAndType is the funnel every FeedResponse + // page uses when deserializing pkranges. Confirm it routes through the + // PartitionKeyRange(ObjectNode) ctor and therefore inherits the strip. + ObjectNode node = fullPkRangeNode(); + Object result = + JsonSerializable.instantiateFromObjectNodeAndType(node, PartitionKeyRange.class); + + assertTrue(result instanceof PartitionKeyRange); + PartitionKeyRange range = (PartitionKeyRange) result; + for (String dropped : Arrays.asList( + "_rid", "_etag", "ridPrefix", "_self", "ownedArchivalPKRangeIds", "_ts", "lsn")) { + assertEquals(range.has(dropped), false, dropped + " must be stripped via FeedResponse funnel"); + } + assertEquals(range.getId(), "0"); + } +} diff --git a/sdk/cosmos/azure-cosmos/CHANGELOG.md b/sdk/cosmos/azure-cosmos/CHANGELOG.md index 5146e18db2e8..4e0090254c2c 100644 --- a/sdk/cosmos/azure-cosmos/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos/CHANGELOG.md @@ -10,6 +10,9 @@ #### Other Changes +#### Other Changes +* Reduced memory footprint of deserialized `PartitionKeyRange` instances by stripping unused fields in the `PartitionKeyRange(ObjectNode)` constructor — the universal funnel for every partition key range the SDK deserializes from a service response (FeedResponse pages, change feed, etc.). The dropped fields (`_rid`, `_etag`, `ridPrefix`, `_self`, `ownedArchivalPKRangeIds`, `_ts`, `lsn`) match the explicit deny-list from the equivalent [Python optimization](https://github.com/Azure/azure-sdk-for-python/pull/46297) so the cross-SDK choice stays aligned. All other fields (including ones not currently consumed by the Java SDK such as `throughputFraction`, `status`, `_lsn`, plus any future server-added field) pass through unchanged. Per-client routing-map heap reduction scales as `O(clients × collections × pkRanges)` and is material for accounts with many physical partitions. + ### 4.81.0 (2026-06-08) #### Features Added diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java index 4488426683d0..66a48e20ed62 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java @@ -16,14 +16,57 @@ public class PartitionKeyRange extends Resource { public static final String MAXIMUM_EXCLUSIVE_EFFECTIVE_PARTITION_KEY = "FF"; public static final String MASTER_PARTITION_KEY_RANGE_ID = "M"; + /** + * Fields the Cosmos DB service returns on every partition key range that the SDK does not + * need to retain in heap for the lifetime of the {@link com.azure.cosmos.implementation.routing.CollectionRoutingMap}. + * + *

The set is kept in lock-step with the equivalent Python optimization in + * azure-sdk-for-python#46297 + * (item #2 — "Strip unused fields → compact PKRange"). Cross-SDK alignment is intentional: + * a field that Java does not consume today may be wired up tomorrow, so the call about + * what is safe to drop is made once across the SDKs rather than re-derived per-language.

+ * + *

The list is a deny-list, not an allow-list, so any future field added by the service is + * preserved automatically with no SDK change.

+ */ + private static final String[] DROPPED_FIELDS = new String[] { + "_rid", + "_etag", + "ridPrefix", + "_self", + "ownedArchivalPKRangeIds", + "_ts", + "lsn" + }; + /** * Constructor. * - * @param objectNode the {@link ObjectNode} that represent the - * {@link JsonSerializable} + *

Fields listed in {@link #DROPPED_FIELDS} are removed from {@code objectNode} as part of + * construction so the resulting instance retains only the fields the SDK actually needs. + * This is the universal funnel for every {@code PartitionKeyRange} the SDK deserializes from + * a service response (see {@link JsonSerializable#instantiateFromObjectNodeAndType}), so the + * memory saving applies to all routing-map cache entries and any other code path that + * consumes deserialized partition key ranges.

+ * + *

The argument is mutated in place. This is safe because every production caller obtains + * {@code objectNode} from Jackson deserialization and does not retain another reference to + * it. Tests that need to preserve a fully-populated source object should use + * {@code objectNode.deepCopy()} before handing it to this constructor.

+ * + * @param objectNode the {@link ObjectNode} that represents the {@link JsonSerializable} */ public PartitionKeyRange(ObjectNode objectNode) { - super(objectNode); + super(stripUnusedFields(objectNode)); + } + + private static ObjectNode stripUnusedFields(ObjectNode objectNode) { + if (objectNode != null) { + for (String field : DROPPED_FIELDS) { + objectNode.remove(field); + } + } + return objectNode; } /** From 0be5ba7cf90a1868a319a53c2c712396da8b6722 Mon Sep 17 00:00:00 2001 From: Annie Liang Date: Mon, 15 Jun 2026 13:38:06 -0700 Subject: [PATCH 2/5] Switch PartitionKeyRange field strip to allow-list (Python parity) Replace the deny-list of 7 known service fields with an allow-list of the 6 fields the SDK actually needs: id, minInclusive, maxExclusive, parents, status, throughputFraction. This mirrors the slots of Python's PKRange namedtuple in Azure/azure-sdk-for-python#46297 and bounds per-instance heap against any future server-side payload growth. Previously the deny-list let new or undocumented fields (e.g. _lsn, or anything the service may add later) silently inflate the cache. Tests updated to pin allow-list semantics, including a test that an unknown future field is dropped rather than passed through. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../implementation/PartitionKeyRangeTest.java | 69 ++++++++++--------- sdk/cosmos/azure-cosmos/CHANGELOG.md | 2 +- .../implementation/PartitionKeyRange.java | 50 ++++++++------ 3 files changed, 66 insertions(+), 55 deletions(-) diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java index 07e67fe29b3f..319d745aa18e 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java @@ -8,6 +8,7 @@ import org.testng.annotations.Test; import java.util.Arrays; +import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; @@ -17,9 +18,9 @@ * Tests for {@link PartitionKeyRange}, focused on the memory-saving "strip unused fields" behavior * applied when constructing from a Jackson {@link ObjectNode}. * - *

The strip set is intentionally kept aligned with - * azure-sdk-for-python#46297. - * These tests pin that contract.

+ *

The retained-field set is intentionally kept aligned with + * azure-sdk-for-python#46297 + * (Python's {@code PKRange} namedtuple). These tests pin that contract.

*/ public class PartitionKeyRangeTest { @@ -44,31 +45,36 @@ public class PartitionKeyRangeTest { + "\"_lsn\":87" + "}"; + /** + * Allow-list aligned with Python's {@code PKRange} namedtuple slots + * ({@code id}, {@code minInclusive}, {@code maxExclusive}, {@code parents}, + * {@code status}, {@code throughputFraction}). + */ + private static final List KEPT_FIELDS = Arrays.asList( + "id", "minInclusive", "maxExclusive", "parents", "status", "throughputFraction"); + + /** All non-kept fields present in the full payload above; everything here must be stripped. */ + private static final List STRIPPED_FIELDS = Arrays.asList( + "_rid", "_etag", "ridPrefix", "_self", "ownedArchivalPKRangeIds", "_ts", "lsn", "_lsn"); + private static ObjectNode fullPkRangeNode() throws Exception { return (ObjectNode) MAPPER.readTree(FULL_PK_RANGE_JSON); } @Test(groups = "unit") - public void objectNodeConstructor_stripsPythonAlignedFieldSet() throws Exception { - // Pin the deny-list to the exact set agreed across SDKs (Python PR 46297). + public void objectNodeConstructor_stripsEverythingNotOnAllowList() throws Exception { + // Pin the allow-list: every field not on Python's PKRange namedtuple must be dropped. ObjectNode node = fullPkRangeNode(); PartitionKeyRange range = new PartitionKeyRange(node); - // Fields that MUST be dropped. - assertEquals(range.has("_rid"), false, "_rid must be stripped"); - assertEquals(range.has("_etag"), false, "_etag must be stripped"); - assertEquals(range.has("ridPrefix"), false, "ridPrefix must be stripped"); - assertEquals(range.has("_self"), false, "_self must be stripped"); - assertEquals(range.has("ownedArchivalPKRangeIds"), false, "ownedArchivalPKRangeIds must be stripped"); - assertEquals(range.has("_ts"), false, "_ts must be stripped"); - assertEquals(range.has("lsn"), false, "lsn must be stripped"); + for (String dropped : STRIPPED_FIELDS) { + assertEquals(range.has(dropped), false, dropped + " must be stripped (not on allow-list)"); + } } @Test(groups = "unit") - public void objectNodeConstructor_preservesFieldsNotOnDropList() throws Exception { - // Forward-compat: fields not on the deny-list pass through even if the Java SDK - // does not currently consume them. This matches Python's choice and protects - // future usage. + public void objectNodeConstructor_preservesAllowListedFields() throws Exception { + // Every field on the allow-list must survive the strip. ObjectNode node = fullPkRangeNode(); PartitionKeyRange range = new PartitionKeyRange(node); @@ -79,29 +85,27 @@ public void objectNodeConstructor_preservesFieldsNotOnDropList() throws Exceptio assertNotNull(range.getParents()); assertEquals(range.getParents().size(), 0); - // Not currently consumed but kept (mirrors Python). - assertTrue(range.has("throughputFraction"), "throughputFraction should be preserved"); - assertTrue(range.has("status"), "status should be preserved"); - assertTrue(range.has("_lsn"), "_lsn should be preserved"); - assertTrue(range.has("parents"), "parents should be preserved"); + for (String kept : KEPT_FIELDS) { + assertTrue(range.has(kept), kept + " must be preserved (on allow-list)"); + } } @Test(groups = "unit") - public void objectNodeConstructor_passesThroughUnknownFutureField() throws Exception { - // Deny-list (not allow-list) semantics: a new server-side field tomorrow is preserved - // automatically with zero SDK change. + public void objectNodeConstructor_dropsUnknownFutureField() throws Exception { + // Allow-list (not deny-list) semantics: a new server-side field tomorrow is dropped + // by default so per-instance heap stays bounded against payload growth. Mirrors + // Python's PKRange namedtuple, which has no slot for unknown fields. String json = "{" + "\"id\":\"0\",\"minInclusive\":\"\",\"maxExclusive\":\"FF\"," - + "\"_rid\":\"X==\"," // dropped - + "\"futureFieldA\":\"hello\"," // not on drop list -> kept - + "\"futureFieldB\":{\"nested\":42}" // not on drop list -> kept + + "\"futureFieldA\":\"hello\"," + + "\"futureFieldB\":{\"nested\":42}" + "}"; ObjectNode node = (ObjectNode) MAPPER.readTree(json); PartitionKeyRange range = new PartitionKeyRange(node); - assertEquals(range.has("_rid"), false); - assertTrue(range.has("futureFieldA"), "unknown future field must pass through"); - assertTrue(range.has("futureFieldB"), "unknown future nested field must pass through"); + assertEquals(range.getId(), "0"); + assertEquals(range.has("futureFieldA"), false, "unknown future field must be dropped by allow-list"); + assertEquals(range.has("futureFieldB"), false, "unknown future nested field must be dropped by allow-list"); } @Test(groups = "unit") @@ -165,8 +169,7 @@ public void deserializationFunnelStripsForFeedResponsePath() throws Exception { assertTrue(result instanceof PartitionKeyRange); PartitionKeyRange range = (PartitionKeyRange) result; - for (String dropped : Arrays.asList( - "_rid", "_etag", "ridPrefix", "_self", "ownedArchivalPKRangeIds", "_ts", "lsn")) { + for (String dropped : STRIPPED_FIELDS) { assertEquals(range.has(dropped), false, dropped + " must be stripped via FeedResponse funnel"); } assertEquals(range.getId(), "0"); diff --git a/sdk/cosmos/azure-cosmos/CHANGELOG.md b/sdk/cosmos/azure-cosmos/CHANGELOG.md index 4e0090254c2c..be9dcb8f7e70 100644 --- a/sdk/cosmos/azure-cosmos/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos/CHANGELOG.md @@ -11,7 +11,7 @@ #### Other Changes #### Other Changes -* Reduced memory footprint of deserialized `PartitionKeyRange` instances by stripping unused fields in the `PartitionKeyRange(ObjectNode)` constructor — the universal funnel for every partition key range the SDK deserializes from a service response (FeedResponse pages, change feed, etc.). The dropped fields (`_rid`, `_etag`, `ridPrefix`, `_self`, `ownedArchivalPKRangeIds`, `_ts`, `lsn`) match the explicit deny-list from the equivalent [Python optimization](https://github.com/Azure/azure-sdk-for-python/pull/46297) so the cross-SDK choice stays aligned. All other fields (including ones not currently consumed by the Java SDK such as `throughputFraction`, `status`, `_lsn`, plus any future server-added field) pass through unchanged. Per-client routing-map heap reduction scales as `O(clients × collections × pkRanges)` and is material for accounts with many physical partitions. +* Reduced memory footprint of deserialized `PartitionKeyRange` instances by stripping unused fields in the `PartitionKeyRange(ObjectNode)` constructor — the universal funnel for every partition key range the SDK deserializes from a service response (FeedResponse pages, change feed, etc.). The retained fields (`id`, `minInclusive`, `maxExclusive`, `parents`, `status`, `throughputFraction`) mirror the slots of Python's `PKRange` namedtuple in the equivalent [Python optimization](https://github.com/Azure/azure-sdk-for-python/pull/46297) so the cross-SDK choice stays aligned. The implementation is an allow-list — any field not on this list (including any field added by the service in the future) is dropped, keeping per-instance heap bounded against payload growth. Per-client routing-map heap reduction scales as `O(clients × collections × pkRanges)` and is material for accounts with many physical partitions. ### 4.81.0 (2026-06-08) diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java index 66a48e20ed62..2c4755af21d9 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java @@ -6,7 +6,11 @@ import com.azure.cosmos.implementation.routing.Range; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Set; /** * Represent a partition key range in the Azure Cosmos DB database service. @@ -17,32 +21,38 @@ public class PartitionKeyRange extends Resource { public static final String MASTER_PARTITION_KEY_RANGE_ID = "M"; /** - * Fields the Cosmos DB service returns on every partition key range that the SDK does not - * need to retain in heap for the lifetime of the {@link com.azure.cosmos.implementation.routing.CollectionRoutingMap}. + * Fields of the Cosmos DB service partition key range payload that the SDK retains in heap + * for the lifetime of the {@link com.azure.cosmos.implementation.routing.CollectionRoutingMap}. * *

The set is kept in lock-step with the equivalent Python optimization in * azure-sdk-for-python#46297 * (item #2 — "Strip unused fields → compact PKRange"). Cross-SDK alignment is intentional: - * a field that Java does not consume today may be wired up tomorrow, so the call about - * what is safe to drop is made once across the SDKs rather than re-derived per-language.

+ * the call about which fields are needed is made once across SDKs rather than re-derived + * per-language, and both SDKs make the same memory-vs-future-flexibility trade-off.

* - *

The list is a deny-list, not an allow-list, so any future field added by the service is - * preserved automatically with no SDK change.

+ *

This is an allow-list: any field the service returns that is not in this set + * (including any field added by the service in the future) is dropped at construction. + * That keeps per-instance heap bounded against server-side payload growth. Adding a new + * field to the allow-list is a one-line change here when a consumer needs it.

+ * + *

The retained fields mirror the slots of Python's {@code PKRange} namedtuple: + * {@code id}, {@code minInclusive}, {@code maxExclusive}, {@code parents}, + * {@code status}, {@code throughputFraction}.

*/ - private static final String[] DROPPED_FIELDS = new String[] { - "_rid", - "_etag", - "ridPrefix", - "_self", - "ownedArchivalPKRangeIds", - "_ts", - "lsn" - }; + private static final Set KEPT_FIELDS = Collections.unmodifiableSet( + new HashSet<>(Arrays.asList( + Constants.Properties.ID, + "minInclusive", + "maxExclusive", + Constants.Properties.PARENTS, + "status", + "throughputFraction" + ))); /** * Constructor. * - *

Fields listed in {@link #DROPPED_FIELDS} are removed from {@code objectNode} as part of + *

Fields not listed in {@link #KEPT_FIELDS} are removed from {@code objectNode} as part of * construction so the resulting instance retains only the fields the SDK actually needs. * This is the universal funnel for every {@code PartitionKeyRange} the SDK deserializes from * a service response (see {@link JsonSerializable#instantiateFromObjectNodeAndType}), so the @@ -57,14 +67,12 @@ public class PartitionKeyRange extends Resource { * @param objectNode the {@link ObjectNode} that represents the {@link JsonSerializable} */ public PartitionKeyRange(ObjectNode objectNode) { - super(stripUnusedFields(objectNode)); + super(stripToKeptFields(objectNode)); } - private static ObjectNode stripUnusedFields(ObjectNode objectNode) { + private static ObjectNode stripToKeptFields(ObjectNode objectNode) { if (objectNode != null) { - for (String field : DROPPED_FIELDS) { - objectNode.remove(field); - } + objectNode.retain(KEPT_FIELDS); } return objectNode; } From 6901e6e2ec1294399f39c190518263b82c58cf6c Mon Sep 17 00:00:00 2001 From: Annie Liang Date: Mon, 15 Jun 2026 14:12:08 -0700 Subject: [PATCH 3/5] Address review: consolidate CHANGELOG entry under single Other Changes header - Remove duplicate '#### Other Changes' header (Copilot review comment). - Shorten the PR entry per xinlian12's suggestion, linking to the PR instead of restating the design in the changelog. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- sdk/cosmos/azure-cosmos/CHANGELOG.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/sdk/cosmos/azure-cosmos/CHANGELOG.md b/sdk/cosmos/azure-cosmos/CHANGELOG.md index be9dcb8f7e70..eee4f87437f9 100644 --- a/sdk/cosmos/azure-cosmos/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos/CHANGELOG.md @@ -9,9 +9,7 @@ #### Bugs Fixed #### Other Changes - -#### Other Changes -* Reduced memory footprint of deserialized `PartitionKeyRange` instances by stripping unused fields in the `PartitionKeyRange(ObjectNode)` constructor — the universal funnel for every partition key range the SDK deserializes from a service response (FeedResponse pages, change feed, etc.). The retained fields (`id`, `minInclusive`, `maxExclusive`, `parents`, `status`, `throughputFraction`) mirror the slots of Python's `PKRange` namedtuple in the equivalent [Python optimization](https://github.com/Azure/azure-sdk-for-python/pull/46297) so the cross-SDK choice stays aligned. The implementation is an allow-list — any field not on this list (including any field added by the service in the future) is dropped, keeping per-instance heap bounded against payload growth. Per-client routing-map heap reduction scales as `O(clients × collections × pkRanges)` and is material for accounts with many physical partitions. +* Reduced memory footprint of deserialized `PartitionKeyRange` instances by stripping unused fields in the `PartitionKeyRange(ObjectNode)` constructor - See PR [49513](https://github.com/Azure/azure-sdk-for-java/pull/49513). ### 4.81.0 (2026-06-08) From c62ed2022befc4e0329a1ba5a83ee520fa3fa65b Mon Sep 17 00:00:00 2001 From: Annie Liang Date: Mon, 15 Jun 2026 14:40:57 -0700 Subject: [PATCH 4/5] Keep _rid on PartitionKeyRange allow-list (fixes AddressResolver retry) Reviewer @xinlian12 (blocking) and the Kafka CI failure (CosmosSinkTaskTest.retryOnServiceUnavailable -> 'INVALID resource id null') both point at the same root cause: AddressResolver.isSameCollection() calls getResourceId() on PartitionKeyRange instances during target-change detection on a 410/Gone retry. Without _rid on the allow-list, ResourceId.parse(null) throws. Add _rid (Constants.Properties.R_ID) to KEPT_FIELDS. This is a Java-specific deviation from Python's PKRange namedtuple (Python's address-resolution path does not have the equivalent dependency); the rest of the allow-list still mirrors Python. Tests: - Update KEPT_FIELDS / STRIPPED_FIELDS in PartitionKeyRangeTest to reflect _rid is now retained. - Add the recommended getResourceId() assertion on a stripped instance. - Adjust the parents test to assert _rid survives instead of being stripped. Also revises the javadoc on KEPT_FIELDS to call out the Java-specific _rid retention with the exact AddressResolver reason, so future readers don't try to remove it again. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../implementation/PartitionKeyRangeTest.java | 22 ++++++++++++++----- .../implementation/PartitionKeyRange.java | 21 ++++++++++-------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java index 319d745aa18e..48a822425fe4 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java @@ -46,16 +46,20 @@ public class PartitionKeyRangeTest { + "}"; /** - * Allow-list aligned with Python's {@code PKRange} namedtuple slots + * Allow-list kept in heap on every deserialized {@link PartitionKeyRange}. + * + *

Includes Python's {@code PKRange} namedtuple slots * ({@code id}, {@code minInclusive}, {@code maxExclusive}, {@code parents}, - * {@code status}, {@code throughputFraction}). + * {@code status}, {@code throughputFraction}) plus {@code _rid} — Java-specific because + * {@code AddressResolver.isSameCollection} reads {@code getResourceId()} on a + * {@code PartitionKeyRange} during retry target-change detection.

*/ private static final List KEPT_FIELDS = Arrays.asList( - "id", "minInclusive", "maxExclusive", "parents", "status", "throughputFraction"); + "id", "minInclusive", "maxExclusive", "parents", "status", "throughputFraction", "_rid"); /** All non-kept fields present in the full payload above; everything here must be stripped. */ private static final List STRIPPED_FIELDS = Arrays.asList( - "_rid", "_etag", "ridPrefix", "_self", "ownedArchivalPKRangeIds", "_ts", "lsn", "_lsn"); + "_etag", "ridPrefix", "_self", "ownedArchivalPKRangeIds", "_ts", "lsn", "_lsn"); private static ObjectNode fullPkRangeNode() throws Exception { return (ObjectNode) MAPPER.readTree(FULL_PK_RANGE_JSON); @@ -85,6 +89,12 @@ public void objectNodeConstructor_preservesAllowListedFields() throws Exception assertNotNull(range.getParents()); assertEquals(range.getParents().size(), 0); + // _rid is on the allow-list specifically so AddressResolver.isSameCollection + // can call getResourceId() on a deserialized PartitionKeyRange during retry + // target-change detection. Without this, ResourceId.parse(null) throws + // "INVALID resource id null" on the first retry after a 410/Gone. + assertEquals(range.getResourceId(), "90t-ALzvP44CAAAAAAAAUA=="); + for (String kept : KEPT_FIELDS) { assertTrue(range.has(kept), kept + " must be preserved (on allow-list)"); } @@ -122,10 +132,10 @@ public void objectNodeConstructor_preservesNonEmptyParents() throws Exception { assertNotNull(range.getParents()); assertEquals(range.getParents().size(), 1); assertEquals(range.getParents().get(0), "0"); - // Dropped fields still gone. - assertEquals(range.has("_rid"), false); + // Dropped fields still gone. _rid stays now that it's on the allow-list. assertEquals(range.has("_self"), false); assertEquals(range.has("lsn"), false); + assertEquals(range.getResourceId(), "X=="); } @Test(groups = "unit") diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java index 2c4755af21d9..af26e84df06d 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java @@ -24,20 +24,22 @@ public class PartitionKeyRange extends Resource { * Fields of the Cosmos DB service partition key range payload that the SDK retains in heap * for the lifetime of the {@link com.azure.cosmos.implementation.routing.CollectionRoutingMap}. * - *

The set is kept in lock-step with the equivalent Python optimization in + *

The set is broadly aligned with the equivalent Python optimization in * azure-sdk-for-python#46297 - * (item #2 — "Strip unused fields → compact PKRange"). Cross-SDK alignment is intentional: - * the call about which fields are needed is made once across SDKs rather than re-derived - * per-language, and both SDKs make the same memory-vs-future-flexibility trade-off.

+ * (item #2 — "Strip unused fields → compact PKRange"), which retains + * {@code id}, {@code minInclusive}, {@code maxExclusive}, {@code parents}, + * {@code status}, and {@code throughputFraction}. Java additionally keeps {@code _rid} + * because {@link com.azure.cosmos.implementation.directconnectivity.AddressResolver#isSameCollection} + * calls {@code getResourceId()} on {@code PartitionKeyRange} instances during target-change + * detection on retry — stripping it would surface as {@code "INVALID resource id null"} + * from {@code ResourceId.parse(null)} the next time the SDK retries an address-staleness + * check (e.g. after a 410/Gone). Python's address-resolution path does not have the + * equivalent dependency, so the SDKs intentionally diverge on this one field.

* *

This is an allow-list: any field the service returns that is not in this set * (including any field added by the service in the future) is dropped at construction. * That keeps per-instance heap bounded against server-side payload growth. Adding a new * field to the allow-list is a one-line change here when a consumer needs it.

- * - *

The retained fields mirror the slots of Python's {@code PKRange} namedtuple: - * {@code id}, {@code minInclusive}, {@code maxExclusive}, {@code parents}, - * {@code status}, {@code throughputFraction}.

*/ private static final Set KEPT_FIELDS = Collections.unmodifiableSet( new HashSet<>(Arrays.asList( @@ -46,7 +48,8 @@ public class PartitionKeyRange extends Resource { "maxExclusive", Constants.Properties.PARENTS, "status", - "throughputFraction" + "throughputFraction", + Constants.Properties.R_ID ))); /** From e4d84323ba292f71806a852d5fcce7d87a7958e0 Mon Sep 17 00:00:00 2001 From: Annie Liang Date: Tue, 16 Jun 2026 08:51:55 -0700 Subject: [PATCH 5/5] Remove unused PartitionKeyRange(String) constructor The single-arg JSON constructor was only used by the now-removed stringConstructor_isUnaffectedByStrip test. No production code calls it (the deserialization funnel uses PartitionKeyRange(ObjectNode) via JsonSerializable.instantiateFromObjectNodeAndType). Removing it eliminates a path that bypasses the allow-list strip. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../cosmos/implementation/PartitionKeyRangeTest.java | 10 ---------- .../cosmos/implementation/PartitionKeyRange.java | 11 ----------- 2 files changed, 21 deletions(-) diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java index 48a822425fe4..339f3f95ad53 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/PartitionKeyRangeTest.java @@ -158,16 +158,6 @@ public void objectNodeConstructor_handlesNull() { new PartitionKeyRange((ObjectNode) null); } - @Test(groups = "unit") - public void stringConstructor_isUnaffectedByStrip() { - // The (String) ctor goes through a different superclass path (JsonSerializable(String)) - // and is used by tests/samples that may want full fidelity for round-trip JSON. It is - // intentionally NOT touched by the strip optimization; this test pins that. - PartitionKeyRange range = new PartitionKeyRange(FULL_PK_RANGE_JSON); - assertEquals(range.has("_rid"), true, "string-ctor PKR retains full fidelity"); - assertEquals(range.has("_self"), true, "string-ctor PKR retains full fidelity"); - } - @Test(groups = "unit") public void deserializationFunnelStripsForFeedResponsePath() throws Exception { // JsonSerializable.instantiateFromObjectNodeAndType is the funnel every FeedResponse diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java index af26e84df06d..6488d1d57b4d 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java @@ -87,17 +87,6 @@ public PartitionKeyRange() { super(); } - /** - * Initialize a partition key range object from json string. - * - * @param jsonString - * the json string that represents the partition key range - * object. - */ - public PartitionKeyRange(String jsonString) { - super(jsonString); - } - /** * Set id of partition key range * @param id the name of the resource.