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
21 changes: 16 additions & 5 deletions loopx/control_plane/quota/turn_envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,14 @@ def _apply_context_projection_changes(
return cast(dict[str, Any], projected)


def pack_turn_source(source: Mapping[str, Any]) -> dict[str, str] | None:
def pack_turn_source(
source: Mapping[str, Any], *, max_encoded_fraction: float = 1.0,
) -> dict[str, str] | None:
"""Use the lossless wire for bounded sources that compress well."""
raw = _encode_rpc_json(source)
if 16 * 1024 <= len(raw) <= 1024 * 1024:
data = base64.b64encode(zlib.compress(raw, level=1)).decode("ascii")
if len(data) + 128 < len(raw):
if len(data) + 128 < len(raw) * max_encoded_fraction:
return {"encoding": "deflate-base64-json-v0", "data": data}
return None

Expand Down Expand Up @@ -114,10 +116,19 @@ def _turn_envelope_result(
addition_tokens = source_number_tokens(params["context_additions"])
if addition_tokens:
request["context_addition_tokens"] = addition_tokens
if operation == "capability_automation_source" and set(params) == {"payload"} and isinstance(payload, Mapping):
transport = pack_turn_source(payload)
source_field = "context" if operation == "context_delivery" else "payload"
compact_source = (
operation in {"compose_complete", "attach_complete_turn_context", "context_delivery"}
or (operation == "capability_automation_source" and set(params) == {"payload"})
)
source = params.get(source_field)
if compact_source and isinstance(source, Mapping):
# Base64 of ordinary prose can cost more tokens than inline JSON.
# Large repeated Goal bodies qualify only with a threefold byte reduction.
fraction = 1.0 if operation == "capability_automation_source" else 1 / 3
transport = pack_turn_source(source, max_encoded_fraction=fraction)
if transport is not None:
del request["payload"]
del request[source_field]
request["source_transport"] = transport
result = effect_runtime_projection_result("quota.turn_envelope.evaluate", request)
if not isinstance(result, Mapping):
Expand Down
10 changes: 9 additions & 1 deletion loopx/control_plane/quota/turn_envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1421,8 +1421,16 @@ const resolveViewWriteback = (
): JsonObject => object(actionProjection(payload, false, precision, verifiedSourceHash).writeback);

export function evaluateTurnEnvelope(value: unknown): JsonObject {
const request = requireJsonObject(value, "turn envelope request");
let request = requireJsonObject(value, "turn envelope request");
const operation = request.operation;
if (Object.hasOwn(request, "source_transport") && (operation === "compose_complete" ||
operation === "attach_complete_turn_context" || operation === "context_delivery")) {
const field = operation === "context_delivery" ? "context" : "payload";
const source = decodeTurnSource(request, field);
// Projection edits must still address the caller's original inline shape.
const {source_transport: _transport, ...options} = request;
request = {...options, [field]: source};
}
if (operation === "session_plan") return turnSessionPlan(request);
if (operation === "planning_facts") return completePlanningFacts(request);
if (operation === "recorded_plan_lineage") {
Expand Down
2 changes: 1 addition & 1 deletion loopx/control_plane/quota/turn_envelope_codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ export function coldPath(
};
}

export function decodeTurnSource(request: JsonObject, inlineField: "payload" | "source"): JsonObject {
export function decodeTurnSource(request: JsonObject, inlineField: "payload" | "source" | "context"): JsonObject {
const transport = requireJsonObject(request.source_transport, "Turn composition source transport");
const { encoding, data } = transport;
const maxSourceBytes = 1024 * 1024;
Expand Down
66 changes: 66 additions & 0 deletions tests/control_plane/test_complete_numeric_transport.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Complete consumer costs and the explicit experimental hash transition."""
from copy import deepcopy
import json
from hashlib import sha256

import pytest

Expand Down Expand Up @@ -118,3 +119,68 @@ def measured_rpc(method, params, **kwargs):
# RPC directions through composition, Host input, cold/delta and recovery;
# larger fractional spellings do not justify per-value provenance growth.
assert totals[1] / totals[0] <= 1.25 * source_sizes[1] / source_sizes[0]


def test_bounded_guard_transport_matches_inline_through_native_readback(tmp_path, monkeypatch):
isolate_sqlite_runtime(tmp_path, monkeypatch)
source = _quota_payload()
source["observations"] = {"text": "repeatable synthesis evidence. " * 960,
"values": [-0.0, 1.0, 2**60 + 1]}
additions = {"projection_evidence": {"value": 2**60 + 3}}
scope = dict(goal_id="fixture", agent_id="reader", session_id="native", context_epoch="epoch")
requests = []
rpc = turn.effect_runtime_projection_result

def observe(method, params):
requests.append(params)
return rpc(method, params)

def guard():
decision = turn.compose_turn_decision(source)
bound = turn.attach_complete_turn_context(decision, additions)
delivered = turn.prepare_context_delivery(bound, scope=scope, capture_id="original", surface="complete_turn",
native_projection={"path": str(tmp_path / "original.json"), "sha256": "a" * 64},
include_initial_read_plan=True)
return decision, bound, delivered

monkeypatch.setattr(turn, "effect_runtime_projection_result", observe)
compact = guard()
fields = ["payload", "payload", "context"]
assert len(requests) == len(fields)
for request, field in zip(requests, fields, strict=True):
assert field not in request and "source_transport" in request
with pytest.raises(RuntimeError, match="invalid Turn composition source transport"):
rpc("quota.turn_envelope.evaluate", {**request, field: {}})
compact_bytes = sum(len(_json(request).encode()) for request in requests)
requests.clear()
with monkeypatch.context() as patch:
patch.setattr(turn, "pack_turn_source", lambda source, **kwargs: None)
inline = guard()
assert compact_bytes < sum(len(_json(request).encode()) for request in requests)
assert _json(compact) == _json(inline)
bound, delivered = compact[1:]
assert _json(delivered["context"]["observations"]) == _json(source["observations"])
assert delivered["context"]["projection_evidence"] == additions["projection_evidence"]
bound["observations"]["values"][-1] -= 1
with pytest.raises(RuntimeError, match="integrity mismatch"):
turn.attach_complete_turn_context(bound, {})


def test_guard_preserves_inline_transport_for_dense_evidence(monkeypatch):
source = {"evidence": [sha256(str(index).encode()).hexdigest() for index in range(512)]}
# The optional capability transport can save bytes here, but the modest
# saving would send mostly base64 through each ordinary admission request.
assert turn.pack_turn_source(source) is not None
requests = []

def observe(method, params):
requests.append(params)
return {}

monkeypatch.setattr(turn, "effect_runtime_projection_result", observe)
for operation, field in (("compose_complete", "payload"),
("attach_complete_turn_context", "payload"),
("context_delivery", "context")):
turn._turn_envelope_result(operation, **{field: source})
assert requests[-1][field] is source
assert "source_transport" not in requests[-1]
10 changes: 8 additions & 2 deletions tests/control_plane/test_complete_turn_decision.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,10 @@ def test_plan_uses_one_complete_source_check_without_weakening_refusal(monkeypat
def observed(method, params, **kwargs):
if method == "quota.turn_envelope.evaluate":
calls.append(params["operation"])
if params["operation"] == "session_plan":
# Session reuse consumes validated lineage, never the full Goal body.
assert {"payload", "context", "envelope", "complete_host_request",
"source_transport"}.isdisjoint(params)
return invoke(method, params, **kwargs)

monkeypatch.setattr(transport, "effect_runtime_projection_result", observed)
Expand All @@ -335,8 +339,10 @@ def plan():
result = plan()
assert result["route"]["would_invoke_host"] is True
assert result["transaction"]["turn_instance_id"] == "original-turn"
assert calls == (["consumer_version", "driver_lineage"] if case == "historical"
else ["planning_facts"])
expected = ["consumer_version", "driver_lineage"] if case == "historical" else ["planning_facts"]
if not error:
expected.append("session_plan")
assert calls == expected
assert (envelope, contract) == original


Expand Down
Loading