diff --git a/loopx/control_plane/coordination/local_authority.py b/loopx/control_plane/coordination/local_authority.py index 922d23dcfb..9ef681b04e 100644 --- a/loopx/control_plane/coordination/local_authority.py +++ b/loopx/control_plane/coordination/local_authority.py @@ -18,7 +18,7 @@ from ...command_invocation import loopx_cli_argv from ..agents.workspace_guard import _git_worktree_root from .authority_source_capture import authority_registry_source -from ..runtime.time import now_local_iso as now_local +from ..runtime.time import now_local_iso from ..effect_runtime import ( CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS, EffectRuntimeResponseAmbiguous, @@ -259,7 +259,7 @@ def claim_canonical_todo_if_promoted( if task_lease_idempotency_key is not None else None ), - "observed_at": now_local(), + "observed_at": now_local_iso(timespec="milliseconds"), "dry_run": dry_run, }, timeout=CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS, diff --git a/loopx/control_plane/quota/execution_preparation.py b/loopx/control_plane/quota/execution_preparation.py index dc1a4a2005..d3156749ce 100644 --- a/loopx/control_plane/quota/execution_preparation.py +++ b/loopx/control_plane/quota/execution_preparation.py @@ -210,7 +210,7 @@ def commit_execution_loss_closeout( "payload": load_project_registry(registry_path), "lifetime_sources": lifetime_sources}, "locks": witnesses, "intent": {"delivery_outcome": delivery_outcome, "delivery_boundary": delivery_boundary, "progress_observation": progress}, "control_writer_proof": dict(requested_proof) if requested_proof else None, - "requested_effects": dict(requested_effects), "observed_at": now_local_iso()} + "requested_effects": dict(requested_effects), "observed_at": now_local_iso(timespec="microseconds")} try: result = effect_runtime_result( "quota.execution_loss_closeout.commit", diff --git a/loopx/control_plane/work_items/task_lease_acquire_decision.ts b/loopx/control_plane/work_items/task_lease_acquire_decision.ts index 4ba77519d2..f9cff44c9f 100644 --- a/loopx/control_plane/work_items/task_lease_acquire_decision.ts +++ b/loopx/control_plane/work_items/task_lease_acquire_decision.ts @@ -9,6 +9,7 @@ import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; import {requireJsonObject, requireStringLiteral} from "../runtime_decode.ts"; import type {JsonObject} from "../effect_program.ts"; import type {TodoFact, LeaseRecord} from "./task_lease_acquire.ts"; +import {leaseEventTimestamp} from "./task_lease_record.ts"; import {normalizeTodoRepository} from "../todos/work_requirements.ts"; import {leaseWriteRepository, leaseRepositoryRejection, repositoryScopesMayOverlap} from "./task_lease_repository.ts"; @@ -777,7 +778,7 @@ export function materializeTaskLeaseAcquire(identity: {goal_id: string; todo_id: if (decision.outcome !== "apply" || decision.next_lease === null) { throw new EffectRuntimeRequestError("lease materialization requires an apply decision"); } - const at = now.toISOString().replace(/\.\d{3}Z$/u, "Z"); + const at = leaseEventTimestamp(now); return {schema_version: "task_lease_v0", goal_id: identity.goal_id, todo_id: identity.todo_id, owner: command.owner, idempotency_key: command.idempotency_key, ...(decision.next_lease.write_workspace ? {write_workspace: leaseWorkspace(decision.next_lease.write_workspace)} : {}), diff --git a/loopx/control_plane/work_items/task_lease_lifecycle_decision.ts b/loopx/control_plane/work_items/task_lease_lifecycle_decision.ts index 388bc436e7..98538ccd9f 100644 --- a/loopx/control_plane/work_items/task_lease_lifecycle_decision.ts +++ b/loopx/control_plane/work_items/task_lease_lifecycle_decision.ts @@ -4,6 +4,7 @@ import {leaseOwnerRejection as ownerRejection, type LeaseEligibilityTodo} from " import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; import { type JsonObject } from "../effect_program.ts"; import { requireJsonObject, requireStringLiteral } from "../runtime_decode.ts"; +import {leaseEventTimestamp} from "./task_lease_record.ts"; import {leaseEpoch, utcIsoformat, type LeaseRecord} from "./task_lease_acquire.ts"; import {normalizeTodoRepository} from "../todos/work_requirements.ts"; import {leaseWriteRepository, leaseRepositoryRejection} from "./task_lease_repository.ts"; @@ -309,7 +310,7 @@ export function decideTaskLeaseLifecycle( * or timestamps. Release retains the fence generation as historical evidence. */ export function releasedTaskLeaseRecord(lease: LeaseRecord, at: Date): LeaseRecord { return {...lease, lease_epoch: leaseEpoch(lease), status: "released", - released_at: utcIsoformat(at), updated_at: utcIsoformat(at)}; + released_at: leaseEventTimestamp(at), updated_at: leaseEventTimestamp(at)}; } export function materializeTaskLeaseLifecycle(lease: LeaseRecord, @@ -323,7 +324,7 @@ export function materializeTaskLeaseLifecycle(lease: LeaseRecord, return {...lease, ...(command.operation === "transfer" ? {owner: next.owner, idempotency_key: next.idempotency_key, lease_epoch: next.lease_epoch} : {}), - version: next.version, updated_at: utcIsoformat(at), + version: next.version, updated_at: leaseEventTimestamp(at), expires_at: utcIsoformat(new Date(at.valueOf() + command.ttl_seconds! * 1000))}; } diff --git a/loopx/control_plane/work_items/task_lease_record.ts b/loopx/control_plane/work_items/task_lease_record.ts index 19109eb1a2..e6a218b9a8 100644 --- a/loopx/control_plane/work_items/task_lease_record.ts +++ b/loopx/control_plane/work_items/task_lease_record.ts @@ -32,6 +32,12 @@ export class TaskLeaseAcquireError extends Error { } } +/** Preserve observed event order for receipt-bound recovery. Lease deadlines + * keep their existing whole-second wire semantics. */ +export function leaseEventTimestamp(at: Date): string { + return at.toISOString().replace(/\.000Z$/u, "Z"); +} + export function leaseInteger( lease: LeaseRecord | null, field: "version" | "lease_epoch" | "acquire_ttl_seconds", diff --git a/tests/control_plane/test_execution_loss_closeout_cli.py b/tests/control_plane/test_execution_loss_closeout_cli.py index 71471e462d..caa04c2268 100644 --- a/tests/control_plane/test_execution_loss_closeout_cli.py +++ b/tests/control_plane/test_execution_loss_closeout_cli.py @@ -8,6 +8,7 @@ import sys import pytest +from loopx import rollout_event_log from loopx.agent_registry import registered_agent_ids_for_goal from canonical_authority_fixture import initialize_canonical_source_fixture, isolate_sqlite_runtime @@ -256,7 +257,6 @@ def now(cls, tz=None): # Registered transport clock seams, never edits to persisted lease bytes. monkeypatch.setattr(runtime_time, "datetime", AfterExpiryDatetime) - monkeypatch.setattr(local_authority, "now_local", lambda: after_expiry.isoformat()) monkeypatch.setattr(task_lease, "now_utc", lambda: after_expiry.astimezone(timezone.utc)) assert runtime_time.now_utc() == after_expiry.astimezone(timezone.utc) replacement = _claim(context, replacement_owner, "execution-loss-replacement-claim") @@ -549,6 +549,73 @@ def test_closeout_preserves_the_original_turn_and_releases_the_next_guard( _assert_no_completion_or_debit(context) +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("whole_second_writer", [False, True], ids=["precise", "legacy-clock"]) +def test_replacement_and_closeout_in_receipt_second(tmp_path, monkeypatch, capsys, provider, + whole_second_writer): + second = datetime.now(timezone.utc).replace(microsecond=0) + clock = second + timedelta(milliseconds=250) + + class FixtureDatetime(datetime): + @classmethod + def now(cls, tz=None): + return clock.astimezone(tz) if tz else clock.astimezone().replace(tzinfo=None) + + monkeypatch.setattr(runtime_time, "datetime", FixtureDatetime) + monkeypatch.setattr(rollout_event_log, "datetime", FixtureDatetime) + monkeypatch.setattr(task_lease, "now_utc", lambda: clock) + context = _fixture(tmp_path, monkeypatch, capsys, provider, replace=False, source_profile=False) + original = _readback(context) + assert runtime_time.parse_timestamp(original.heartbeat_receipt["recorded_at"]) == clock + + run = context["cli"] + binding = ["--goal-id", context["goal_id"], "--todo-id", context["todo"]] + first = context["original_lease"] + clock = second + timedelta(milliseconds=450) + code, released = run("task-lease", "release", *binding, "--owner", OWNER, + "--idempotency-key", first["idempotency_key"], + "--expected-version", str(first["version"])) + assert code == 0, released + assert runtime_time.parse_timestamp(_lease(context)["released_at"]) == clock + + clock = second + timedelta(milliseconds=650) + if whole_second_writer: + # A legacy writer can only attest to the second it observed. + monkeypatch.setattr(local_authority, "now_local_iso", lambda *, timespec: second.isoformat()) + code, claimed = run("todo", "claim", *binding, "--agent-id", OWNER, "--claimed-by", OWNER, + "--claim-operation-id", "replacement-within-receipt-second") + assert code == 0, claimed + lease = _lease(context) + assert lease["lease_epoch"] > first["lease_epoch"] + if whole_second_writer: + assert runtime_time.parse_timestamp(lease["acquired_at"]) == second + rejected = _reject_without_effect(context, _closeout_args(context, lease=lease)) + assert "clock is stale or ambiguous" in str(rejected) + return + assert runtime_time.parse_timestamp(lease["acquired_at"]) == clock + + clock = second + timedelta(milliseconds=725) + code, renewed = run("task-lease", "renew", *binding, "--owner", OWNER, + "--idempotency-key", lease["idempotency_key"], + "--expected-version", str(lease["version"]), "--ttl-seconds", "2700") + assert code == 0, renewed + current = _lease(context) + assert runtime_time.parse_timestamp(current["updated_at"]) == clock + argv = _closeout_args(context, lease=current) + + # A clock behind the renewal still cannot establish the required ordering. + clock = second + timedelta(milliseconds=700) + _reject_without_effect(context, argv) + clock = second + timedelta(milliseconds=850) + code, closed = run(*argv) + assert code == 0 and closed["settlement_progress"]["no_spend"] is True, closed + assert closed["settlement_identity"] == original.identity.value.as_dict() + code, replay = run(*argv) + assert code == 0 and replay["idempotent_replay"] and not replay["appended"], replay + assert _receipt_lines(context) == context["receipt_lines"] + _assert_no_completion_or_debit(context) + + @pytest.mark.parametrize("provider", ["file", "sqlite"]) def test_rejects_same_generation_and_business_side_effects(tmp_path, monkeypatch, capsys, provider): context = _fixture(tmp_path, monkeypatch, capsys, provider, replace=False, source_profile=False) diff --git a/tests/test_task_lease_worktree.py b/tests/test_task_lease_worktree.py index c0c5b22df8..f573dc79a6 100644 --- a/tests/test_task_lease_worktree.py +++ b/tests/test_task_lease_worktree.py @@ -263,7 +263,7 @@ def snapshot(): # Only the accepted operation's clock is synthetic. Git observation, the # managed claim, its receipt and both provider transactions remain real. with monkeypatch.context() as clock: - clock.setattr("loopx.control_plane.coordination.local_authority.now_local", lambda: "2001-01-01T00:00:00Z") + clock.setattr("loopx.control_plane.coordination.local_authority.now_local_iso", lambda *, timespec: "2001-01-01T00:00:00Z") assert claim("a", "expired-original")["execution_managed"] monkeypatch.chdir(b) assert claim("b", "peer-current")["execution_managed"]