feat(strategy-state): persist instance-scoped slot maps
This commit is contained in:
@@ -28,7 +28,7 @@ from trex_core.application.ports import IntentRecord
|
||||
from trex_core.application.strategy_state import (
|
||||
SetResult,
|
||||
StrategyStateEntry,
|
||||
_cas,
|
||||
_STATE_CAP_BYTES,
|
||||
)
|
||||
from trex_core.domain.slot import Slot, SlotNotFoundError, SlotState, SlotTransitionRecord
|
||||
|
||||
@@ -701,13 +701,7 @@ class PostgreSQLLedgerOutbox:
|
||||
|
||||
|
||||
class PgStrategyStateStore:
|
||||
"""slot_strategy_state-backed StrategyStateStore (dcy-028 / REQ-079).
|
||||
|
||||
Stores opaque per-strategy state keyed by (slot_id, strategy_id). The CAS
|
||||
decision is the same `_cas` used by the in-memory double; occupancy_seq and
|
||||
slot_active are supplied by the caller (fetched from the slot) so the store
|
||||
only owns the slot_strategy_state table.
|
||||
"""
|
||||
"""PostgreSQL slot-scoped strategy-instance map store."""
|
||||
|
||||
def __init__(self, dsn: str, *, psycopg_module: Any = None) -> None:
|
||||
self._psycopg = _require_psycopg(psycopg_module)
|
||||
@@ -716,71 +710,65 @@ class PgStrategyStateStore:
|
||||
def set(
|
||||
self,
|
||||
slot_id: UUID,
|
||||
strategy_id: str,
|
||||
strategy_instance_id: str,
|
||||
*,
|
||||
expected_occupancy_seq: int,
|
||||
expected_version: int,
|
||||
data: str,
|
||||
current_occupancy_seq: int,
|
||||
slot_active: bool,
|
||||
) -> SetResult:
|
||||
if not slot_active:
|
||||
return SetResult(ok=False, reason="slot_inactive")
|
||||
if len(data.encode("utf-8")) > _STATE_CAP_BYTES:
|
||||
return SetResult(ok=False, reason="state_too_large")
|
||||
now = datetime.now(tz=timezone.utc)
|
||||
with self._psycopg.connect(self._dsn, autocommit=False) as conn:
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT occupancy_seq, version, data, updated_at "
|
||||
"FROM slot_strategy_state "
|
||||
"WHERE slot_id = %s AND strategy_id = %s FOR UPDATE",
|
||||
(slot_id, strategy_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
existing = (
|
||||
StrategyStateEntry(
|
||||
strategy_id=strategy_id,
|
||||
occupancy_seq=int(row[0]),
|
||||
version=int(row[1]),
|
||||
data=row[2],
|
||||
updated_at=row[3],
|
||||
)
|
||||
if row is not None
|
||||
else None
|
||||
)
|
||||
result = _cas(
|
||||
existing,
|
||||
expected_occupancy_seq=expected_occupancy_seq,
|
||||
expected_version=expected_version,
|
||||
data=data,
|
||||
current_occupancy_seq=current_occupancy_seq,
|
||||
slot_active=slot_active,
|
||||
)
|
||||
if not result.ok:
|
||||
conn.rollback()
|
||||
return result
|
||||
cur.execute(
|
||||
"INSERT INTO slot_strategy_state "
|
||||
"(slot_id, strategy_id, occupancy_seq, version, data, updated_at) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s) "
|
||||
"ON CONFLICT (slot_id, strategy_id) DO UPDATE SET "
|
||||
"occupancy_seq = EXCLUDED.occupancy_seq, "
|
||||
"version = EXCLUDED.version, data = EXCLUDED.data, "
|
||||
"updated_at = EXCLUDED.updated_at",
|
||||
"INSERT INTO slot_strategy_state (slot_id, data) "
|
||||
"SELECT %s, jsonb_build_object(%s, jsonb_build_object("
|
||||
"'version', 1, 'data', %s, 'updated_at', %s)) WHERE %s = 0 "
|
||||
"ON CONFLICT (slot_id) DO UPDATE SET data = jsonb_set("
|
||||
"slot_strategy_state.data, ARRAY[%s], jsonb_build_object("
|
||||
"'version', %s + 1, 'data', %s, 'updated_at', %s), true) "
|
||||
"WHERE COALESCE((slot_strategy_state.data -> %s ->> 'version')::bigint, 0) = %s "
|
||||
"RETURNING data -> %s ->> 'version'",
|
||||
(
|
||||
slot_id,
|
||||
strategy_id,
|
||||
current_occupancy_seq,
|
||||
result.version,
|
||||
strategy_instance_id,
|
||||
data,
|
||||
datetime.now(tz=timezone.utc),
|
||||
now,
|
||||
expected_version,
|
||||
strategy_instance_id,
|
||||
expected_version,
|
||||
data,
|
||||
now,
|
||||
strategy_instance_id,
|
||||
expected_version,
|
||||
strategy_instance_id,
|
||||
),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
cur.execute(
|
||||
"SELECT COALESCE((data -> %s ->> 'version')::bigint, 0) "
|
||||
"FROM slot_strategy_state WHERE slot_id = %s",
|
||||
(strategy_instance_id, slot_id),
|
||||
)
|
||||
conflict = cur.fetchone()
|
||||
return SetResult(
|
||||
ok=False,
|
||||
reason="version_conflict",
|
||||
version=int(conflict[0]) if conflict is not None else 0,
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
return SetResult(ok=True, version=int(row[0]))
|
||||
except BaseException:
|
||||
conn.rollback()
|
||||
raise
|
||||
|
||||
def get_for_slots(
|
||||
self, slot_ids: list[UUID], current_occupancy_seq: dict[UUID, int]
|
||||
self, slot_ids: list[UUID]
|
||||
) -> dict[UUID, dict[str, StrategyStateEntry]]:
|
||||
if not slot_ids:
|
||||
return {}
|
||||
@@ -788,26 +776,16 @@ class PgStrategyStateStore:
|
||||
with self._psycopg.connect(self._dsn) as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT slot_id, strategy_id, occupancy_seq, version, data, updated_at "
|
||||
"SELECT slot_id, data "
|
||||
"FROM slot_strategy_state WHERE slot_id = ANY(%s)",
|
||||
(list(slot_ids),),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
sid = row[0] if isinstance(row[0], UUID) else UUID(str(row[0]))
|
||||
# stale-occupancy entries are invisible (dcy-028 FR-3 defense)
|
||||
if int(row[2]) != current_occupancy_seq.get(sid):
|
||||
continue
|
||||
out.setdefault(sid, {})[row[1]] = StrategyStateEntry(
|
||||
strategy_id=row[1],
|
||||
occupancy_seq=int(row[2]),
|
||||
version=int(row[3]),
|
||||
data=row[4],
|
||||
updated_at=row[5],
|
||||
)
|
||||
for instance_id, entry in row[1].items():
|
||||
out.setdefault(sid, {})[instance_id] = StrategyStateEntry(
|
||||
version=int(entry["version"]),
|
||||
data=entry["data"],
|
||||
updated_at=datetime.fromisoformat(entry["updated_at"]),
|
||||
)
|
||||
return out
|
||||
|
||||
def delete_all(self, slot_id: UUID) -> None:
|
||||
with self._psycopg.connect(self._dsn, autocommit=False) as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM slot_strategy_state WHERE slot_id = %s", (slot_id,))
|
||||
conn.commit()
|
||||
|
||||
Reference in New Issue
Block a user