Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,19 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

### Added

- **The benchmark harnesses can run against a Postgres memory** (#200).
`AREEV_BENCH_DB` (or `receipts/run.py --db`) names the memory — a file path
or a `postgres://…?schema=…` DSN, handed to `areev.Areev` verbatim — for the
receipts experience/evaluation/regress legs and the PAST-Bench backend,
which had both hard-coded a file under their work directory. What a schema
cannot do is be copied, and the harnesses now say so: `evaluate.py` runs
every arm on the one memory and produces arm A by rolling back on it
(last, and for real — `dryrun.sh` takes arm A after the regress leg, with
the new `--append`, since that rollback ends the state regress verifies);
snapshots and per-pass learner copies are refused on
a DSN; the loop policy a leg records goes to that leg's work dir. A DSN is
printed and recorded only redacted. Unset, the published file-backed runs
are unchanged — the keyless dry run's summaries match the baseline.
- **`areev::blob_get` works on the Postgres tier** — the whole class of
attachment-parsing capability tools was unavailable on the backend the
server tier actually runs on. `{"blob": {"read": true}}` (#106) is what lets
Expand Down
5 changes: 4 additions & 1 deletion crates/areev-bench/BENCH-TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,10 @@ on its own cadence, and a node that skipped itself every pass is furniture.
**Two files.** The journal lives in `runs.db`, the agent's memory in its own
file. The driver holds the journal's writer handle for the whole run, and the
host tools are subprocesses that open the agent memory; one file for both is
`STO-E002`.
`STO-E002`. When the agent memory is a Postgres schema (`AREEV_BENCH_DB`), the
journal stays a local file — the provisioned role has no CREATE for a second
schema — and `learn(policy_dir=…)` names the directory it and the pass's
policy file go to, since a DSN has no "beside".

Declare the cadence as a Trigger grain (`bench_run.author_trigger`) even when
the harness is its evaluator: a reader of the memory can then see what was
Expand Down
10 changes: 10 additions & 0 deletions crates/areev-bench/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,16 @@ and a reader should not have to grep to learn that.
memory the arm must not change with `read_only=True`: writes then fail
`STO-E004` and the freeze is the store's guarantee rather than the
harness's intention.
- **A memory is a file path or a DSN.** `AREEV_BENCH_DB` (receipts also takes
`run.py --db`) names it, and it is handed to `areev.Areev` verbatim, so a
harness must not derive anything from it with `os.path` — `is_dsn` /
`memory_ref` / `memory_present` / `redact` in the track's bridge are the one
place the two are told apart. What a schema cannot do is be COPIED: an arm
built by copying a memory (snapshots, per-pass learner copies) is refused on
a DSN rather than silently ignored, and `evaluate.py` produces its rollback
arm on the one memory instead. On Postgres a schema is the isolation unit
and `STO-E002` never arises; the single-writer rule above is the embedded
backend's.
- **Statistics have one source of truth.** `scripts/aba_stats.py`'s
`mcnemar_exact` is imported, not reimplemented; `aba_arm_stats.py
--selftest` gates it in CI.
Expand Down
12 changes: 12 additions & 0 deletions crates/areev-bench/persist/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,15 @@ python pastbench/summarize.py ~/mg/local/areev-runs/persist/pilot
# Horizon: Harbor 0.22 with the areev wheel, agents/areev_agent linked into the checkout
AGENT=areev-governed OUT=~/mg/local/areev-runs/persist/hz sh horizon/run.sh
```

## Running against a Postgres memory

The PAST-Bench backend (`pastbench/areev_backend.py`) derives each family's
memory as `<state_root>/areev_state/memory.db`. With `AREEV_BENCH_DB` set to a
`postgres://…?schema=…` DSN it opens that instead, verbatim — the Cloud leg,
one provisioned schema per family. Two consequences, stated because they are
the only places the run differs: the benchmark's own file operations on the
state root (`reset_state`, `clone_state`) do not touch a Postgres memory, so
provisioning and resetting the schema between families is the caller's job;
and the loop policy the governed close records goes to the run's artifacts
directory rather than beside the file. A DSN is never written unredacted.
59 changes: 47 additions & 12 deletions crates/areev-bench/persist/pastbench/areev_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,30 @@

# ---------------------------------------------------------------- the file

def is_dsn(path):
"""A `postgres://` memory (one schema), as opposed to a file."""
return str(path).startswith(("postgres://", "postgresql://"))


def redact(path):
"""A memory reference safe to print or record: a DSN loses its password."""
s = str(path)
return re.sub(r"://([^:/@]+):[^@]*@", r"://\1:***@", s) if is_dsn(s) else s


def memory_present(path):
"""Whether there is a memory to read. A file: it exists. A DSN: yes —
a Postgres memory is provisioned by whoever hands the DSN over, and an
absent schema surfaces from the open as `STO-E008`, never as "empty"."""
return True if is_dsn(path) else Path(path).exists()


def memory_ref(value):
"""`Path` for a file, `str` for a DSN — the one place the two are told
apart on the way in, so `with_memory` can hand either to `areev.Areev`."""
return str(value) if is_dsn(value) else Path(value)


def with_memory(path, actor, fn):
"""Open as `actor`, run `fn(db)`, and guarantee the handle is released —
the embedded backend is single-writer per process, and a handle that
Expand Down Expand Up @@ -378,7 +402,7 @@ def render_home(db_path, out_dir):
d = out_dir / sub
if d.exists():
shutil.rmtree(d)
if not Path(db_path).exists():
if not memory_present(db_path):
return {"notes": 0, "profile": 0, "skills": 0}

def go(db):
Expand Down Expand Up @@ -642,7 +666,7 @@ def __init__(self, spec, request: StartSessionRequest) -> None:
super().__init__(spec, request)
cfg = (request.model.extra_body or {}).get("areev") or {}
self.cfg = cfg
self.db_path = Path(cfg["db_path"]) if cfg.get("db_path") else None
self.db_path = memory_ref(cfg["db_path"]) if cfg.get("db_path") else None
self.artifacts_dir = Path(cfg["artifacts_dir"]) if cfg.get("artifacts_dir") else None
self.persist = bool(cfg.get("persistence_enabled")) and self.db_path is not None
self.governed = bool(cfg.get("governed"))
Expand Down Expand Up @@ -674,7 +698,8 @@ def __init__(self, spec, request: StartSessionRequest) -> None:
self._task_tools = [t.model_copy(deep=True) for t in request.tools]
self._mem_tools = persistence_tools(self.tool_config) if self.persist else []
if self.persist:
self.db_path.parent.mkdir(parents=True, exist_ok=True)
if not is_dsn(self.db_path):
self.db_path.parent.mkdir(parents=True, exist_ok=True)
if self.governed:
self._journal_previous_outcome()
self._inject_memory()
Expand All @@ -696,7 +721,7 @@ def _inject_memory(self):
def go(db):
return notes_block(db, now), profile_block(db), skills_block(db)
notes_text, profile_text, skills_text = (
with_memory(self.db_path, ACTOR_AGENT, go) if self.db_path.exists()
with_memory(self.db_path, ACTOR_AGENT, go) if memory_present(self.db_path)
else (empty_notes_block(), empty_profile_block(), empty_skills_block()))
lines = ["", "## Persistent memory",
"Everything below was saved in earlier sessions; apply it without being asked. "
Expand All @@ -714,7 +739,7 @@ def go(db):
# "searchable", it never searched once in the three families
# whose answer lived in one (defect #16). The memory knows its
# sessions; list them, most recent first.
titles = with_memory(self.db_path, ACTOR_AGENT, session_titles) if self.db_path.exists() else []
titles = with_memory(self.db_path, ACTOR_AGENT, session_titles) if memory_present(self.db_path) else []
lines.append("### Earlier sessions (%d) — records this task may depend on; call session_search "
"BEFORE acting when the task refers to anything from before" % len(titles))
lines += ["- " + t for t in titles[:30]] or ["- (none yet)"]
Expand Down Expand Up @@ -782,7 +807,7 @@ def _journal_previous_outcome(self):
if score:
source = prev.name
break
if not score or not self.db_path.exists():
if not score or not memory_present(self.db_path):
return

def go(db):
Expand Down Expand Up @@ -1103,7 +1128,7 @@ def close(self, reason: str = "") -> None:
self.artifacts_dir.mkdir(parents=True, exist_ok=True)
if self.persist and self.governed:
try:
self._ledger["governance"] = govern(self.db_path, self.family_id, self.seed)
self._ledger["governance"] = govern(self.db_path, self.family_id, self.seed, policy_dir=self.artifacts_dir)
except Exception as exc: # a governance failure is a finding, not a crash
self._ledger["governance"] = {"error": "%s: %s" % (type(exc).__name__, str(exc)[:300])}
session = {"session_id": self.session_id, "task_id": self.task_id, "started_at": self._started,
Expand Down Expand Up @@ -1153,7 +1178,7 @@ def parse_proposal(summary):
return "advisory", s.strip()


def govern(db_path, family_id, seed):
def govern(db_path, family_id, seed, policy_dir=None):
"""One governed pass at episode close: propose under the runner, decide
under the reviewer, both recorded. Returns the ledger entry."""
import reviewer as rv # persist/reviewer.py, on sys.path via run.py
Expand All @@ -1177,7 +1202,10 @@ def govern(db_path, family_id, seed):
extra = os.environ.get("AREEV_LOOP_POLICY_EXTRA")
if extra:
policy.update(json.loads(extra))
policy_path = Path(db_path).parent / "loop-policy.json"
# Beside the ledger for a file; a DSN has no "beside", so the run's
# artifacts dir (or the working directory) takes it.
policy_dir = Path(db_path).parent if not is_dsn(db_path) else Path(policy_dir or ".")
policy_path = policy_dir / "loop-policy.json"
policy_path.write_text(json.dumps(policy), encoding="utf-8")

rep = json.loads(with_memory(
Expand Down Expand Up @@ -1302,8 +1330,15 @@ def __init__(self, agent_name: str) -> None:
self.agent_name = agent_name
self.governed = agent_name.endswith("governed")

def db_path(self, state_root: Path) -> Path:
return Path(state_root) / DB_NAME
def db_path(self, state_root: Path):
"""The memory for a family: `AREEV_BENCH_DB` when set (#200) — a
`postgres://…?schema=…` DSN handed to `areev.Areev` verbatim — else
the file under the state root. With a DSN, `reset_state` /
`clone_state` (the harness's file operations on the state root) do
not touch the memory: provisioning and resetting a schema is the
caller's job, which is what a Cloud run does."""
dsn = os.environ.get("AREEV_BENCH_DB")
return dsn if dsn else Path(state_root) / DB_NAME

def materialize_inputs(self, *, state_root, initial_home_fixture_dir, preseed_artifacts_dir) -> None:
state_root = Path(state_root)
Expand All @@ -1329,7 +1364,7 @@ def build_extra_body(self, *, state_root, artifacts_dir, persistence_enabled, se
def snapshot_before(self, state_root, *, include_contents: bool = False) -> dict[str, Any]:
state_root = Path(state_root)
db = self.db_path(state_root)
if not db.exists():
if not memory_present(db):
return _empty_artifact_summary(state_root)
rendered = state_root / "rendered"
render_home(db, rendered)
Expand Down
34 changes: 34 additions & 0 deletions crates/areev-bench/receipts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,37 @@ which one it is running.

Python 3 stdlib plus the `areev` binding built from this tree. No SDKs: the
model legs are the bench's JSON-on-stdio adapters in `../scripts/`.

## Running against a Postgres memory

Every phase opens its memory through `areev.Areev(...)`, which takes a file
path or a `postgres://…?schema=…` DSN. `AREEV_BENCH_DB` (or `run.py --db`)
names the memory and is passed through **verbatim**, so a Cloud-provisioned
schema — owner role with no `CREATE`, `?provision=never` on the DSN — runs the
same harness the file-backed results were produced with. Unset, nothing
changes: the published file-backed runs are unaffected.

What a schema cannot do is be copied, and three things copy the file:

- **`evaluate.py`'s arms.** On a file, arms B and A each get their own copy
and A is produced by `rollback_all` on its copy. On a DSN every arm reads
the **one** memory, and arm A is produced by rolling the applied
recommendations back on that memory — so A runs last, whatever `--arms`
says, and the rollback is real: when the evaluation ends the memory holds
no applied lessons. The harness prints this before it starts. It is also
why `dryrun.sh` reorders the legs on a DSN: B and B2 (journaling B, which
regress's verify needs), then regress, then arm A alone with
`evaluate.py --append` — added to the trials already taken, last of all,
because after it there is nothing applied left to verify.
- **`run.py --snapshot-every` / `--snapshot-at`** copy the memory aside for
the learning curve. Refused on a DSN; run the curve on a file.
- **`learners.py`** copies the memory once per pass. Refused on a DSN.

`run.py` refuses a DSN whose schema already holds grains (the file-path rule,
"a stale memory would poison the run", asked of the schema). The loop policy
each leg records (`loop-policy.json`, `regress-policy.json`) lands in that
leg's `--workdir`, since a DSN has no "beside", and `regress.py` reads the
run's `run.config.json` from the parent of its work dir (`--run-config` to
say otherwise). A DSN is printed and recorded
(`run.config.json` → `memory`) with its password redacted, and only when one
was given.
42 changes: 34 additions & 8 deletions crates/areev-bench/receipts/dryrun.sh
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,38 @@ echo "######## 1. experience (A0 journaled first, every lesson measured)"
--seed 1 --experience "$N" --eval "$HELD" --learn-every "$EVERY" \
--measure --journal-baseline

echo "######## 2. paired evaluation (B journaled)"
"$PY" "$HERE/evaluate.py" --dataset "$DATASET" --learned-db "$WORKDIR/ledger.db" \
--workdir "$WORKDIR/eval" --seed 1 --experience "$N" --eval "$HELD" --journal B=eval-b
"$PY" "$HERE/stats.py" "$WORKDIR/eval/trials.json"
step_eval() {
# $1: the arms; $2: "--append" to add them to the trials already taken
"$PY" "$HERE/evaluate.py" --dataset "$DATASET" --learned-db "$WORKDIR/ledger.db" \
--workdir "$WORKDIR/eval" --seed 1 --experience "$N" --eval "$HELD" \
--journal B=eval-b --arms "$1" ${2:-}
}

echo "######## 3. verify → forced regression → revert"
unset AREEV_MOCK_LLM_FIXTURE
"$PY" "$HERE/regress.py" --dataset "$DATASET" --learned-db "$WORKDIR/ledger.db" \
--workdir "$WORKDIR/regress" --seed 1 --experience "$N" --eval "$HELD"
step_regress() {
echo "######## 3. verify → forced regression → revert"
unset AREEV_MOCK_LLM_FIXTURE
"$PY" "$HERE/regress.py" --dataset "$DATASET" --learned-db "$WORKDIR/ledger.db" \
--workdir "$WORKDIR/regress" --seed 1 --experience "$N" --eval "$HELD"
}

case "${AREEV_BENCH_DB:-}" in
postgres://*|postgresql://*)
# One Postgres memory, no copies, so evaluate's arm A is a real rollback
# on it, after which nothing is applied for regress to verify — and
# regress's verify needs arm B's pass journaled first. So: B and B2,
# then regress (which leaves the good lesson in force and the planted
# one reverted), then arm A appended to the same trials, last of all.
echo "######## 2. paired evaluation (B journaled; arm A after regress — the memory is a DSN)"
step_eval B,B2
step_regress
echo "######## 2b. paired evaluation, arm A (rollback on the DSN memory)"
step_eval A --append
"$PY" "$HERE/stats.py" "$WORKDIR/eval/trials.json"
;;
*)
echo "######## 2. paired evaluation (B journaled)"
step_eval B,B2,A
"$PY" "$HERE/stats.py" "$WORKDIR/eval/trials.json"
step_regress
;;
esac
Loading