Skip to content

Commit 2d711a4

Browse files
dolhoclaude
andcommitted
fix(db): coerce every agent_sync_state integer at its own column's ceiling (#2827)
`_coerce_nonneg_int` admitted anything up to INT8_MAX for all eight int columns, but only `git_dir_bytes` is BIGINT on PostgreSQL (#2800). The other seven are int4, so a value the boundary admitted but the column could not hold made the whole upsert raise NumericValueOutOfRange and the agent's sync health went dark. The four ahead/behind counters were not coerced at all. - default ceiling is now INT4_MAX; `git_dir_bytes` and the lock-report ints opt into INT8_MAX explicitly - `_coerce_counter` bounds ahead_main/behind_main/ahead_working/ behind_working (and the legacy ahead/behind keys) the same way Tests drive INT4_MAX+1 through `_sync_agent` per column (rejected → NULL/0, BIGINT admitted), pin that INT4_MAX itself lands, and round-trip each column's admitted maximum through SyncStateOperations on both backends. Mutation (default ceiling back to INT8, counter left raw) → 3 red. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VpvcfgWkmQPD7DrDLmATTf
1 parent 2627928 commit 2d711a4

3 files changed

Lines changed: 124 additions & 8 deletions

File tree

‎src/backend/services/sync_health_service.py‎

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -97,22 +97,53 @@ def _poll_interval_seconds() -> int:
9797
MAINTENANCE_FAILURES_ALERT_THRESHOLD = 3
9898

9999

100-
def _coerce_nonneg_int(value) -> Optional[int]:
100+
# PostgreSQL column ceilings. `Integer` is int4 there (SQLite's INTEGER is 64-bit
101+
# either way, which is how #2800 shipped): a value the boundary admits but the
102+
# column cannot hold makes the whole upsert raise `NumericValueOutOfRange`, and
103+
# the agent's sync health goes dark. So the boundary's ceiling MUST match the
104+
# column's (#2827): int4 for the counters, int8 only for the one byte count that
105+
# was widened.
106+
INT4_MAX = 2**31 - 1
107+
INT8_MAX = 2**63 - 1
108+
109+
110+
def _coerce_nonneg_int(value, *, ceiling: int = INT4_MAX) -> Optional[int]:
101111
"""Boundary guard for agent-supplied numbers (#1595).
102112
103113
`sync-state.json` is agent-writable: a compromised/prompt-injected agent
104114
can persist arbitrary JSON into it, and SQLite's dynamic typing would
105115
accept strings/objects silently. Same posture as `/health clone_status`
106116
(enum only, never agent-supplied strings). bool is an int subclass —
107117
rejected explicitly.
118+
119+
`ceiling` is the destination's own bound (#2827). It shipped as a flat
120+
`< 2**63` for every caller while seven of the eight `agent_sync_state`
121+
columns it feeds are int4 — so an agent writing `2**40` into `pack_count`
122+
made every upsert for it raise on PostgreSQL, exactly the #2800 class one
123+
column over. The default is the int4 column bound because that is what
124+
almost every consumer is; a caller with a wider destination says so.
108125
"""
109126
if isinstance(value, bool):
110127
return None
111-
if isinstance(value, int) and 0 <= value < 2**63:
128+
if isinstance(value, int) and 0 <= value <= ceiling:
112129
return value
113130
return None
114131

115132

133+
def _coerce_counter(payload: dict, *keys: str) -> int:
134+
"""An agent-supplied ahead/behind counter, coerced, defaulting to 0 (#2827).
135+
136+
The first key present wins (`ahead_main`, else the legacy `ahead`). These
137+
four used to be passed UNCOERCED into int4 columns — a stranger to the
138+
`_coerce_nonneg_int` guard two lines above them.
139+
"""
140+
for key in keys:
141+
if key in payload and payload[key] is not None:
142+
coerced = _coerce_nonneg_int(payload[key])
143+
return coerced if coerced is not None else 0
144+
return 0
145+
146+
116147
# #2742: an explicit UTC offset, which `startup.sh` always writes (`...Z`).
117148
_ISO_OFFSET_RE = re.compile(r"[+-]\d{2}:?\d{2}$")
118149

@@ -191,8 +222,9 @@ def _coerce_lock_stuck(value):
191222
"""
192223
if not isinstance(value, dict):
193224
return None
225+
# Log-only ints, never a column: the wide ceiling is honest here.
194226
coerced = {
195-
key: _coerce_nonneg_int(value.get(key))
227+
key: _coerce_nonneg_int(value.get(key), ceiling=INT8_MAX)
196228
for key in ("age_seconds", "stable_for_seconds", "sightings", "size_bytes")
197229
}
198230
if all(v is None for v in coerced.values()):
@@ -397,7 +429,8 @@ async def _sync_agent(self, config) -> None:
397429
) or 0
398430

399431
# #1595: agent-supplied ints coerced at the boundary (see helper).
400-
git_dir_bytes = _coerce_nonneg_int(sync_state.get("git_dir_bytes"))
432+
# #2827: each at ITS column's ceiling — git_dir_bytes is the one BIGINT.
433+
git_dir_bytes = _coerce_nonneg_int(sync_state.get("git_dir_bytes"), ceiling=INT8_MAX)
401434
pack_count = _coerce_nonneg_int(sync_state.get("pack_count"))
402435
loose_objects = _coerce_nonneg_int(sync_state.get("loose_objects"))
403436
maintenance_failures = _coerce_nonneg_int(
@@ -411,10 +444,11 @@ async def _sync_agent(self, config) -> None:
411444
last_error_summary=last_error_summary,
412445
last_remote_sha_main=payload.get("last_remote_sha_main"),
413446
last_remote_sha_working=local_head_sha,
414-
ahead_main=payload.get("ahead_main") or payload.get("ahead") or 0,
415-
behind_main=payload.get("behind_main") or payload.get("behind") or 0,
416-
ahead_working=payload.get("ahead_working") or 0,
417-
behind_working=payload.get("behind_working") or 0,
447+
# #2827: coerced like their siblings — these four went in raw.
448+
ahead_main=_coerce_counter(payload, "ahead_main", "ahead"),
449+
behind_main=_coerce_counter(payload, "behind_main", "behind"),
450+
ahead_working=_coerce_counter(payload, "ahead_working"),
451+
behind_working=_coerce_counter(payload, "behind_working"),
418452
git_dir_bytes=git_dir_bytes, # #1596 bloat observability
419453
pack_count=pack_count, # #1595
420454
loose_objects=loose_objects, # #1595

‎tests/unit/test_1595_sync_health_signals.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,12 @@ def test_values(self, tmp_db):
153153
assert _coerce_nonneg_int(True) is None # bool is an int subclass
154154
assert _coerce_nonneg_int(-1) is None
155155
assert _coerce_nonneg_int(2**63) is None
156+
# #2827: the default ceiling is the int4 column's; the widened column
157+
# opts into int8 explicitly.
158+
assert _coerce_nonneg_int(2**31) is None
159+
assert _coerce_nonneg_int(2**31 - 1) == 2**31 - 1
160+
assert _coerce_nonneg_int(2**31, ceiling=2**63 - 1) == 2**31
161+
assert _coerce_nonneg_int(2**63 - 1, ceiling=2**63 - 1) == 2**63 - 1
156162
assert _coerce_nonneg_int("1000000") is None
157163
assert _coerce_nonneg_int({"nested": 1}) is None
158164
assert _coerce_nonneg_int(3.5) is None
@@ -172,6 +178,62 @@ def test_malformed_agent_values_stored_as_null(self, service, seed_agent, tmp_db
172178
assert row["loose_objects"] is None
173179
assert row["maintenance_failures"] == 0
174180

181+
def test_every_column_is_bounded_by_its_own_postgres_type(self, service, seed_agent, tmp_db):
182+
"""#2827: the boundary's ceiling matches the COLUMN's. Seven of the eight
183+
int columns are int4 on PostgreSQL; only `git_dir_bytes` was widened
184+
(#2800). A value the boundary admits but the column cannot hold makes
185+
the whole upsert raise `NumericValueOutOfRange` and the agent's sync
186+
health goes dark — so `2**40` in `pack_count` must be rejected HERE
187+
(stored as NULL / 0), while the same value in `git_dir_bytes` is fine.
188+
The four ahead/behind counters used to go in entirely uncoerced.
189+
"""
190+
from services.sync_health_service import INT4_MAX
191+
seed_agent("alpha")
192+
too_big = INT4_MAX + 1
193+
payload = _payload(
194+
git_dir_bytes=2**40, # BIGINT: admitted
195+
pack_count=too_big, # int4: rejected → NULL
196+
loose_objects=too_big, # int4: rejected → NULL
197+
maintenance_failures=too_big, # int4: rejected → 0 (the column default)
198+
)
199+
payload.update(ahead_main=too_big, behind_main=too_big,
200+
ahead_working=too_big, behind_working="lots")
201+
_sync_once(service, payload)
202+
from database import db
203+
row = db.get_sync_state("alpha")
204+
assert row["git_dir_bytes"] == 2**40
205+
assert row["pack_count"] is None and row["loose_objects"] is None
206+
assert row["maintenance_failures"] == 0
207+
assert (row["ahead_main"], row["behind_main"], row["ahead_working"], row["behind_working"]) == (0, 0, 0, 0)
208+
209+
def test_the_maximum_each_column_admits_is_stored(self, service, seed_agent, tmp_db):
210+
"""...and the ceiling is the bound, not a lower one: INT4_MAX itself lands."""
211+
from services.sync_health_service import INT4_MAX, INT8_MAX
212+
seed_agent("alpha")
213+
payload = _payload(git_dir_bytes=INT8_MAX, pack_count=INT4_MAX,
214+
loose_objects=INT4_MAX, maintenance_failures=INT4_MAX)
215+
payload.update(ahead_main=INT4_MAX, behind_main=INT4_MAX,
216+
ahead_working=INT4_MAX, behind_working=INT4_MAX)
217+
_sync_once(service, payload)
218+
from database import db
219+
row = db.get_sync_state("alpha")
220+
assert row["git_dir_bytes"] == INT8_MAX
221+
assert row["pack_count"] == row["loose_objects"] == row["maintenance_failures"] == INT4_MAX
222+
assert row["ahead_main"] == row["behind_main"] == row["ahead_working"] == row["behind_working"] == INT4_MAX
223+
224+
def test_the_legacy_ahead_key_is_coerced_too(self, service, seed_agent, tmp_db):
225+
"""`ahead`/`behind` are the pre-P6 names; `_coerce_counter` reads them
226+
second and bounds them the same way."""
227+
from services.sync_health_service import INT4_MAX
228+
seed_agent("alpha")
229+
payload = _payload()
230+
del payload["ahead_main"], payload["behind_main"]
231+
payload.update(ahead=7, behind=INT4_MAX + 1)
232+
_sync_once(service, payload)
233+
from database import db
234+
row = db.get_sync_state("alpha")
235+
assert (row["ahead_main"], row["behind_main"]) == (7, 0)
236+
175237

176238
# ---------------------------------------------------------------------------
177239
# Round-trip through the real ops + harness (guards db/tables.py columns)

‎tests/unit/test_1596_git_sync_observability.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,26 @@ def test_upsert_and_read_git_dir_bytes(self, db_backend):
4343
row = ops.get("a1")
4444
assert row["git_dir_bytes"] == 47244640256
4545

46+
def test_every_int_column_round_trips_its_own_maximum(self, db_backend):
47+
"""#2827 AC: the maximum the boundary admits for each of the eight int
48+
columns persists on BOTH backends. On PostgreSQL this is the proof
49+
that boundary and column agree — INT4_MAX in an int4 column, INT8_MAX
50+
in the one BIGINT — where a mismatch is `NumericValueOutOfRange`."""
51+
from services.sync_health_service import INT4_MAX, INT8_MAX
52+
ops = _ops()
53+
ops.upsert(
54+
"a2", last_sync_status="success",
55+
git_dir_bytes=INT8_MAX,
56+
pack_count=INT4_MAX, loose_objects=INT4_MAX, maintenance_failures=INT4_MAX,
57+
ahead_main=INT4_MAX, behind_main=INT4_MAX,
58+
ahead_working=INT4_MAX, behind_working=INT4_MAX,
59+
)
60+
row = ops.get("a2")
61+
assert row["git_dir_bytes"] == INT8_MAX
62+
for col in ("pack_count", "loose_objects", "maintenance_failures",
63+
"ahead_main", "behind_main", "ahead_working", "behind_working"):
64+
assert row[col] == INT4_MAX, col
65+
4666
def test_git_dir_bytes_is_64_bit_on_postgres(self, db_backend):
4767
"""#2800: the declared type, not just one value that happened to fit.
4868

0 commit comments

Comments
 (0)