Files

111 lines
3.6 KiB
Python

"""Worker-owned location experience with bounded asynchronous persistence."""
import logging
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from k1link.simulation.ai_polygon.spatial_experience import (
LocationExperience,
read,
save,
source_key,
)
class ExperienceAdapter:
def __init__(self, run, inputs, directory):
self.run_id = run["run_id"]
self.execution = inputs["sha256"]
self.geometry = inputs["robot"]["geometry"]
source = dict(
world_sha256=run["world"]["sha256"],
collider_sha256=run["world"]["collider_sha256"],
robot_sha256=inputs["robot"]["sha256"],
)
# Use the canonical state path supplied by the worker, not a resolved episode junction.
self.path = Path(run["_spatial_experience_root"]) / (source_key(source) + ".json")
self.publication = directory.parent / "spatial-experience.json"
self.can_persist = True
try:
document = read(self.path, source)
except FileNotFoundError:
document = None
except (ValueError, OSError):
logging.exception("Stored location experience could not be read")
document = None
self.can_persist = False
self.memory = LocationExperience(source, document)
self.writer = ThreadPoolExecutor(max_workers=1, thread_name_prefix="spatial-experience")
self.pending = None
self.stamp = -float("inf")
self.saved = -1
def observe(self, inputs, goal, result):
pose = inputs["source.pose"]
xyz = list(pose[:3])
xyz[2] -= self.geometry["body_contact_height_m"]
self.memory.observe(
xyz,
goal,
result,
inputs["source.simulation-time"],
time.time(),
self.run_id,
str(inputs.get("source.observation-id", "")),
self.execution,
pose,
)
self.flush()
def costs(self, pose, candidates):
return self.memory.costs(pose, candidates, time.time())
def flush(self, force=False):
if not self.can_persist:
return
if self.pending is not None:
if not self.pending.done():
return
try:
self.pending.result()
except OSError:
self.saved = -1
logging.exception(
"Location experience persistence failed; live sensing remains authoritative"
)
self.pending = None
if self.saved == self.memory.revision or (not force and time.monotonic() - self.stamp < 5):
return
document = self.memory.document()
# Detach mutable records before handing them to the writer.
import copy
document = copy.deepcopy(document)
def write():
save(self.path, document)
save(self.publication, document)
self.pending = self.writer.submit(write)
self.saved = self.memory.revision
self.stamp = time.monotonic()
def close(self):
if self.pending:
try:
self.pending.result()
except OSError:
self.saved = -1
logging.exception("Final location experience write failed")
self.pending = None
self.flush(force=True)
self.writer.shutdown(wait=True)
if self.pending:
try:
self.pending.result()
except OSError:
logging.exception(
"Location experience remains unsaved; navigation resources may close"
)