codecop 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/budget.py
ADDED
|
@@ -0,0 +1,980 @@
|
|
|
1
|
+
"""One run, one budget: every paid step of a scan under one ceiling, one ledger, one queue.
|
|
2
|
+
|
|
3
|
+
What rules and the sandbox cannot judge goes into one queue (statements to rank, production statements that need
|
|
4
|
+
variants, scenario variants, loop members, scan groups, join statements, table sizes), deduplicated and ordered by
|
|
5
|
+
value: with a pull, the measured share of the database's reads; without one, request paths and recurring work first,
|
|
6
|
+
then the rest of the app and job code. Tests, migrations, scripts, tooling, other engines and what a rule set aside never
|
|
7
|
+
enter it. The run spends in that order until the queue is empty or the budget is reached; every item it did not ask
|
|
8
|
+
about keeps the step that would judge it and its estimate ("not asked yet").
|
|
9
|
+
|
|
10
|
+
Every agent call goes through `Run.wrap(runner)`: one ledger (`agent_ledger.json` in the out dir, cumulative over runs)
|
|
11
|
+
records the step, the items, the estimate, what the agent CLI reported it cost and how long it took, and a call is not
|
|
12
|
+
started when what is left of the budget could not pay for it. Costs are the agent CLI's figures at API rates: billed to an
|
|
13
|
+
API key, or, on a plan login, an estimate of usage ("usage", never a bill).
|
|
14
|
+
|
|
15
|
+
Settings under `[agent]` in codecop.toml (AGENT_DEFAULTS); the defaults are generous: the budget is a guard for a large repository,
|
|
16
|
+
not a target.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import inspect
|
|
22
|
+
import json
|
|
23
|
+
import math
|
|
24
|
+
import os
|
|
25
|
+
import sys
|
|
26
|
+
import threading
|
|
27
|
+
import time
|
|
28
|
+
from datetime import datetime, timezone
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from .agent import AgentError
|
|
32
|
+
|
|
33
|
+
LEDGER_FILE = "agent_ledger.json"
|
|
34
|
+
PLAN_FILE = "agent_plan.json"
|
|
35
|
+
CONSENT_FILE = "agent_budget.json" # in <repo>/.codecop: a budget above confirm_above_usd that was confirmed for this repository
|
|
36
|
+
|
|
37
|
+
AGENT_DEFAULTS = {
|
|
38
|
+
"budget_usd": 50.0, # one ceiling for the whole run, every paid step, est. at API rates
|
|
39
|
+
"confirm_above_usd": 100.0, # a budget above this (from settings) is confirmed once per repository
|
|
40
|
+
"pr_budget_usd": 5.0, # the budget of a `--changed-since` scan
|
|
41
|
+
"concurrency": 6, # agent calls at a time
|
|
42
|
+
"call_timeout_s": 1800, # one agent call; a rank batch that times out is asked again in two halves
|
|
43
|
+
"min_call_usd": 0.5, # a call is not started with less than this left: it could not finish
|
|
44
|
+
"max_call_usd": 5.0, # what one call may spend (and holds of the budget while it runs) when its step gives
|
|
45
|
+
# no cap of its own: calls side by side must not each hold everything that is left
|
|
46
|
+
"cost_per_item_usd_low": 0.03, # the first-run prior per item (a rough prior)
|
|
47
|
+
"cost_per_item_usd_high": 0.06, # ... after the first calls the repository's own ledger decides (learned)
|
|
48
|
+
"cost_per_table_usd_low": 0.05, # the profile step per table (a rough prior)
|
|
49
|
+
"cost_per_table_usd_high": 0.25,
|
|
50
|
+
"cost_per_assembled_usd_low": 0.10, # a query written out from its builder (`rank --focus assembled`): the agent reads
|
|
51
|
+
"cost_per_assembled_usd_high": 0.40, # ... the builder and its callers, so more than a rank item; learned after the first calls
|
|
52
|
+
"areas_call_usd_low": 0.05, # the one call that classifies the code areas
|
|
53
|
+
"areas_call_usd_high": 0.30,
|
|
54
|
+
"call_usd_low": 0.05, # what one call costs at least, however few items it asks about
|
|
55
|
+
"call_usd_high": 0.15,
|
|
56
|
+
"seconds_per_call_low": 45,
|
|
57
|
+
"seconds_per_call_high": 320,
|
|
58
|
+
"api_key_first_run_wait_s": 5, # the first run billed to an API key waits this long after the plan (Ctrl-C spends nothing)
|
|
59
|
+
# the agent CLI said the account cannot run more now (agent.UsageLimitError): a pause, not a failure
|
|
60
|
+
"limit_retries": 6, # a rate limit (429) or an overloaded service: the call is tried again this many times
|
|
61
|
+
"limit_backoff_s": 30, # ... first after this long, then twice as long each time (at most limit_backoff_max_s)
|
|
62
|
+
"limit_backoff_max_s": 600,
|
|
63
|
+
"usage_limit_wait_max_s": 1800, # the plan's usage window is used up: wait for its reset when it is at most this far
|
|
64
|
+
# away, then go on; further away, nothing more is asked in this run (the next scan
|
|
65
|
+
# continues from what is stored, nothing paid twice)
|
|
66
|
+
}
|
|
67
|
+
# items asked in one call, per step: loops and groups follow [loops] agent_sites_per_call and [groupbench]
|
|
68
|
+
# agent_groups_per_call (scan copies them in), the others [agent] items_per_call
|
|
69
|
+
SIDE_BY_SIDE = ("loops", "groups") # steps whose calls run side by side with no cap of their own (BudgetRunner)
|
|
70
|
+
# assemble 6, not 8: its first call runs alone (rank.run_plan) and is slow per statement, and its cost is per statement
|
|
71
|
+
# (the builder each one reads), not per call; rank stays 40: a rank call's shared context is a small part of its cost
|
|
72
|
+
ITEMS_PER_CALL = {"rank": 40, "observed": 20, "scenario": 20, "assemble": 6, "loops": 12, "groups": 8}
|
|
73
|
+
# A list, not a tuple: a kind of finding (kinds/) adds its own question kind with register_queue_kind.
|
|
74
|
+
KINDS = ["statement", "assembled", "observed_variant", "scenario_variant", "loop", "group", "table_profile", "areas"]
|
|
75
|
+
STEP_OF = {"statement": "rank", "assembled": "assemble", "observed_variant": "observed", "scenario_variant": "scenario", "loop": "loops",
|
|
76
|
+
"group": "groups", "table_profile": "profile", "areas": "areas"}
|
|
77
|
+
KIND_LABEL = {"statement": "statements", "assembled": "statements built at run time", "observed_variant": "observed variants",
|
|
78
|
+
"scenario_variant": "scenario variants", "loop": "loops", "group": "groups", "table_profile": "table sizes",
|
|
79
|
+
"areas": "code areas"}
|
|
80
|
+
# The step command that judges one item when it is not asked in this run (also what `next_step` names).
|
|
81
|
+
NEXT_STEP = {"statement": "ask_agent_to_rank", "assembled": "ask_agent_to_assemble", "observed_variant": "ask_agent_for_observed_variant",
|
|
82
|
+
"scenario_variant": "ask_agent_for_scenario_variant", "loop": "ask_agent_for_loop_variant",
|
|
83
|
+
"group": "ask_agent_for_group_variant", "table_profile": "ask_agent_for_table_profile", "areas": "ask_agent_for_areas"}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# A registered kind's first-run prior per item (low, high), before its own ledger has calls.
|
|
87
|
+
STEP_COST: dict[str, tuple[float, float]] = {}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def register_queue_kind(kind: str, *, step: str, label: str, next_step: str, items_per_call: int = 20,
|
|
91
|
+
cost: tuple[float, float] = (0.03, 0.06)) -> None:
|
|
92
|
+
"""Add a question kind of a kind of finding (kinds/__init__.py) to the one queue: its step, its words, its next step,
|
|
93
|
+
items per call and the prior per item. The same name again replaces it."""
|
|
94
|
+
if kind not in KINDS:
|
|
95
|
+
KINDS.append(kind)
|
|
96
|
+
STEP_OF[kind], KIND_LABEL[kind], NEXT_STEP[kind] = step, label, next_step
|
|
97
|
+
ITEMS_PER_CALL[step] = int(items_per_call)
|
|
98
|
+
STEP_COST[step] = (float(cost[0]), float(cost[1]))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def agent_settings(config: dict | None) -> dict:
|
|
102
|
+
"""The `[agent]` table of codecop.toml over the defaults. Numbers must be zero or more; `items_per_call` is a table of whole
|
|
103
|
+
numbers above zero by step (rank, observed, scenario); `budget_usd = "none"` (or false) means no ceiling."""
|
|
104
|
+
cfg = dict(config or {})
|
|
105
|
+
out = dict(AGENT_DEFAULTS)
|
|
106
|
+
for key, default in AGENT_DEFAULTS.items():
|
|
107
|
+
value = cfg.get(key)
|
|
108
|
+
if value is None:
|
|
109
|
+
continue
|
|
110
|
+
if key == "budget_usd" and (value is False or str(value).strip().lower() in ("none", "off", "unlimited")):
|
|
111
|
+
out[key] = None
|
|
112
|
+
continue
|
|
113
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:
|
|
114
|
+
raise ValueError(f"agent.{key} must be a number of zero or more.")
|
|
115
|
+
out[key] = type(default)(value)
|
|
116
|
+
per = dict(ITEMS_PER_CALL)
|
|
117
|
+
for key, value in (cfg.get("items_per_call") or {}).items():
|
|
118
|
+
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
|
119
|
+
raise ValueError(f"agent.items_per_call.{key} must be a whole number above zero.")
|
|
120
|
+
per[key] = value
|
|
121
|
+
out["items_per_call"] = per
|
|
122
|
+
out["concurrency"] = max(int(out["concurrency"]), 1)
|
|
123
|
+
out["call_timeout_s"] = max(int(out["call_timeout_s"]), 1)
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def parse_budget(text: str | float | None) -> tuple[bool, float | None]:
|
|
128
|
+
"""(given, value) for a `--budget` value: a number of dollars, or `none` for no ceiling. Not given: (False, None)."""
|
|
129
|
+
if text is None or (isinstance(text, str) and not text.strip()):
|
|
130
|
+
return False, None
|
|
131
|
+
if isinstance(text, (int, float)) and not isinstance(text, bool):
|
|
132
|
+
if text < 0:
|
|
133
|
+
raise ValueError("--budget must be zero or more, or `none`.")
|
|
134
|
+
return True, float(text)
|
|
135
|
+
t = str(text).strip().lower().lstrip("$")
|
|
136
|
+
if t in ("none", "off", "unlimited", "no"):
|
|
137
|
+
return True, None
|
|
138
|
+
try:
|
|
139
|
+
value = float(t)
|
|
140
|
+
except ValueError as e:
|
|
141
|
+
raise ValueError(f"--budget must be a number of dollars or `none`, not {text!r}.") from e
|
|
142
|
+
if value < 0:
|
|
143
|
+
raise ValueError("--budget must be zero or more, or `none`.")
|
|
144
|
+
return True, value
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def billing_mode(runner=None) -> str:
|
|
148
|
+
"""`api_key` or `plan` (the agent CLI's own login), from the runner when there is one."""
|
|
149
|
+
if runner is not None and hasattr(runner, "billing_mode"):
|
|
150
|
+
try:
|
|
151
|
+
return runner.billing_mode()
|
|
152
|
+
except Exception:
|
|
153
|
+
pass
|
|
154
|
+
return "api_key" if os.environ.get("ANTHROPIC_API_KEY") else "plan"
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def money(amount: float | None, billing: str, *, approx: bool = True) -> str:
|
|
158
|
+
"""A figure the way a person reads it: `usage ≈ $5.10` on a plan login (not billed per token), `cost $5.10` on an API key."""
|
|
159
|
+
if amount is None:
|
|
160
|
+
return "no limit"
|
|
161
|
+
if billing == "api_key":
|
|
162
|
+
return f"cost ${amount:,.2f}"
|
|
163
|
+
return f"usage {'≈ ' if approx else ''}${amount:,.2f}"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def basis(billing: str) -> str:
|
|
167
|
+
return ("billed to the API key, as reported by the agent CLI" if billing == "api_key"
|
|
168
|
+
else "est. at API rates; plan login, not billed per token" if billing == "plan" else "est. at API rates")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def now() -> str:
|
|
172
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _read(path: Path, default):
|
|
176
|
+
try:
|
|
177
|
+
return json.loads(path.read_text()) if path.exists() else default
|
|
178
|
+
except (OSError, ValueError):
|
|
179
|
+
return default
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# ---- the ledger -------------------------------------------------------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
def load_ledger(out_dir: Path | None) -> dict:
|
|
185
|
+
data = _read(out_dir / LEDGER_FILE, None) if out_dir else None
|
|
186
|
+
if isinstance(data, dict) and isinstance(data.get("runs"), list):
|
|
187
|
+
return data
|
|
188
|
+
return {"schema_version": 1, "runs": []}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def ledger_total(ledger: dict) -> float:
|
|
192
|
+
return round(sum(float(c.get("cost_usd") or 0) for r in ledger.get("runs") or [] for c in r.get("calls") or []), 4)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def learned_per_item(ledger: dict, step: str) -> float | None:
|
|
196
|
+
"""What one item of this step cost on average in this repository's earlier calls (done calls that said how many items
|
|
197
|
+
they asked about), or None before the first."""
|
|
198
|
+
cost = items = 0.0
|
|
199
|
+
for r in ledger.get("runs") or []:
|
|
200
|
+
for c in r.get("calls") or []:
|
|
201
|
+
if c.get("step") == step and c.get("status") == "done" and int(c.get("items") or 0) > 0 and float(c.get("cost_usd") or 0) > 0:
|
|
202
|
+
cost += float(c["cost_usd"])
|
|
203
|
+
items += int(c["items"])
|
|
204
|
+
return cost / items if items else None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class Estimator:
|
|
208
|
+
"""Cost ranges per item: the repository's own ledger once it has calls of a step, the settings' prior before that."""
|
|
209
|
+
|
|
210
|
+
def __init__(self, settings: dict, ledger: dict | None = None):
|
|
211
|
+
self.s, self.ledger = settings, ledger or {"runs": []}
|
|
212
|
+
|
|
213
|
+
def per_item(self, step: str) -> tuple[float, float, str]:
|
|
214
|
+
if step == "profile":
|
|
215
|
+
learned = learned_per_item(self.ledger, "profile")
|
|
216
|
+
if learned:
|
|
217
|
+
return round(learned * 0.8, 4), round(learned * 1.5, 4), "learned"
|
|
218
|
+
return float(self.s["cost_per_table_usd_low"]), float(self.s["cost_per_table_usd_high"]), "prior"
|
|
219
|
+
if step == "areas":
|
|
220
|
+
return float(self.s["areas_call_usd_low"]), float(self.s["areas_call_usd_high"]), "prior"
|
|
221
|
+
if step == "assemble":
|
|
222
|
+
learned = learned_per_item(self.ledger, "assemble")
|
|
223
|
+
if learned:
|
|
224
|
+
return round(learned * 0.8, 4), round(learned * 1.5, 4), "learned"
|
|
225
|
+
return float(self.s["cost_per_assembled_usd_low"]), float(self.s["cost_per_assembled_usd_high"]), "prior"
|
|
226
|
+
if step in STEP_COST:
|
|
227
|
+
learned = learned_per_item(self.ledger, step)
|
|
228
|
+
if learned:
|
|
229
|
+
return round(learned * 0.8, 4), round(learned * 1.5, 4), "learned"
|
|
230
|
+
return STEP_COST[step][0], STEP_COST[step][1], "prior"
|
|
231
|
+
learned = learned_per_item(self.ledger, step) or (learned_per_item(self.ledger, "rank") if step != "rank" else None)
|
|
232
|
+
if learned:
|
|
233
|
+
return round(learned * 0.8, 4), round(learned * 1.5, 4), "learned"
|
|
234
|
+
return float(self.s["cost_per_item_usd_low"]), float(self.s["cost_per_item_usd_high"]), "prior"
|
|
235
|
+
|
|
236
|
+
def range(self, step: str, n: int) -> tuple[float, float]:
|
|
237
|
+
lo, hi, _ = self.per_item(step)
|
|
238
|
+
return round(lo * n, 2), round(hi * n, 2)
|
|
239
|
+
|
|
240
|
+
def seconds(self, calls: int, concurrency: int) -> tuple[int, int]:
|
|
241
|
+
waves = math.ceil(calls / max(concurrency, 1)) if calls else 0
|
|
242
|
+
return int(waves * self.s["seconds_per_call_low"]), int(waves * self.s["seconds_per_call_high"])
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class _Note(threading.local):
|
|
246
|
+
step = ""
|
|
247
|
+
items = 0
|
|
248
|
+
estimate: tuple = (0.0, 0.0)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class Gate:
|
|
252
|
+
"""At most `limit` agent calls at a time across every step of the run; the limit is lowered after a usage or rate
|
|
253
|
+
limit (and never raised again in the run)."""
|
|
254
|
+
|
|
255
|
+
def __init__(self, limit: int):
|
|
256
|
+
self.limit = max(int(limit), 1)
|
|
257
|
+
self.active = 0
|
|
258
|
+
self.cond = threading.Condition()
|
|
259
|
+
|
|
260
|
+
def __enter__(self):
|
|
261
|
+
with self.cond:
|
|
262
|
+
while self.active >= self.limit:
|
|
263
|
+
self.cond.wait()
|
|
264
|
+
self.active += 1
|
|
265
|
+
return self
|
|
266
|
+
|
|
267
|
+
def __exit__(self, *exc):
|
|
268
|
+
with self.cond:
|
|
269
|
+
self.active -= 1
|
|
270
|
+
self.cond.notify_all()
|
|
271
|
+
return False
|
|
272
|
+
|
|
273
|
+
def lower(self, to: int | None = None) -> int:
|
|
274
|
+
with self.cond:
|
|
275
|
+
self.limit = max(int(to if to is not None else self.limit // 2), 1)
|
|
276
|
+
self.cond.notify_all()
|
|
277
|
+
return self.limit
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class Pool:
|
|
281
|
+
"""What the engines of one scan share when they run side by side, each in its own process (multi.scan_engines): one
|
|
282
|
+
gate (agent calls at a time across every engine), one budget (what every engine spent and holds), and the sandbox,
|
|
283
|
+
used by one engine at a time (`sandbox`, a lock). Made before the engine processes start (fork) and handed to each
|
|
284
|
+
engine's Run (`pool=`)."""
|
|
285
|
+
|
|
286
|
+
def __init__(self, budget_usd: float | None, concurrency: int, ctx=None):
|
|
287
|
+
import multiprocessing as mp
|
|
288
|
+
ctx = ctx or mp.get_context("fork")
|
|
289
|
+
self.budget = budget_usd
|
|
290
|
+
self.cond = ctx.Condition(ctx.RLock()) # guards every value below; Runs of the pool use it as their lock
|
|
291
|
+
self._limit = ctx.Value("i", max(int(concurrency), 1), lock=False)
|
|
292
|
+
self._active = ctx.Value("i", 0, lock=False)
|
|
293
|
+
self._spent = ctx.Value("d", 0.0, lock=False)
|
|
294
|
+
self._reserved = ctx.Value("d", 0.0, lock=False)
|
|
295
|
+
self.sandbox = ctx.RLock()
|
|
296
|
+
self.planned = ctx.Event() # the first engine made its plan (and its over-budget choice)
|
|
297
|
+
self._choice = ctx.Array("c", 16)
|
|
298
|
+
|
|
299
|
+
@property
|
|
300
|
+
def spent(self) -> float:
|
|
301
|
+
return self._spent.value
|
|
302
|
+
|
|
303
|
+
@property
|
|
304
|
+
def reserved(self) -> float:
|
|
305
|
+
return self._reserved.value
|
|
306
|
+
|
|
307
|
+
def add(self, spent: float = 0.0, reserved: float = 0.0) -> None:
|
|
308
|
+
with self.cond:
|
|
309
|
+
self._spent.value += spent
|
|
310
|
+
self._reserved.value += reserved
|
|
311
|
+
if reserved < 0 or spent:
|
|
312
|
+
self.cond.notify_all()
|
|
313
|
+
|
|
314
|
+
def chose(self, choice: str | None) -> None:
|
|
315
|
+
"""The first engine's answer to the over-budget question: the later engines start with it."""
|
|
316
|
+
self._choice.value = (choice or "").encode()[:15]
|
|
317
|
+
self.planned.set()
|
|
318
|
+
|
|
319
|
+
@property
|
|
320
|
+
def choice(self) -> str | None:
|
|
321
|
+
return self._choice.value.decode() or None
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
class SharedGate:
|
|
325
|
+
"""Gate over a Pool: at most the pool's limit of agent calls at a time across the processes and threads that share it."""
|
|
326
|
+
|
|
327
|
+
WAIT_S = 5.0 # a waiter looks again at least this often (a process that died holding a slot is not waited on forever)
|
|
328
|
+
|
|
329
|
+
def __init__(self, pool: Pool):
|
|
330
|
+
self.pool = pool
|
|
331
|
+
self.cond = pool.cond
|
|
332
|
+
|
|
333
|
+
@property
|
|
334
|
+
def limit(self) -> int:
|
|
335
|
+
return self.pool._limit.value
|
|
336
|
+
|
|
337
|
+
@property
|
|
338
|
+
def active(self) -> int:
|
|
339
|
+
return self.pool._active.value
|
|
340
|
+
|
|
341
|
+
def __enter__(self):
|
|
342
|
+
with self.cond:
|
|
343
|
+
while self.pool._active.value >= self.pool._limit.value:
|
|
344
|
+
self.cond.wait(self.WAIT_S)
|
|
345
|
+
self.pool._active.value += 1
|
|
346
|
+
return self
|
|
347
|
+
|
|
348
|
+
def __exit__(self, *exc):
|
|
349
|
+
with self.cond:
|
|
350
|
+
self.pool._active.value -= 1
|
|
351
|
+
self.cond.notify_all()
|
|
352
|
+
return False
|
|
353
|
+
|
|
354
|
+
def lower(self, to: int | None = None) -> int:
|
|
355
|
+
with self.cond:
|
|
356
|
+
self.pool._limit.value = max(int(to if to is not None else self.pool._limit.value // 2), 1)
|
|
357
|
+
self.cond.notify_all()
|
|
358
|
+
return self.pool._limit.value
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
class Run:
|
|
362
|
+
"""One run's budget and its ledger. Thread-safe: rank's batches run side by side."""
|
|
363
|
+
|
|
364
|
+
def __init__(self, out_dir: Path | None, budget_usd: float | None, *, settings: dict | None = None, billing: str = "plan",
|
|
365
|
+
run_id: str = "", on_call=None, basis_text: str = "", pool: Pool | None = None):
|
|
366
|
+
self.out_dir = out_dir
|
|
367
|
+
self.budget = budget_usd
|
|
368
|
+
self.settings = settings or agent_settings(None)
|
|
369
|
+
self.billing = billing
|
|
370
|
+
# a Condition: a call that needs budget other calls hold waits for them (BudgetRunner._once)
|
|
371
|
+
self.pool = pool
|
|
372
|
+
self.lock = pool.cond if pool is not None else threading.Condition()
|
|
373
|
+
self._spent = 0.0
|
|
374
|
+
self._reserved = 0.0
|
|
375
|
+
self.calls: list[dict] = []
|
|
376
|
+
self.on_call = on_call or (lambda call, run: None)
|
|
377
|
+
self.note = _Note()
|
|
378
|
+
self.stopped_by_budget = False
|
|
379
|
+
# the agent CLI's usage or rate limit (agent.UsageLimitError): each event, and whether the run stopped asking
|
|
380
|
+
self.limits: list[dict] = []
|
|
381
|
+
self.stopped_by_limit: dict | None = None
|
|
382
|
+
self.stopped_first = "" # "budget" or "usage_limit": what stopped the asking first
|
|
383
|
+
self.gate = SharedGate(pool) if pool is not None else Gate(int(self.settings.get("concurrency") or 6))
|
|
384
|
+
self.sleep = time.sleep # tests replace it
|
|
385
|
+
self.ledger = load_ledger(out_dir)
|
|
386
|
+
self.estimator = Estimator(self.settings, self.ledger)
|
|
387
|
+
self.record = {"run_id": run_id or now(), "started_at": now(), "budget_usd": budget_usd, "budget_basis": basis_text,
|
|
388
|
+
"billing": billing, "calls": self.calls, "limits": self.limits}
|
|
389
|
+
self.ledger["runs"].append(self.record)
|
|
390
|
+
|
|
391
|
+
def on_limit(self, e, attempt: int) -> float | None:
|
|
392
|
+
"""After a call ran into a limit: the seconds to wait before it is tried again, or None when this run asks nothing
|
|
393
|
+
more. Concurrency is halved (a usage limit: one call at a time)."""
|
|
394
|
+
s = self.settings
|
|
395
|
+
kind = getattr(e, "kind", "usage_limit")
|
|
396
|
+
resets = getattr(e, "resets_at", None)
|
|
397
|
+
wait: float | None
|
|
398
|
+
if kind == "usage_limit":
|
|
399
|
+
to = resets - time.time() if resets else None
|
|
400
|
+
if to is not None and to <= float(s.get("usage_limit_wait_max_s", 1800)):
|
|
401
|
+
wait = max(to, 0.0) + 15.0
|
|
402
|
+
elif to is None and attempt < int(s.get("limit_retries", 6)):
|
|
403
|
+
wait = min(float(s.get("limit_backoff_s", 30)) * (2 ** attempt), float(s.get("limit_backoff_max_s", 600)))
|
|
404
|
+
else:
|
|
405
|
+
wait = None
|
|
406
|
+
after = self.gate.lower(1)
|
|
407
|
+
else:
|
|
408
|
+
wait = (min(float(s.get("limit_backoff_s", 30)) * (2 ** attempt), float(s.get("limit_backoff_max_s", 600)))
|
|
409
|
+
if attempt < int(s.get("limit_retries", 6)) else None)
|
|
410
|
+
after = self.gate.lower()
|
|
411
|
+
event = {"kind": kind, "at": now(), "attempt": attempt + 1, "concurrency_after": after,
|
|
412
|
+
**({"resets_at": datetime.fromtimestamp(resets, timezone.utc).isoformat(timespec="seconds")} if resets else {}),
|
|
413
|
+
**({"limit_type": e.limit_type} if getattr(e, "limit_type", "") else {}),
|
|
414
|
+
"waited_s": round(wait, 1) if wait is not None else None, "message": str(e)[:200]}
|
|
415
|
+
with self.lock:
|
|
416
|
+
self.limits.append(event)
|
|
417
|
+
if wait is None and self.stopped_by_limit is None:
|
|
418
|
+
self.stopped_by_limit = event
|
|
419
|
+
self.stopped_first = self.stopped_first or "usage_limit"
|
|
420
|
+
self.save()
|
|
421
|
+
return wait
|
|
422
|
+
|
|
423
|
+
# what this run spent and holds; with a pool, every change is also the pool's (one budget for every engine)
|
|
424
|
+
@property
|
|
425
|
+
def spent(self) -> float:
|
|
426
|
+
return self._spent
|
|
427
|
+
|
|
428
|
+
@spent.setter
|
|
429
|
+
def spent(self, value: float) -> None:
|
|
430
|
+
if self.pool is not None:
|
|
431
|
+
self.pool.add(spent=value - self._spent)
|
|
432
|
+
self._spent = value
|
|
433
|
+
|
|
434
|
+
@property
|
|
435
|
+
def reserved(self) -> float:
|
|
436
|
+
return self._reserved
|
|
437
|
+
|
|
438
|
+
@reserved.setter
|
|
439
|
+
def reserved(self, value: float) -> None:
|
|
440
|
+
if self.pool is not None:
|
|
441
|
+
self.pool.add(reserved=value - self._reserved)
|
|
442
|
+
freed = value < self._reserved
|
|
443
|
+
self._reserved = value
|
|
444
|
+
if freed:
|
|
445
|
+
with self.lock:
|
|
446
|
+
self.lock.notify_all() # a call waiting for budget this one held
|
|
447
|
+
|
|
448
|
+
def held(self) -> float:
|
|
449
|
+
"""What calls running now hold of the budget (every engine's, with a pool)."""
|
|
450
|
+
return self.pool.reserved if self.pool is not None else self._reserved
|
|
451
|
+
|
|
452
|
+
# what is left: None means no ceiling
|
|
453
|
+
def left(self) -> float | None:
|
|
454
|
+
if self.budget is None:
|
|
455
|
+
return None
|
|
456
|
+
if self.pool is not None and self.pool.budget is not None:
|
|
457
|
+
return round(self.pool.budget - self.pool.spent - self.pool.reserved, 6)
|
|
458
|
+
return round(self.budget - self.spent - self.reserved, 6)
|
|
459
|
+
|
|
460
|
+
def remaining(self) -> float | None:
|
|
461
|
+
if self.budget is None:
|
|
462
|
+
return None
|
|
463
|
+
if self.pool is not None and self.pool.budget is not None:
|
|
464
|
+
return max(round(self.pool.budget - self.pool.spent, 6), 0.0)
|
|
465
|
+
return max(round(self.budget - self.spent, 6), 0.0)
|
|
466
|
+
|
|
467
|
+
def can_pay(self, amount: float) -> bool:
|
|
468
|
+
left = self.left()
|
|
469
|
+
return left is None or left >= max(float(amount), 0.0)
|
|
470
|
+
|
|
471
|
+
def save(self) -> None:
|
|
472
|
+
if not self.out_dir:
|
|
473
|
+
return
|
|
474
|
+
try:
|
|
475
|
+
self.out_dir.mkdir(parents=True, exist_ok=True)
|
|
476
|
+
self.record["spent_usd"] = round(self.spent, 6)
|
|
477
|
+
self.record["finished_at"] = now()
|
|
478
|
+
(self.out_dir / LEDGER_FILE).write_text(json.dumps(self.ledger, indent=1, ensure_ascii=False))
|
|
479
|
+
except OSError:
|
|
480
|
+
pass
|
|
481
|
+
|
|
482
|
+
def tell(self, step: str, items: int = 0, estimate: tuple = (0.0, 0.0)) -> None:
|
|
483
|
+
"""Say, for the calls this thread makes next, which step they belong to and how many items each asks about."""
|
|
484
|
+
self.note.step, self.note.items, self.note.estimate = step, int(items), tuple(estimate)
|
|
485
|
+
|
|
486
|
+
def wrap(self, runner, step: str = "") -> "BudgetRunner":
|
|
487
|
+
return runner if isinstance(runner, BudgetRunner) else BudgetRunner(runner, self, step)
|
|
488
|
+
|
|
489
|
+
def add(self, call: dict, freed: float = 0.0) -> None:
|
|
490
|
+
"""Record a call; `freed`: what it held of the budget, given back in the same step as its cost is counted (between
|
|
491
|
+
the two, a call side by side would see budget that is spent)."""
|
|
492
|
+
with self.lock:
|
|
493
|
+
self.calls.append(call)
|
|
494
|
+
self.spent += float(call.get("cost_usd") or 0)
|
|
495
|
+
if freed:
|
|
496
|
+
self.reserved -= freed
|
|
497
|
+
self.save()
|
|
498
|
+
try:
|
|
499
|
+
self.on_call(call, self)
|
|
500
|
+
except Exception:
|
|
501
|
+
pass
|
|
502
|
+
|
|
503
|
+
def spent_by_step(self) -> dict[str, float]:
|
|
504
|
+
out: dict[str, float] = {}
|
|
505
|
+
for c in self.calls:
|
|
506
|
+
out[c.get("step") or "other"] = round(out.get(c.get("step") or "other", 0.0) + float(c.get("cost_usd") or 0), 6)
|
|
507
|
+
return out
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
class BudgetRunner:
|
|
511
|
+
"""An agent runner that goes through the run's ledger: every call is recorded, a call is given at most what is left of
|
|
512
|
+
the budget, and a call is not started when less than `min_call_usd` is left (AgentError "budget reached")."""
|
|
513
|
+
|
|
514
|
+
def __init__(self, inner, run: Run, step: str = ""):
|
|
515
|
+
self.inner, self.run_, self.step = inner, run, step
|
|
516
|
+
self.name = getattr(inner, "name", "agent")
|
|
517
|
+
try:
|
|
518
|
+
params = inspect.signature(inner.run).parameters
|
|
519
|
+
self._timeout = "timeout_s" in params or any(p.kind == p.VAR_KEYWORD for p in params.values())
|
|
520
|
+
except (TypeError, ValueError):
|
|
521
|
+
self._timeout = False
|
|
522
|
+
|
|
523
|
+
def __getattr__(self, name): # billing_mode, billing_note, available, default_model ...
|
|
524
|
+
return getattr(self.inner, name)
|
|
525
|
+
|
|
526
|
+
def tell(self, step: str, items: int = 0, estimate: tuple | None = None) -> None:
|
|
527
|
+
"""What the next calls of this thread ask about (step, items); the estimate from the run's own estimator."""
|
|
528
|
+
self.run_.tell(step, items, estimate if estimate is not None else self.run_.estimator.range(step, items))
|
|
529
|
+
|
|
530
|
+
def run(self, prompt, schema, cwd, *, model=None, max_budget_usd=None, timeout_s=None):
|
|
531
|
+
"""One agent call. A usage or rate limit is a pause: the call waits (Run.on_limit) and is tried again; when the run
|
|
532
|
+
cannot wait, it raises UsageLimitError and every later call of the run does too, without starting."""
|
|
533
|
+
from .agent import UsageLimitError
|
|
534
|
+
r = self.run_
|
|
535
|
+
step = r.note.step or self.step or "other"
|
|
536
|
+
items, estimate = r.note.items, r.note.estimate
|
|
537
|
+
attempt = 0
|
|
538
|
+
while True:
|
|
539
|
+
if r.stopped_by_limit is not None:
|
|
540
|
+
call = {"step": step, "items": items, "status": "not_started", "reason": "usage_limit", "cost_usd": 0.0,
|
|
541
|
+
"estimate_low_usd": estimate[0] if estimate else 0.0, "estimate_high_usd": estimate[1] if estimate else 0.0,
|
|
542
|
+
"at": now()}
|
|
543
|
+
with r.lock:
|
|
544
|
+
r.calls.append(call)
|
|
545
|
+
r.save()
|
|
546
|
+
raise UsageLimitError(f"not asked: the agent's usage limit stopped this run ({r.stopped_by_limit.get('message', '')})",
|
|
547
|
+
kind="usage_limit")
|
|
548
|
+
try:
|
|
549
|
+
with r.gate:
|
|
550
|
+
return self._once(prompt, schema, cwd, model, max_budget_usd, timeout_s, step, items, estimate)
|
|
551
|
+
except UsageLimitError as e:
|
|
552
|
+
wait = r.on_limit(e, attempt)
|
|
553
|
+
if wait is None:
|
|
554
|
+
raise
|
|
555
|
+
attempt += 1
|
|
556
|
+
r.sleep(wait)
|
|
557
|
+
|
|
558
|
+
def _once(self, prompt, schema, cwd, model, max_budget_usd, timeout_s, step, items, estimate):
|
|
559
|
+
from .agent import UsageLimitError
|
|
560
|
+
r = self.run_
|
|
561
|
+
with r.lock:
|
|
562
|
+
left = r.left()
|
|
563
|
+
cap, held = max_budget_usd, 0.0
|
|
564
|
+
if left is not None:
|
|
565
|
+
floor = float(r.settings["min_call_usd"])
|
|
566
|
+
# calls side by side (other steps, other engines) hold what they may spend: a call that needs more than is
|
|
567
|
+
# left now waits for them to finish instead of starting short or being refused while budget is only held
|
|
568
|
+
while left < max(floor, float(cap or 0.0)) and r.held() > 1e-9:
|
|
569
|
+
r.lock.wait(SharedGate.WAIT_S)
|
|
570
|
+
left = r.left()
|
|
571
|
+
if left < floor:
|
|
572
|
+
r.stopped_by_budget = True
|
|
573
|
+
r.stopped_first = r.stopped_first or "budget"
|
|
574
|
+
call = {"step": step, "items": items, "status": "not_started", "reason": "budget", "cost_usd": 0.0,
|
|
575
|
+
"estimate_low_usd": estimate[0] if estimate else 0.0, "estimate_high_usd": estimate[1] if estimate else 0.0,
|
|
576
|
+
"at": now()}
|
|
577
|
+
r.calls.append(call)
|
|
578
|
+
r.save()
|
|
579
|
+
raise AgentError(f"budget reached: ${max(left, 0):.2f} of the run budget ${r.budget:.2f} is left, "
|
|
580
|
+
f"less than one call needs (agent.min_call_usd {floor:g})")
|
|
581
|
+
# a step that gives no cap of its own (the loop and group steps, calls side by side) holds at most
|
|
582
|
+
# max_call_usd: held as all that is left, the first call made every other one "budget reached"
|
|
583
|
+
if cap is None and step in SIDE_BY_SIDE:
|
|
584
|
+
share = max(left / max(r.gate.limit, 1), floor) # every call that may run beside it gets its share
|
|
585
|
+
cap = min(left, float(r.settings.get("max_call_usd") or left), share)
|
|
586
|
+
elif cap is None:
|
|
587
|
+
# any other step with no cap of its own (profile, areas, the kinds' questions) runs beside other steps
|
|
588
|
+
# and engines now: it holds max_call_usd or its share of what is left, whichever is more
|
|
589
|
+
cap = min(left, max(float(r.settings.get("max_call_usd") or left), left / max(r.gate.limit, 1)))
|
|
590
|
+
else:
|
|
591
|
+
cap = left if cap is None else min(cap, left)
|
|
592
|
+
held = cap
|
|
593
|
+
r.reserved += held
|
|
594
|
+
kw = {"model": model, "max_budget_usd": cap}
|
|
595
|
+
if self._timeout:
|
|
596
|
+
kw["timeout_s"] = int(timeout_s or r.settings["call_timeout_s"])
|
|
597
|
+
started = time.monotonic()
|
|
598
|
+
call = {"step": step, "items": items, "estimate_low_usd": estimate[0] if estimate else 0.0,
|
|
599
|
+
"estimate_high_usd": estimate[1] if estimate else 0.0, "at": now(), "billing": r.billing}
|
|
600
|
+
try:
|
|
601
|
+
result = self.inner.run(prompt, schema, cwd, **kw)
|
|
602
|
+
except UsageLimitError as e:
|
|
603
|
+
# the account's limit, not this call's fault: nothing was answered, nothing is counted as spent
|
|
604
|
+
call.update(status="failed", reason=e.kind, error=str(e)[:300], cost_usd=0.0, cost_reported=False,
|
|
605
|
+
duration_s=round(time.monotonic() - started, 1), usage_limit=True)
|
|
606
|
+
r.add(call, freed=held)
|
|
607
|
+
raise
|
|
608
|
+
except AgentError as e:
|
|
609
|
+
over = "budget" in str(e).lower()
|
|
610
|
+
# a call that ran into its limit does not say what it spent: count its whole cap, so the total stays under the budget
|
|
611
|
+
call.update(status="failed", reason="budget" if over else "agent_error", error=str(e)[:300],
|
|
612
|
+
cost_usd=round(float(cap or 0.0), 6) if over else 0.0, cost_reported=False,
|
|
613
|
+
duration_s=round(time.monotonic() - started, 1), usage_limit=_usage_limit(str(e)))
|
|
614
|
+
if over:
|
|
615
|
+
r.stopped_by_budget = True
|
|
616
|
+
r.stopped_first = r.stopped_first or "budget"
|
|
617
|
+
r.add(call, freed=held)
|
|
618
|
+
raise
|
|
619
|
+
except Exception as e:
|
|
620
|
+
call.update(status="failed", reason="agent_error", error=f"{type(e).__name__}: {e}"[:300], cost_usd=0.0,
|
|
621
|
+
duration_s=round(time.monotonic() - started, 1))
|
|
622
|
+
r.add(call, freed=held)
|
|
623
|
+
raise
|
|
624
|
+
call.update(status="done", cost_usd=round(float(getattr(result, "cost_usd", 0) or 0), 6), cost_reported=True,
|
|
625
|
+
duration_s=round(float(getattr(result, "duration_s", 0) or (time.monotonic() - started)), 1),
|
|
626
|
+
model=getattr(result, "model", ""), turns=int(getattr(result, "turns", 0) or 0),
|
|
627
|
+
usage=dict(getattr(result, "usage", {}) or {}),
|
|
628
|
+
**({"limit": dict(result.limit)} if getattr(result, "limit", None) else {}))
|
|
629
|
+
r.add(call, freed=held)
|
|
630
|
+
return result
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def _usage_limit(message: str) -> bool:
|
|
634
|
+
"""Whether a failed call looks like the plan's usage limit (not verified against the agent CLI's real wording)."""
|
|
635
|
+
m = message.lower()
|
|
636
|
+
return any(w in m for w in ("usage limit", "rate limit", "rate_limit", "limit reached", "429", "overloaded"))
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
# ---- the queue --------------------------------------------------------------------------------------------------------
|
|
640
|
+
|
|
641
|
+
def item(kind: str, ref: str, *, label: str = "", file: str = "", line: int = 0, share: float | None = None,
|
|
642
|
+
path: bool = False, score: float = 0.0, units: int = 1, why: str = "", group: str = "") -> dict:
|
|
643
|
+
"""One thing the agent would judge. `share`: the measured share of all bytes read (with a pull); `path`: on a request
|
|
644
|
+
path or recurring work; `units`: what the estimate counts (statements, members, tables); `group`: items asked about
|
|
645
|
+
in one call that cannot be split (loops, groups)."""
|
|
646
|
+
return {"kind": kind, "step": STEP_OF[kind], "ref": ref, "label": label or ref, "file": file, "line": int(line or 0),
|
|
647
|
+
"share": share, "path": bool(path), "score": float(score or 0), "units": max(int(units), 1), "why": why,
|
|
648
|
+
**({"group": group} if group else {})}
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def value_key(it: dict) -> tuple:
|
|
652
|
+
"""Measured share first (largest first), then request paths and recurring work, then the rest by static score. The
|
|
653
|
+
code-area roles and the table sizes come before everything: the queue's order and the proof depend on them."""
|
|
654
|
+
if it.get("kind") in ("areas", "table_profile"):
|
|
655
|
+
return (-1, 0.0, 0, 0.0)
|
|
656
|
+
share = it.get("share")
|
|
657
|
+
if share is not None and share > 0:
|
|
658
|
+
return (0, -float(share), 0, -it.get("score", 0.0))
|
|
659
|
+
return (1, 0.0, 0 if it.get("path") else 1, -it.get("score", 0.0))
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def why_text(it: dict) -> str:
|
|
663
|
+
if it.get("why"):
|
|
664
|
+
return it["why"]
|
|
665
|
+
if it.get("share"):
|
|
666
|
+
return f"{float(it['share']):.1%} of reads"
|
|
667
|
+
return "on a request path or recurring work" if it.get("path") else "app or job code"
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
def plan(items: list[dict], budget: float | None, estimator: Estimator, *, concurrency: int, items_per_call: dict,
|
|
671
|
+
reserve: tuple[float, float] = (0.0, 0.0)) -> dict:
|
|
672
|
+
"""The run's plan: the queue in value order, its estimate by kind, and which items fit the budget.
|
|
673
|
+
|
|
674
|
+
Items are taken in value order while the middle of their estimate fits what the budget leaves after `reserve` (the
|
|
675
|
+
table-size step the proof needs). Items that are asked in one call together (`group`) fit as a whole or not at all."""
|
|
676
|
+
queue = sorted(items, key=value_key)
|
|
677
|
+
for i, it in enumerate(queue):
|
|
678
|
+
lo, hi = estimator.range(it["step"], it["units"])
|
|
679
|
+
it["est_low_usd"], it["est_high_usd"], it["order"] = lo, hi, i
|
|
680
|
+
# a call costs at least its own overhead (reading the repository, the schema), however few items it asks about: each
|
|
681
|
+
# step's estimate is at least its calls x call_usd_low/high (one item alone costs a whole call's overhead)
|
|
682
|
+
floor_lo, floor_hi = float(estimator.s.get("call_usd_low") or 0), float(estimator.s.get("call_usd_high") or 0)
|
|
683
|
+
by_step: dict[str, list[dict]] = {}
|
|
684
|
+
for it in queue:
|
|
685
|
+
by_step.setdefault(it.get("group") or it["step"], []).append(it)
|
|
686
|
+
for key, members in by_step.items():
|
|
687
|
+
step = members[0]["step"]
|
|
688
|
+
units = sum(m["units"] for m in members)
|
|
689
|
+
n_calls = math.ceil(units / max(items_per_call.get(step, units) or 1, 1)) if step in items_per_call else 1
|
|
690
|
+
for attr, floor in (("est_low_usd", floor_lo), ("est_high_usd", floor_hi)):
|
|
691
|
+
short = round(n_calls * floor - sum(m[attr] for m in members), 2)
|
|
692
|
+
if short > 0:
|
|
693
|
+
members[0][attr] = round(members[0][attr] + short, 2)
|
|
694
|
+
total_lo = round(sum(it["est_low_usd"] for it in queue) + reserve[0], 2)
|
|
695
|
+
total_hi = round(sum(it["est_high_usd"] for it in queue) + reserve[1], 2)
|
|
696
|
+
room = None if budget is None else max(budget - (reserve[0] + reserve[1]) / 2, 0.0)
|
|
697
|
+
used, chosen, groups = 0.0, [], {}
|
|
698
|
+
for it in queue:
|
|
699
|
+
if it.get("group"):
|
|
700
|
+
groups.setdefault(it["group"], []).append(it)
|
|
701
|
+
seen_groups: set[str] = set()
|
|
702
|
+
for it in queue:
|
|
703
|
+
g = it.get("group")
|
|
704
|
+
if g:
|
|
705
|
+
if g in seen_groups:
|
|
706
|
+
continue
|
|
707
|
+
seen_groups.add(g)
|
|
708
|
+
members = groups[g]
|
|
709
|
+
mid = sum((m["est_low_usd"] + m["est_high_usd"]) / 2 for m in members)
|
|
710
|
+
if room is None or used + mid <= room + 1e-9:
|
|
711
|
+
used += mid
|
|
712
|
+
chosen += members
|
|
713
|
+
continue
|
|
714
|
+
mid = (it["est_low_usd"] + it["est_high_usd"]) / 2
|
|
715
|
+
if room is None or used + mid <= room + 1e-9:
|
|
716
|
+
used += mid
|
|
717
|
+
chosen.append(it)
|
|
718
|
+
picked = {id(x) for x in chosen}
|
|
719
|
+
for it in queue:
|
|
720
|
+
it["fits"] = id(it) in picked
|
|
721
|
+
by_kind: dict[str, dict] = {}
|
|
722
|
+
for it in queue:
|
|
723
|
+
k = by_kind.setdefault(it["kind"], {"kind": it["kind"], "label": KIND_LABEL[it["kind"]], "items": 0, "units": 0,
|
|
724
|
+
"est_low_usd": 0.0, "est_high_usd": 0.0, "fit_items": 0})
|
|
725
|
+
k["items"] += 1
|
|
726
|
+
k["units"] += it["units"]
|
|
727
|
+
k["est_low_usd"] = round(k["est_low_usd"] + it["est_low_usd"], 2)
|
|
728
|
+
k["est_high_usd"] = round(k["est_high_usd"] + it["est_high_usd"], 2)
|
|
729
|
+
k["fit_items"] += int(it["fits"])
|
|
730
|
+
calls = sum(math.ceil(v["units"] / max(items_per_call.get(STEP_OF[k], 40), 1)) if STEP_OF[k] in items_per_call else 1
|
|
731
|
+
for k, v in by_kind.items())
|
|
732
|
+
secs = estimator.seconds(calls, concurrency)
|
|
733
|
+
fit_lo = round(sum(it["est_low_usd"] for it in queue if it["fits"]) + reserve[0], 2)
|
|
734
|
+
fit_hi = round(sum(it["est_high_usd"] for it in queue if it["fits"]) + reserve[1], 2)
|
|
735
|
+
return {"queue": queue, "by_kind": [by_kind[k] for k in KINDS if k in by_kind], "items": len(queue),
|
|
736
|
+
"est_low_usd": total_lo, "est_high_usd": total_hi, "reserve_low_usd": reserve[0], "reserve_high_usd": reserve[1],
|
|
737
|
+
"calls": calls, "seconds_low": secs[0], "seconds_high": secs[1], "budget_usd": budget,
|
|
738
|
+
"over_budget": budget is not None and total_hi > budget + 1e-9,
|
|
739
|
+
"fit_items": sum(1 for it in queue if it["fits"]), "fit_low_usd": fit_lo, "fit_high_usd": fit_hi,
|
|
740
|
+
"estimate_basis": {k: estimator.per_item(STEP_OF[k])[2] for k in by_kind}}
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def chosen(p: dict, kind: str) -> list[dict]:
|
|
744
|
+
return [it for it in p["queue"] if it["kind"] == kind and it.get("fits")]
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def not_asked(queue: list[dict]) -> dict:
|
|
748
|
+
"""The items left unasked: count, estimate, and by kind and by where they run."""
|
|
749
|
+
left = [it for it in queue]
|
|
750
|
+
lo = round(sum(it.get("est_low_usd", 0) for it in left), 2)
|
|
751
|
+
hi = round(sum(it.get("est_high_usd", 0) for it in left), 2)
|
|
752
|
+
by_kind: dict[str, dict] = {}
|
|
753
|
+
for it in left:
|
|
754
|
+
k = by_kind.setdefault(it["kind"], {"items": 0, "est_low_usd": 0.0, "est_high_usd": 0.0, "next_step": NEXT_STEP[it["kind"]]})
|
|
755
|
+
k["items"] += 1
|
|
756
|
+
k["est_low_usd"] = round(k["est_low_usd"] + it.get("est_low_usd", 0), 2)
|
|
757
|
+
k["est_high_usd"] = round(k["est_high_usd"] + it.get("est_high_usd", 0), 2)
|
|
758
|
+
paths = [it for it in left if it.get("path") or it.get("share")]
|
|
759
|
+
return {"items": len(left), "est_low_usd": lo, "est_high_usd": hi, "by_kind": by_kind,
|
|
760
|
+
"on_request_paths": {"items": len(paths), "est_low_usd": round(sum(i.get("est_low_usd", 0) for i in paths), 2),
|
|
761
|
+
"est_high_usd": round(sum(i.get("est_high_usd", 0) for i in paths), 2)},
|
|
762
|
+
"share_of_reads": round(sum(float(i.get("share") or 0) for i in left), 6)}
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
def public_item(it: dict) -> dict:
|
|
766
|
+
"""An item as the plan file and the report keep it: no SQL, labels and numbers only."""
|
|
767
|
+
keep = ("kind", "step", "ref", "label", "file", "line", "share", "path", "units", "est_low_usd", "est_high_usd", "fits", "order")
|
|
768
|
+
return {**{k: it.get(k) for k in keep if it.get(k) is not None}, "why": why_text(it), "next_step": NEXT_STEP[it["kind"]],
|
|
769
|
+
**({"state": it["state"]} if it.get("state") else {})}
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
# ---- what is printed --------------------------------------------------------------------------------------------------
|
|
773
|
+
|
|
774
|
+
def _bar(value: float, top: float, width: int = 16) -> str:
|
|
775
|
+
if top <= 0:
|
|
776
|
+
return ""
|
|
777
|
+
n = max(int(round(width * value / top)), 1 if value > 0 else 0)
|
|
778
|
+
return "█" * n
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def _mins(seconds: float) -> str:
|
|
782
|
+
return f"{seconds / 60:.0f} min" if seconds >= 90 else f"{seconds:.0f} s"
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def plan_lines(p: dict, billing: str, *, pulled: bool, budget_basis: str = "", cached: int = 0, set_aside: dict | None = None) -> list[str]:
|
|
786
|
+
"""Before: what will be judged, by step, its range and time, and what the budget buys."""
|
|
787
|
+
lines = ["Plan what rules cannot judge est. (API rates)"]
|
|
788
|
+
top = max((k["est_high_usd"] for k in p["by_kind"]), default=0.0)
|
|
789
|
+
if set_aside and set_aside.get("items"):
|
|
790
|
+
codes = " · ".join(f"{n} {c.replace('_', ' ')}" for c, n in sorted((set_aside.get("codes") or {}).items()))
|
|
791
|
+
lines.append(f" set aside by rule {set_aside['items']:>5} {codes} $0")
|
|
792
|
+
if cached:
|
|
793
|
+
lines.append(f" answered before {cached:>5} stored verdicts, not paid again $0")
|
|
794
|
+
for k in p["by_kind"]:
|
|
795
|
+
lines.append(f" {k['label']:<16}{k['items']:>6} {_bar(k['est_high_usd'], top):<16} ${k['est_low_usd']:,.2f}–{k['est_high_usd']:,.2f}")
|
|
796
|
+
if not p["by_kind"]:
|
|
797
|
+
lines.append(" nothing to ask: every item is answered or set aside by rule")
|
|
798
|
+
lines.append(f" total ${p['est_low_usd']:,.2f}–{p['est_high_usd']:,.2f} · {_mins(p['seconds_low'])}–{_mins(p['seconds_high'])}")
|
|
799
|
+
noun = "usage, not billed per token" if billing == "plan" else "billed to the API key" if billing == "api_key" else "est. at API rates"
|
|
800
|
+
budget = "no limit" if p["budget_usd"] is None else f"${p['budget_usd']:,.2f}"
|
|
801
|
+
lines.append(f" budget {budget}" + (f" ({budget_basis})" if budget_basis else "") + f" · {'plan login: ' if billing == 'plan' else ''}{noun}")
|
|
802
|
+
if p["over_budget"] and p["fit_items"] < p["items"]:
|
|
803
|
+
lines.append(f" the budget covers about {p['fit_items']:,} of {p['items']:,} items in value order "
|
|
804
|
+
f"(est. ${p['fit_low_usd']:,.2f}–{p['fit_high_usd']:,.2f}); the rest is listed as not asked yet, with its estimate")
|
|
805
|
+
elif p["over_budget"]:
|
|
806
|
+
lines.append(f" the estimate's high end is above the budget: items are asked in value order and the run stops cleanly "
|
|
807
|
+
f"at ${p['budget_usd']:,.2f} if it gets there; what is left is listed as not asked yet, with its estimate")
|
|
808
|
+
lines.append(" order: share of database reads" if pulled else
|
|
809
|
+
" order: request paths first (no database pull; `codecop scan --env-file .env` orders by real load)")
|
|
810
|
+
return lines
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
def progress_line(run: Run, judged: int, total: int, verified: int | None = None) -> str:
|
|
814
|
+
"""During: one plain line per agent call, readable on a terminal and in a CI log alike."""
|
|
815
|
+
done = sum(1 for c in run.calls if c.get("status") == "done")
|
|
816
|
+
failed = sum(1 for c in run.calls if c.get("status") == "failed")
|
|
817
|
+
budget = "" if run.budget is None else f" of ${run.budget:,.2f}"
|
|
818
|
+
text = f"Ask {done} call{'s' if done != 1 else ''} done" + (f", {failed} failed" if failed else "") \
|
|
819
|
+
+ f" {money(run.spent, run.billing)}{budget}"
|
|
820
|
+
if total:
|
|
821
|
+
text += f" · judged {judged:,}/{total:,}"
|
|
822
|
+
if verified is not None:
|
|
823
|
+
text += f" · {verified} verified"
|
|
824
|
+
return text
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def summary(run: Run | None, p: dict | None, findings: dict | None, after_queue: list[dict], *, pulled: bool,
|
|
828
|
+
reused_items: int = 0, earlier_total: float | None = None, verified_units: dict | None = None) -> dict:
|
|
829
|
+
"""After: what was spent and what it bought. Only sandbox-verified fixes count as fixes; an agent's claim never does.
|
|
830
|
+
`verified_units`: loop members and scan groups the sandbox verified ({loops: n, groups: n}), counted beside the
|
|
831
|
+
statements."""
|
|
832
|
+
billing = run.billing if run else "plan"
|
|
833
|
+
spent = round(run.spent, 4) if run else 0.0
|
|
834
|
+
calls = [c for c in (run.calls if run else []) if c.get("status") == "done"]
|
|
835
|
+
judged = sum(int(c.get("items") or 0) for c in calls)
|
|
836
|
+
fs = (findings or {}).get("findings") or []
|
|
837
|
+
verified = [f for f in fs if f.get("status") == "verified"]
|
|
838
|
+
units = {k: int(v or 0) for k, v in (verified_units or {}).items() if v}
|
|
839
|
+
verified = verified + [{} for _ in range(sum(units.values()))]
|
|
840
|
+
covered = 0.0
|
|
841
|
+
for f in verified:
|
|
842
|
+
share = ((f.get("measured") or {}).get("share_of_read_bytes") or ((f.get("observed") or {}).get("share_of_read_bytes")))
|
|
843
|
+
if share:
|
|
844
|
+
covered += float(share)
|
|
845
|
+
left = not_asked(after_queue)
|
|
846
|
+
# why what is left was not asked: the budget (the plan did not fit it, or the run reached it) or the agent's usage
|
|
847
|
+
# limit (it fitted the budget, and the account could not run more). Said apart: one is a choice, the other a pause.
|
|
848
|
+
fitted = {(it["kind"], it["ref"]) for it in (p or {}).get("queue") or [] if it.get("fits")}
|
|
849
|
+
limited = [it for it in after_queue if (it["kind"], it["ref"]) in fitted] if run is not None and run.stopped_by_limit else []
|
|
850
|
+
if limited:
|
|
851
|
+
left["usage_limit"] = {"items": len(limited), "est_low_usd": round(sum(i.get("est_low_usd", 0) for i in limited), 2),
|
|
852
|
+
"est_high_usd": round(sum(i.get("est_high_usd", 0) for i in limited), 2)}
|
|
853
|
+
left["budget_items"] = len(after_queue) - len(limited)
|
|
854
|
+
per_all = bool(reused_items) and earlier_total is not None
|
|
855
|
+
paid = float(earlier_total) if per_all else spent
|
|
856
|
+
out = {
|
|
857
|
+
"schema_version": 1,
|
|
858
|
+
"billing": billing, "cost_basis": basis(billing),
|
|
859
|
+
"budget_usd": run.budget if run else None, "budget_basis": (run.record.get("budget_basis") if run else "") or "",
|
|
860
|
+
"spent_usd": spent, "calls": len(calls), "calls_failed": sum(1 for c in (run.calls if run else []) if c.get("status") == "failed"),
|
|
861
|
+
"stopped_by_budget": bool(run and run.stopped_by_budget),
|
|
862
|
+
"stopped_by_usage_limit": (dict(run.stopped_by_limit) if run and run.stopped_by_limit else None),
|
|
863
|
+
"stopped_first": (run.stopped_first if run else "") or "",
|
|
864
|
+
"usage_limits": {"events": len(run.limits), "kinds": sorted({e["kind"] for e in run.limits}),
|
|
865
|
+
"waited_s": round(sum(float(e.get("waited_s") or 0) for e in run.limits), 1),
|
|
866
|
+
"concurrency_after": run.gate.limit} if run and run.limits else None,
|
|
867
|
+
"spent_by_step": run.spent_by_step() if run else {},
|
|
868
|
+
"planned": {k: p[k] for k in ("items", "est_low_usd", "est_high_usd", "fit_items", "fit_low_usd", "fit_high_usd", "over_budget",
|
|
869
|
+
"seconds_low", "seconds_high")} | {"by_kind": p["by_kind"]} if p else None,
|
|
870
|
+
"judged_items": judged, "reused_items": int(reused_items),
|
|
871
|
+
"verified_fixes": len(verified),
|
|
872
|
+
"verified_by_kind": {"statements": len(verified) - sum(units.values()), **units},
|
|
873
|
+
# a run that reused earlier answers did not pay for the fixes they led to: per fix over every run of the out dir then
|
|
874
|
+
"cost_per_verified_fix_usd": (round(paid / len(verified), 2) if verified and paid else None),
|
|
875
|
+
"cost_per_verified_fix_basis": "all runs" if per_all else "this run",
|
|
876
|
+
"cost_per_judged_item_usd": round(spent / judged, 4) if judged and spent else None,
|
|
877
|
+
"reads_covered_by_verified_fixes": round(min(covered, 1.0), 6) if pulled else None,
|
|
878
|
+
"not_asked": left,
|
|
879
|
+
"not_asked_items": [public_item(i) for i in after_queue[:500]],
|
|
880
|
+
"not_asked_items_more": max(len(after_queue) - 500, 0),
|
|
881
|
+
**({"ledger_total_usd": earlier_total} if earlier_total is not None else {}),
|
|
882
|
+
}
|
|
883
|
+
return out
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def after_lines(s: dict, *, minutes: float | None = None) -> list[str]:
|
|
887
|
+
billing = s["billing"]
|
|
888
|
+
head = f"Done " + (f"{minutes:.0f} min · " if minutes is not None and minutes >= 1.5 else "") + money(s["spent_usd"], billing)
|
|
889
|
+
if s.get("budget_usd") is not None:
|
|
890
|
+
head += f" of ${s['budget_usd']:,.2f}"
|
|
891
|
+
head += " (est. at API rates)" if billing != "api_key" else " (billed to the API key)"
|
|
892
|
+
lines = [head]
|
|
893
|
+
lines.append(f" judged {s['judged_items']:,} by the agent this run" + (f" · {s['reused_items']:,} answered before, not paid again" if s.get("reused_items") else ""))
|
|
894
|
+
fix = f" verified {s['verified_fixes']} fix{'es' if s['verified_fixes'] != 1 else ''} (sandbox: same rows, reads less)"
|
|
895
|
+
if s.get("cost_per_verified_fix_usd"):
|
|
896
|
+
fix += f" · ${s['cost_per_verified_fix_usd']:,.2f} per verified fix" + (
|
|
897
|
+
" (over every run of this out dir)" if s.get("cost_per_verified_fix_basis") == "all runs" else "")
|
|
898
|
+
lines.append(fix)
|
|
899
|
+
if s.get("usage_limits"):
|
|
900
|
+
u = s["usage_limits"]
|
|
901
|
+
lines.append(f" agent limits: {u['events']} pause(s) ({', '.join(k.replace('_', ' ') for k in u['kinds'])}), waited "
|
|
902
|
+
f"{u['waited_s'] / 60:.0f} min, then {u['concurrency_after']} call(s) at a time")
|
|
903
|
+
if s.get("cost_per_judged_item_usd"):
|
|
904
|
+
lines.append(f" ${s['cost_per_judged_item_usd']:,.3f} per judged item")
|
|
905
|
+
if s.get("reads_covered_by_verified_fixes") is not None:
|
|
906
|
+
lines.append(f" reads covered by a verified fix: {s['reads_covered_by_verified_fixes']:.1%} of measured database reads")
|
|
907
|
+
na = s["not_asked"]
|
|
908
|
+
if na["items"]:
|
|
909
|
+
lines.append(f" not asked yet {na['items']:,} · est. ${na['est_low_usd']:,.2f}–{na['est_high_usd']:,.2f}")
|
|
910
|
+
for kind, k in sorted(na["by_kind"].items(), key=lambda kv: -kv[1]["est_high_usd"]):
|
|
911
|
+
lines.append(f" {k['items']:,} {KIND_LABEL.get(kind, kind)} est. ${k['est_low_usd']:,.2f}–{k['est_high_usd']:,.2f}")
|
|
912
|
+
ul = na.get("usage_limit")
|
|
913
|
+
if ul:
|
|
914
|
+
stop = s.get("stopped_by_usage_limit") or {}
|
|
915
|
+
lines.append(f" of them {ul['items']:,} not asked because the agent's usage limit was reached (not the budget)"
|
|
916
|
+
+ (f"; it resets {stop['resets_at']}" if stop.get("resets_at") else "")
|
|
917
|
+
+ f" · est. ${ul['est_low_usd']:,.2f}–{ul['est_high_usd']:,.2f}")
|
|
918
|
+
lines.append(" continue codecop scan (after the limit resets; nothing paid twice)")
|
|
919
|
+
elif s.get("stopped_by_budget") or (s.get("planned") or {}).get("over_budget"):
|
|
920
|
+
lines.append(" continue codecop scan --budget N (nothing paid twice)")
|
|
921
|
+
else:
|
|
922
|
+
lines.append(" not asked 0 · the next scan pays only for statements that change")
|
|
923
|
+
return lines
|
|
924
|
+
|
|
925
|
+
|
|
926
|
+
# ---- the one question -------------------------------------------------------------------------------------------------
|
|
927
|
+
|
|
928
|
+
def interactive() -> bool:
|
|
929
|
+
"""A person at a terminal (never in CI)."""
|
|
930
|
+
if os.environ.get("CI") or os.environ.get("GITHUB_ACTIONS"):
|
|
931
|
+
return False
|
|
932
|
+
try:
|
|
933
|
+
return sys.stdin.isatty() and sys.stdout.isatty()
|
|
934
|
+
except (AttributeError, ValueError):
|
|
935
|
+
return False
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
def over_budget_choice(p: dict, billing: str, *, ask: bool, read=input, write=print) -> str:
|
|
939
|
+
"""The only question a run asks, before anything is spent, on a terminal, when the estimate's high end is above the
|
|
940
|
+
budget: Enter spends the budget in value order (`budget`), `a` judges everything (`all`), `n` is a free look (`none`).
|
|
941
|
+
Without a terminal or with --yes: `budget`, never asked."""
|
|
942
|
+
if not p.get("over_budget") or not ask:
|
|
943
|
+
return "budget"
|
|
944
|
+
noun = "usage" if billing == "plan" else "cost"
|
|
945
|
+
write(f" The estimate (${p['est_low_usd']:,.2f}–{p['est_high_usd']:,.2f}) is above the budget (${p['budget_usd']:,.2f}).")
|
|
946
|
+
write(f" [Enter] spend ${p['budget_usd']:,.2f} in value order" + (f": about {p['fit_items']:,} of {p['items']:,} items" if p.get("items") else ""))
|
|
947
|
+
write(f" [a] judge everything, est. {noun} ${p['est_low_usd']:,.2f}–{p['est_high_usd']:,.2f}")
|
|
948
|
+
write(" [n] free look: rules and sandbox only")
|
|
949
|
+
try:
|
|
950
|
+
answer = (read(" > ") or "").strip().lower()
|
|
951
|
+
except EOFError:
|
|
952
|
+
answer = ""
|
|
953
|
+
return "all" if answer in ("a", "all") else "none" if answer in ("n", "no", "none") else "budget"
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
def confirmed_budget(repo_root: Path, budget: float) -> bool:
|
|
957
|
+
data = _read(repo_root / ".codecop" / CONSENT_FILE, {})
|
|
958
|
+
try:
|
|
959
|
+
return float(data.get("confirmed_budget_usd") or 0) >= budget
|
|
960
|
+
except (TypeError, ValueError):
|
|
961
|
+
return False
|
|
962
|
+
|
|
963
|
+
|
|
964
|
+
def remember_budget(repo_root: Path, budget: float) -> None:
|
|
965
|
+
try:
|
|
966
|
+
(repo_root / ".codecop").mkdir(parents=True, exist_ok=True)
|
|
967
|
+
(repo_root / ".codecop" / CONSENT_FILE).write_text(json.dumps({"confirmed_budget_usd": budget, "at": now()}, indent=1))
|
|
968
|
+
except OSError:
|
|
969
|
+
pass
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def write_plan(out_dir: Path, p: dict, extra: dict | None = None) -> dict:
|
|
973
|
+
"""agent_plan.json: the queue (labels and numbers, no SQL) and the estimate, for the report and the console."""
|
|
974
|
+
doc = {"schema_version": 1, "generated_at": now(), **{k: v for k, v in p.items() if k != "queue"},
|
|
975
|
+
"queue": [public_item(it) for it in p["queue"]], **(extra or {})}
|
|
976
|
+
try:
|
|
977
|
+
(out_dir / PLAN_FILE).write_text(json.dumps(doc, indent=1, ensure_ascii=False))
|
|
978
|
+
except OSError:
|
|
979
|
+
pass
|
|
980
|
+
return doc
|