Skip to content

Commit ddebfd6

Browse files
zlareb1claude
andauthored
A code backfill that could not write part of the index exits non-zero and names what is missing (#1715)
* A code backfill that could not write part of the index exits non-zero and names what is missing The backfill buffers a round's rows and sends one INSERT per table when a later read or write of the round needs them written. An INSERT that failed there, such as one past the write timeout, dropped its rows and those of every table queued behind it, and raised in whichever file's ingest had started the write. That file counted as one error, inside the 1% of files a run of 100 or more may fail and still exit 0, or a stage inside the ingest logged the exception and no file counted at all. The rows dropped belong to any file of the round. The round counts the rows a failed write did not send, by table. The counts ride the batch counters, so a `--workers` process reports them, and the index phase exits 1 with the pass, the tables, the row counts and the command to run again on stderr. The watermark is written as it is for file errors, an edge pass with a failed write stays owed, and the cursor stays before the first batch with a failed write so that a run stopped after it resumes there. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: Lareb Zafar <lareb.zafar@clickhouse.com> * A backfill write that fails as a round ends is counted and reported with the rest The write that ends a round is sent by the round, in no file's ingest, so its failure left the batch as an exception: the command ended with a traceback, or the parent's "backfill worker N exited" under `--workers`, with no row report, no re-run line and no watermark, and the counts of earlier failed writes in the run were not printed. The last file's `code_files` row is always in that write. The batch sends it itself, prints the failure and keeps the round's count, so the run finishes and exits 1 with the report. An oversize file's record that could not be written is one file error again. That record is written on its own, not through the round's buffer, and what fails there can be a read. The count for the exit code is taken on its own line before the report is printed, and both passes' rows are read by pass before the edge pass's join the run's counters. A test drives `_Run.batch` and `_Run.edge_batch` with a store whose `code_edges` INSERT fails once, in a file's ingest and as a round ends. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: Lareb Zafar <lareb.zafar@clickhouse.com> * A failed backfill write stops the run at its batch, and the next run resumes there A write outage that lasts used to be walked through: the failed write as a round ended was caught, the batch went on, and with inserts failing and reads working the run ingested every remaining file and then the whole edge pass. Under --embed each of those files' new chunks is embedded before the buffered insert that then drops them, and the cursor did not move, so the re-run paid for them again. If ClickHouse was still unreachable at the end, the git_head write raised and the run ended in a traceback with no report. A batch a failed write left rows out of now stops the run the way a held batch does, in either pass: the batch ends with the round the write belongs to, `_Run.batch` and `_Run.edge_batch` return why, and the paths that stop a held run (no further batch in this process or handed to a worker, the cursor kept, no watermark, exit 1) apply. The report is printed, the edge pass stays owed, and the next run resumes at that batch or at the pass. With that, the rows are counted into the batch's counters as each round ends, however it ends, so a batch held after a failed write still reports them; the run's `loom.worker_status` row counts the rows left out as failures, so it no longer says `ok` beside exit 1; and a run that reaches its end has no `unwritten:<table>` counter, so the span attributes and the exit-code allowance are as on main. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: Lareb Zafar <lareb.zafar@clickhouse.com> --------- Signed-off-by: Lareb Zafar <lareb.zafar@clickhouse.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
1 parent f981b13 commit ddebfd6

8 files changed

Lines changed: 415 additions & 51 deletions

‎docs/operations/code-index-operations.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,22 @@ docker exec loom-workers loom code backfill-prs --namespace code-myrepo --org ac
283283
once the pass is done, so a resumed run, or a rerun after an interrupted pass, still
284284
runs it. `--dialect-folder-pass` lets SQL files of undecided dialect take the dialect
285285
their directory agrees on.
286+
- A failed insert of the rows the index phase indexed, for example one that ran past
287+
`LOOM_CH_TIMEOUT_WRITE_S`, stops the run. The round of files that write belongs to
288+
finishes, no later round or batch starts (under `--workers`, the batches already
289+
running beside it finish), no watermark is written, and the command exits 1. Its last
290+
lines on stderr name the pass, the tables and how many rows the failed writes left
291+
out, then the command to run again. The count is an upper bound, because a write the
292+
client gave up on can still have landed. The cursor stays before that batch and an
293+
edge pass stopped this way stays owed, so the re-run resumes there, keeps the rows
294+
already in the index and writes the rest. One failed write can drop rows of several
295+
files, so it is not a file error: with no row left out, a run of 100 files or more
296+
exits 0 with up to 1% of its files failing, a smaller run with none. The record of a
297+
file over `LOOM_CODE_INGEST_MAX_FILE_BYTES` is written on its own, and a failure there
298+
is that file's error. Any other failed write ends the command with the error itself
299+
and no such lines: the write that closes a round a held model call or a signal had
300+
already stopped, a cursor or watermark write, and the insert of
301+
`--dialect-folder-pass`.
286302
- `backfill-prs` loads merged-PR history from GitHub, resumable by cursor and bounded by
287303
GitHub's rate limit (`LOOM_CODE_PR_BACKFILL_MONTHS`, default 12). `backfill-reviews`
288304
adds inline review comments, `backfill-assignees` requested reviewers, and

‎server/cli/code_backfill.py‎

Lines changed: 121 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import logging
1111
import os
1212
import pathlib
13+
import shlex
1314
import sys
1415
import time
1516
from collections.abc import AsyncGenerator, Awaitable, Callable
@@ -80,6 +81,29 @@ def add_counters(total: dict[str, int], part: dict[str, int]) -> None:
8081
total[key] = total.get(key, 0) + n
8182

8283

84+
# Counter keys `unwritten:<table>`: rows a failed write left out of the index. They ride
85+
# a batch's counters, so a `--workers` process reports them as it reports its errors.
86+
UNWRITTEN = "unwritten:"
87+
88+
89+
def count_unwritten(counters: dict[str, int], by_table: dict[str, int]) -> None:
90+
add_counters(counters, {UNWRITTEN + table: n for table, n in by_table.items()})
91+
92+
93+
def unwritten(counters: dict[str, int]) -> dict[str, int]:
94+
"""table -> rows a pass's failed writes left out, from its counters."""
95+
return {
96+
key.removeprefix(UNWRITTEN): n
97+
for key, n in counters.items()
98+
if key.startswith(UNWRITTEN) and n
99+
}
100+
101+
102+
def write_failed(counters: dict[str, int]) -> str:
103+
"""Why a batch a failed write left rows out of stops its run, "" when none did."""
104+
return "a write failed" if unwritten(counters) else ""
105+
106+
83107
@dataclass
84108
class _Run:
85109
"""What the index phase's cursor batches and its edge pass run with: one in the CLI
@@ -188,8 +212,9 @@ async def one(self, reads: Any, path: str, source: bytes) -> None:
188212
counters["embed_reused"] = counters.get("embed_reused", 0) + stats.embed_reused
189213

190214
async def batch(self, paths: list[str]) -> str:
191-
"""One cursor batch of the index phase: "" once written, else why it was held."""
192-
return await _held_batch(
215+
"""One cursor batch of the index phase: "" once written, else why it stops the
216+
run: the org's switch held it, or a write of it failed."""
217+
held = await _held_batch(
193218
self.repo,
194219
self.org,
195220
self.ns,
@@ -199,10 +224,12 @@ async def batch(self, paths: list[str]) -> str:
199224
denylist=self.denylist,
200225
git_dir=self.cfg.git_dir,
201226
head=self.head,
227+
counters=self.counters,
202228
embedding_model=self.model_name,
203229
# Only an embedding run asks the reuse namespace for vectors.
204230
reuse_from=self.cfg.embed_reuse_from if self.embedder is not None else "",
205231
)
232+
return held or write_failed(self.counters)
206233

207234
async def edge_one(self, reads: Any, path: str, src: bytes) -> None:
208235
from server.code.app.index.ingest import ingest_file
@@ -228,8 +255,8 @@ async def edge_one(self, reads: Any, path: str, src: bytes) -> None:
228255
self.edges["files"] += 1
229256
self.edges["edges"] += stats.edges_new
230257

231-
async def edge_batch(self, paths: list[str]) -> None:
232-
"""One batch of the edge pass."""
258+
async def edge_batch(self, paths: list[str]) -> str:
259+
"""One batch of the edge pass: "" once written, else why it stops the run."""
233260
await _backfill_batch_rounds(
234261
self.repo,
235262
self.org,
@@ -240,9 +267,11 @@ async def edge_batch(self, paths: list[str]) -> None:
240267
denylist=self.denylist,
241268
git_dir=self.cfg.git_dir,
242269
head=self.head,
270+
counters=self.edges,
243271
embedding_model=self.model_name,
244272
edges_only=True,
245273
)
274+
return write_failed(self.edges)
246275

247276

248277
async def worker_run(args: argparse.Namespace, head: str) -> _Run:
@@ -274,8 +303,8 @@ def _workers_for(
274303
async def _index_batches(
275304
run: _Run, batches: list[tuple[int, list[str]]], workers: code_backfill_workers.Workers | None
276305
) -> AsyncGenerator[tuple[int, list[str], dict[str, int], str], None]:
277-
"""The index phase's cursor batches in order, each with its own counters and why the
278-
org's switch held it ("" once written): in this process, or across `workers`."""
306+
"""The index phase's cursor batches in order, each with its own counters and why it
307+
stops the run ("" once written): in this process, or across `workers`."""
279308
if workers is not None:
280309
async for done in workers.index_batches(batches):
281310
yield done
@@ -299,8 +328,9 @@ async def _index_phase(
299328
started: float,
300329
) -> str:
301330
"""Run the batches, moving the cursor past each one once every earlier one is
302-
written; why the org's switch held one, "" once all are written. A batch written
303-
beside the held one is counted and the cursor stays."""
331+
written; why one stopped the run (the org's switch held it, or a write of it
332+
failed), "" once all are written. A batch written beside that one is counted and
333+
the cursor stays, so the next run resumes there."""
304334
held = ""
305335
paths_file = bool(getattr(run.args, "paths_file", ""))
306336
async with contextlib.aclosing(_index_batches(run, batches, workers)) as done:
@@ -420,15 +450,23 @@ async def _backfill_run(args: argparse.Namespace, stack: contextlib.AsyncExitSta
420450
elif owed == "workers":
421451
print("--workers: batches were written side by side; the edge pass binds them")
422452
second = await _second_edge_pass(run, paths, workers)
423-
if held:
424-
# The batches written before the hold are compacted, republished and recorded.
425-
await _close_index(repo, counters, org, ns, model_name, started, head, mode)
426-
return 1
453+
# By pass, read before the edge pass's rows join the run's counters below.
454+
lost = {"index phase": unwritten(counters), "second edge pass": unwritten(second or {})}
427455
if second is not None:
428456
counters["edges_second_pass"] = second["edges"]
457+
# The run's counters, printed and recorded, hold both passes' errors and rows
458+
# left out; the lines on stderr split the rows by pass.
429459
counters["errors"] += second["errors"]
430-
if not paths_file and not second["errors"]:
431-
await repo.set_state(org, ns, owed_key, "")
460+
count_unwritten(counters, lost["second edge pass"])
461+
if held or lost["second edge pass"]:
462+
# A hold or a failed write stopped the run: no watermark, and the cursor and the
463+
# owed edge pass say where the next run starts. The batches written before the
464+
# stop are compacted, republished and recorded.
465+
await _close_index(repo, counters, org, ns, model_name, started, head, mode)
466+
_say_unwritten(head, lost)
467+
return 1
468+
if second is not None and not paths_file and not second["errors"]:
469+
await repo.set_state(org, ns, owed_key, "")
432470
if getattr(args, "dialect_folder_pass", False):
433471
folder = await _dialect_folder_pass(repo, org, ns, head)
434472
counters["dialect_inherited"] = folder["inherited"]
@@ -602,12 +640,15 @@ async def _second_edge_pass(
602640
print(f"second edge pass: {len(paths)} files against the finished name table")
603641
if workers is None:
604642
for _b, chunk in batches:
605-
await run.edge_batch(chunk)
643+
if await run.edge_batch(chunk):
644+
break
606645
else:
607646
for part in await workers.edge_batches(batches):
608647
add_counters(counters, part)
648+
why = write_failed(counters)
649+
ended = f"stopped: {why}" if why else "complete"
609650
print(
610-
f"second edge pass complete: files={counters['files']} edges=+{counters['edges']} "
651+
f"second edge pass {ended}: files={counters['files']} edges=+{counters['edges']} "
611652
f"errors={counters['errors']} in {time.monotonic() - started:.0f}s"
612653
)
613654
return counters
@@ -681,7 +722,8 @@ async def _close_index(
681722
started=started,
682723
done=counters["files"],
683724
rows_written=counters["chunks"] + counters["symbols"] + counters["edges"],
684-
errors=counters["errors"],
725+
# A row a failed write left out is a failure of the pass, as a file's error is.
726+
errors=counters["errors"] + sum(unwritten(counters).values()),
685727
counters=counters,
686728
phase="index",
687729
head=head[:12],
@@ -724,11 +766,13 @@ async def _held_batch(
724766
denylist: Any,
725767
git_dir: str,
726768
head: str,
769+
counters: dict[str, int],
727770
embedding_model: str,
728771
reuse_from: str,
729772
) -> str:
730773
"""One cursor batch as the org's model calls, so its switch applies to them;
731-
"" once written, else why the switch held it (the cursor stays)."""
774+
"" once written, else why the switch held it (the cursor stays). The rows its
775+
failed writes left out are added to `counters` either way."""
732776
try:
733777
with customer.for_org(org, namespace=ns):
734778
await _backfill_batch_rounds(
@@ -741,6 +785,7 @@ async def _held_batch(
741785
denylist=denylist,
742786
git_dir=git_dir,
743787
head=head,
788+
counters=counters,
744789
embedding_model=embedding_model,
745790
reuse_from=reuse_from,
746791
)
@@ -760,6 +805,7 @@ async def _backfill_batch_rounds(
760805
denylist: Any,
761806
git_dir: str,
762807
head: str,
808+
counters: dict[str, int],
763809
embedding_model: str = "",
764810
reuse_from: str = "",
765811
edges_only: bool = False,
@@ -775,7 +821,15 @@ async def _backfill_batch_rounds(
775821
With `embedding_model` the round also reads its chunk index, a refused path's
776822
rows and, from `reuse_from`, the vectors its new files copy, once each; the
777823
edge pass (`edges_only`) reads no chunk but a refused path's.
778-
Round size 0 keeps the per-file reads (the wrapper then only delegates)."""
824+
Round size 0 keeps the per-file reads (the wrapper then only delegates).
825+
826+
The rows a round's failed writes left out are added to `counters` as the round
827+
ends, however it ends, and the batch ends with that round: the run stops there
828+
and the next one resumes at this batch. A write is sent when a later read or write
829+
of the round needs the buffer written, so its failure raises in that file's
830+
ingest, where it is one file's error or a stage's logged failure; the rows it
831+
dropped belong to any file of the round. The write as a round ends is sent here,
832+
in no file's ingest: its failure is printed."""
779833
from server.code.app.index.pass_budget import git_text_source
780834
from server.code.app.index.round_reads import RoundReads, round_size, rounds
781835

@@ -784,16 +838,31 @@ async def _backfill_batch_rounds(
784838
for rnd in rounds(batch_paths, size):
785839
found = dict(await asyncio.gather(*(source(p) for p in rnd)))
786840
sources = {p: src for p, src in found.items() if src is not None}
787-
async with RoundReads(repo, org, ns) as reads:
788-
if size > 0:
789-
await reads.prefetch(
790-
sources,
791-
denylist,
792-
embedding_model=embedding_model,
793-
edges_only=edges_only,
794-
reuse_from=reuse_from,
841+
reads = RoundReads(repo, org, ns)
842+
try:
843+
async with reads:
844+
if size > 0:
845+
await reads.prefetch(
846+
sources,
847+
denylist,
848+
embedding_model=embedding_model,
849+
edges_only=edges_only,
850+
reuse_from=reuse_from,
851+
)
852+
await gather_or_cancel(
853+
*(one(reads, p, sources[p]) for p in rnd if p in sources)
795854
)
796-
await gather_or_cancel(*(one(reads, p, sources[p]) for p in rnd if p in sources))
855+
try:
856+
await reads.flush()
857+
except Exception as e: # noqa: BLE001 — counted below; the run reports it
858+
print(
859+
f" ! write as the round of {rnd[0]} ended: {type(e).__name__}: {e}",
860+
file=sys.stderr,
861+
)
862+
finally:
863+
count_unwritten(counters, reads.unwritten)
864+
if reads.unwritten:
865+
return
797866

798867

799868
async def _backfill_head(git_dir: str, cfg: Any, args: argparse.Namespace) -> str:
@@ -815,14 +884,37 @@ async def _backfill_head(git_dir: str, cfg: Any, args: argparse.Namespace) -> st
815884
return await gitrepo.head_sha(git_dir, cfg.git_branch)
816885

817886

887+
def _say_unwritten(head: str, lost: dict[str, dict[str, int]]) -> None:
888+
"""Say on stderr what the run's failed writes left out of the index, by pass and
889+
table, and the command that writes it; nothing when every write landed. The count
890+
is an upper bound: a write the client gave up on can still have landed."""
891+
rows = sum(n for by_table in lost.values() for n in by_table.values())
892+
if not rows:
893+
return
894+
passes = "; ".join(
895+
f"{name}: " + ", ".join(f"{table} {n}" for table, n in by_table.items())
896+
for name, by_table in lost.items()
897+
if by_table
898+
)
899+
print(
900+
f"backfill at {head[:12]}: failed writes left up to {rows} rows out of the index "
901+
f"({passes})\nre-run to write them (rows already in the index are kept): "
902+
+ shlex.join(["loom", *sys.argv[1:]]),
903+
file=sys.stderr,
904+
)
905+
906+
818907
def backfill_index_exit_code(files: int, errors: int) -> int:
819908
"""Per-file parse errors are skipped and reported inline, and the
820909
watermark advances regardless — so the exit code must describe the
821910
PHASE, not demand a perfect corpus. All-or-nothing here would abort a
822911
`set -e` runbook AFTER the phase completed, before embeddings,
823912
over one pathological generated file in 10K. Tolerate up
824913
to 1% file errors on runs large enough for a rate to mean something;
825-
small delta passes stay strict, where one error IS the signal."""
914+
small delta passes stay strict, where one error IS the signal.
915+
916+
A failed write is not a file's error: it drops rows of every file whose rows
917+
shared its buffer, so it stops the run before this allowance applies."""
826918
tolerated = files // 100 if files >= 100 else 0
827919
return 0 if errors <= tolerated else 1
828920

‎server/cli/code_backfill_workers.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747

4848
_SPAWN = multiprocessing.get_context("spawn") # a fresh interpreter: no copy of the parent's loop
4949

50-
# (first index, paths, counters, why the org's switch held it: "" once written)
50+
# (first index, paths, counters, why it stops the run: "" once written)
5151
Done = tuple[int, list[str], dict[str, int], str]
5252

5353

@@ -252,8 +252,8 @@ async def _batch(kind: str, paths: list[str]) -> tuple[dict[str, int], str]:
252252
held = await run.batch(paths)
253253
return run.counters, held
254254
run.edges = edge_counters()
255-
await run.edge_batch(paths)
256-
return run.edges, ""
255+
held = await run.edge_batch(paths)
256+
return run.edges, held
257257

258258
conn = assignment.conn
259259
_note(worker=assignment.number)

‎server/code/app/index/round_reads.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,10 @@ def __init__(self, repo: Any, org: str, ns: str, *, tier: str = TIER) -> None:
137137
self._pending_paths: set[str] = set()
138138
self._pending_rows = 0
139139
self.flushes = 0
140+
# table -> rows a failed flush did not write: the INSERT that raised and every
141+
# table queued behind it. The flush raises in whichever file's read or write
142+
# started it, so only this count says how much the round lost.
143+
self.unwritten: dict[str, int] = {}
140144
# A flush in progress still counts as buffered: its paths are not yet
141145
# durable, so a concurrent reader (the dependents' tasks) waits on the
142146
# lock rather than read around it.
@@ -209,18 +213,23 @@ async def __aexit__(self, *exc: object) -> None:
209213

210214
async def flush(self) -> None:
211215
"""Write the buffered rows, one INSERT per table in first-write order;
212-
returns once every earlier flush is durable too."""
216+
returns once every earlier flush is durable too. An INSERT that raises ends the
217+
flush: its rows and the tables behind it are dropped and counted in `unwritten`."""
213218
async with self._flush_lock:
214219
pending, self._pending = self._pending, {}
215220
self._inflight_paths, self._pending_paths = self._pending_paths, set()
216221
self._inflight_keys, self._pending_keys = self._pending_keys, _BufferedKeys()
217222
self._pending_rows = 0
223+
written = 0
218224
try:
219225
for table, rows in pending.items():
220226
await self._repo.insert_rows(table, rows)
227+
written += 1
221228
finally:
222229
self._inflight_paths = set()
223230
self._inflight_keys = _BufferedKeys()
231+
for table, rows in list(pending.items())[written:]:
232+
self.unwritten[table] = self.unwritten.get(table, 0) + len(rows)
224233
if pending:
225234
self.flushes += 1
226235

0 commit comments

Comments
 (0)