Skip to content

Commit 72f6681

Browse files
authored
fix(turn): preserve journal numbers with shared sparse transport (#7709)
* fix(turn): preserve original numeric evidence in journals Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> * docs(turn): state journal source preservation and transport cost Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> * fix: preserve journal source numbers with shared sparse IO metadata Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --------- Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent fc81eca commit 72f6681

11 files changed

Lines changed: 333 additions & 72 deletions

‎docs/architecture/rfcs/controller-executor-unified-contract-v0.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,21 @@ the existing context-delivery owner. C1 must converge the remaining composition
130130
and consumer assumptions, rather than introduce another capture service or
131131
rewrite already shared delta/native-resume logic.
132132

133+
Journal persistence is an independent source-fidelity prerequisite. The proposed
134+
Python adapter reuses context delivery's sparse number-token collector; both
135+
TypeScript consumers reuse one source-number validator. Journals remain JSON
136+
objects, with metadata only for integral floats, signed zero and unsafe integers.
137+
The journal owner restores these numbers before atomic publication and retains
138+
their distinctions in replay and immutable-plan comparisons. Ordinary native
139+
objects retain their encoding; historical receipts are not rewritten.
140+
141+
The interim whole-JSON-string carrier failed the existing 2 MiB request boundary
142+
for a synthetic 1.55-million-character quoted body accepted by the object path.
143+
Keep that negative result: qualify the sparse replacement against the same
144+
workload and limit, including number-dense overhead. Neither this prerequisite
145+
nor a component byte saving qualifies the unified writer/consumer cutover or
146+
long-horizon net benefit.
147+
133148
| Current source / obligation | Present envelope treatment | Required C1 disposition |
134149
| --- | --- | --- |
135150
| `interaction_contract.agent_channel.work_context` and pending required reads | `work_context` plus `required_reads`; identical inline material can be referenced | One complete requirement/evidence source with resolvable references; preserve pending reads and their completion conditions |

‎docs/architecture/rfcs/controller-executor-unified-contract-v0.zh-CN.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,17 @@ Quota capture 与 Turn journal capture 都调用
104104
context-delivery owner。C1 应收敛剩余的组合逻辑与消费者假设,不另建 capture service,
105105
也不重写已经共享的差分与 native-resume 逻辑。
106106

107+
Journal 持久化是独立的来源保真前置。本次提议由 Python adapter 复用 context
108+
delivery 的稀疏数值 token 收集器;两个 TypeScript 消费者复用同一来源数值校验器。
109+
Journal 继续传递 JSON 对象,仅为整值浮点、带符号零和非安全整数增加元数据。
110+
Journal owner 在原子发布前恢复这些数值,并在重放与不可变 plan 比较中保留其
111+
区别。普通原生对象保留已有编码,不改写历史回执。
112+
113+
中间的完整 JSON 字符串方案,在合成的 155 万字符带引号正文上超过既有 2 MiB
114+
请求边界;原对象路径能够接收同一负载。保留这一负面结果:稀疏替代须在相同
115+
负载与上限下比较,包括数值密集时的元数据开销。该前置或组件字节减少,都不
116+
构成统一 writer/consumer 切换或长程净收益的资格。
117+
107118
| 当前来源 / 义务 | 当前 envelope 处理 | C1 必须保留的归属与语义 |
108119
| --- | --- | --- |
109120
| `interaction_contract.agent_channel.work_context` 与未完成必读 | `work_context` 加 `required_reads`;相同内联材料可改用引用 | 一份完整要求/证据来源与可解析引用;保留未完成必读及其完成条件 |

‎docs/reference/protocols/loopx-turn-v0.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,24 @@ completed effects remain proved; other effects are unknown, not `false`. The
516516
writer's empty-map rejection is retained: no pending intent uses an absent field;
517517
committed history is carried by completed checkpoints, not retained intents.
518518

519+
Python-origin journal snapshots remain JSON objects through that same TypeScript
520+
writer. They reuse context delivery's sparse numeric IO metadata and validator
521+
to preserve integral floats, signed zero and unsafe integers before atomic
522+
publication. Replay and immutable-plan comparison distinguish these source
523+
numbers; refusals retain the original file. Ordinary objects without metadata
524+
retain their encoding and operation identity; historical receipts are not
525+
rewritten. This remains one RPC under the existing 2 MiB request limit and avoids
526+
double escaping evidence text. Metadata still costs bytes for number-dense
527+
sources. Source fidelity and transport checks do not establish latency or
528+
long-horizon benefit.
529+
530+
Python 来源的 journal 快照仍经同一 TypeScript writer 传递 JSON 对象,复用
531+
context delivery 的稀疏数值 IO 元数据与校验器,在原子发布前保留整值浮点、带
532+
符号零和非安全整数。重放与不可变 plan 比较区分这些来源数值;拒绝时保留原
533+
文件。无元数据的普通对象保留已有编码与操作身份,不改写历史回执。仍为一次
534+
RPC,沿用 2 MiB 请求上限,避免证据正文的双重转义;数值密集来源仍有元数据
535+
字节成本。来源保真与传输检查不代表延迟或长程收益已得到验证。
536+
519537
If executing `run-once` raises unexpectedly, its error response retains the
520538
original error and resume key, marks uncertain current-invocation `effects` as
521539
`null`, and adds `journal_observation` from this same read-only TS owner. Its

‎loopx/control_plane/effect_runtime.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import hashlib
44
import json
5+
import math
56
import os
67
import secrets
78
import socket
@@ -87,6 +88,31 @@
8788
_RuntimeSourceSnapshot = tuple[tuple[str, int, int, int], ...]
8889

8990

91+
def source_number_tokens(value: object) -> list[list[Any]]:
92+
"""Carry numeric IO spellings that a JavaScript number cannot distinguish.
93+
94+
This is transport metadata, not a hash codec or a projection policy.
95+
Fractional doubles and safe integers keep their existing object transport.
96+
"""
97+
tokens: list[list[Any]] = []
98+
99+
def visit(item: object, path: list[str | int]) -> None:
100+
if isinstance(item, float) and not math.isfinite(item):
101+
raise ValueError("Context source numbers must be finite")
102+
if (isinstance(item, float) and item.is_integer()
103+
or type(item) is int and abs(item) > 2**53 - 1):
104+
tokens.append([path, json.dumps(item, allow_nan=False)])
105+
elif isinstance(item, Mapping):
106+
for key, child in item.items():
107+
visit(child, [*path, key])
108+
elif isinstance(item, (list, tuple)):
109+
for index, child in enumerate(item):
110+
visit(child, [*path, index])
111+
112+
visit(value, [])
113+
return tokens
114+
115+
90116
class _RuntimeSourceChanged(RuntimeError):
91117
def __init__(self, snapshot: _RuntimeSourceSnapshot) -> None:
92118
super().__init__("runtime source changed while hashing")

‎loopx/control_plane/quota/diagnostic_projection.ts‎

Lines changed: 2 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,9 @@
55
* decision. This projection grants no admission or execution authority.
66
*/
77
import type {JsonObject} from "../effect_program.ts";
8-
import {jsonObject} from "../runtime_decode.ts";
8+
import {jsonObject, sourceNumberTokens} from "../runtime_decode.ts";
99
import {TODO_CANONICAL_READ_RECORD_FIELDS} from "../coordination/coordination_state_contract.ts";
1010
import {canonicalAuthorityJson, authorityUnicodeCompare} from "../coordination/authority_store_codec.ts";
11-
import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts";
1211

1312
type ProjectionPath = (string | number)[];
1413
type ProjectionChange = {path: ProjectionPath; value: unknown} |
@@ -33,30 +32,7 @@ function contextObjectPaths(source: JsonObject): WeakMap<object, ProjectionPath>
3332
export function contextSourceIdentity(source: JsonObject, supplied?: unknown):
3433
(value: unknown, path: ProjectionPath) => string {
3534
if (supplied === undefined) return value => JSON.stringify(canonicalAuthorityJson(value));
36-
if (!Array.isArray(supplied)) throw new EffectRuntimeRequestError("context source number tokens must be an array");
37-
const tokens: {path: ProjectionPath; token: string}[] = [], seen = new Set<string>();
38-
for (const entry of supplied) {
39-
if (!Array.isArray(entry) || entry.length !== 2 || !Array.isArray(entry[0]) || !entry[0].length ||
40-
typeof entry[1] !== "string" || !/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(entry[1])) {
41-
throw new EffectRuntimeRequestError("invalid context source number token");
42-
}
43-
const path: ProjectionPath = entry[0], token: string = entry[1];
44-
let value: unknown = source;
45-
for (const key of path) {
46-
if (value === null || typeof value !== "object" ||
47-
!(Array.isArray(value) ? typeof key === "number" && Number.isSafeInteger(key) && key >= 0
48-
: typeof key === "string") || !Object.hasOwn(value, key)) {
49-
throw new EffectRuntimeRequestError("context source number token path is unavailable");
50-
}
51-
value = (value as Record<string | number, unknown>)[key];
52-
}
53-
const key = JSON.stringify(path);
54-
if (seen.has(key) || typeof value !== "number" || !Number.isFinite(value) || !Object.is(JSON.parse(token), value)) {
55-
throw new EffectRuntimeRequestError("context source number token differs from input");
56-
}
57-
seen.add(key);
58-
tokens.push({path, token});
59-
}
35+
const tokens = sourceNumberTokens(source, supplied);
6036
const paths = contextObjectPaths(source);
6137
return (value, path) => {
6238
const original = value !== null && typeof value === "object" ? paths.get(value) : undefined;

‎loopx/control_plane/quota/turn_envelope.py‎

Lines changed: 2 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,11 @@
33
from __future__ import annotations
44

55
import json
6-
import math
76
from collections.abc import Mapping
87
from dataclasses import dataclass
98
from typing import Any
109

11-
from ..effect_runtime import EffectRuntimeRejected, effect_runtime_result
10+
from ..effect_runtime import EffectRuntimeRejected, effect_runtime_result, source_number_tokens
1211
from ..scheduler.execution_context import (
1312
SchedulerExecutionContextResolution,
1413
render_scheduler_execution_args,
@@ -57,7 +56,7 @@ def _turn_envelope_result(
5756

5857
request = {"operation": operation, **params}
5958
if operation in {"context_delivery", "context_recovery"}:
60-
tokens = _source_number_tokens(params)
59+
tokens = source_number_tokens(params)
6160
if tokens:
6261
request["source_number_tokens"] = tokens
6362
try:
@@ -74,30 +73,6 @@ def _turn_envelope_result(
7473
return dict(result)
7574

7675

77-
def _source_number_tokens(value: object) -> list[list[Any]]:
78-
"""Transport sparse numeric source identity; no carrier or sharing policy."""
79-
tokens: list[list[Any]] = []
80-
81-
def visit(item: object, path: list[str | int]) -> None:
82-
if isinstance(item, float) and not math.isfinite(item):
83-
raise ValueError("Context source numbers must be finite")
84-
# Fractional doubles retain their identity through JSON/JavaScript.
85-
# Only integral floats (including signed zero) and unsafe integers
86-
# can become indistinguishable from a different Python source number.
87-
if (isinstance(item, float) and item.is_integer()
88-
or type(item) is int and abs(item) > 2**53 - 1):
89-
tokens.append([path, json.dumps(item, allow_nan=False)])
90-
elif isinstance(item, Mapping):
91-
for key, child in item.items():
92-
visit(child, [*path, key])
93-
elif isinstance(item, (list, tuple)):
94-
for index, child in enumerate(item):
95-
visit(child, [*path, index])
96-
97-
visit(value, [])
98-
return tokens
99-
100-
10176
def assert_turn_envelope_consumer_version(envelope: Mapping[str, Any]) -> None:
10277
"""Use the typed wire-version gate before any Host consumes this packet."""
10378
_turn_envelope_result("consumer_version", envelope=dict(envelope))

‎loopx/control_plane/runtime_decode.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,39 @@ export function requireJsonObject(value: unknown, label: string): JsonObject {
1414
return result;
1515
}
1616

17+
/** Sparse IO spellings, validated against the already decoded source.
18+
* Shared by context identity and durable journal publication; no carrier,
19+
* authority or projection decision is made here. */
20+
export function sourceNumberTokens(source: JsonObject, supplied?: unknown):
21+
{path: (string | number)[]; token: string}[] {
22+
if (supplied === undefined) return [];
23+
if (!Array.isArray(supplied)) throw new EffectRuntimeRequestError("context source number tokens must be an array");
24+
const tokens: {path: (string | number)[]; token: string}[] = [], seen = new Set<string>();
25+
for (const entry of supplied) {
26+
if (!Array.isArray(entry) || entry.length !== 2 || !Array.isArray(entry[0]) || !entry[0].length ||
27+
typeof entry[1] !== "string" || !/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(entry[1])) {
28+
throw new EffectRuntimeRequestError("invalid context source number token");
29+
}
30+
const path: (string | number)[] = entry[0], token: string = entry[1];
31+
let value: unknown = source;
32+
for (const key of path) {
33+
if (value === null || typeof value !== "object" ||
34+
!(Array.isArray(value) ? typeof key === "number" && Number.isSafeInteger(key) && key >= 0
35+
: typeof key === "string") || !Object.hasOwn(value, key)) {
36+
throw new EffectRuntimeRequestError("context source number token path is unavailable");
37+
}
38+
value = (value as Record<string | number, unknown>)[key];
39+
}
40+
const key = JSON.stringify(path);
41+
if (seen.has(key) || typeof value !== "number" || !Number.isFinite(value) || !Object.is(JSON.parse(token), value)) {
42+
throw new EffectRuntimeRequestError("context source number token differs from input");
43+
}
44+
seen.add(key);
45+
tokens.push({path, token});
46+
}
47+
return tokens;
48+
}
49+
1750
export function requireBoolean(value: unknown, label: string): boolean {
1851
if (typeof value !== "boolean") {
1952
throw new EffectRuntimeRequestError(`${label} must be a boolean`);

0 commit comments

Comments
 (0)