From 251df3bf073df58cef27c9dfee4508f62fe977cc Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:48:40 +0300 Subject: [PATCH] fix: allow independent upstream auto PR reviews in parallel --- docs/UPSTREAM_AUTO.md | 28 +++++++- scripts/upstream_auto.py | 60 ++++++++++++----- tests/test_upstream_auto.py | 125 ++++++++++++++++++++++++++++++++++-- 3 files changed, 190 insertions(+), 23 deletions(-) diff --git a/docs/UPSTREAM_AUTO.md b/docs/UPSTREAM_AUTO.md index a90c5cb4..724e18ac 100644 --- a/docs/UPSTREAM_AUTO.md +++ b/docs/UPSTREAM_AUTO.md @@ -51,6 +51,19 @@ separate publication mandate, or a task's own `STOP` and read-only restrictions. 3. Normalize source identity, intervention ID and PR target before comparing work. Existing five-source CAS claims cover their **batch** domain; they do not prove exclusive ownership of PR-maintenance or outcome-review tasks. + **Resource scope follows the operation, not just the repository:** + - `READ_ONLY_REVIEW` of one PR reserves its exact `pr:owner/repo#number` + identity, **not** `source:owner/repo`. Other independent PR reviews in + the same repository may be selected in parallel. This is a deliberate + manifest contract: stale broad source locks in new PR review cards fail + validation rather than silently serializing every review. + - `INTERNAL_PREPARE` needs explicit `source:owner/repo` locks for each PR + target, in addition to the PR key. Mutable work therefore remains + conservatively serialized at repository scope until a separately + reviewed, complete path/branch/dependency lock scheme exists. + - A source-level claim is still mandatory for each frozen batch member, + and intervention-specific review without a PR retains its exact + intervention identity. No PR-level lock substitutes for batch source CAS. 4. Prefer genuine maintainer review/CI events and safely resumable work over speculative discovery; balance lane WIP, starvation and risk. Explain each suggested priority with time-of-check source refs, without promoting a @@ -72,7 +85,9 @@ separate publication mandate, or a task's own `STOP` and read-only restrictions. The selector sorts by explicit priority, age (bounded anti-starvation boost), and work-class weight: urgent maintainer/CI feedback and existing outcomes generally precede speculative new screening. WIP caps are `maintenance=2`, -`outcomes=2`, `portfolio=1`, `batch=1`. These are provisional workload +`outcomes=2`, `batch=1`. Portfolio uses **two independent read-only reviews** +and **one mutable preparation** as separate per-operation caps, with a total +ceiling of three. These are provisional workload heuristics, **not** VSM S2 decisions by themselves. `status` makes **no write**, takes no reservation and creates no new Organization `NOW`/`NEXT` entry. @@ -103,6 +118,17 @@ only reserves the named local task. The agent must **revalidate current source, owner permissions and task-specific tests before any work**, execute at most one admitted action, record the actual owner result, and release with an attributable reason. A release does not itself prove successful execution. +New claim/release events additionally record `operation` to make WIP +attribution reproducible after the original worklist expires. Historic ledger +events without that field remain readable; until release, a legacy portfolio +claim consumes **both** operation caps conservatively and cannot be silently +reclassified by a new task proposal. + +At **any** subsequent mutable write or integration boundary the native owner +must re-read the exact PR head and base, changed files including rename/delete +identities, and relevant dependencies, then prove the writes do not overlap +or serialize them. A read-only task's disjoint changed-file preview is **not** +proof of merge compatibility, nor authority to modify a branch or merge. `resume` never silently reassigns a claim. Claims older than 24 hours are reported as `STALE_CLAIM_UNRESOLVED` until auditable recovery; they are not automatically stolen, expired or treated as completed. diff --git a/scripts/upstream_auto.py b/scripts/upstream_auto.py index 17221e2d..3d3f15a8 100644 --- a/scripts/upstream_auto.py +++ b/scripts/upstream_auto.py @@ -30,8 +30,9 @@ class AutoError(ValueError): LEDGER_REF = "refs/heads/upstream-auto-task-reservations" LANE_OWNER = {"maintenance": 125, "outcomes": 159, "portfolio": 150, "batch": 56} -LANE_WIP_CAP = {"maintenance": 2, "outcomes": 2, "portfolio": 1, +LANE_WIP_CAP = {"maintenance": 2, "outcomes": 2, "portfolio": 3, "batch": 1} +PORTFOLIO_OPERATION_WIP_CAP = {"READ_ONLY_REVIEW": 2, "INTERNAL_PREPARE": 1} LANE_BONUS = {"maintenance": 8, "outcomes": 7, "batch": 5, "portfolio": 4} PRIORITY_BASE = {"P0": 100, "P1": 70, "P2": 40, "P3": 10} @@ -48,6 +49,7 @@ class AutoError(ValueError): "priority", "operation", "head_sha"} EVENT_FIELDS = {"action", "claim_id", "task_id", "actor", "resources", "owner_issue", "evidence_url", "timestamp"} +EVENT_OPERATION = {"operation"} def _timestamp(value): @@ -111,7 +113,7 @@ def validate_manifest(data, *, now=None): raise AutoError("Unknown task admission status") if raw["priority"] not in PRIORITY_BASE: raise AutoError("Unknown task priority") - if raw["operation"] not in {"READ_ONLY_REVIEW", "INTERNAL_PREPARE"}: + if not isinstance(raw["operation"], str) or raw["operation"] not in {"READ_ONLY_REVIEW", "INTERNAL_PREPARE"}: raise AutoError("External writes are not an Upstream Auto task operation") queue_time, observed = _timestamp(raw["queued_at"]), _timestamp(raw["observed_at"]) if queue_time > observed or observed > snapshot or now - observed > timedelta(minutes=60): @@ -131,8 +133,13 @@ def validate_manifest(data, *, now=None): evidence_url = _issue_url(raw["evidence_url"]) pr_refs = [k[3:] for k in keys if k.startswith("pr:")] evidence = urlparse(evidence_url).path.casefold() - if any("source:" + name.split("#", 1)[0] not in keys for name in pr_refs): - raise AutoError("PR task needs its normalized source resource lock") + if pr_refs and raw["operation"] == "READ_ONLY_REVIEW" and any( + key.startswith("source:") for key in keys): + raise AutoError("READ_ONLY_REVIEW PR must lock the exact PR, not a repository-wide source") + if raw["operation"] == "INTERNAL_PREPARE" and ( + not any(key.startswith("source:") for key in keys) + or any("source:" + name.split("#", 1)[0] not in keys for name in pr_refs)): + raise AutoError("INTERNAL_PREPARE requires source locks for mutable PR resources") if pr_refs and not any(evidence == "/" + name.replace("#", "/pull/") for name in pr_refs): raise AutoError("PR work evidence must link to its exact target PR") task = dict(raw, resources=keys) @@ -161,8 +168,14 @@ def replay(ledger): _issue_url(event["evidence_url"]) _timestamp(event["timestamp"]) keys = _resources(event["resources"]) + if ("operation" in event and + (not isinstance(event["operation"], str) + or event["operation"] not in PORTFOLIO_OPERATION_WIP_CAP)): + raise AutoError("Unknown task claim operation") if action == "CLAIM": - if set(event) != EVENT_FIELDS or claim_id in seen or event["task_id"] in {x["task_id"] for x in active.values()}: + if (set(event) not in (EVENT_FIELDS, EVENT_FIELDS | EVENT_OPERATION) + or claim_id in seen + or event["task_id"] in {x["task_id"] for x in active.values()}): raise AutoError("Duplicate task claim") collision = [k for k in keys if k in resources] if collision: @@ -172,10 +185,12 @@ def replay(ledger): seen.add(claim_id) else: prior = active.get(claim_id) - if (set(event) != EVENT_FIELDS | {"reason"} + if (set(event) not in (EVENT_FIELDS | {"reason"}, + EVENT_FIELDS | EVENT_OPERATION | {"reason"}) or prior is None or not isinstance(event["reason"], str) or len(event["reason"].strip()) < 15 or _timestamp(event["timestamp"]) < _timestamp(prior["timestamp"]) + or event.get("operation") != prior.get("operation") or any(event[k] != prior[k] for k in ("task_id", "actor", "resources", "owner_issue"))): raise AutoError("Release requires active original claim, actor and auditable reason") for key in keys: @@ -191,17 +206,19 @@ def plan(manifest, ledger, *, now=None): active = replay(ledger) busy = {key for event in active.values() for key in event["resources"]} lane_active = {lane: 0 for lane in LANE_OWNER} + portfolio_operations = {op: 0 for op in PORTFOLIO_OPERATION_WIP_CAP} for event in active.values(): - lane = next((t["lane"] for t in tasks if t["task_id"] == event["task_id"]), None) + # Claims may outlive a worklist; never trust the new proposal to + # reclassify an already held reservation's operation or owner lane. + lane = next((k for k, v in LANE_OWNER.items() if v == event["owner_issue"]), None) if lane is not None: lane_active[lane] += 1 - # Existing claims not present in the input must still count against WIP. - # Their lane is derivable from stable owner issue, not current manifest. - for event in active.values(): - if not any(t["task_id"] == event["task_id"] for t in tasks): - lane = next((k for k, v in LANE_OWNER.items() if v == event["owner_issue"]), None) - if lane is not None: - lane_active[lane] += 1 + if lane == "portfolio": + # Historical v1 claims have no operation field. Conservatively + # count each toward both operation caps until released. + modes = (event["operation"],) if "operation" in event else PORTFOLIO_OPERATION_WIP_CAP + for mode in modes: + portfolio_operations[mode] += 1 eligible, blocked = [], [] for task in tasks: if task["status"] != "ACTIONABLE": @@ -213,6 +230,10 @@ def plan(manifest, ledger, *, now=None): if lane_active[task["lane"]] >= LANE_WIP_CAP[task["lane"]]: blocked.append({"task_id": task["task_id"], "reason": "LANE_WIP_CAP"}) continue + if (task["lane"] == "portfolio" and + portfolio_operations[task["operation"]] >= PORTFOLIO_OPERATION_WIP_CAP[task["operation"]]): + blocked.append({"task_id": task["task_id"], "reason": "PORTFOLIO_OPERATION_WIP_CAP"}) + continue age_hours = max(0, (now - _timestamp(task["queued_at"])).total_seconds() // 3600) score = PRIORITY_BASE[task["priority"]] + min(60, age_hours * 2) + LANE_BONUS[task["lane"]] eligible.append({"task_id": task["task_id"], "lane": task["lane"], @@ -258,6 +279,7 @@ def live_preflight(manifest, task, reader): """Live source identity/PR state gate; semantic actionability remains agent-owned.""" if reader is None: raise AutoError("BLOCKED_GITHUB_VISIBILITY: live reader required before claim") + base_shas = {} try: branch = reader.get("/repos/opensiro/upstream/branches/main") if branch.get("commit", {}).get("sha") != manifest["upstream_main_sha"]: @@ -273,6 +295,11 @@ def live_preflight(manifest, task, reader): pr = reader.get(f"/repos/{repo}/pulls/{number}") if pr.get("head", {}).get("sha") != task["head_sha"]: raise AutoError("BLOCKED_PR_HEAD_CHANGED: re-read before dispatch") + if task["operation"] == "INTERNAL_PREPARE": + base_sha = pr.get("base", {}).get("sha") + if not isinstance(base_sha, str) or not SHA.fullmatch(base_sha): + raise AutoError("BLOCKED_PR_BASE_VISIBILITY: mutable PR base not pinned") + base_shas[identifier] = base_sha if task["lane"] in {"maintenance", "portfolio"} and pr.get("state") != "open": raise AutoError("BLOCKED_PR_LIFECYCLE: review target no longer open") except AutoError: @@ -280,7 +307,8 @@ def live_preflight(manifest, task, reader): except (BatchError, KeyError, TypeError, ValueError, OSError) as exc: raise AutoError("BLOCKED_GITHUB_VISIBILITY: incomplete first-party readback") from exc return {"owner_issue": task["owner_issue"], "main_sha": manifest["upstream_main_sha"], - "head_sha": task["head_sha"], "status": "LIVE_PREFLIGHT_PASS"} + "head_sha": task["head_sha"], "pr_base_shas": base_shas, + "status": "LIVE_PREFLIGHT_PASS"} def _append(root, remote, parent, ledger, event, *, write): @@ -331,6 +359,7 @@ def claim(root, remote, manifest, actor, *, task_id=None, write=False, reader=No event = {"action": "CLAIM", "claim_id": uuid.uuid4().hex, "task_id": task_ref, "actor": actor, "resources": selected["resources"], "owner_issue": selected["owner_issue"], + "operation": task["operation"], "evidence_url": selected["evidence_url"], "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ")} receipt = _append(root, remote, parent, ledger, event, write=write) @@ -354,6 +383,7 @@ def resume(root, remote, actor, *, now=None): age = now - _timestamp(event["timestamp"]) result.append({"claim_id": event["claim_id"], "task_id": event["task_id"], "owner_issue": event["owner_issue"], "resources": event["resources"], + "operation": event.get("operation", "UNKNOWN_LEGACY"), "status": "STALE_CLAIM_UNRESOLVED" if age > timedelta(hours=24) else "CLAIMED_NEEDS_REVALIDATION"}) return {"status": "RESUME_INSPECTION_ONLY", "claims": result} diff --git a/tests/test_upstream_auto.py b/tests/test_upstream_auto.py index 80c8cb05..1cc704bb 100644 --- a/tests/test_upstream_auto.py +++ b/tests/test_upstream_auto.py @@ -26,15 +26,18 @@ def stamp(dt): def task(id, *, lane="maintenance", repo="example/repo", priority="P2", - queued_hours=1, status="ACTIONABLE", resources=None): + queued_hours=1, status="ACTIONABLE", resources=None, + pr_number=4, operation="READ_ONLY_REVIEW"): if resources is None: - resources = [f"source:{repo}", f"pr:{repo}#4"] + resources = [f"pr:{repo}#{pr_number}"] + if operation == "INTERNAL_PREPARE": + resources.append(f"source:{repo}") return {"task_id": id, "lane": lane, "owner_issue": mod.LANE_OWNER[lane], "resources": resources, - "evidence_url": f"https://github.com/{repo}/pull/4", + "evidence_url": f"https://github.com/{repo}/pull/{pr_number}", "queued_at": stamp(NOW - timedelta(hours=queued_hours)), "observed_at": stamp(NOW - timedelta(minutes=3)), - "status": status, "priority": priority, "operation": "READ_ONLY_REVIEW", + "status": status, "priority": priority, "operation": operation, "head_sha": HEAD if any(k.startswith("pr:") for k in resources) else None} @@ -52,8 +55,10 @@ def get(self, path): "/repos/opensiro/upstream/issues/150", "/repos/opensiro/upstream/issues/56"): return {"state": "open"} - if path in ("/repos/example/repo/pulls/4", "/repos/other/repo/pulls/4"): - return {"state": "open", "head": {"sha": HEAD}} + if path in ("/repos/example/repo/pulls/4", "/repos/other/repo/pulls/4", + "/repos/opensiro/upstream/pulls/111", "/repos/opensiro/upstream/pulls/55"): + return {"state": "open", "head": {"sha": HEAD}, + "base": {"sha": SHA}} raise AssertionError("Unexpected GitHub API path: " + path) @@ -115,13 +120,106 @@ def test_pr_identity_evidence_and_resource_lock_must_agree(self): with self.assertRaisesRegex(mod.AutoError, "exact target PR"): mod.validate_manifest(manifest(item), now=NOW) item["evidence_url"] = "https://github.com/example/repo/pull/4" + self.assertEqual(mod.validate_manifest(manifest(item), now=NOW)[0]["resources"], + ["pr:example/repo#4"]) + item["resources"] = ["source:example/repo", "pr:example/repo#4"] + with self.assertRaisesRegex(mod.AutoError, "READ_ONLY_REVIEW PR"): + mod.validate_manifest(manifest(item), now=NOW) + item["operation"] = "INTERNAL_PREPARE" + self.assertEqual(mod.validate_manifest(manifest(item), now=NOW)[0]["operation"], + "INTERNAL_PREPARE") item["resources"] = ["pr:example/repo#4"] - with self.assertRaisesRegex(mod.AutoError, "source resource lock"): + with self.assertRaisesRegex(mod.AutoError, "requires source locks"): mod.validate_manifest(manifest(item), now=NOW) item["resources"] = ["source:EXAMPLE/REPO", "source:example/repo", "pr:example/repo#4"] with self.assertRaisesRegex(mod.AutoError, "duplicate resource key"): mod.validate_manifest(manifest(item), now=NOW) + def test_independent_portfolio_pr_reviews_do_not_take_repo_wide_lock(self): + pr111 = task("portfolio:111", lane="portfolio", repo="opensiro/upstream", pr_number=111) + pr55 = task("portfolio:55", lane="portfolio", repo="opensiro/upstream", pr_number=55) + worklist = manifest(pr111, pr55) + self.assertEqual(mod.validate_manifest(worklist, now=NOW)[0]["resources"], + ["pr:opensiro/upstream#111"]) + with tempfile.TemporaryDirectory() as temp: + one, two = make_fixture(Path(temp)) + first = mod.claim(one, "origin", worklist, "agent-one", task_id=pr111["task_id"], + write=True, reader=FakeReader(), now=NOW) + self.assertEqual(first["status"], "WRITTEN_CAS") + view = mod.plan(worklist, mod.fetch_ledger(two, "origin")[1], now=NOW) + self.assertEqual(view["selected"]["task_id"], pr55["task_id"]) + duplicate = copy.deepcopy(pr111) + duplicate["task_id"] = "portfolio:duplicate111" + self.assertIn({"task_id": duplicate["task_id"], "reason": "CLAIMED_RESOURCE"}, + mod.plan(manifest(duplicate), mod.fetch_ledger(two, "origin")[1], + now=NOW)["blocked"]) + second = mod.claim(two, "origin", worklist, "agent-two", task_id=pr55["task_id"], + write=True, reader=FakeReader(), now=NOW) + self.assertEqual(second["status"], "WRITTEN_CAS") + active = mod.replay(mod.fetch_ledger(one, "origin")[1]) + self.assertEqual(len(active), 2) + self.assertEqual({e["operation"] for e in active.values()}, {"READ_ONLY_REVIEW"}) + third = task("portfolio:third", lane="portfolio", repo="other/repo") + third_view = mod.plan(manifest(third), mod.fetch_ledger(one, "origin")[1], now=NOW) + self.assertIn({"task_id": third["task_id"], "reason": "PORTFOLIO_OPERATION_WIP_CAP"}, + third_view["blocked"]) + + def test_overlapping_mutable_portfolio_pr_tasks_remain_serial(self): + first = task("portfolio:write111", lane="portfolio", repo="opensiro/upstream", + pr_number=111, operation="INTERNAL_PREPARE") + second = task("portfolio:write55", lane="portfolio", repo="opensiro/upstream", + pr_number=55, operation="INTERNAL_PREPARE") + active = {"schema_version": 1, "events": [{"action": "CLAIM", "claim_id": "a" * 32, + "task_id": first["task_id"], "actor": "agent-one", "resources": sorted(first["resources"]), + "owner_issue": 150, "evidence_url": first["evidence_url"], + "operation": "INTERNAL_PREPARE", "timestamp": stamp(NOW)}]} + view = mod.plan(manifest(first, second), active, now=NOW) + self.assertIn({"task_id": second["task_id"], "reason": "CLAIMED_RESOURCE"}, view["blocked"]) + distinct = task("portfolio:write-other", lane="portfolio", repo="other/repo", + operation="INTERNAL_PREPARE") + view = mod.plan(manifest(distinct), active, now=NOW) + self.assertIn({"task_id": distinct["task_id"], "reason": "PORTFOLIO_OPERATION_WIP_CAP"}, + view["blocked"]) + + def test_legacy_portfolio_claim_is_conservative_and_release_replays(self): + old = task("portfolio:old111", lane="portfolio", repo="opensiro/upstream", pr_number=111) + historical = {"action": "CLAIM", "claim_id": "a" * 32, + "task_id": old["task_id"], "actor": "agent-one", + "resources": ["pr:opensiro/upstream#111", "source:opensiro/upstream"], + "owner_issue": 150, "evidence_url": old["evidence_url"], + "timestamp": stamp(NOW)} + remaining = task("portfolio:review55", lane="portfolio", repo="opensiro/upstream", + pr_number=55) + write = task("portfolio:write55", lane="portfolio", repo="opensiro/upstream", + pr_number=55, operation="INTERNAL_PREPARE") + ledger = {"schema_version": 1, "events": [historical]} + view = mod.plan(manifest(remaining, write), ledger, now=NOW) + self.assertEqual(view["selected"]["task_id"], remaining["task_id"]) + self.assertIn({"task_id": write["task_id"], "reason": "CLAIMED_RESOURCE"}, view["blocked"]) + other_write = task("portfolio:write-other", lane="portfolio", repo="other/repo", + operation="INTERNAL_PREPARE") + other_view = mod.plan(manifest(other_write), ledger, now=NOW) + self.assertIn({"task_id": other_write["task_id"], + "reason": "PORTFOLIO_OPERATION_WIP_CAP"}, other_view["blocked"]) + released = {**historical, "action": "RELEASE", "timestamp": stamp(NOW), + "reason": "Legacy review handoff recorded to owner"} + self.assertEqual(mod.replay({"schema_version": 1, "events": [historical, released]}), {}) + + def test_new_claim_operation_is_attributable_and_cannot_change_on_release(self): + item = task("portfolio:new", lane="portfolio", repo="opensiro/upstream", pr_number=111) + event = {"action": "CLAIM", "claim_id": "a" * 32, "task_id": item["task_id"], + "actor": "agent-one", "resources": item["resources"], + "owner_issue": 150, "evidence_url": item["evidence_url"], + "operation": "READ_ONLY_REVIEW", "timestamp": stamp(NOW)} + release = {**event, "action": "RELEASE", "reason": "Attributable complete owner handoff"} + self.assertEqual(mod.replay({"schema_version": 1, "events": [event, release]}), {}) + tampered = {**release, "operation": "INTERNAL_PREPARE"} + with self.assertRaisesRegex(mod.AutoError, "Release requires active original"): + mod.replay({"schema_version": 1, "events": [event, tampered]}) + malformed = {**event, "operation": ["READ_ONLY_REVIEW"]} + with self.assertRaisesRegex(mod.AutoError, "Unknown task claim operation"): + mod.replay({"schema_version": 1, "events": [malformed]}) + def test_blocked_or_empty_proposal_is_not_auto_promoted(self): blocked = task("maintenance:blocked", status="AWAITING_EXTERNAL") view = mod.plan(manifest(blocked), {"schema_version": 1, "events": []}, now=NOW) @@ -163,6 +261,19 @@ def test_live_preflight_mismatched_pr_head_and_owner(self): item = task("maintenance:review") self.assertEqual(mod.live_preflight(manifest(item), item, FakeReader())["status"], "LIVE_PREFLIGHT_PASS") + mutable = task("portfolio:prepare", lane="portfolio", operation="INTERNAL_PREPARE") + self.assertEqual(mod.live_preflight(manifest(mutable), mutable, FakeReader()) + ["pr_base_shas"]["example/repo#4"], SHA) + + class MissingBase(FakeReader): + def get(self, path): + data = super().get(path) + if path.endswith("/pulls/4"): + data.pop("base", None) + return data + + with self.assertRaisesRegex(mod.AutoError, "BLOCKED_PR_BASE_VISIBILITY"): + mod.live_preflight(manifest(mutable), mutable, MissingBase()) class MovedHead(FakeReader): def get(self, path):