Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(memory): keep sidecar stop working after create_time clock steps (#1541)

rkrkrkk367353e0da3b
diff --git a/core/memory/process.py b/core/memory/process.py
index a8dfaeaf3..a30bcf7d2 100644
--- a/core/memory/process.py
+++ b/core/memory/process.py
@@ -3,10 +3,12 @@
from __future__ import annotations
import asyncio
+import errno
import hashlib
import inspect
import json
import logging
+import math
import os
import signal
import stat
@@ -975,12 +977,13 @@ class EverOSProcess:
while time.monotonic() < deadline:
if process.returncode is not None:
raise RuntimeError("sidecar exited before readiness")
- if not _host_identity_is_live(self._host, process.pid, self._owned_processes):
- raise RuntimeError("sidecar ownership changed before readiness")
- _merge_owned_processes(
+ if not _refresh_owned_process_tree(
+ self._host,
self._owned_processes,
- self._host.snapshot_tree(process.pid, self._process_group),
- )
+ process.pid,
+ self._process_group,
+ ):
+ raise RuntimeError("sidecar ownership changed before readiness")
if self._socket_path.exists():
self._secure_socket()
if await client.health():
@@ -1075,7 +1078,22 @@ class EverOSProcess:
except Exception:
if not self._desired_running:
return
- logger.warning("EverOS sidecar safety monitor rejected the child tree")
+ recorded_stamp = (
+ self._owned_processes.get(process.pid) if process.pid is not None else None
+ )
+ live_stamp = None
+ if process.pid is not None:
+ try:
+ live_stamp = _process_creation_stamp(psutil.Process(process.pid))
+ except Exception:
+ live_stamp = None
+ logger.exception(
+ "EverOS sidecar safety monitor rejected the child tree "
+ "(pid %s recorded_stamp=%s live_stamp=%s)",
+ process.pid,
+ recorded_stamp,
+ live_stamp,
+ )
async with self._lifecycle_lock:
if process is not self._process:
return
@@ -1191,10 +1209,13 @@ class EverOSProcess:
return
def _refresh_owned_processes(self, pid: int) -> dict[int, float]:
- _merge_owned_processes(
+ if not _refresh_owned_process_tree(
+ self._host,
self._owned_processes,
- self._host.snapshot_tree(pid, self._process_group),
- )
+ pid,
+ self._process_group,
+ ):
+ raise RuntimeError("sidecar ownership changed during monitoring")
unverifiable = {
process_id: created_at
for process_id, created_at in self._owned_processes.items()
@@ -1465,14 +1486,15 @@ class EverOSRebuildProcess:
_REBUILD_HANDSHAKE_TIMEOUT_SECONDS,
)
)
- _merge_owned_processes(
+ if not _refresh_owned_process_tree(
+ self._host,
identities,
- self._host.snapshot_tree(process.pid, process_group),
- )
+ process.pid,
+ process_group,
+ ):
+ raise RuntimeError("could not establish rebuild process ownership")
if not stopped:
raise RuntimeError("rebuild child did not enter ownership handshake")
- if not _host_identity_is_live(self._host, process.pid, identities):
- raise RuntimeError("could not establish rebuild process ownership")
self._ownership.record_launch(
process.pid,
identities[process.pid],
@@ -1811,6 +1833,15 @@ class SidecarOwnership:
"socket_path": str(self._socket_path),
"provider_root": str(self._provider_root),
}
+ if _uses_linux_starttime_stamp():
+ # In-memory identity is boot-relative starttime ticks. Keep the
+ # historical wall-clock field so older readers still parse the file,
+ # and persist the stamp so a later boot does not depend on CLOCK_REALTIME.
+ record["starttime_ticks"] = created_at
+ wall_create_time = _process_wall_create_time(pid)
+ # Never store ticks in create_time: older readers treat that field
+ # as epoch seconds. Omit a wall value rather than invent one.
+ record["create_time"] = wall_create_time
if role is not None:
record["role"] = role.value
record["python"] = str(python) if python is not None else None
@@ -1888,7 +1919,7 @@ class SidecarOwnership:
await self._reap_unidentified_child()
_remove_sidecar_record(self.record_path)
return
- confirmed_create_time = identity.create_time if identity is not None else None
+ confirmed_create_time = identity.stamp if identity is not None else None
if verdict is _RecordedSidecar.UNVERIFIABLE or confirmed_create_time is None:
# A live pid the OS will not describe well enough to rule out as our
# own sidecar. Keep the record and fail the launch, exactly as for an
@@ -1956,7 +1987,13 @@ class SidecarOwnership:
# Only rediscover while the recorded root is still the process we
# identified; a dead root's pid may already have been recycled.
process_group = self._host.process_group(pid)
- _merge_owned_processes(identities, self._host.snapshot_tree(pid, process_group))
+ if not _refresh_owned_process_tree(
+ self._host,
+ identities,
+ pid,
+ process_group,
+ ):
+ process_group = None
else:
process_group = None
self._host.signal(identities, signum, process_group=process_group)
@@ -2187,7 +2224,7 @@ class SidecarOwnership:
identity = self._host.inspect_identity(pid)
if (
identity is None
- or identity.create_time != created_at
+ or identity.stamp != created_at
or identity.cmdline is None
or not _cmdline_matches_role(
identity.cmdline,
@@ -2211,7 +2248,7 @@ class SidecarOwnership:
own_uid = getuid() if callable(getuid) else None
if (
identity is None
- or identity.create_time != created_at
+ or identity.stamp != created_at
or identity.cmdline is None
or not identity.cmdline
or not _cmdline_matches_role(
@@ -2534,8 +2571,7 @@ async def _terminate_owned_process_tree(
stop_timeout_seconds: float,
) -> None:
identities = dict(owned_processes or {})
- if _host_identity_is_live(host, process.pid, identities):
- _merge_owned_processes(identities, host.snapshot_tree(process.pid, process_group))
+ _refresh_owned_process_tree(host, identities, process.pid, process_group)
host.signal(
identities,
signal.SIGTERM,
@@ -2551,8 +2587,7 @@ async def _terminate_owned_process_tree(
return
kill_signal = getattr(signal, "SIGKILL", signal.SIGTERM)
- if _host_identity_is_live(host, process.pid, identities):
- _merge_owned_processes(identities, host.snapshot_tree(process.pid, process_group))
+ _refresh_owned_process_tree(host, identities, process.pid, process_group)
host.signal(
identities,
kill_signal,
@@ -2621,12 +2656,99 @@ class _ProcessIdentity:
about a process and withhold others: macOS reads ``create_time`` and ``uids``
for any pid but refuses ``cmdline`` outside the caller's own uid. ``None``
therefore means "not disclosed", never "does not match".
+
+ ``stamp`` is the identity value from ``_process_creation_stamp``:
+ Linux starttime ticks, or ``psutil.Process.create_time()`` elsewhere.
+ ``wall_create_time`` retains the epoch value needed to compare a live Linux
+ process with a legacy record that predates ``starttime_ticks``.
"""
- create_time: float | None
+ stamp: float | None
cmdline: tuple[str, ...] | None
uid: int | None
environment: Mapping[str, str] | None = None
+ wall_create_time: float | None = None
+
+
+def _uses_linux_starttime_stamp() -> bool:
+ """Whether this host identifies processes by boot-relative starttime ticks."""
+
+ return sys.platform.startswith("linux")
+
+
+def _parse_proc_stat_starttime(stat_data: bytes) -> float:
+ """Parse ``/proc/<pid>/stat`` field 22 (starttime, clock ticks).
+
+ Field 2 (``comm``) is parenthesized and may contain spaces or parentheses,
+ so tokens after the last ``)`` are field 3 onward.
+ """
+
+ close = stat_data.rfind(b")")
+ if close < 0:
+ raise ValueError("proc stat comm field is missing")
+ fields = stat_data[close + 1 :].split()
+ try:
+ return float(fields[19])
+ except (IndexError, ValueError) as exc:
+ raise ValueError("proc stat starttime field is missing") from exc
+
+
+def _read_linux_starttime_ticks(pid: int) -> float:
+ """Read boot-relative starttime ticks for ``pid`` from ``/proc``."""
+
+ try:
+ data = Path(f"/proc/{pid}/stat").read_bytes()
+ except FileNotFoundError as exc:
+ raise psutil.NoSuchProcess(pid=pid) from exc
+ except PermissionError as exc:
+ raise psutil.AccessDenied(pid=pid) from exc
+ except OSError as exc:
+ if exc.errno in {errno.EACCES, errno.EPERM}:
+ raise psutil.AccessDenied(pid=pid) from exc
+ if exc.errno in {errno.ENOENT, errno.ESRCH}:
+ raise psutil.NoSuchProcess(pid=pid) from exc
+ raise
+ try:
+ return _parse_proc_stat_starttime(data)
+ except ValueError as exc:
+ raise psutil.AccessDenied(pid=pid) from exc
+
+
+def _process_creation_stamp(process: psutil.Process) -> float:
+ """Stable process-identity stamp.
+
+ On Linux this is ``/proc/<pid>/stat`` starttime ticks, which do not move
+ when CLOCK_REALTIME is stepped. Other platforms keep the spawn-time
+ ``psutil.Process.create_time()`` value, which those kernels record
+ absolutely and do not drift. Missing ``/proc`` falls back to
+ ``create_time()`` so test doubles without a real pid still work.
+ """
+
+ if _uses_linux_starttime_stamp():
+ try:
+ return _read_linux_starttime_ticks(int(process.pid))
+ except psutil.NoSuchProcess:
+ return float(process.create_time())
+ return float(process.create_time())
+
+
+def _process_wall_create_time(pid: int) -> float | None:
+ """Wall-clock ``psutil`` create_time, or ``None`` when the OS withholds it."""
+
+ try:
+ return float(psutil.Process(pid).create_time())
+ except psutil.Error:
+ return None
+
+
+def _is_identity_stamp(value: object) -> bool:
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
+ return False
+ try:
+ stamp = float(value)
+ except (OverflowError, ValueError):
+ return False
+ return math.isfinite(stamp) and stamp >= 0.0
class _RecordedSidecar(Enum):
@@ -2655,7 +2777,7 @@ def _inspect_process_identity(pid: int) -> _ProcessIdentity | None:
except psutil.NoSuchProcess:
return None
except psutil.Error:
- return _ProcessIdentity(create_time=None, cmdline=None, uid=None, environment=None)
+ return _ProcessIdentity(stamp=None, cmdline=None, uid=None, environment=None)
try:
if process.status() == psutil.STATUS_ZOMBIE:
return None
@@ -2666,10 +2788,11 @@ def _inspect_process_identity(pid: int) -> _ProcessIdentity | None:
try:
cmdline = _disclosed_identity_field(process.cmdline)
return _ProcessIdentity(
- create_time=_disclosed_identity_field(process.create_time),
+ stamp=_disclosed_identity_field(lambda: _process_creation_stamp(process)),
cmdline=None if cmdline is None else tuple(str(value) for value in cmdline),
uid=_process_real_uid(process),
environment=_disclosed_process_environment(process),
+ wall_create_time=_disclosed_identity_field(process.create_time),
)
except psutil.NoSuchProcess:
# The process exited between the reads. That is "gone", which retires the
@@ -2768,21 +2891,35 @@ def _recorded_sidecar_create_time(
socket_path: Path,
provider_root: Path,
) -> float | None:
- """The creation time a record can be matched against, or ``None``.
+ """The identity stamp a record can be matched against, or ``None``.
- A malformed creation time can never be matched by any process, so it yields
- nothing this launch may act on.
+ New Linux records persist ``starttime_ticks`` and that stamp is preferred.
+ Legacy records keep wall-clock ``create_time``. A malformed stamp can never
+ be matched by any process, so it yields nothing this launch may act on.
"""
matched = _record_for_this_installation(record, socket_path=socket_path, provider_root=provider_root)
if matched is None:
return None
+ if "starttime_ticks" in matched:
+ ticks = matched.get("starttime_ticks")
+ return float(ticks) if _is_identity_stamp(ticks) else None
created_at = matched.get("create_time")
- if not isinstance(created_at, (int, float)) or isinstance(created_at, bool):
+ if not _is_identity_stamp(created_at):
return None
return float(created_at)
+def _recorded_sidecar_has_starttime_ticks(
+ record: object,
+ *,
+ socket_path: Path,
+ provider_root: Path,
+) -> bool:
+ matched = _record_for_this_installation(record, socket_path=socket_path, provider_root=provider_root)
+ return matched is not None and _is_identity_stamp(matched.get("starttime_ticks"))
+
+
def _recorded_sidecar_group(
record: object,
*,
@@ -2950,6 +3087,93 @@ def _cmdline_matches_role(
)
+def _legacy_sidecar_record(record: object) -> bool:
+ return isinstance(record, dict) and record.get("role") is None
+
+
+def _recorded_child_python_missing(record: object) -> bool:
+ return not _legacy_sidecar_record(record) and _recorded_child_python(record) is None
+
+
+def _cmdline_matches_recorded_child(
+ record: object,
+ cmdline: tuple[str, ...] | None,
+ *,
+ socket_path: Path,
+ role: _MemoryChildRole,
+) -> bool | None:
+ """Whether a disclosed cmdline matches the record.
+
+ ``None`` means the command line was not disclosed.
+ """
+
+ if cmdline is None:
+ return None
+ if _legacy_sidecar_record(record):
+ return _cmdline_serves_socket(cmdline, socket_path)
+ recorded_python = _recorded_child_python(record)
+ if recorded_python is None:
+ return False
+ return _cmdline_matches_role(
+ cmdline,
+ role=role,
+ socket_path=socket_path,
+ python=recorded_python,
+ )
+
+
+def _legacy_recorded_wall_create_time(identity: _ProcessIdentity) -> float | None:
+ """Wall-clock create_time captured with the rest of the identity snapshot."""
+
+ wall = identity.wall_create_time
+ if wall is not None and not _is_identity_stamp(wall):
+ return None
+ return wall
+
+
+def _legacy_create_time_mismatch_verdict(
+ record: object,
+ identity: _ProcessIdentity,
+ *,
+ socket_path: Path,
+ provider_root: Path,
+ role: _MemoryChildRole,
+) -> _RecordedSidecar | None:
+ """Resolve a legacy wall-clock ``create_time`` mismatch.
+
+ Legacy wall-clock values can move by any amount after a clock correction,
+ so their magnitude is not identity evidence. Returns ``None`` only when
+ the exact command, uid, and provider root still prove this installation's
+ child. A disclosed contradiction is ``NOT_OURS`` and a withheld deciding
+ fact is ``UNVERIFIABLE``.
+ """
+
+ if _recorded_child_python_missing(record):
+ return _RecordedSidecar.UNVERIFIABLE
+ command_match = _cmdline_matches_recorded_child(
+ record,
+ identity.cmdline,
+ socket_path=socket_path,
+ role=role,
+ )
+ if command_match is None:
+ return _RecordedSidecar.UNVERIFIABLE
+ if not command_match:
+ return _RecordedSidecar.NOT_OURS
+ getuid = getattr(os, "getuid", None)
+ own_uid = getuid() if callable(getuid) else None
+ if own_uid is not None:
+ if identity.uid is None:
+ return _RecordedSidecar.UNVERIFIABLE
+ if identity.uid != own_uid:
+ return _RecordedSidecar.NOT_OURS
+ if identity.environment is None:
+ return _RecordedSidecar.NOT_OURS
+ if not _provider_roots_match(identity.environment.get("EVEROS_ROOT"), provider_root):
+ return _RecordedSidecar.NOT_OURS
+ return None
+
+
def _classify_recorded_child(
record: object,
identity: _ProcessIdentity | None,
@@ -2965,30 +3189,43 @@ def _classify_recorded_child(
)
if identity is None or recorded_create_time is None:
return _RecordedSidecar.NOT_OURS
+ has_starttime_ticks = _recorded_sidecar_has_starttime_ticks(
+ record,
+ socket_path=socket_path,
+ provider_root=provider_root,
+ )
+ live_recorded_stamp = (
+ identity.stamp if has_starttime_ticks else _legacy_recorded_wall_create_time(identity)
+ )
getuid = getattr(os, "getuid", None)
own_uid = getuid() if callable(getuid) else None
if identity.uid is not None and own_uid is not None and identity.uid != own_uid:
return _RecordedSidecar.NOT_OURS
- if identity.create_time is not None and identity.create_time != recorded_create_time:
- return _RecordedSidecar.NOT_OURS
- legacy_sidecar = isinstance(record, dict) and record.get("role") is None
- recorded_python = None if legacy_sidecar else _recorded_child_python(record)
- if not legacy_sidecar and recorded_python is None:
+ if live_recorded_stamp is not None and not _is_identity_stamp(live_recorded_stamp):
return _RecordedSidecar.UNVERIFIABLE
- if identity.cmdline is not None:
- matches_command = (
- _cmdline_serves_socket(identity.cmdline, socket_path)
- if legacy_sidecar
- else _cmdline_matches_role(
- identity.cmdline,
- role=role,
- socket_path=socket_path,
- python=recorded_python,
- )
- )
- if not matches_command:
+ if live_recorded_stamp is not None and live_recorded_stamp != recorded_create_time:
+ if has_starttime_ticks:
return _RecordedSidecar.NOT_OURS
- if not legacy_sidecar and identity.environment is not None:
+ drift_verdict = _legacy_create_time_mismatch_verdict(
+ record,
+ identity,
+ socket_path=socket_path,
+ provider_root=provider_root,
+ role=role,
+ )
+ if drift_verdict is not None:
+ return drift_verdict
+ if _recorded_child_python_missing(record):
+ return _RecordedSidecar.UNVERIFIABLE
+ command_match = _cmdline_matches_recorded_child(
+ record,
+ identity.cmdline,
+ socket_path=socket_path,
+ role=role,
+ )
+ if command_match is False:
+ return _RecordedSidecar.NOT_OURS
+ if not _legacy_sidecar_record(record) and identity.environment is not None:
if (
not _provider_roots_match(
identity.environment.get("EVEROS_ROOT"),
@@ -2997,11 +3234,11 @@ def _classify_recorded_child(
or identity.environment.get("AVIBE_MEMORY_CHILD_ROLE") != role.value
):
return _RecordedSidecar.NOT_OURS
- if identity.create_time is None or identity.cmdline is None:
+ if live_recorded_stamp is None or command_match is None:
return _RecordedSidecar.UNVERIFIABLE
if own_uid is not None and identity.uid is None:
return _RecordedSidecar.UNVERIFIABLE
- if not legacy_sidecar and identity.environment is None:
+ if not _legacy_sidecar_record(record) and identity.environment is None:
return _RecordedSidecar.UNVERIFIABLE
return _RecordedSidecar.OURS
@@ -3016,12 +3253,15 @@ def _classify_recorded_sidecar(
"""Decide what a recorded pid is, so the caller knows what it may do.
``OURS`` is the only verdict that permits a signal, and it still demands that
- the creation time, the real uid, and the exact ``-m`` entrypoint plus
- ``--uds`` argument all agree with the record. Any single disclosed fact that
- contradicts the record settles the matter as ``NOT_OURS`` -- a recycled pid
- or another user's process is safe to stop worrying about. What must not be
- waved through is a live pid whose deciding facts were never disclosed:
- treating it as gone would start a replacement sidecar beside it.
+ the identity stamp, the real uid, and the exact ``-m`` entrypoint plus
+ ``--uds`` argument all agree with the record. New records prefer
+ ``starttime_ticks``; a legacy wall-clock ``create_time`` mismatch may still
+ be ``OURS`` when cmdline, uid, and ``EVEROS_ROOT`` all match. Any single
+ disclosed fact that contradicts the record
+ settles the matter as ``NOT_OURS`` -- a recycled pid or another user's
+ process is safe to stop worrying about. What must not be waved through is
+ a live pid whose deciding facts were never disclosed: treating it as gone
+ would start a replacement sidecar beside it.
"""
return _classify_recorded_child(
@@ -3089,7 +3329,7 @@ def _processes_serving_owned_socket(*, socket_path: Path) -> dict[int, float]:
cmdline = _disclosed_identity_field(candidate.cmdline)
if cmdline is None or not _cmdline_serves_socket(tuple(str(value) for value in cmdline), socket_path):
continue
- created_at = _disclosed_identity_field(candidate.create_time)
+ created_at = _disclosed_identity_field(lambda: _process_creation_stamp(candidate))
except psutil.Error:
continue
# A claimed process whose creation time is withheld carries the negative
@@ -3120,7 +3360,7 @@ def _processes_serving_owned_root(*, provider_root: Path) -> dict[int, float]:
if not _cmdline_is_sidecar(rendered):
continue
environment = _disclosed_process_environment(candidate)
- created_at = _disclosed_identity_field(candidate.create_time)
+ created_at = _disclosed_identity_field(lambda: _process_creation_stamp(candidate))
except psutil.NoSuchProcess:
continue
except psutil.Error:
@@ -3170,7 +3410,7 @@ def _processes_rebuilding_owned_root(
python=python,
):
continue
- created_at = _disclosed_identity_field(candidate.create_time)
+ created_at = _disclosed_identity_field(lambda: _process_creation_stamp(candidate))
environment = _disclosed_process_environment(candidate)
except psutil.NoSuchProcess:
continue
@@ -3232,7 +3472,7 @@ def _processes_syncing_owned_root(
):
continue
try:
- created_at = _disclosed_identity_field(candidate.create_time)
+ created_at = _disclosed_identity_field(lambda: _process_creation_stamp(candidate))
environment = _disclosed_process_environment(candidate)
except psutil.NoSuchProcess:
continue
@@ -3281,7 +3521,7 @@ async def _wait_for_identities_exit(identities: Mapping[int, float], timeout_sec
def _snapshot_owned_processes(pid: int, process_group: int | None) -> dict[int, float]:
- """Record `(pid, create_time)` identities while the child is still owned."""
+ """Record `(pid, stamp)` identities while the child is still owned."""
identities: dict[int, float] = {}
try:
@@ -3291,7 +3531,7 @@ def _snapshot_owned_processes(pid: int, process_group: int | None) -> dict[int,
candidates = []
for candidate in candidates:
try:
- identities.setdefault(candidate.pid, candidate.create_time())
+ identities.setdefault(candidate.pid, _process_creation_stamp(candidate))
except psutil.Error:
continue
_merge_owned_processes(identities, _snapshot_process_group(process_group))
@@ -3305,7 +3545,7 @@ def _snapshot_process_group(process_group: int | None) -> dict[int, float]:
for candidate in psutil.process_iter():
try:
if os.getpgid(candidate.pid) == process_group:
- identities[candidate.pid] = candidate.create_time()
+ identities[candidate.pid] = _process_creation_stamp(candidate)
except psutil.AccessDenied:
# The member exists but its identity cannot be verified. Keep it with a
# sentinel so the "all confirmed" check sees an unverifiable member and
@@ -3332,11 +3572,30 @@ def _host_identity_is_live(
return created_at is not None and process_id in host.live({process_id: created_at})
-def _owned_process_identity_is_live(process_id: int, identities: Mapping[int, float]) -> bool:
+def _refresh_owned_process_tree(
+ host: _ProcessHost,
+ identities: dict[int, float],
+ process_id: int,
+ process_group: int | None,
+) -> bool:
+ """Extend ownership only while the captured root identity remains live."""
+
created_at = identities.get(process_id)
- if created_at is None:
+ if created_at is None or not _host_identity_is_live(
+ host,
+ process_id,
+ {process_id: created_at},
+ ):
+ return False
+ discovered = host.snapshot_tree(process_id, process_group)
+ if discovered.get(process_id) != created_at or not _host_identity_is_live(
+ host,
+ process_id,
+ {process_id: created_at},
+ ):
return False
- return process_id in _live_owned_processes({process_id: created_at})
+ _merge_owned_processes(identities, discovered)
+ return True
def _live_owned_processes(identities: Mapping[int, float]) -> dict[int, float]:
@@ -3344,7 +3603,7 @@ def _live_owned_processes(identities: Mapping[int, float]) -> dict[int, float]:
for process_id, created_at in identities.items():
try:
candidate = psutil.Process(process_id)
- if candidate.create_time() != created_at:
+ if _process_creation_stamp(candidate) != created_at:
continue
if candidate.status() == psutil.STATUS_ZOMBIE:
continue
@@ -3360,13 +3619,13 @@ def _live_owned_processes(identities: Mapping[int, float]) -> dict[int, float]:
def _confirmed_owned_processes(identities: Mapping[int, float]) -> dict[int, float]:
- """Return identities whose current creation time is readable and unchanged."""
+ """Return identities whose current creation stamp is readable and unchanged."""
confirmed: dict[int, float] = {}
for process_id, created_at in identities.items():
try:
candidate = psutil.Process(process_id)
- if candidate.create_time() != created_at or candidate.status() == psutil.STATUS_ZOMBIE:
+ if _process_creation_stamp(candidate) != created_at or candidate.status() == psutil.STATUS_ZOMBIE:
continue
except psutil.Error:
# AccessDenied is live-but-unverified: retain it for reaping, but
@@ -3429,7 +3688,9 @@ def _signal_owned_group_or_process(
if process.returncode is not None:
return
created_at = identities.get(process.pid)
- if created_at is None or process.pid not in _confirmed_owned_processes({process.pid: created_at}):
+ if created_at is None or process.pid not in _confirmed_owned_processes(
+ {process.pid: created_at}
+ ):
return
try:
process.send_signal(signum)
@@ -3441,7 +3702,7 @@ def _signal_owned_processes(identities: Mapping[int, float], signum: int) -> Non
for process_id, created_at in _confirmed_owned_processes(identities).items():
try:
candidate = psutil.Process(process_id)
- if candidate.create_time() != created_at:
+ if _process_creation_stamp(candidate) != created_at:
continue
candidate.send_signal(signum)
except (psutil.NoSuchProcess, psutil.AccessDenied):
@@ -3463,8 +3724,12 @@ async def _wait_for_owned_exit(
waiter = asyncio.create_task(process.wait(), name="memory-everos-reap")
try:
while time.monotonic() < deadline:
- if _owned_process_identity_is_live(process.pid, identities):
- _merge_owned_processes(identities, _snapshot_owned_processes(process.pid, process_group))
+ _refresh_owned_process_tree(
+ _SystemProcessHost(),
+ identities,
+ process.pid,
+ process_group,
+ )
if waiter.done() and not _live_owned_processes(identities):
await waiter
return True
diff --git a/core/memory/runtime.py b/core/memory/runtime.py
index a35dbb477..5cd615459 100644
--- a/core/memory/runtime.py
+++ b/core/memory/runtime.py
@@ -2848,6 +2848,7 @@ class MemoryRuntime:
except Exception:
# Retain the supervisor: only its successful stop proves
# that no owned child tree remains.
+ logger.exception("Memory sidecar restart failed")
self._runtime_error = "memory_restart_failed"
return {"ok": False, "error": self._runtime_error}
self._process = None
diff --git a/core/memory/sync_process.py b/core/memory/sync_process.py
index 9ba9b00cb..a248bd2a8 100644
--- a/core/memory/sync_process.py
+++ b/core/memory/sync_process.py
@@ -31,6 +31,8 @@ from core.memory.process import (
_ProviderRootBusy,
_ProviderRootLock,
_ensure_owner_directory,
+ _is_identity_stamp,
+ _process_creation_stamp,
_provider_rebuild_lock_path,
_provider_root_coordination_path,
_provider_roots_match,
@@ -41,6 +43,7 @@ from core.memory.process import (
_finish_cleanup_despite_cancellation,
_finish_handoff_despite_cancellation,
_terminate_owned_process_tree,
+ _uses_linux_starttime_stamp,
)
@@ -98,14 +101,16 @@ class _ParentIdentity:
pid: int
create_time: float
uid: int | None
+ stamp: float | None = None
def _parent_identity() -> _ParentIdentity:
process = psutil.Process(os.getpid())
create_time = float(process.create_time())
+ stamp = _process_creation_stamp(process)
getter = getattr(os, "getuid", None)
uid = int(getter()) if callable(getter) else None
- return _ParentIdentity(os.getpid(), create_time, uid)
+ return _ParentIdentity(os.getpid(), create_time, uid, stamp)
class SyncOwnership:
@@ -272,12 +277,16 @@ class SyncOwnership:
parent_identity = self.host.inspect_identity(int(record["parent_pid"]))
if parent_identity is not None:
expected_uid = record.get("parent_uid")
- if parent_identity.create_time is None or (
- expected_uid is not None and parent_identity.uid is None
- ):
+ if expected_uid is not None and parent_identity.uid is None:
raise SyncOwnershipError("sync parent identity is unavailable")
if (
- parent_identity.create_time == float(record["parent_create_time"])
+ _recorded_sync_time_matches(
+ parent_identity,
+ record,
+ stamp_key="parent_starttime_ticks",
+ wall_key="parent_create_time",
+ subject="parent",
+ )
and parent_identity.uid == expected_uid
and record.get("cleanup_failed") is not True
):
@@ -314,7 +323,7 @@ class SyncOwnership:
**record,
"state": "finalized",
"pid": pid,
- "create_time": created_at,
+ **_sync_recorded_child_times(identity, captured_stamp=created_at),
"process_group": group,
}
_validate_child_identity(identity, record, provider_root=self.provider_root)
@@ -344,13 +353,17 @@ class SyncOwnership:
if foreign:
raise SyncOwnershipError("sync process group contains unverifiable members")
identities: dict[int, float] = {}
- if identity is not None and record.get("create_time") is not None:
- identities[pid] = float(record["create_time"])
+ if identity is not None and identity.stamp is not None:
+ identities[pid] = float(identity.stamp)
for member_pid, created_at in claimed.items():
member = self.host.inspect_identity(member_pid)
if member is None:
continue
- member_record = {**record, "pid": member_pid, "create_time": created_at}
+ member_record = {
+ **record,
+ "pid": member_pid,
+ **_sync_recorded_child_times(member, captured_stamp=created_at),
+ }
_validate_child_identity(
member,
member_record,
@@ -462,6 +475,10 @@ class EverOSSyncProcess:
"role": SYNC_ROLE,
"argv": argv,
}
+ if _uses_linux_starttime_stamp():
+ if not _is_identity_stamp(parent.stamp):
+ return SyncProcessResult.FAILED
+ pending["parent_starttime_ticks"] = parent.stamp
process: asyncio.subprocess.Process | None = None
group: int | None = None
identities: dict[int, float] = {}
@@ -494,10 +511,24 @@ class EverOSSyncProcess:
identity = self._ownership.host.inspect_identity(process.pid)
if identity is None or group is None:
raise SyncOwnershipError("sync child identity could not be observed")
- _validate_child_identity(identity, {**pending, "pid": process.pid, "create_time": identity.create_time}, provider_root=self.provider_root)
- if identity.create_time is None:
+ _validate_child_identity(
+ identity,
+ {
+ **pending,
+ "pid": process.pid,
+ **_sync_recorded_child_times(identity),
+ },
+ provider_root=self.provider_root,
+ )
+ if identity.stamp is None:
raise SyncOwnershipError("sync child creation time is unavailable")
- finalized = {**pending, "state": "finalized", "pid": process.pid, "create_time": identity.create_time, "process_group": group}
+ finalized = {
+ **pending,
+ "state": "finalized",
+ "pid": process.pid,
+ **_sync_recorded_child_times(identity),
+ "process_group": group,
+ }
self._ownership.finalize(finalized, nonce=nonce)
process.send_signal(signal.SIGCONT)
if spawn_interrupted:
@@ -510,7 +541,7 @@ class EverOSSyncProcess:
result = SyncProcessResult.TIMED_OUT
except asyncio.CancelledError:
result = SyncProcessResult.INTERRUPTED
- identities[process.pid] = float(identity.create_time)
+ identities[process.pid] = float(identity.stamp)
await self._terminate_owned_sync_tree(
process,
process_group=group,
@@ -693,12 +724,77 @@ def _validate_record(record: Mapping[str, Any], *, provider_root: Path) -> None:
parent_uid = record.get("parent_uid")
if not isinstance(parent_pid, int) or parent_pid <= 1:
raise SyncOwnershipError("sync parent pid is invalid")
- if not isinstance(parent_create_time, (int, float)) or isinstance(parent_create_time, bool):
+ if not _is_identity_stamp(parent_create_time):
raise SyncOwnershipError("sync parent create-time is invalid")
+ if "parent_starttime_ticks" in record and not _is_identity_stamp(
+ record.get("parent_starttime_ticks")
+ ):
+ raise SyncOwnershipError("sync parent start-time is invalid")
+ create_time = record.get("create_time")
+ if create_time is not None and not _is_identity_stamp(create_time):
+ raise SyncOwnershipError("sync child create-time is invalid")
+ if "starttime_ticks" in record and not _is_identity_stamp(record.get("starttime_ticks")):
+ raise SyncOwnershipError("sync child start-time is invalid")
+ if record.get("state") == "finalized" and (
+ "starttime_ticks" not in record and not _is_identity_stamp(create_time)
+ ):
+ raise SyncOwnershipError("sync child creation time is invalid")
if parent_uid is not None and (not isinstance(parent_uid, int) or isinstance(parent_uid, bool) or parent_uid < 0):
raise SyncOwnershipError("sync parent uid is invalid")
+def _sync_recorded_child_times(
+ identity: _ProcessIdentity,
+ *,
+ captured_stamp: float | None = None,
+) -> dict[str, float | None]:
+ stamp = identity.stamp if captured_stamp is None else captured_stamp
+ if not _is_identity_stamp(stamp):
+ raise SyncOwnershipError("sync child creation time is unavailable")
+ if _uses_linux_starttime_stamp():
+ wall = identity.wall_create_time
+ return {
+ "create_time": float(wall) if _is_identity_stamp(wall) else None,
+ "starttime_ticks": float(stamp),
+ }
+ return {"create_time": float(stamp)}
+
+
+def _recorded_sync_time_matches(
+ identity: _ProcessIdentity,
+ record: Mapping[str, Any],
+ *,
+ stamp_key: str,
+ wall_key: str,
+ subject: str,
+) -> bool:
+ if stamp_key in record:
+ live = identity.stamp
+ if not _is_identity_stamp(live):
+ raise SyncOwnershipError(f"sync {subject} creation time is unavailable")
+ return float(live) == float(record[stamp_key])
+ if subject == "parent":
+ # A legacy record can only be read by a later process. The writer is
+ # gone, so exact wall equality is the remaining parent identity; uid
+ # alone would treat a recycled same-uid pid as the original owner.
+ wall = identity.wall_create_time
+ if not _is_identity_stamp(wall):
+ raise SyncOwnershipError(f"sync {subject} creation time is unavailable")
+ return float(wall) == float(record[wall_key])
+ if _uses_linux_starttime_stamp():
+ wall = identity.wall_create_time
+ if not _is_identity_stamp(wall):
+ raise SyncOwnershipError(f"sync {subject} creation time is unavailable")
+ # Legacy child records still have argv/root/role/nonce to authenticate
+ # after a CLOCK_REALTIME step. Presence of a readable wall time is
+ # enough to continue to those facts.
+ return True
+ live = identity.stamp
+ if not _is_identity_stamp(live):
+ raise SyncOwnershipError(f"sync {subject} creation time is unavailable")
+ return float(live) == float(record[wall_key])
+
+
def _validate_child_identity(
identity: _ProcessIdentity,
record: Mapping[str, Any],
@@ -706,12 +802,14 @@ def _validate_child_identity(
provider_root: Path,
require_argv: bool = True,
) -> None:
- expected_create = record.get("create_time")
- if expected_create is not None:
- if identity.create_time is None:
- raise SyncOwnershipError("sync child creation time is unavailable")
- if identity.create_time != float(expected_create):
- raise _SyncIdentityMismatch("sync child creation time does not match")
+ if not _recorded_sync_time_matches(
+ identity,
+ record,
+ stamp_key="starttime_ticks",
+ wall_key="create_time",
+ subject="child",
+ ):
+ raise _SyncIdentityMismatch("sync child creation time does not match")
uid = record.get("parent_uid")
if uid is not None:
if identity.uid is None:
diff --git a/tests/test_memory_process.py b/tests/test_memory_process.py
index ce7c2aa6d..18aff2668 100644
--- a/tests/test_memory_process.py
+++ b/tests/test_memory_process.py
@@ -760,6 +760,39 @@ def test_sidecar_safety_monitor_ignores_expected_shutdown(tmp_path: Path, caplog
assert process._process is child
+def test_sidecar_safety_monitor_logs_the_underlying_exception(
+ tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class _Child:
+ pid = 999_999
+ returncode = None
+
+ process = EverOSProcess(
+ sys.executable,
+ effective_home=tmp_path,
+ settings=_settings(),
+ _host=_FakeProcessHost(),
+ )
+ child = _Child()
+ process._process = child
+ process._desired_running = True
+ process._owned_processes = {child.pid: 11.0}
+
+ def reject_tree(_pid: int) -> dict[int, float]:
+ raise RuntimeError("sidecar ownership changed during monitoring")
+
+ monkeypatch.setattr(process, "_refresh_owned_processes", reject_tree)
+
+ with caplog.at_level(logging.ERROR, logger=memory_process.logger.name):
+ asyncio.run(process._monitor_child(child))
+
+ assert "EverOS sidecar safety monitor rejected the child tree" in caplog.text
+ assert "sidecar ownership changed during monitoring" in caplog.text
+ assert "recorded_stamp=11.0" in caplog.text
+
+
async def test_sidecar_stop_reaps_a_descendant_that_leaves_the_child_group(tmp_path: Path) -> None:
child_pid_path = tmp_path / "detached-child.pid"
script = (
@@ -818,6 +851,100 @@ def test_sidecar_cleanup_skips_a_reused_pid_identity(monkeypatch, tmp_path: Path
assert signals == []
+async def test_sidecar_stop_reaps_direct_child_after_create_time_clock_step(
+ monkeypatch,
+ tmp_path: Path,
+) -> None:
+ """A CLOCK_REALTIME step must not block SIGTERM for a stable child stamp."""
+
+ child = await asyncio.create_subprocess_exec(
+ sys.executable,
+ "-c",
+ "import time; time.sleep(60)",
+ start_new_session=True,
+ )
+ try:
+ host = _SystemProcessHost()
+ process_group = os.getpgid(child.pid)
+ identities = host.snapshot_tree(child.pid, process_group)
+ captured_stamp = identities[child.pid]
+ original_process = memory_process.psutil.Process
+ original_iter = memory_process.psutil.process_iter
+ original_stamp = memory_process._process_creation_stamp
+
+ def _stamp_immune_to_wall_drift(proc: object) -> float:
+ if getattr(proc, "pid", None) == child.pid:
+ return captured_stamp
+ return original_stamp(proc)
+
+ class _ShiftedProcess:
+ def __init__(self, process_id: int) -> None:
+ self._inner = original_process(process_id)
+ self.pid = process_id
+
+ def create_time(self) -> float:
+ return float(self._inner.create_time()) + 48.0
+
+ def __getattr__(self, name: str):
+ return getattr(self._inner, name)
+
+ def _shifted_iter(*args, **kwargs):
+ for candidate in original_iter(*args, **kwargs):
+ try:
+ yield _ShiftedProcess(candidate.pid)
+ except (psutil.Error, OSError):
+ continue
+
+ monkeypatch.setattr(memory_process.psutil, "Process", _ShiftedProcess)
+ monkeypatch.setattr(memory_process.psutil, "process_iter", _shifted_iter)
+ monkeypatch.setattr(memory_process, "_process_creation_stamp", _stamp_immune_to_wall_drift)
+ process = EverOSProcess(sys.executable, effective_home=tmp_path, settings=_settings())
+ await process._terminate_owned_tree(
+ child,
+ process_group=process_group,
+ owned_processes=identities,
+ )
+ assert child.returncode is not None
+ assert not _pid_exists(child.pid)
+ finally:
+ if child.returncode is None:
+ child.terminate()
+ try:
+ await asyncio.wait_for(child.wait(), timeout=3.0)
+ except TimeoutError:
+ child.kill()
+ await child.wait()
+
+
+async def test_sidecar_stop_does_not_signal_real_child_when_identity_stamp_is_poisoned() -> None:
+ child = await asyncio.create_subprocess_exec(
+ sys.executable,
+ "-c",
+ "import time; time.sleep(60)",
+ start_new_session=True,
+ )
+ try:
+ process_group = os.getpgid(child.pid)
+ identities = {child.pid: _ORPHAN_CREATE_TIME}
+ memory_process._signal_owned_group_or_process(
+ child,
+ process_group,
+ identities,
+ signal.SIGTERM,
+ )
+ await asyncio.sleep(0.05)
+ assert child.returncode is None
+ assert _pid_exists(child.pid)
+ finally:
+ if child.returncode is None:
+ child.terminate()
+ try:
+ await asyncio.wait_for(child.wait(), timeout=3.0)
+ except TimeoutError:
+ child.kill()
+ await child.wait()
+
+
async def test_sidecar_cleanup_never_signals_spawned_pid_after_identity_changes(monkeypatch, tmp_path: Path) -> None:
signals: list[tuple[str, int]] = []
@@ -856,7 +983,13 @@ async def test_sidecar_cleanup_never_signals_spawned_pid_after_identity_changes(
def send_signal(self, signum: int) -> None:
signals.append(("psutil", signum))
+ def _reused_stamp(_proc: object) -> float:
+ # Linux identity is starttime ticks, not create_time(). Shift the
+ # stamp itself so this still models a recycled pid on CI.
+ return captured_at + 1.0
+
monkeypatch.setattr(memory_process.psutil, "Process", _ReusedProcess)
+ monkeypatch.setattr(memory_process, "_process_creation_stamp", _reused_stamp)
try:
host.signal(identities, signal.SIGTERM)
host.signal(
@@ -878,6 +1011,99 @@ async def test_sidecar_cleanup_never_signals_spawned_pid_after_identity_changes(
await child.wait()
+def test_sidecar_cleanup_reverifies_asyncio_pid_before_signaling(monkeypatch) -> None:
+ signals: list[int] = []
+
+ class _Transport:
+ _proc = SimpleNamespace(returncode=None)
+
+ def get_pid(self) -> int:
+ return _ORPHAN_PID
+
+ def get_returncode(self) -> None:
+ # Models the interval after waitpid() reaped the child but before
+ # asyncio's scheduled process-exited callback updates the transport.
+ return None
+
+ def send_signal(self, signum: int) -> None:
+ signals.append(signum)
+
+ class _Protocol:
+ stdin = None
+ stdout = None
+ stderr = None
+
+ process = asyncio.subprocess.Process(_Transport(), _Protocol(), None)
+ monkeypatch.setattr(memory_process, "_confirmed_owned_processes", lambda _identities: {})
+
+ _SystemProcessHost().signal(
+ {_ORPHAN_PID: _ORPHAN_CREATE_TIME},
+ signal.SIGTERM,
+ process=process,
+ )
+
+ assert signals == []
+
+
+async def test_sidecar_wait_never_discovers_from_a_reused_asyncio_pid(monkeypatch) -> None:
+ identities = {_ORPHAN_PID: _ORPHAN_CREATE_TIME}
+ snapshot_calls: list[tuple[int, int | None]] = []
+
+ class _ReapedChild:
+ pid = _ORPHAN_PID
+ returncode = None
+
+ async def wait(self) -> int:
+ return 0
+
+ def snapshot(pid: int, process_group: int | None) -> dict[int, float]:
+ snapshot_calls.append((pid, process_group))
+ return {
+ _ORPHAN_PID: _ORPHAN_CREATE_TIME + 1,
+ _ORPHAN_DESCENDANT_PID: _ORPHAN_CREATE_TIME + 2,
+ }
+
+ monkeypatch.setattr(memory_process, "_snapshot_owned_processes", snapshot)
+ monkeypatch.setattr(memory_process, "_live_owned_processes", lambda _identities: {})
+
+ assert await memory_process._wait_for_owned_exit(
+ _ReapedChild(),
+ process_group=_ORPHAN_PID,
+ identities=identities,
+ timeout_seconds=0.1,
+ )
+ assert snapshot_calls == []
+ assert identities == {_ORPHAN_PID: _ORPHAN_CREATE_TIME}
+
+
+def test_owned_tree_refresh_reverifies_the_root_after_snapshot() -> None:
+ identities = {_ORPHAN_PID: _ORPHAN_CREATE_TIME}
+
+ class _ReusingHost(_FakeProcessHost):
+ def snapshot_tree(self, pid: int, process_group: int | None) -> dict[int, float]:
+ snapshot = super().snapshot_tree(pid, process_group)
+ self.live_processes[pid] = _ORPHAN_CREATE_TIME + 1
+ return snapshot
+
+ host = _ReusingHost(
+ live_processes=dict(identities),
+ trees={
+ (_ORPHAN_PID, _ORPHAN_PID): {
+ _ORPHAN_PID: _ORPHAN_CREATE_TIME,
+ _ORPHAN_DESCENDANT_PID: _ORPHAN_CREATE_TIME + 2,
+ }
+ },
+ )
+
+ assert not memory_process._refresh_owned_process_tree(
+ host,
+ identities,
+ _ORPHAN_PID,
+ _ORPHAN_PID,
+ )
+ assert identities == {_ORPHAN_PID: _ORPHAN_CREATE_TIME}
+
+
def test_sidecar_cleanup_does_not_group_signal_an_unconfirmed_member(monkeypatch) -> None:
group_signals: list[tuple[int, int]] = []
child_signals: list[int] = []
@@ -1063,8 +1289,9 @@ def _orphan_record(process: EverOSProcess, **overrides) -> dict:
def _orphan_identity(process: EverOSProcess, **overrides) -> _ProcessIdentity:
+ creation_stamp = overrides.pop("stamp", overrides.pop("create_time", _ORPHAN_CREATE_TIME))
fields = {
- "create_time": _ORPHAN_CREATE_TIME,
+ "stamp": creation_stamp,
"cmdline": (
sys.executable,
"-m",
@@ -1073,6 +1300,7 @@ def _orphan_identity(process: EverOSProcess, **overrides) -> _ProcessIdentity:
str(process.socket_path),
),
"uid": os.getuid() if hasattr(os, "getuid") else None,
+ "wall_create_time": overrides.pop("wall_create_time", creation_stamp),
}
fields.update(overrides)
return _ProcessIdentity(**fields)
@@ -1151,6 +1379,11 @@ def test_recorded_sidecar_identity_accepts_only_a_provably_owned_orphan(tmp_path
(_orphan_record(process), _orphan_identity(process, create_time=None, cmdline=None, uid=None)),
# The creation time alone is withheld, so pid reuse cannot be ruled out.
(_orphan_record(process), _orphan_identity(process, create_time=None)),
+ # Linux starttime ticks cannot be compared with a legacy epoch value.
+ (
+ _orphan_record(process),
+ _orphan_identity(process, create_time=424_242.0, wall_create_time=None),
+ ),
]
for record, identity in unverifiable:
assert verdict(record, identity) is _RecordedSidecar.UNVERIFIABLE, (record, identity)
@@ -1162,6 +1395,269 @@ def test_recorded_sidecar_identity_accepts_only_a_provably_owned_orphan(tmp_path
)
+def test_inspect_identity_keeps_wall_clock_beside_linux_starttime_ticks(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(memory_process, "_uses_linux_starttime_stamp", lambda: True)
+ monkeypatch.setattr(memory_process, "_read_linux_starttime_ticks", lambda _pid: 99.0)
+ monkeypatch.setattr(memory_process.psutil, "Process", _guarded_process_class(uid=4_242))
+
+ identity = memory_process._inspect_process_identity(_ORPHAN_PID)
+
+ assert identity == _ProcessIdentity(
+ stamp=99.0,
+ cmdline=None,
+ uid=4_242,
+ wall_create_time=_ORPHAN_CREATE_TIME,
+ )
+
+
+def test_linux_creation_stamp_reads_starttime_ticks_not_wall_clock(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ticks = 424_242.0
+ monkeypatch.setattr(memory_process, "_uses_linux_starttime_stamp", lambda: True)
+ monkeypatch.setattr(memory_process, "_read_linux_starttime_ticks", lambda _pid: ticks)
+
+ class _Proc:
+ pid = 99
+
+ def create_time(self) -> float:
+ return _ORPHAN_CREATE_TIME + 48.0
+
+ assert memory_process._process_creation_stamp(_Proc()) == ticks
+
+
+def test_parse_proc_stat_starttime_handles_spaces_in_comm() -> None:
+ # Field 2 (comm) can contain spaces and parentheses. Field 22 is starttime.
+ after_comm = [b"S"] + [b"0"] * 18 + [b"987654", b"1"]
+ stat_data = b"42 (python 3.11) " + b" ".join(after_comm)
+ assert memory_process._parse_proc_stat_starttime(stat_data) == 987654.0
+
+
+def test_linux_starttime_reader_accepts_non_utf8_comm(monkeypatch: pytest.MonkeyPatch) -> None:
+ after_comm = [b"S"] + [b"0"] * 18 + [b"987654", b"1"]
+ stat_data = b"42 (worker-\xff) " + b" ".join(after_comm)
+
+ monkeypatch.setattr(Path, "read_bytes", lambda _path: stat_data)
+ monkeypatch.setattr(
+ Path,
+ "read_text",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(
+ UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid start byte")
+ ),
+ )
+
+ assert memory_process._read_linux_starttime_ticks(_ORPHAN_PID) == 987654.0
+
+
+ "stamp",
+ [-1.0, float("nan"), float("inf"), float("-inf"), 10**1000],
+)
+def test_identity_stamps_must_be_finite_and_non_negative(stamp: float | int) -> None:
+ assert not memory_process._is_identity_stamp(stamp)
+
+
+def test_legacy_record_rejects_a_nan_creation_stamp(tmp_path: Path) -> None:
+ process = _orphan_process(tmp_path)
+ assert _classify_recorded_sidecar(
+ _orphan_record(process, create_time=float("nan")),
+ _orphan_identity(
+ process,
+ wall_create_time=_ORPHAN_CREATE_TIME + 48.0,
+ environment={"EVEROS_ROOT": str(process.provider_root)},
+ ),
+ socket_path=process.socket_path,
+ provider_root=process.provider_root,
+ ) is _RecordedSidecar.NOT_OURS
+
+
+def test_legacy_record_treats_a_nan_live_creation_stamp_as_unverifiable(tmp_path: Path) -> None:
+ process = _orphan_process(tmp_path)
+ assert _classify_recorded_sidecar(
+ _orphan_record(process),
+ _orphan_identity(
+ process,
+ wall_create_time=float("nan"),
+ environment={"EVEROS_ROOT": str(process.provider_root)},
+ ),
+ socket_path=process.socket_path,
+ provider_root=process.provider_root,
+ ) is _RecordedSidecar.UNVERIFIABLE
+
+
+def test_creation_stamp_falls_back_to_create_time_off_linux(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(memory_process, "_uses_linux_starttime_stamp", lambda: False)
+
+ class _Proc:
+ pid = 99
+
+ def create_time(self) -> float:
+ return _ORPHAN_CREATE_TIME
+
+ assert memory_process._process_creation_stamp(_Proc()) == _ORPHAN_CREATE_TIME
+
+
+def test_legacy_record_accepts_arbitrary_create_time_drift_when_facts_match(
+ tmp_path: Path,
+) -> None:
+ ticks = 424_242.0
+ drifted = _ORPHAN_CREATE_TIME + 86_400.0
+ host = _FakeProcessHost(live_processes={_ORPHAN_PID: ticks})
+ process = _orphan_process(tmp_path, host=host)
+ host.identities[_ORPHAN_PID] = _orphan_identity(
+ process,
+ create_time=ticks,
+ wall_create_time=drifted,
+ environment={"EVEROS_ROOT": str(process.provider_root)},
+ )
+ record_path = _write_orphan_record(process, _orphan_record(process))
+
+ asyncio.run(process._ownership.reap())
+
+ assert host.signal_calls == [({_ORPHAN_PID: ticks}, signal.SIGTERM, None, None)]
+ assert not record_path.exists()
+
+
+def test_legacy_record_rejects_create_time_drift_when_cmdline_mismatches(
+ tmp_path: Path,
+) -> None:
+ process = _orphan_process(tmp_path)
+ assert _classify_recorded_sidecar(
+ _orphan_record(process),
+ _orphan_identity(
+ process,
+ create_time=424_242.0,
+ wall_create_time=_ORPHAN_CREATE_TIME + 86_400.0,
+ cmdline=(sys.executable, "-m", "http.server"),
+ environment={"EVEROS_ROOT": str(process.provider_root)},
+ ),
+ socket_path=process.socket_path,
+ provider_root=process.provider_root,
+ ) is _RecordedSidecar.NOT_OURS
+
+
+def test_legacy_record_treats_undisclosed_cmdline_as_unverifiable_on_create_time_drift(
+ tmp_path: Path,
+) -> None:
+ process = _orphan_process(tmp_path)
+ assert _classify_recorded_sidecar(
+ _orphan_record(process),
+ _orphan_identity(
+ process,
+ create_time=424_242.0,
+ wall_create_time=_ORPHAN_CREATE_TIME + 86_400.0,
+ cmdline=None,
+ environment={"EVEROS_ROOT": str(process.provider_root)},
+ ),
+ socket_path=process.socket_path,
+ provider_root=process.provider_root,
+ ) is _RecordedSidecar.UNVERIFIABLE
+
+
+def test_recorded_sidecar_prefers_starttime_ticks_over_create_time(tmp_path: Path) -> None:
+ process = _orphan_process(tmp_path)
+ record = _orphan_record(process, starttime_ticks=99.0, create_time=_ORPHAN_CREATE_TIME)
+ assert _classify_recorded_sidecar(
+ record,
+ _orphan_identity(process, create_time=99.0),
+ socket_path=process.socket_path,
+ provider_root=process.provider_root,
+ ) is _RecordedSidecar.OURS
+ assert _classify_recorded_sidecar(
+ record,
+ _orphan_identity(process, create_time=_ORPHAN_CREATE_TIME),
+ socket_path=process.socket_path,
+ provider_root=process.provider_root,
+ ) is _RecordedSidecar.NOT_OURS
+
+
+def test_sidecar_record_writes_starttime_ticks_on_linux(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(memory_process, "_uses_linux_starttime_stamp", lambda: True)
+ monkeypatch.setattr(
+ memory_process,
+ "_process_wall_create_time",
+ lambda _pid: _ORPHAN_CREATE_TIME,
+ )
+ process = _orphan_process(tmp_path)
+ process._ownership.record_path.parent.mkdir(parents=True, exist_ok=True)
+
+ process._ownership.record_launch(_ORPHAN_PID, 4242.0, _ORPHAN_PID)
+ recorded = json.loads(process._ownership.record_path.read_text(encoding="utf-8"))
+
+ assert recorded["create_time"] == _ORPHAN_CREATE_TIME
+ assert recorded["starttime_ticks"] == 4242.0
+
+
+def test_sidecar_record_omits_wall_create_time_when_undisclosed(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(memory_process, "_uses_linux_starttime_stamp", lambda: True)
+ monkeypatch.setattr(memory_process, "_process_wall_create_time", lambda _pid: None)
+ process = _orphan_process(tmp_path)
+ process._ownership.record_path.parent.mkdir(parents=True, exist_ok=True)
+
+ process._ownership.record_launch(_ORPHAN_PID, 4242.0, _ORPHAN_PID)
+ recorded = json.loads(process._ownership.record_path.read_text(encoding="utf-8"))
+
+ assert recorded["create_time"] is None
+ assert recorded["starttime_ticks"] == 4242.0
+
+
+def test_legacy_linux_ticks_identity_reaps_after_arbitrary_wall_clock_step(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ ticks = 424_242.0
+ drifted_wall = _ORPHAN_CREATE_TIME + 86_400.0
+ helper = {_ORPHAN_GROUP_HELPER_PID: _ORPHAN_CREATE_TIME + 1}
+ host = _FakeProcessHost(
+ process_groups={_ORPHAN_PID: _ORPHAN_PID},
+ groups={_ORPHAN_PID: (dict(helper), [])},
+ live_processes={_ORPHAN_PID: ticks, **helper},
+ trees={(_ORPHAN_PID, _ORPHAN_PID): {_ORPHAN_PID: ticks, **helper}},
+ )
+ process = _orphan_process(tmp_path, host=host)
+ host.identities[_ORPHAN_PID] = _orphan_identity(
+ process,
+ stamp=ticks,
+ wall_create_time=drifted_wall,
+ environment={"EVEROS_ROOT": str(process.provider_root)},
+ )
+ record_path = _write_orphan_record(process, _orphan_record(process))
+
+ asyncio.run(process._ownership.reap())
+
+ signaled = {pid for call in host.signal_calls for pid in call[0]}
+ assert _ORPHAN_PID in signaled
+ assert _ORPHAN_GROUP_HELPER_PID in signaled
+ assert not record_path.exists()
+
+
+def test_legacy_linux_ticks_identity_accepts_large_wall_drift_with_exact_facts(
+ tmp_path: Path,
+) -> None:
+ process = _orphan_process(tmp_path)
+ assert _classify_recorded_sidecar(
+ _orphan_record(process),
+ _orphan_identity(
+ process,
+ stamp=424_242.0,
+ wall_create_time=_ORPHAN_CREATE_TIME + 7 * 86_400.0,
+ environment={"EVEROS_ROOT": str(process.provider_root)},
+ ),
+ socket_path=process.socket_path,
+ provider_root=process.provider_root,
+ ) is _RecordedSidecar.OURS
+
+
def test_new_sidecar_role_record_reaps_with_exact_role_environment(tmp_path: Path) -> None:
host = _FakeProcessHost(
process_groups={_ORPHAN_PID: _ORPHAN_PID},
@@ -1283,7 +1779,12 @@ def test_process_identity_reports_undisclosed_fields_instead_of_gone(
identity = memory_process._inspect_process_identity(_ORPHAN_PID)
- assert identity == _ProcessIdentity(create_time=_ORPHAN_CREATE_TIME, cmdline=None, uid=4_242)
+ assert identity == _ProcessIdentity(
+ stamp=_ORPHAN_CREATE_TIME,
+ cmdline=None,
+ uid=4_242,
+ wall_create_time=_ORPHAN_CREATE_TIME,
+ )
class _Zombie(guarded):
def status(self) -> str:
@@ -1310,9 +1811,10 @@ def test_process_identity_reports_undisclosed_fields_instead_of_gone(
monkeypatch.setattr(memory_process.psutil, "Process", _NoUidsPlatform)
assert memory_process._inspect_process_identity(_ORPHAN_PID) == _ProcessIdentity(
- create_time=_ORPHAN_CREATE_TIME,
+ stamp=_ORPHAN_CREATE_TIME,
cmdline=None,
uid=None,
+ wall_create_time=_ORPHAN_CREATE_TIME,
)
@@ -1480,7 +1982,7 @@ def test_sidecar_launch_fails_closed_on_a_live_pid_it_cannot_describe(
socket_path=short_socket_path,
)
host.identities[_ORPHAN_PID] = _ProcessIdentity(
- create_time=_ORPHAN_CREATE_TIME,
+ stamp=_ORPHAN_CREATE_TIME,
cmdline=None,
uid=os.getuid() if hasattr(os, "getuid") else None,
)
@@ -1520,7 +2022,7 @@ def test_sidecar_launch_proceeds_past_a_recycled_pid_owned_by_another_user(
socket_path=short_socket_path,
)
host.identities[_ORPHAN_PID] = _ProcessIdentity(
- create_time=_ORPHAN_CREATE_TIME,
+ stamp=_ORPHAN_CREATE_TIME,
cmdline=None,
uid=foreign_uid,
)
@@ -1542,11 +2044,16 @@ def test_sidecar_records_a_verified_launch_identity_privately(tmp_path: Path) ->
process._ownership.record_launch(_ORPHAN_PID, _ORPHAN_CREATE_TIME, _ORPHAN_PID)
recorded = json.loads(process._ownership.record_path.read_text(encoding="utf-8"))
- assert recorded == _orphan_record(
+ expected = _orphan_record(
process,
role="sidecar",
python=sys.executable,
)
+ if memory_process._uses_linux_starttime_stamp():
+ expected["starttime_ticks"] = _ORPHAN_CREATE_TIME
+ # Fake pid has no wall-clock create_time; do not store ticks there.
+ expected["create_time"] = None
+ assert recorded == expected
assert stat.S_IMODE(process._ownership.record_path.lstat().st_mode) == 0o600
process._ownership.record_path.unlink()
@@ -2689,7 +3196,7 @@ def test_sidecar_and_rebuild_use_one_physical_identity_for_a_symlinked_home(
"python": sys.executable,
}
legacy_spelling_identity = _ProcessIdentity(
- create_time=_ORPHAN_CREATE_TIME,
+ stamp=_ORPHAN_CREATE_TIME,
cmdline=(
sys.executable,
"-m",
@@ -2702,6 +3209,7 @@ def test_sidecar_and_rebuild_use_one_physical_identity_for_a_symlinked_home(
"EVEROS_ROOT": str(logical_provider_root),
"AVIBE_MEMORY_CHILD_ROLE": "sidecar",
},
+ wall_create_time=_ORPHAN_CREATE_TIME,
)
assert _classify_recorded_child(
legacy_spelling_record,
@@ -4126,8 +4634,9 @@ def _rebuild_record(process: EverOSRebuildProcess, **overrides) -> dict:
def _rebuild_identity(process: EverOSRebuildProcess, **overrides) -> _ProcessIdentity:
+ creation_stamp = overrides.pop("stamp", overrides.pop("create_time", _ORPHAN_CREATE_TIME))
fields = {
- "create_time": _ORPHAN_CREATE_TIME,
+ "stamp": creation_stamp,
"cmdline": (
sys.executable,
"-m",
@@ -4141,6 +4650,7 @@ def _rebuild_identity(process: EverOSRebuildProcess, **overrides) -> _ProcessIde
"EVEROS_ROOT": str(process._provider_root),
"AVIBE_MEMORY_CHILD_ROLE": "cascade_rebuild",
},
+ "wall_create_time": overrides.pop("wall_create_time", creation_stamp),
}
fields.update(overrides)
return _ProcessIdentity(**fields)
@@ -4548,7 +5058,7 @@ async def test_rebuild_boot_without_artifact_python_discovers_and_reaps_child(
process_groups={_ORPHAN_PID: _ORPHAN_PID},
identities={
_ORPHAN_PID: _ProcessIdentity(
- create_time=_ORPHAN_CREATE_TIME,
+ stamp=_ORPHAN_CREATE_TIME,
cmdline=(
sys.executable,
"-m",
@@ -4613,7 +5123,7 @@ async def test_rebuild_boot_discovers_an_orphan_from_the_previous_artifact(
process_groups={_ORPHAN_PID: _ORPHAN_PID},
identities={
_ORPHAN_PID: _ProcessIdentity(
- create_time=_ORPHAN_CREATE_TIME,
+ stamp=_ORPHAN_CREATE_TIME,
cmdline=(
str(old_python),
"-m",
@@ -4722,7 +5232,7 @@ async def test_rebuild_boot_discovers_exact_survivor_after_reaping_valid_record(
_ORPHAN_PID: _rebuild_identity(process),
_ORPHAN_DESCENDANT_PID: _rebuild_identity(
process,
- create_time=_ORPHAN_CREATE_TIME + 1,
+ stamp=_ORPHAN_CREATE_TIME + 1,
),
}
)
@@ -4977,7 +5487,7 @@ async def test_sidecar_start_refuses_live_cross_home_peer_on_shared_root(
root_sidecars={_ORPHAN_PID: _ORPHAN_CREATE_TIME},
identities={
_ORPHAN_PID: _ProcessIdentity(
- create_time=_ORPHAN_CREATE_TIME,
+ stamp=_ORPHAN_CREATE_TIME,
cmdline=(
sys.executable,
"-m",
diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.py
index 8d44538a7..bfe171527 100644
--- a/tests/test_memory_runtime.py
+++ b/tests/test_memory_runtime.py
@@ -6684,6 +6684,7 @@ async def test_rebuild_settlement_survives_candidate_activation_failure(
async def test_runtime_restart_stop_failure_retains_old_process_and_paused_claims(
tmp_path: Path,
memory_runtime_factory,
+ caplog,
) -> None:
factory = FakeEverOSProcessFactory()
runtime = memory_runtime_factory(
@@ -6695,10 +6696,13 @@ async def test_runtime_restart_stop_failure_retains_old_process_and_paused_claim
old = FakeEverOSProcess(stop_failure=RuntimeError("still owned"))
runtime._process = old
- assert await runtime.restart() == {
- "ok": False,
- "error": "memory_restart_failed",
- }
+ with caplog.at_level(logging.ERROR, logger=memory_runtime.logger.name):
+ assert await runtime.restart() == {
+ "ok": False,
+ "error": "memory_restart_failed",
+ }
+ assert "Memory sidecar restart failed" in caplog.text
+ assert "still owned" in caplog.text
assert runtime._process is old
assert factory.created == []
assert runtime.module._worker._claims_paused is True
diff --git a/tests/test_memory_sync_process.py b/tests/test_memory_sync_process.py
index 661b19836..5984beb94 100644
--- a/tests/test_memory_sync_process.py
+++ b/tests/test_memory_sync_process.py
@@ -44,9 +44,9 @@ class _Host:
del socket_path, provider_root
assert role is _MemoryChildRole.CASCADE_SYNC
return {
- pid: float(identity.create_time)
+ pid: float(identity.stamp)
for pid, identity in self.identities.items()
- if identity.create_time is not None
+ if identity.stamp is not None
}, []
def signal(self, identities, signum, *, process_group=None, process=None):
@@ -245,11 +245,12 @@ async def test_recycled_sync_leader_retires_stale_finalized_record(tmp_path: Pat
memory_dir = tmp_path / "memory"
root = memory_dir / "everos-root"
record = _record(root, state="finalized", pid=451)
+ record["starttime_ticks"] = 10.5
uid = os.getuid() if hasattr(os, "getuid") else None
host = _Host(
{
451: _ProcessIdentity(
- create_time=99.5,
+ stamp=99.5,
cmdline=tuple(record["argv"]),
uid=uid,
environment={},
@@ -272,10 +273,11 @@ async def test_live_parent_keeps_singleton_sync_record_and_child_untouched(tmp_p
host = _Host(
{
99: _ProcessIdentity(
- create_time=8.25,
+ stamp=8.25,
cmdline=("avibe",),
uid=uid,
environment={},
+ wall_create_time=8.25,
)
}
)
@@ -289,6 +291,194 @@ async def test_live_parent_keeps_singleton_sync_record_and_child_untouched(tmp_p
assert host.signals == []
+async def test_legacy_recycled_parent_pid_does_not_block_cleanup(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(memory_sync_process, "_uses_linux_starttime_stamp", lambda: True)
+ memory_dir = tmp_path / "memory"
+ root = memory_dir / "everos-root"
+ uid = os.getuid() if hasattr(os, "getuid") else None
+
+ class RecycledParentHost(_Host):
+ def recorded_group_members(self, process_group, *, socket_path, provider_root, role=None):
+ del process_group, socket_path, provider_root, role
+ return {}, []
+
+ host = RecycledParentHost(
+ {
+ 99: _ProcessIdentity(
+ stamp=424_242.0,
+ cmdline=("avibe",),
+ uid=uid,
+ environment={},
+ wall_create_time=8.25 + 86_400.0,
+ )
+ }
+ )
+ ownership = SyncOwnership(sync_record_path(memory_dir), provider_root=root, host=host)
+ ownership.write(_record(root, state="finalized", pid=451))
+
+ await ownership.reconcile()
+
+ assert not ownership.path.exists()
+ assert host.signals == []
+
+
+async def test_legacy_sync_child_with_wall_clock_record_is_not_removed_as_recycled(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(memory_sync_process, "_uses_linux_starttime_stamp", lambda: True)
+ memory_dir = tmp_path / "memory"
+ root = memory_dir / "everos-root"
+ uid = os.getuid() if hasattr(os, "getuid") else None
+ record = _record(root, state="finalized", pid=451)
+ environment = {
+ "EVEROS_ROOT": str(root),
+ "AVIBE_MEMORY_CHILD_ROLE": SYNC_ROLE,
+ SYNC_NONCE_ENV: "a" * 64,
+ SYNC_PARENT_PID_ENV: "99",
+ SYNC_PARENT_CREATE_TIME_ENV: float(8.25).hex(),
+ SYNC_PARENT_UID_ENV: "" if uid is None else str(uid),
+ }
+ host = _Host(
+ {
+ 451: _ProcessIdentity(
+ stamp=424_242.0,
+ cmdline=tuple(record["argv"]),
+ uid=uid,
+ environment=environment,
+ wall_create_time=10.5 + 86_400.0,
+ )
+ }
+ )
+ ownership = SyncOwnership(sync_record_path(memory_dir), provider_root=root, host=host)
+ ownership.write(record)
+
+ await ownership.reconcile()
+
+ assert host.signals
+ assert host.signals[0][0] == {451: 424_242.0}
+ assert not ownership.path.exists()
+
+
+async def test_legacy_sync_child_with_clock_step_still_rejects_mismatched_facts(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(memory_sync_process, "_uses_linux_starttime_stamp", lambda: True)
+ memory_dir = tmp_path / "memory"
+ root = memory_dir / "everos-root"
+ uid = os.getuid() if hasattr(os, "getuid") else None
+ record = _record(root, state="finalized", pid=451)
+ environment = {
+ "EVEROS_ROOT": str(root),
+ "AVIBE_MEMORY_CHILD_ROLE": SYNC_ROLE,
+ SYNC_NONCE_ENV: "a" * 64,
+ SYNC_PARENT_PID_ENV: "99",
+ SYNC_PARENT_CREATE_TIME_ENV: float(8.25).hex(),
+ SYNC_PARENT_UID_ENV: "" if uid is None else str(uid),
+ }
+ host = _Host(
+ {
+ 451: _ProcessIdentity(
+ stamp=424_242.0,
+ cmdline=(str(root.parent / "runtime" / "bin" / "python"), "-m", "other"),
+ uid=uid,
+ environment=environment,
+ wall_create_time=10.5 + 86_400.0,
+ )
+ }
+ )
+ ownership = SyncOwnership(sync_record_path(memory_dir), provider_root=root, host=host)
+ ownership.write(record)
+
+ await ownership.reconcile()
+
+ assert not ownership.path.exists()
+ assert host.signals == []
+
+
+async def test_legacy_sync_child_without_wall_time_keeps_record(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(memory_sync_process, "_uses_linux_starttime_stamp", lambda: True)
+ memory_dir = tmp_path / "memory"
+ root = memory_dir / "everos-root"
+ uid = os.getuid() if hasattr(os, "getuid") else None
+ record = _record(root, state="finalized", pid=451)
+ host = _Host(
+ {
+ 451: _ProcessIdentity(
+ stamp=424_242.0,
+ cmdline=tuple(record["argv"]),
+ uid=uid,
+ environment={},
+ wall_create_time=None,
+ )
+ }
+ )
+ ownership = SyncOwnership(sync_record_path(memory_dir), provider_root=root, host=host)
+ ownership.write(record)
+
+ with pytest.raises(SyncOwnershipError, match="creation time is unavailable"):
+ await ownership.reconcile()
+
+ assert ownership.path.exists()
+ assert host.signals == []
+
+
+async def test_current_sync_parent_prefers_stable_stamp_over_wall_time(
+ tmp_path: Path,
+) -> None:
+ memory_dir = tmp_path / "memory"
+ root = memory_dir / "everos-root"
+ uid = os.getuid() if hasattr(os, "getuid") else None
+ record = _record(root, state="finalized", pid=451)
+ record["parent_starttime_ticks"] = 424_242.0
+ host = _Host(
+ {
+ 99: _ProcessIdentity(
+ stamp=424_242.0,
+ cmdline=("avibe",),
+ uid=uid,
+ environment={},
+ wall_create_time=record["parent_create_time"] + 1_000.0,
+ )
+ }
+ )
+ ownership = SyncOwnership(sync_record_path(memory_dir), provider_root=root, host=host)
+ ownership.write(record)
+
+ with pytest.raises(SyncOwnershipError, match="live parent"):
+ await ownership.reconcile()
+
+ assert ownership.path.exists()
+ assert host.signals == []
+
+
[email protected]("field", ["starttime_ticks", "parent_starttime_ticks"])
[email protected]("stamp", [-1.0, float("nan")])
+async def test_sync_record_rejects_invalid_stable_stamps(
+ field: str,
+ stamp: float,
+ tmp_path: Path,
+) -> None:
+ memory_dir = tmp_path / "memory"
+ root = memory_dir / "everos-root"
+ record = _record(root, state="finalized", pid=451)
+ record[field] = stamp
+ ownership = SyncOwnership(sync_record_path(memory_dir), provider_root=root, host=_Host())
+ ownership.write(record)
+
+ with pytest.raises(SyncOwnershipError, match="start-time is invalid"):
+ await ownership.reconcile()
+
+ assert ownership.path.exists()
+
+
async def test_retained_failed_cleanup_reconciles_while_its_parent_is_live(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
@@ -308,10 +498,11 @@ async def test_retained_failed_cleanup_reconciles_while_its_parent_is_live(
host = RetainedCleanupHost(
{
99: _ProcessIdentity(
- create_time=8.25,
+ stamp=8.25,
cmdline=("avibe",),
uid=uid,
environment={},
+ wall_create_time=8.25,
)
}
)
@@ -356,10 +547,11 @@ async def test_retained_pending_cleanup_reconciles_while_its_parent_is_live(
host = RetainedPendingHost(
{
99: _ProcessIdentity(
- create_time=8.25,
+ stamp=8.25,
cmdline=("avibe",),
uid=uid,
environment={},
+ wall_create_time=8.25,
)
}
)
@@ -410,10 +602,11 @@ async def test_handleless_spawn_failure_marks_discovered_pending_record_retryabl
host = HandlelessSpawnHost(
{
parent.pid: _ProcessIdentity(
- create_time=parent.create_time,
+ stamp=parent.create_time,
cmdline=("avibe",),
uid=uid,
environment={},
+ wall_create_time=parent.create_time,
)
}
)
@@ -457,10 +650,11 @@ async def test_handleless_spawn_failure_marks_uncertain_pending_record_retryable
host = UncertainHandlelessSpawnHost(
{
parent.pid: _ProcessIdentity(
- create_time=parent.create_time,
+ stamp=parent.create_time,
cmdline=("avibe",),
uid=uid,
environment={},
+ wall_create_time=parent.create_time,
)
}
)
@@ -525,7 +719,7 @@ async def test_sync_cleanup_runtime_error_marks_the_finalized_record(
def inspect_identity(self, pid):
assert pid == process.pid
return _ProcessIdentity(
- create_time=10.5,
+ stamp=10.5,
cmdline=(str(python), *SYNC_ARGV),
uid=os.getuid() if hasattr(os, "getuid") else None,
environment=self.environment,
@@ -701,10 +895,11 @@ async def test_finalized_sync_reconciliation_cleans_exact_recorded_group(tmp_pat
host = _Host(
{
451: _ProcessIdentity(
- create_time=10.5,
+ stamp=10.5,
cmdline=tuple(record["argv"]),
uid=uid,
environment=environment,
+ wall_create_time=10.5,
)
}
)
@@ -732,7 +927,7 @@ async def test_gone_leader_with_live_helper_is_swept_before_retirement(tmp_path:
SYNC_PARENT_UID_ENV: "" if uid is None else str(uid),
}
helper = _ProcessIdentity(
- create_time=11.5,
+ stamp=11.5,
cmdline=("/runtime/bin/python", "-c", "everos-helper"),
uid=uid,
environment=helper_env,
@@ -772,7 +967,7 @@ async def test_orphan_reconciliation_rescans_group_before_retiring_record(
if self.scans == 1:
return {777: 11.5}, []
self.identities[778] = _ProcessIdentity(
- create_time=12.5,
+ stamp=12.5,
cmdline=("/runtime/bin/python", "-c", "replacement-helper"),
uid=uid,
environment=helper_env,
@@ -881,7 +1076,11 @@ def test_sync_environment_has_no_host_source_path(tmp_path: Path) -> None:
assert all("SOURCE_ROOT" not in key for key in env)
-async def test_sync_finalizes_ownership_before_sigcont_and_cleans_group(tmp_path: Path) -> None:
+async def test_sync_finalizes_ownership_before_sigcont_and_cleans_group(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(memory_sync_process, "_uses_linux_starttime_stamp", lambda: True)
python = tmp_path / "runtime" / "bin" / "python"
python.parent.mkdir(parents=True)
python.write_bytes(b"python")
@@ -897,6 +1096,9 @@ async def test_sync_finalizes_ownership_before_sigcont_and_cleans_group(tmp_path
assert signum.name == "SIGCONT"
record = json.loads(record_path.read_text(encoding="utf-8"))
assert record["state"] == "finalized"
+ assert record["create_time"] == 1_700_000_010.5
+ assert record["starttime_ticks"] == 10.5
+ assert record["parent_starttime_ticks"] is not None
events.append("continued")
async def wait(self):
@@ -938,10 +1140,11 @@ async def test_sync_finalizes_ownership_before_sigcont_and_cleans_group(tmp_path
assert pid == process.pid
events.append("validated")
return _ProcessIdentity(
- create_time=10.5,
+ stamp=10.5,
cmdline=(str(python), *SYNC_ARGV),
uid=os.getuid() if hasattr(os, "getuid") else None,
environment=self.environment,
+ wall_create_time=1_700_000_010.5,
)
def live(self, identities):
@@ -1028,7 +1231,7 @@ async def test_sync_spawn_handoff_finishes_before_honoring_cancellation(tmp_path
def inspect_identity(self, pid):
assert pid == process.pid
return _ProcessIdentity(
- create_time=10.5,
+ stamp=10.5,
cmdline=(str(python), *SYNC_ARGV),
uid=os.getuid() if hasattr(os, "getuid") else None,
environment=self.environment,
@@ -1066,7 +1269,7 @@ async def test_sync_spawn_handoff_finishes_before_honoring_cancellation(tmp_path
async def test_sync_cleanup_rescans_a_group_after_the_leader_exits(tmp_path: Path) -> None:
helper = _ProcessIdentity(
- create_time=11.5,
+ stamp=11.5,
cmdline=("/runtime/bin/python", *SYNC_ARGV),
uid=os.getuid() if hasattr(os, "getuid") else None,
environment={},