Add vector infrastructure maps and persistent location experience
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
# Location experience
|
||||
|
||||
The worker owns bounded summaries under `state/spatial-experience`, keyed by
|
||||
world + collider + robot SHA256. Exact measured visits (0.5m indexing, observed
|
||||
XYZ retained) and confirmed failed attempts survive pause, return and process
|
||||
restart. At most 20,000 visited cells and 1,000 attempts; oldest summaries expire
|
||||
from this bounded store when capacity is reached. This is explicitly requested
|
||||
location knowledge, separate from the live-only operator telemetry store.
|
||||
|
||||
A failure needs matching pose/simulation-time/execution identity and repeated
|
||||
stationary controller rejection for 0.5 simulation seconds. Network timeouts and
|
||||
stale observations never create obstacles. `no-permitted-goal` is a perception
|
||||
limitation, not evidence of physical occupancy. Attempts retain origin, target,
|
||||
reason, timestamps, count, run and observation identity. A successful visit to the
|
||||
target from the attempted direction resolves that record. Motion control still
|
||||
uses current measurements. Fresh failures only add a bounded, ten-minute-decaying
|
||||
cost to already-admissible recovery choices from the same approach; they never
|
||||
veto free space or authorize driving. Historical entries remain visible afterward.
|
||||
|
||||
A separate asynchronous writer publishes summaries every five seconds. The worker
|
||||
synchronizes them through an authenticated bounded endpoint; Mission Core retains
|
||||
a mirror for inspection in planning. A changed scene/collider/robot cannot silently
|
||||
reuse old decisions. Corrupt persisted input is reported and ignored for navigation.
|
||||
The map layer can show/hide visits and attempted directions; attempt markers expose
|
||||
human-readable reasons and successful revisits.
|
||||
|
||||
Global transferable learning is deliberately outside this implementation. Accumulating
|
||||
location records is not model training. Cross-location generalization requires a
|
||||
separate situation representation, evaluation and admission process.
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Package current source plus simulation adapters into a digest-addressed archive."""
|
||||
|
||||
import argparse
|
||||
import ast
|
||||
import hashlib
|
||||
import json
|
||||
import tarfile
|
||||
@@ -23,6 +24,11 @@ for profile in (root / "simulation/ai-polygon/robots").glob("*.json"):
|
||||
asset = root / json.loads(profile.read_text())["visual"]["source"]
|
||||
if asset not in files:
|
||||
files.append(asset)
|
||||
# Reject a broken Python artifact before staging or touching the running worker.
|
||||
for source in files:
|
||||
if source.suffix == ".py":
|
||||
ast.parse(source.read_bytes(), filename=str(source))
|
||||
|
||||
manifest = {
|
||||
p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
"""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"
|
||||
)
|
||||
@@ -175,7 +175,7 @@ class ObservedGoals:
|
||||
count = min(2*count, len(barriers))
|
||||
return cost
|
||||
|
||||
def maneuver(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None):
|
||||
def maneuver(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None, experience_cost=None):
|
||||
"""Measured local destinations may temporarily move away from the task.
|
||||
|
||||
This removes the greedy progress constraint ONLY during a surveyed
|
||||
@@ -254,6 +254,8 @@ class ObservedGoals:
|
||||
score = np.linalg.norm(candidates[:, :2]-target, axis=1) + .2*turning + .15*distance
|
||||
score += self.boundary_cost(candidates, geometry, now)
|
||||
score += self.clearance_cost(candidates, pose, geometry, now)[0]
|
||||
if experience_cost is not None:
|
||||
score += np.asarray(experience_cost(pose, candidates))
|
||||
# Recovery actions need a fair turn, as in Nav2's RoundRobin recovery
|
||||
# subtree. Distance-to-task alone can spend every retry on almost the
|
||||
# same forward approach before ever considering a measured retreat.
|
||||
|
||||
@@ -380,6 +380,7 @@ class NavigationClient:
|
||||
|
||||
|
||||
class ComposedInference:
|
||||
experience = None
|
||||
def __init__(self, root: Path, run, directory: Path, mission=None):
|
||||
profile = json.loads((root / "models.worker-006.json").read_text())
|
||||
self.graph = compose(root, run["request"].get("composition"))
|
||||
@@ -433,6 +434,10 @@ class ComposedInference:
|
||||
self.navigation_evidence = {}
|
||||
self.pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="simulation-module")
|
||||
self.directory = directory
|
||||
self.experience = None
|
||||
if run.get("_spatial_experience_root") and run["world"].get("collider_sha256"):
|
||||
from experience_adapter import ExperienceAdapter
|
||||
self.experience = ExperienceAdapter(run, self.inputs, directory)
|
||||
names = self.models.labels
|
||||
if self.segmenter_id == "simulation-sam3-surfaces":
|
||||
from k1link.simulation.ai_polygon.concept_surfaces import LABELS
|
||||
@@ -655,7 +660,8 @@ class ComposedInference:
|
||||
return observed_goals.maneuver(
|
||||
inputs["source.lidar"], inputs["source.pose"], target, prior, excluded,
|
||||
self.geometry, time.monotonic(), self.mission.goals_permitted
|
||||
if isinstance(self.mission, RoutedMission) else None)
|
||||
if isinstance(self.mission, RoutedMission) else None,
|
||||
experience_cost=self.experience.costs if self.experience else None)
|
||||
|
||||
self.goal, intent = self.mission.update(
|
||||
inputs["source.pose"],
|
||||
@@ -1020,6 +1026,8 @@ class ComposedInference:
|
||||
# direction and this transaction's range/support gates. It does
|
||||
# not use the older local translation goal retained during survey.
|
||||
self.intent_captured_at = calibration["captured_at"]
|
||||
if self.experience is not None:
|
||||
self.experience.observe(inputs, self.goal, result)
|
||||
self.navigation_evidence = {
|
||||
"mission": intent,
|
||||
"environment": self.environment,
|
||||
@@ -1199,6 +1207,8 @@ class ComposedInference:
|
||||
)
|
||||
|
||||
def close(self):
|
||||
if self.experience is not None:
|
||||
self.experience.close()
|
||||
self.pool.shutdown(wait=True, cancel_futures=True)
|
||||
self.models.close()
|
||||
self.navigation.close()
|
||||
|
||||
@@ -93,6 +93,15 @@ def publish_previews(client, episode, run_id, stopped):
|
||||
stopped.wait(1)
|
||||
|
||||
|
||||
def publish_experience(client, episode, world_id):
|
||||
"""Publish the last bounded summary, including the child writer's final flush."""
|
||||
from k1link.simulation.ai_polygon.spatial_experience import read as read_experience
|
||||
|
||||
path = episode / "spatial-experience.json"
|
||||
if path.exists():
|
||||
client.request("/worker/worlds/" + world_id + "/spatial-experience", read_experience(path))
|
||||
|
||||
|
||||
def preparation_heartbeat(client, hello, run_id):
|
||||
"""One-thread lease/control pulse; reconnect only this same expired owner."""
|
||||
last_poll = -float("inf")
|
||||
@@ -189,6 +198,7 @@ def main():
|
||||
"project_assets.py",
|
||||
"decode_collision.cjs",
|
||||
"navigation_client.py",
|
||||
"experience_adapter.py",
|
||||
"route_view.py",
|
||||
"observer_camera.py",
|
||||
"inference_preview.py",
|
||||
@@ -384,6 +394,7 @@ def main():
|
||||
raise RuntimeError("An existing episode must never be replayed")
|
||||
episode = create_episode(args.state, run["run_id"], args.evidence_root)
|
||||
run_file = episode / "run.json"
|
||||
run["_spatial_experience_root"] = str(args.state / "spatial-experience")
|
||||
write_json(run_file, run)
|
||||
channel = StateChannel(episode)
|
||||
channel.write("control", run)
|
||||
@@ -438,6 +449,7 @@ def main():
|
||||
):
|
||||
raise ValueError("Saved task and simulation surface identities differ")
|
||||
run["terrain_manifest"] = str(terrain_path)
|
||||
run["_spatial_experience_root"] = str(args.state / "spatial-experience")
|
||||
write_json(run_file, run)
|
||||
with (episode / "isaac.log").open("wb") as output:
|
||||
child = subprocess.Popen(
|
||||
@@ -484,6 +496,8 @@ def main():
|
||||
|
||||
stop_deadline = None
|
||||
last_snapshot = -1
|
||||
experience_stamp = None
|
||||
experience_checked = -float("inf")
|
||||
preview_sender = threading.Thread(
|
||||
target=publish_previews,
|
||||
args=(client, episode, run["run_id"], preview_stopped),
|
||||
@@ -531,6 +545,14 @@ def main():
|
||||
if snapshot and snapshot["sequence"] > last_snapshot:
|
||||
client.request("/worker/runs/" + run["run_id"] + "/snapshot", snapshot)
|
||||
last_snapshot = snapshot["sequence"]
|
||||
if now-experience_checked >= 5:
|
||||
experience_checked = now
|
||||
memory_file = episode / "spatial-experience.json"
|
||||
if memory_file.exists():
|
||||
stamp = memory_file.stat().st_mtime_ns
|
||||
if stamp != experience_stamp:
|
||||
publish_experience(client, episode, run["world"]["world_id"])
|
||||
experience_stamp = stamp
|
||||
except Exception as exc:
|
||||
registered = False
|
||||
logging.warning(
|
||||
@@ -595,6 +617,10 @@ def main():
|
||||
while True:
|
||||
try:
|
||||
client.request("/worker/register", hello)
|
||||
try:
|
||||
publish_experience(client, episode, run["world"]["world_id"])
|
||||
except Exception:
|
||||
logging.exception("Final location experience sync pending; worker copy retained")
|
||||
client.request(
|
||||
"/worker/runs/" + run["run_id"] + "/finish",
|
||||
finish,
|
||||
|
||||
Reference in New Issue
Block a user