perf(environment): compare recorded state without serializing JSON (#12255)

This commit is contained in:
ShuaixinHuang authored and GitHub committed 2026-11-19 06:16:01 -05:00
1 parent 3506672e9f
commit 09f59494e2
2 files changed
+46 -7

No files matched your search

@@ -7,7 +7,6 @@ import {
import type { OffsetDateTimeInstant } from "../offsetDateTime.js";
import type { StateRecordChronology } from "./StateRecordChronology.js";
import type { ListQuery } from "./environmentStateListQuery.js";
import { canonicalJson } from "../comparisonSemantics.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import type { JsonValue } from "../jsonValue.js";
import type { StateWritePlan } from "./environmentStateWriteRules.js";
@@ -350,15 +349,36 @@ export const setOwnMember = (
});
};
/** Equal JSON values; object member order carries no meaning. */
/** Equal admitted JSON values. Object member order carries no meaning. */
export const same = (
left: JsonValue | undefined,
right: JsonValue | undefined,
): boolean =>
left === undefined || right === undefined
? left === right
: canonicalJson(left, "Environment state") ===
canonicalJson(right, "Environment state");
): boolean => {
if (left === right) return true;
if (
left === null ||
right === null ||
typeof left !== "object" ||
typeof right !== "object"
)
return false;
if (Array.isArray(left)) {
if (!Array.isArray(right) || left.length !== right.length) return false;
for (let index = 0; index < left.length; index++)
if (!same(left[index], right[index])) return false;
return true;
}
if (Array.isArray(right)) return false;
const keys = Object.keys(left);
if (keys.length !== Object.keys(right).length) return false;
for (const key of keys)
if (
!Object.prototype.propertyIsEnumerable.call(right, key) ||
!same(left[key], right[key])
)
return false;
return true;
};
/** A path segment percent-decoded, or as written when it does not decode. */
export const decodedSegment = (segment: string): string => {
@@ -27,6 +27,7 @@ import {
identityCandidates,
replaceAt,
renderStateList,
same,
type JsonObject,
type StateRecordFacts,
} from "./environmentStateRules.js";
@@ -2186,3 +2187,21 @@ it.each([true, false])(
).toBe(false);
},
);
it("compares admitted state values by JSON meaning and preserves own keys", () => {
const left = ownedJsonObjectSchema.parse(
JSON.parse('{"__proto__":{"q":1},"value":[-0,"𐐷"],"nested":{"b":2,"a":1}}'),
);
const right = ownedJsonObjectSchema.parse(
JSON.parse('{"nested":{"a":1,"b":2},"value":[0,"𐐷"],"__proto__":{"q":1}}'),
);
expect(same(left, right)).toBe(true);
expect(same(left, { ...right, value: ["𐐷", 0] })).toBe(false);
expect(same({ value: null }, { other: null })).toBe(false);
const hidden = Object.defineProperty({ other: null }, "value", {
value: null,
});
expect(same({ value: null }, hidden)).toBe(false);
expect(same(undefined, null)).toBe(false);
expect(same({ constructor: 1 }, { constructor: 2 })).toBe(false);
});