Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 51 additions & 18 deletions loopx/control_plane/coordination/authority_store_codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@ export function isAuthorityJsonObject(value: unknown): value is JsonObject {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

export function authorityUnicodeCompare(left: string, right: string): number {
// Walk code points without allocating two arrays for every sort comparison.
// JS's default sort compares UTF-16 units, which would change persisted
// revisions for supplementary characters relative to BMP characters.
let leftIndex = 0, rightIndex = 0;
function compareCodePointsFrom(left: string, right: string, startIndex: number): number {
let leftIndex = startIndex;
let rightIndex = startIndex;
while (leftIndex < left.length && rightIndex < right.length) {
const leftPoint = left.codePointAt(leftIndex)!;
const rightPoint = right.codePointAt(rightIndex)!;
Expand All @@ -25,6 +23,24 @@ export function authorityUnicodeCompare(left: string, right: string): number {
return leftIndex < left.length ? 1 : rightIndex < right.length ? -1 : 0;
}

export function authorityUnicodeCompare(left: string, right: string): number {
// Fast-path code-unit comparison below 0xD800 where UTF-16 order matches
// Unicode code-point order, falling back cleanly for any surrogate units.
const limit = Math.min(left.length, right.length);
for (let index = 0; index < limit; index++) {
const leftUnit = left.charCodeAt(index);
const rightUnit = right.charCodeAt(index);
if (leftUnit !== rightUnit) {
if (leftUnit < 0xd800 && rightUnit < 0xd800) return leftUnit - rightUnit;
return compareCodePointsFrom(left, right, index);
}
if (leftUnit >= 0xd800 && leftUnit <= 0xdfff) {
return compareCodePointsFrom(left, right, index);
}
}
return left.length - right.length;
}

export function hasExactAuthorityKeys(
value: JsonObject,
keys: readonly string[],
Expand Down Expand Up @@ -111,6 +127,15 @@ export function copyAuthorityJson(value: unknown): unknown {
return cloneAuthorityJson(value, new Set<object>(), false);
}

function sortCanonicalKeys(keys: string[]): void {
for (let index = 1; index < keys.length; index++) {
if (authorityUnicodeCompare(keys[index - 1]!, keys[index]!) > 0) {
keys.sort(authorityUnicodeCompare);
return;
}
}
}

function cloneAuthorityJson(value: unknown, stack: Set<object>, canonicalKeys: boolean): unknown {
if (value === null || typeof value === "string" || typeof value === "boolean") {
return value;
Expand Down Expand Up @@ -147,20 +172,28 @@ function cloneAuthorityJson(value: unknown, stack: Set<object>, canonicalKeys: b
stack.add(value);
try {
const keys = Object.keys(value);
if (!canonicalKeys) {
// Fill without inherited setters (including __proto__), then normalize
// to the same ordinary object as Object.fromEntries. No per-field tuples.
const copy: JsonObject = Object.create(null);
for (const key of keys) copy[key] = cloneAuthorityJson(value[key], stack, false);
return Object.setPrototypeOf(copy, Object.prototype);
if (canonicalKeys && keys.length > 1) {
sortCanonicalKeys(keys);
}
// Define own data properties on an ordinary object (avoiding Object.create(null)
// + Object.setPrototypeOf dictionary transitions) while preventing inherited
// setters such as __proto__ via Object.defineProperty.
const copy: JsonObject = {};
for (let index = 0; index < keys.length; index++) {
const key = keys[index]!;
const cloned = cloneAuthorityJson(value[key], stack, canonicalKeys);
if (key in Object.prototype) {
Object.defineProperty(copy, key, {
value: cloned,
writable: true,
enumerable: true,
configurable: true,
});
} else {
copy[key] = cloned;
}
}
keys.sort(authorityUnicodeCompare);
return Object.fromEntries(
keys.map((key) => [
key,
cloneAuthorityJson(value[key], stack, canonicalKeys),
]),
);
return copy;
} finally {
stack.delete(value);
}
Expand Down
75 changes: 54 additions & 21 deletions loopx/control_plane/coordination/coordination_projection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,41 @@ export class CoordinationProjectionRead {
}
}

function assembleReducedProjection(
value: JsonObject,
nextTodos: JsonObject[],
nextLeases: JsonObject[],
readModel: JsonObject | undefined,
): JsonObject {
const rest: JsonObject = {};
for (const key of Object.keys(value)) {
if (key === "todos" || key === "leases" || key === "todo_read_model") continue;
const entry = value[key];
if (key in Object.prototype) {
Object.defineProperty(rest, key, { value: entry, writable: true, enumerable: true, configurable: true });
} else {
rest[key] = entry;
}
}
const canonicalRest = canonicalAuthorityObject(rest, "coordination projection");
canonicalRest.todos = nextTodos;
canonicalRest.leases = nextLeases;
if (readModel !== undefined) {
canonicalRest.todo_read_model = readModel;
}
const keys = Object.keys(canonicalRest).sort(authorityUnicodeCompare);
const assembled: JsonObject = {};
for (const key of keys) {
const entry = canonicalRest[key];
if (key in Object.prototype) {
Object.defineProperty(assembled, key, { value: entry, writable: true, enumerable: true, configurable: true });
} else {
assembled[key] = entry;
}
}
return assembled;
}

/**
* Apply one already-authorized coordination transaction as a pure projection
* reduction. Domain transition policy stays with the LoopX kernel; this
Expand All @@ -394,6 +429,7 @@ export function reduceCoordinationProjection(
const todos = new Map(current.todos);
const leases = new Map(current.leases);
const mutatedRecords = new Set<string>();
const mutatedTodoIds: string[] = [];

const claimMutationTarget = (kind: "todo" | "lease", todoId: string): void => {
const target = `${kind}:${todoId}`;
Expand All @@ -403,6 +439,7 @@ export function reduceCoordinationProjection(
);
}
mutatedRecords.add(target);
if (kind === "todo") mutatedTodoIds.push(todoId);
};

for (const [index, mutation] of mutations.entries()) {
Expand All @@ -424,25 +461,24 @@ export function reduceCoordinationProjection(
}
}
const nextTodos = sortedIds(todos.keys()).map((todoId) => todos.get(todoId)!);
const readModel = previous && coordinationTodoReadModel(nextTodos, previous.readModel.schema_version);
const historicalContract = previous?.historicalContract;
// Ordinary writes should keep a released declaration readable by its
// original consumer. A write that uses newer fields needs the current one.
if (readModel && historicalContract && !usesFieldsOutsideTodoContract(nextTodos, historicalContract)) {
readModel.contract_fields = [...historicalContract.fields];
}
const reduced = canonicalAuthorityObject({
...value,
todos: nextTodos,
leases: sortedIds(leases.keys()).map((todoId) => leases.get(todoId)!),
...(readModel === undefined
? {}
: { todo_read_model: readModel }),
}, "coordination projection");
if (value.todo_read_model !== undefined) {
validateCoordinationTodoReadModel(reduced, expectedGoalId);
const nextLeases = sortedIds(leases.keys()).map((todoId) => leases.get(todoId)!);
let readModel: JsonObject | undefined;
if (previous !== undefined) {
for (const todoId of mutatedTodoIds) {
const updated = todos.get(todoId);
if (updated !== undefined) {
canonicalTodoRecord(updated, `coordination Todo read record ${todoId}`);
}
}
readModel = coordinationTodoReadModel(nextTodos, previous.readModel.schema_version);
const historicalContract = previous.historicalContract;
// Ordinary writes should keep a released declaration readable by its
// original consumer. A write that uses newer fields needs the current one.
if (historicalContract && !usesFieldsOutsideTodoContract(nextTodos, historicalContract)) {
readModel.contract_fields = [...historicalContract.fields];
}
}
return reduced;
return assembleReducedProjection(value, nextTodos, nextLeases, readModel);
}

function mutationTarget(mutation: CoordinationProjectionMutation, index: number): string {
Expand Down Expand Up @@ -476,9 +512,6 @@ export function prepareCoordinationProjectionCommit(
goalId,
input.mutations,
);
if (currentProjection.todo_read_model !== undefined) {
validateCoordinationTodoReadModel(nextProjection, goalId);
}
const targets = input.mutations.map(mutationTarget).sort(authorityUnicodeCompare);
const mutationKinds = input.mutations.map((mutation) => mutation.kind).sort(
authorityUnicodeCompare,
Expand Down
38 changes: 29 additions & 9 deletions loopx/control_plane/coordination/coordination_state_contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,26 @@ export function canonicalTodoDomainRecord(value: unknown, label = "Todo domain r
return record as TodoDomainRecord;
}

const FROZEN_CONTRACT_ALLOWED = new WeakMap<RecordContract, ReadonlySet<string>>();

function allowedFieldsForContract(contract: RecordContract): ReadonlySet<string> {
if (Object.isFrozen(contract) && Object.isFrozen(contract.fields)) {
const cached = FROZEN_CONTRACT_ALLOWED.get(contract);
if (cached !== undefined) return cached;
const set = new Set(contract.fields);
FROZEN_CONTRACT_ALLOWED.set(contract, set);
return set;
}
return new Set(contract.fields);
}

export function canonicalCoordinationRecord(
value: unknown,
contract: RecordContract,
label: string,
): JsonObject {
const record = canonicalAuthorityObject(value, label);
const allowed = new Set(contract.fields);
const allowed = allowedFieldsForContract(contract);
const unknownRequired = contract.required_fields.filter(
(field) => !allowed.has(field),
);
Expand All @@ -85,15 +98,20 @@ export function canonicalCoordinationRecord(
`${label} required fields are absent from fields: ${unknownRequired.join(", ")}`,
);
}
const unexpected = Object.keys(record)
.filter((field) => !allowed.has(field))
.sort((left, right) => left.localeCompare(right));
const unexpected: string[] = [];
for (const field of Object.keys(record)) {
if (!allowed.has(field)) unexpected.push(field);
}
if (unexpected.length > 0) {
unexpected.sort((left, right) => left.localeCompare(right));
throw new AuthorityStoreProtocolError(
`${label} has unversioned fields: ${unexpected.join(", ")}`,
);
}
const missing = contract.required_fields.filter((field) => !(field in record));
const missing: string[] = [];
for (const field of contract.required_fields) {
if (!(field in record)) missing.push(field);
}
if (missing.length > 0) {
throw new AuthorityStoreProtocolError(
`${label} omits required fields: ${missing.join(", ")}`,
Expand All @@ -102,10 +120,12 @@ export function canonicalCoordinationRecord(
// Preserve the generic contract's legacy `in` selection for inherited fields.
// Shipped Todo contracts need no reconstruction: normalization already owns
// every allowed field and nested container in canonical order.
if (contract.fields.some((field) => !Object.hasOwn(record, field) && field in record)) {
return canonicalAuthorityObject(Object.fromEntries(
contract.fields.flatMap((field) => field in record ? [[field, record[field]]] : []),
), label);
for (const field of contract.fields) {
if (!Object.hasOwn(record, field) && field in record) {
return canonicalAuthorityObject(Object.fromEntries(
contract.fields.flatMap((entry) => entry in record ? [[entry, record[entry]]] : []),
), label);
}
}
return record;
}
Expand Down
4 changes: 3 additions & 1 deletion loopx/control_plane/coordination/nokv_authority_store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,8 @@ function validStoreIdentity(value: string, workbench: string): boolean {
return value.startsWith(prefix) && HEX_128_PATTERN.test(value.slice(prefix.length));
}

const FATAL_UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });

/** Stage 2A candidate. No runtime constructs this provider by default. */
export class NoKVAuthorityStore implements AuthorityStore {
readonly providerKind = "nokv" as const;
Expand Down Expand Up @@ -267,7 +269,7 @@ export class NoKVAuthorityStore implements AuthorityStore {
const generation = requireGeneration(result.generation, "NoKV read generation");
let raw: string;
try {
raw = new TextDecoder("utf-8", { fatal: true }).decode(result.bytes);
raw = FATAL_UTF8_DECODER.decode(result.bytes);
} catch (error) {
throw new AuthorityStoreProtocolError(
`NoKV authority store bytes are not UTF-8: ${
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
"node": ">=22.22.3"
},
"scripts": {
"test:control-plane": "node --no-warnings --experimental-sqlite --experimental-strip-types --test --test-concurrency=4 tests/control_plane_ts/*.test.ts",
"test:control-plane": "node scripts/run_control_plane_ts_tests.mjs",
"test:remote-authority": "node --no-warnings --experimental-sqlite --experimental-strip-types --test tests/control_plane_ts/remote_authority_client.test.ts",
"test:control-plane:coverage": "c8 --all --include=loopx/control_plane/**/*.ts --exclude=loopx/control_plane/**/*.generated.ts --reporter=lcov --reporter=text --reports-dir=coverage/control-plane node --no-warnings --experimental-sqlite --experimental-strip-types --test --test-concurrency=4 tests/control_plane_ts/*.test.ts",
"test:control-plane:coverage": "c8 --all --include=loopx/control_plane/**/*.ts --exclude=loopx/control_plane/**/*.generated.ts --reporter=lcov --reporter=text --reports-dir=coverage/control-plane node scripts/run_control_plane_ts_tests.mjs",
"test:dashboard:coverage": "tsc --ignoreConfig --target ES2022 --module ES2022 --moduleResolution Bundler --skipLibCheck --strict --sourceMap --inlineSources --outDir apps/presentation/dashboard/node_modules/.cache/loopx-agent-family apps/presentation/dashboard/src/features/personal-workspace/agent-family.ts && cd apps/presentation/dashboard && npx vite build --ssr smoke/decision-research-surface-coverage.tsx --outDir node_modules/.cache/loopx-decision-research-coverage --emptyOutDir --sourcemap && cd ../../.. && c8 --exclude-node-modules=false --include=apps/presentation/dashboard/node_modules/.cache/loopx-agent-family/agent-family.js --include=apps/presentation/dashboard/node_modules/.cache/loopx-decision-research-coverage/decision-research-surface-coverage.js --reporter=lcov --reporter=text --reports-dir=coverage/dashboard node apps/presentation/dashboard/smoke/dashboard-coverage-runner.mjs",
"typecheck:control-plane": "tsc --project tsconfig.control-plane.json --noEmit"
},
Expand Down
78 changes: 78 additions & 0 deletions scripts/run_control_plane_ts_tests.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
export const REPO_ROOT: string;
export const DEFAULT_TEST_DIR: string;
export const DEFAULT_CONCURRENCY_MIN: number;
export const DEFAULT_CONCURRENCY_MAX: number;
export const HEAVY_LANE_CONCURRENCY: number;
export const HEAVY_CONTROL_PLANE_TEST_FILES: readonly string[];

export function resolveTestConcurrency(
env?: NodeJS.ProcessEnv | Record<string, string | undefined>,
availableParallelism?: number,
): number;

export function shouldEnableCompileCache(
env?: NodeJS.ProcessEnv | Record<string, string | undefined>,
): boolean;

export function listDefaultControlPlaneTestFiles(repoRoot?: string): string[];

export function analyzeCliArgs(argv?: readonly string[]): {
hasExplicitTestTargets: boolean;
hasExplicitConcurrency: boolean;
};

export function buildNodeTestArgs(
argv?: readonly string[],
options?: {
env?: NodeJS.ProcessEnv | Record<string, string | undefined>;
availableParallelism?: number;
repoRoot?: string;
},
): string[];

export type ControlPlaneRunPlan =
| {
mode: "single";
totalConcurrency: number;
args: string[];
}
| {
mode: "two_lane";
totalConcurrency: number;
heavyConcurrency: number;
standardConcurrency: number;
heavyFiles: string[];
standardFiles: string[];
};

export function buildControlPlaneRunPlan(
argv?: readonly string[],
options?: {
env?: NodeJS.ProcessEnv | Record<string, string | undefined>;
availableParallelism?: number;
repoRoot?: string;
},
): ControlPlaneRunPlan;

export function createScopedCompileCache(options?: {
env?: NodeJS.ProcessEnv | Record<string, string | undefined>;
tmpRoot?: string;
}): {
cacheDir: string | null;
cleanup: () => void;
};

export function runControlPlaneTests(
argv?: readonly string[],
options?: {
env?: NodeJS.ProcessEnv | Record<string, string | undefined>;
availableParallelism?: number;
repoRoot?: string;
tmpRoot?: string;
execPath?: string;
},
): Promise<{
status: number | null;
signal: NodeJS.Signals | null;
cacheDir: string | null;
}>;
Loading
Loading