diff --git a/CHANGELOG.md b/CHANGELOG.md index be4a1ee1..01d1d661 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/crates/areev-bench/BENCH-TEMPLATE.md b/crates/areev-bench/BENCH-TEMPLATE.md index 352db915..d714334e 100644 --- a/crates/areev-bench/BENCH-TEMPLATE.md +++ b/crates/areev-bench/BENCH-TEMPLATE.md @@ -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 diff --git a/crates/areev-bench/CLAUDE.md b/crates/areev-bench/CLAUDE.md index 1baf76eb..12578577 100644 --- a/crates/areev-bench/CLAUDE.md +++ b/crates/areev-bench/CLAUDE.md @@ -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. diff --git a/crates/areev-bench/persist/README.md b/crates/areev-bench/persist/README.md index dfd191fc..f3d16a5f 100644 --- a/crates/areev-bench/persist/README.md +++ b/crates/areev-bench/persist/README.md @@ -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 `/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. diff --git a/crates/areev-bench/persist/pastbench/areev_backend.py b/crates/areev-bench/persist/pastbench/areev_backend.py index be3112ef..dd4e57d5 100644 --- a/crates/areev-bench/persist/pastbench/areev_backend.py +++ b/crates/areev-bench/persist/pastbench/areev_backend.py @@ -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 @@ -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): @@ -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")) @@ -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() @@ -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. " @@ -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)"] @@ -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): @@ -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, @@ -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 @@ -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( @@ -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) @@ -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) diff --git a/crates/areev-bench/receipts/README.md b/crates/areev-bench/receipts/README.md index a201cf53..2620783b 100644 --- a/crates/areev-bench/receipts/README.md +++ b/crates/areev-bench/receipts/README.md @@ -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. diff --git a/crates/areev-bench/receipts/dryrun.sh b/crates/areev-bench/receipts/dryrun.sh index 0f45dad2..b4ef4164 100644 --- a/crates/areev-bench/receipts/dryrun.sh +++ b/crates/areev-bench/receipts/dryrun.sh @@ -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 diff --git a/crates/areev-bench/receipts/evaluate.py b/crates/areev-bench/receipts/evaluate.py index 556cf7d6..24309954 100644 --- a/crates/areev-bench/receipts/evaluate.py +++ b/crates/areev-bench/receipts/evaluate.py @@ -47,6 +47,10 @@ def main(): ap.add_argument("--learned-db", required=True, help="memory left by the experience phase") ap.add_argument("--workdir", required=True) ap.add_argument("--arms", default="B,B2,A") + ap.add_argument("--append", action="store_true", + help="add these arms to the trials already in --workdir instead of " + "starting it over — how a Postgres run takes arm A last, after " + "regress has verified the memory arm A rolls back") ap.add_argument("--upto-seq", type=int, default=0, help="with --holdout train: only documents up to this seq; with next: the window starts after it") ap.add_argument("--rows", type=int, default=int(os.environ.get("EVAL_ROWS", "0") or 0), help="with --holdout train/next: how many documents (the split itself keeps --eval); env EVAL_ROWS") @@ -87,22 +91,51 @@ def main(): print("held-out documents: %d (seq %d..%d) evalset %s" % (len(rows), rows[0]["seq"], rows[-1]["seq"], evalset)) - # Two independent copies: the arms must not disturb each other, and the - # experience-phase memory itself is never written to by an arm. - db_b = os.path.join(args.workdir, "arm_b.db") - db_a = os.path.join(args.workdir, "arm_a.db") - mem.copy_memory(args.learned_db, db_b) - mem.copy_memory(args.learned_db, db_a) - rolled = mem.with_memory(db_a, mem.REVIEWER, mem.rollback_all) - print("arm A: rolled back %d recommendation(s)" % len(rolled)) + learned = mem.bench_db(args.learned_db) + arms = [a.strip() for a in args.arms.split(",") if a.strip()] + rolled = [] + if mem.is_dsn(learned): + # A schema is not a file to copy, so every arm reads the ONE memory, + # and arm A is produced by rolling the applied recommendations back + # on it — after the other arms have read it, because that rollback + # is real and destructive: when this evaluation ends the memory holds + # no applied lessons. Said out loud, since it is the only place the + # Postgres run differs from the published file-backed one. + db_b = db_a = learned + if "A" in arms and arms[-1] != "A": + arms = [a for a in arms if a != "A"] + ["A"] + print("memory: %s — one Postgres memory for every arm%s" % ( + mem.redact(learned), + "; arm A runs last, by rollback on that memory (destructive)" if "A" in arms else "")) + else: + # Two independent copies: the arms must not disturb each other, and the + # experience-phase memory itself is never written to by an arm. + db_b = os.path.join(args.workdir, "arm_b.db") + db_a = os.path.join(args.workdir, "arm_a.db") + mem.copy_memory(learned, db_b) + mem.copy_memory(learned, db_a) + rolled = mem.with_memory(db_a, mem.REVIEWER, mem.rollback_all) + print("arm A: rolled back %d recommendation(s)" % len(rolled)) batch_argv = None if args.batch: batch_argv = os.environ.get("AGENT_BATCH_CMD", "").split() or sys.exit("--batch needs AGENT_BATCH_CMD (e.g. '$PY scripts/batch_toolcall.py --base-url ... --model ...')") - journal = open(os.path.join(args.workdir, "eval.jsonl"), "w", encoding="utf-8") - trials, usage, journaled = [], {}, {} - for arm in [a.strip() for a in args.arms.split(",") if a.strip()]: + trials, usage, journaled, prior = [], {}, {}, {} + if args.append: + trials_path = os.path.join(args.workdir, "trials.json") + if os.path.exists(trials_path): + trials = json.load(open(trials_path, encoding="utf-8")) + summary_path = os.path.join(args.workdir, "eval.summary.json") + if os.path.exists(summary_path): + prior = json.load(open(summary_path, encoding="utf-8")) + usage, journaled = dict(prior.get("usage") or {}), dict(prior.get("journaled") or {}) + rolled = list(prior.get("rolled_back") or []) + rolled + journal = open(os.path.join(args.workdir, "eval.jsonl"), "a" if args.append else "w", encoding="utf-8") + for arm in arms: db = db_a if arm == "A" else db_b + if arm == "A" and mem.is_dsn(learned): + rolled = mem.with_memory(db_a, mem.REVIEWER, mem.rollback_all) + print("arm A: rolled back %d recommendation(s) on %s" % (len(rolled), mem.redact(learned))) # Arm C reads the same memory and renders it UNGOVERNED — every # correction verbatim, nothing proposed, reviewed or retracted. It is # the store-everything baseline, and it is deliberately generous: it @@ -115,7 +148,7 @@ def main(): usage[arm] = u if arm in journal_as: journaled[arm] = evalrun.journal_eval_run( - args.journal_into or args.learned_db, evalset, journal_as[arm], t) + args.journal_into or learned, evalset, journal_as[arm], t) print(" journaled arm %s as %s: %s" % (arm, journal_as[arm], json.dumps(journaled[arm]))) with open(os.path.join(args.workdir, "trials.json"), "w", encoding="utf-8") as fh: diff --git a/crates/areev-bench/receipts/learners.py b/crates/areev-bench/receipts/learners.py index a54c87cf..d96c289f 100644 --- a/crates/areev-bench/receipts/learners.py +++ b/crates/areev-bench/receipts/learners.py @@ -89,7 +89,7 @@ def main(): profile, db, "%s %s %s --provider %s --seed %d" % (py, loop, model, pin, p), "%s %s %s --provider %s --seed %d" % (py, loop, gm, gp, p), - judge, policy, verbose=False, + judge, policy, verbose=False, policy_dir=work, # A full sweep, because every pass reflects over the same # already-seen history: without it the watermark leaves the # bundle empty and every model scores zero for the same diff --git a/crates/areev-bench/receipts/memory.py b/crates/areev-bench/receipts/memory.py index 1c8eac8d..c5532c12 100644 --- a/crates/areev-bench/receipts/memory.py +++ b/crates/areev-bench/receipts/memory.py @@ -151,6 +151,28 @@ def _cal_list(values): ] +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. + A file path is returned unchanged.""" + s = str(path) + if not is_dsn(s): + return s + return re.sub(r"://([^:/@]+):[^@]*@", r"://\1:***@", s) + + +def bench_db(default_path, override=None): + """The memory a harness opens (#200): `--db` / `AREEV_BENCH_DB` when set — + a file path or a `postgres://…?schema=…` DSN, handed to `areev.Areev` + verbatim — else the file the harness derives. Unset, every published + file-backed run is unchanged.""" + return override or os.environ.get("AREEV_BENCH_DB") or default_path + + def with_memory(db_path, actor, fn): """Open as `actor`, run `fn(db)`, and guarantee the handle is released. @@ -346,7 +368,7 @@ def judge(system, rule): return judge -def policy_file(db_path, policy, name="loop-policy.json"): +def policy_file(db_path, policy, name="loop-policy.json", policy_dir=None): """The binding takes the host policy as a FILE (host config lives outside the memory, like the CLI's --policy). A JSON string is written beside the memory so the run directory records the policy it ran under; a path is @@ -359,7 +381,11 @@ def policy_file(db_path, policy, name="loop-policy.json"): different one. `run.config.json` was the only honest record. Each leg now writes its own file.""" if policy and policy.lstrip().startswith("{"): - path = os.path.join(os.path.dirname(os.path.abspath(db_path)), name) + # Beside the memory for a file. A Postgres memory has no "beside", so + # the caller's work dir takes it (the run's own record directory). + if policy_dir is None: + policy_dir = os.getcwd() if is_dsn(db_path) else os.path.dirname(os.path.abspath(db_path)) + path = os.path.join(policy_dir, name) with open(path, "w", encoding="utf-8") as fh: fh.write(policy) return path @@ -438,7 +464,7 @@ def _declined_before(ask): def learn(profile, db_path, llm_cmd, ground_cmd, judge=None, policy=None, verbose=True, - full_sweep=False): + full_sweep=False, policy_dir=None): """One governed pass, executed as a journaled `areev run`. propose (the loop's analyzers) → review (the accountant, a client node the @@ -452,7 +478,8 @@ def learn(profile, db_path, llm_cmd, ground_cmd, judge=None, policy=None, verbos return bench_run.learn( sys.modules[__name__], db_path, llm_cmd, ground_cmd, decide=lambda ask: review_pending(profile, db_path, ask, judge), - policy=policy, verbose=verbose, full_sweep=full_sweep) + policy=policy, verbose=verbose, full_sweep=full_sweep, + policy_dir=policy_dir) def rollback_all(db, because="evaluation arm A: withdrawing the learned rules"): @@ -468,8 +495,18 @@ def rollback_all(db, because="evaluation arm A: withdrawing the learned rules"): def copy_memory(src_db, dst_db): - """Copy a memory file with its WAL, so an arm mutates its own copy.""" + """Copy a memory file with its WAL, so an arm mutates its own copy. + + A Postgres memory is a schema, not a file, and cannot be copied from here: + the callers that need a second memory say plainly what they do instead + (`evaluate.py` rolls back on the one memory for arm A; snapshots and + per-pass learner copies are refused).""" import shutil + if is_dsn(src_db) or is_dsn(dst_db): + raise SystemExit( + "cannot copy %s: a Postgres memory is a schema, not a file. Provision a " + "second schema and point AREEV_BENCH_DB at it, or run this step against a " + "file memory." % redact(src_db)) for suffix in ("", "-wal"): if os.path.exists(src_db + suffix): shutil.copy(src_db + suffix, dst_db + suffix) diff --git a/crates/areev-bench/receipts/regress.py b/crates/areev-bench/receipts/regress.py index e29b9d12..b6ff72d4 100644 --- a/crates/areev-bench/receipts/regress.py +++ b/crates/areev-bench/receipts/regress.py @@ -45,7 +45,7 @@ def loop_pass(db_path, now_ms, llm_cmd=None, ground_cmd=None, policy=None, fixture=None, - full_sweep=False): + full_sweep=False, policy_dir=None): """One loop pass under the runner at a pinned engine time. A pass reflects over what is NEW since the last pass (the watermark); the @@ -56,7 +56,7 @@ def loop_pass(db_path, now_ms, llm_cmd=None, ground_cmd=None, policy=None, fixtu os.environ["AREEV_LOOP_NOW_MS"] = str(now_ms) if fixture: os.environ["AREEV_MOCK_LLM_FIXTURE"] = fixture - policy = mem.policy_file(db_path, policy, name="regress-policy.json") + policy = mem.policy_file(db_path, policy, name="regress-policy.json", policy_dir=policy_dir) try: return json.loads(mem.with_memory( db_path, mem.RUNNER, @@ -114,6 +114,10 @@ def main(): ap.add_argument("--learned-db", required=True, help="the experience memory, with A0 and B already journaled") ap.add_argument("--workdir", required=True) + ap.add_argument("--run-config", default=None, + help="the run's run.config.json, whose host policy this leg " + "inherits (default: beside the file memory; for a DSN, " + "the parent of --workdir)") ap.add_argument("--harmful", default=os.path.join(here, "fixtures", "lesson_harmful.json")) ap.add_argument("--mock-llm", default=os.path.join(repo, "examples", "llm", "mock.py")) ap.add_argument("--no-plant", action="store_true", @@ -131,7 +135,9 @@ def main(): agent_argv = os.environ["AGENT_CMD"].split() _, heldout = dataset.split_for(profile, dataset.load(args.dataset), args.seed, args.experience, args.eval) evalset = evalrun.evalset_hash(heldout) - db = args.learned_db + db = mem.bench_db(args.learned_db) + if mem.is_dsn(db): + print("memory: %s" % mem.redact(db)) # Inherit the run's host policy rather than assuming one. The leg that # verifies a run should not quietly differ from it: cell C ran its # experience phase with `evidence_attribution: anonymous` and its regress @@ -140,7 +146,13 @@ def main(): # run and the thing checking it is the kind that goes unnoticed. # `outcome_evalset` is always ours: regress recomputes the evalset hash. policy = {"discover_objective": "learner"} - cfg = os.path.join(os.path.dirname(os.path.abspath(db)), "run.config.json") + cfg = args.run_config + if not cfg: + # Beside a file memory; a DSN has no beside, so the parent of this + # leg's work dir — where dryrun.sh puts the run's. + base = os.path.dirname(os.path.abspath(args.workdir)) if mem.is_dsn(db) \ + else os.path.dirname(os.path.abspath(db)) + cfg = os.path.join(base, "run.config.json") if os.path.exists(cfg): ran_under = json.load(open(cfg)).get("policy") if ran_under: @@ -160,7 +172,7 @@ def check(name, ok, detail=""): # 1. Verify the good lessons: a pass a day after the last apply. B was # journaled after every apply and A0 before every proposal. - rep = loop_pass(db, t0 + 2 * DAY, policy=policy) + rep = loop_pass(db, t0 + 2 * DAY, policy=policy, policy_dir=args.workdir) verdicts = outcomes(db) report["steps"].append({"step": "verify", "loop": rep, "outcomes": verdicts}) n_lessons = len({o["rec_hash"] for o in verdicts}) @@ -184,7 +196,7 @@ def check(name, ok, detail=""): # 2. Admit the harmful lesson through the governed path. t_h = t0 + 2 * DAY + HOUR - rep = loop_pass(db, t_h, llm_cmd=mock_cmd, ground_cmd=mock_cmd, policy=policy, fixture=args.harmful, + rep = loop_pass(db, t_h, llm_cmd=mock_cmd, ground_cmd=mock_cmd, policy=policy, fixture=args.harmful, policy_dir=args.workdir, full_sweep=True) cand = [r for r in pending(db) if harmful_text in (r.get("summary") or "")] check("the harmful lesson reached the queue", len(cand) == 1, json.dumps(rep.get("llm_funnel"))) @@ -208,7 +220,7 @@ def check(name, ok, detail=""): # 4. A day later: regressed → revert proposed → approved → applied. t_r = t_h + DAY + HOUR - rep = loop_pass(db, t_r, policy=policy) + rep = loop_pass(db, t_r, policy=policy, policy_dir=args.workdir) verdicts = [o for o in outcomes(db) if o["rec_hash"] == harmful["hash"]] check("it was measured against the evalset (the metric the policy attached)", any(o["metric"] == "evalset:%s:exact" % evalset for o in verdicts), json.dumps(verdicts)) @@ -238,7 +250,7 @@ def check(name, ok, detail=""): "H %d → R %d exact" % (sum_h["exact"], sum_r["exact"])) # 6. The same fixture model, the next pass: not re-proposed. - rep = loop_pass(db, t_r + 3 * HOUR, llm_cmd=mock_cmd, ground_cmd=mock_cmd, policy=policy, + rep = loop_pass(db, t_r + 3 * HOUR, llm_cmd=mock_cmd, ground_cmd=mock_cmd, policy=policy, policy_dir=args.workdir, fixture=args.harmful, full_sweep=True) again = [r for r in pending(db) if harmful_text in (r.get("summary") or "")] check("the reverted lesson is not re-proposed", len(again) == 0, diff --git a/crates/areev-bench/receipts/run.py b/crates/areev-bench/receipts/run.py index 96ee0ae6..794714ac 100644 --- a/crates/areev-bench/receipts/run.py +++ b/crates/areev-bench/receipts/run.py @@ -37,6 +37,10 @@ def main(): ap.add_argument("--profile", default="sroie") ap.add_argument("--dataset", required=True, help="the corpus JSONL a builder emitted") ap.add_argument("--workdir", required=True) + ap.add_argument("--db", default="", + help="the memory to run against: a file path or a postgres://…?schema=… " + "DSN, passed to areev.Areev verbatim (also AREEV_BENCH_DB); " + "default WORKDIR/ledger.db") ap.add_argument("--seed", type=int, default=1) ap.add_argument("--experience", type=int, default=40) ap.add_argument("--eval", type=int, default=60, @@ -67,8 +71,19 @@ def main(): profile = ledger_profile.get(args.profile) os.makedirs(args.workdir, exist_ok=True) - db_path = os.path.join(args.workdir, "ledger.db") - if os.path.exists(db_path): + db_path = mem.bench_db(os.path.join(args.workdir, "ledger.db"), args.db or None) + if mem.is_dsn(db_path): + # A schema cannot be copied, so the memory checkpoints are a file-only + # feature; and "stale" is asked of the schema, not the filesystem. + if args.snapshot_every or snapshot_at: + raise SystemExit("--snapshot-every/--snapshot-at copy the memory file; a Postgres " + "memory cannot be copied — drop them, or run the curve on a file") + held = mem.with_memory(db_path, mem.REVIEWER, lambda db: json.loads(db.stats())["grains"]) + if held: + raise SystemExit("%s already holds %d grain(s) — a stale memory would poison the " + "run; provision a fresh schema" % (mem.redact(db_path), held)) + print("memory: %s" % mem.redact(db_path)) + elif os.path.exists(db_path): raise SystemExit("%s already exists — a stale memory would poison the run; " "use a fresh --workdir" % db_path) agent_argv = os.environ["AGENT_CMD"].split() @@ -94,6 +109,10 @@ def main(): "eval": args.eval, "evalset": evalset, "policy": policy, "learn_every": args.learn_every, "measure": args.measure, "journal_baseline": args.journal_baseline, + # Only when the memory is not the derived file, so the + # published file-backed records are byte-identical; and + # redacted, so a DSN's password never lands in a record. + **({"memory": mem.redact(db_path)} if (args.db or os.environ.get("AREEV_BENCH_DB")) else {}), "agent_cmd": os.environ.get("AGENT_CMD"), "loop_llm_cmd": llm_cmd, "loop_ground_cmd": ground_cmd, "review_cmd": os.environ.get("REVIEW_CMD")}, fh, indent=1) @@ -202,7 +221,8 @@ def main(): # provider rate-limited past its eight retries; agent calls # already survived that (park-on-failure), the loop did not. try: - res = mem.learn(profile, db_path, llm_cmd, ground_cmd, judge, policy) + res = mem.learn(profile, db_path, llm_cmd, ground_cmd, judge, policy, + policy_dir=args.workdir) except (ValueError, RuntimeError) as e: res = None totals["learn_failures"] += 1 diff --git a/crates/areev-bench/scripts/bench_run.py b/crates/areev-bench/scripts/bench_run.py index ac0a5ca9..8cb2b7a3 100644 --- a/crates/areev-bench/scripts/bench_run.py +++ b/crates/areev-bench/scripts/bench_run.py @@ -40,6 +40,11 @@ keep the separation the harnesses already have: an eval score in the agent's namespace is an agent that can read its own grade. +The journal stays a local file even when the AGENT memory is a Postgres +schema: the Cloud leg's role has no CREATE, so a second schema is not +available to journal into, and the separation is the point rather than the +backend. `learn(policy_dir=...)` says which directory holds it. + ## Keyless `propose` with no `llm_cmd` runs the deterministic analyzers only, so the @@ -230,7 +235,8 @@ def node_results(db, run_id, limit=80): def learn(mem, db_path, llm_cmd, ground_cmd, decide, policy=None, verbose=True, - full_sweep=False, runs_db=None, run_id=None, every_episodes=None): + full_sweep=False, runs_db=None, run_id=None, every_episodes=None, + policy_dir=None): """One governed learning pass, executed as an `areev run`. THE path every harness's `learn()` takes -- there is no second, @@ -243,8 +249,15 @@ def learn(mem, db_path, llm_cmd, ground_cmd, decide, policy=None, verbose=True, Returns the report shape every harness already returned -- pending, applied, rejected, errors, funnel, decisions -- plus the `run_id` that produced it, so a published count can be traced to a journal. + + `db_path` is the agent memory: a file path, or a Postgres DSN on a track + that supports one. A DSN has no directory, so what would have sat BESIDE + the file -- the run journal and the policy the pass ran under -- goes to + `policy_dir`, the leg's own work dir, and the process's cwd without one. """ - workdir = os.path.dirname(os.path.abspath(db_path)) + dsn = bool(getattr(mem, "is_dsn", None) and mem.is_dsn(db_path)) + workdir = policy_dir or (os.getcwd() if dsn + else os.path.dirname(os.path.abspath(db_path))) runs_db = runs_db or os.path.join(workdir, "runs.db") run_id = run_id or _next_run_id(runs_db) track = getattr(mem, "TRACK", None) @@ -252,9 +265,13 @@ def learn(mem, db_path, llm_cmd, ground_cmd, decide, policy=None, verbose=True, raise RuntimeError("%s must declare TRACK (its directory name) to name " "the --tool-cmd's harness" % getattr(mem, "__name__", mem)) + # `policy_dir` is passed only when the caller named one: a track that + # never sees a DSN has no reason to widen its `policy_file` for it, and + # beside-the-file remains the right answer there. payload = { "llm_cmd": llm_cmd, "ground_cmd": ground_cmd, "full_sweep": bool(full_sweep), - "policy": mem.policy_file(db_path, policy), + "policy": mem.policy_file(db_path, policy, + **({"policy_dir": policy_dir} if policy_dir else {})), } captured = {"decisions": [], "approved": 0} @@ -278,8 +295,8 @@ def drive(db): if every_episodes: author_trigger(db, author_plan(db), every_episodes) report = govern(db, run_id, tool_cmd(track), gate, responder=mem.REVIEWER, - agent_db=os.path.abspath(db_path), workdir=workdir, - input_extra=payload) + agent_db=db_path if dsn else os.path.abspath(db_path), + workdir=workdir, input_extra=payload) return report, node_results(db, run_id) report, nodes = with_runs(runs_db, mem.RUNNER, drive)