Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(ultrawiki): embed every passage of an item, not its first 8 000 characters

Ruben Lütke98624874ae3e
diff --git a/jarvis/ultrawiki/chunking.py b/jarvis/ultrawiki/chunking.py
new file mode 100644
index 0000000000..fc474110c9
--- /dev/null
+++ b/jarvis/ultrawiki/chunking.py
@@ -0,0 +1,154 @@
+"""Split a document into overlapping passages for embedding.
+
+Why this module is the precondition for everything else (audit, 2026-07-26):
+the embed stage cut every item at 8 000 characters and produced exactly ONE
+vector for it. A 200 KB source file, a 4 000-message channel export or a long
+design thread reached the vector space as its opening paragraph; the rest sat
+in SQL, findable by exact keyword and invisible to meaning. Pulling more data
+would have changed nothing a user could retrieve — the cap, not the connectors,
+decided what was searchable.
+
+Two things make a passage useful, and they pull against each other:
+
+* **Small enough to be specific.** One vector averages everything inside it.
+ A whole file collapses into a blur that matches every question weakly and
+ none of them well.
+* **Large enough to be self-contained.** A passage cut mid-sentence, or one
+ that drops the heading it belongs under, retrieves as a fragment nobody can
+ act on.
+
+So the splitter prefers real boundaries — paragraph breaks, then line breaks,
+then sentence ends — and only falls back to a hard cut when a single run of
+text has none. Consecutive passages overlap, because the sentence that answers
+a question is regularly the one straddling a boundary.
+
+Code gets one extra rule: a fenced block is never cut open. Half a function
+body is worse than useless — it retrieves as plausible code that does not do
+what it appears to.
+
+Pure text in, pure text out: no I/O, no provider knowledge, no config. The
+embedding backends keep their own token ceilings; this module only bounds
+characters, which is the thing a splitter can actually reason about.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+__all__ = [
+ "Chunk",
+ "DEFAULT_CHUNK_CHARS",
+ "DEFAULT_OVERLAP_CHARS",
+ "chunk_text",
+]
+
+#: Target passage size. ~2 000 characters is roughly 500 tokens: specific
+#: enough that one vector means one thing, long enough to carry its context.
+DEFAULT_CHUNK_CHARS = 2000
+
+#: How much of the previous passage each one repeats. The answer to a question
+#: sits on a boundary often enough that ~15 % overlap measurably beats none.
+DEFAULT_OVERLAP_CHARS = 300
+
+#: Below this a trailing remnant is merged into the previous passage instead of
+#: becoming a passage of its own — a 40-character chunk is noise in the index.
+_MIN_TAIL_CHARS = 200
+
+#: Boundaries to prefer, best first. Each is searched for in the tail of the
+#: window, so a cut lands on a real seam rather than mid-word.
+_BREAKS: tuple[str, ...] = ("\n\n", "\n", ". ", "! ", "? ", "; ", ", ", " ")
+
+#: How far back from the ideal cut a boundary may be found. Beyond this the
+#: passage would be so short that honouring the seam costs more than it buys.
+_BREAK_WINDOW = 400
+
+_FENCE = "```"
+
+
+@dataclass(frozen=True, slots=True)
+class Chunk:
+ """One passage, with its position in the original text."""
+
+ index: int
+ text: str
+ char_start: int
+ char_end: int
+
+
+def _fence_depth(text: str) -> int:
+ """How many code fences are left OPEN in ``text`` (0 or 1 in practice)."""
+ return text.count(_FENCE) % 2
+
+
+def _cut_at(text: str, start: int, limit: int) -> int:
+ """The best end offset for a passage starting at ``start``.
+
+ Walks the preferred boundaries in order and takes the latest one inside the
+ window. Returns the hard limit when the run of text offers no seam at all —
+ a minified bundle or a base64 blob legitimately has none.
+ """
+ if limit >= len(text):
+ return len(text)
+ window_start = max(start + 1, limit - _BREAK_WINDOW)
+ for token in _BREAKS:
+ found = text.rfind(token, window_start, limit)
+ if found > start:
+ return found + len(token)
+ return limit
+
+
+def chunk_text(
+ text: str,
+ *,
+ chunk_chars: int = DEFAULT_CHUNK_CHARS,
+ overlap_chars: int = DEFAULT_OVERLAP_CHARS,
+) -> list[Chunk]:
+ """Split ``text`` into overlapping passages, longest-boundary-first.
+
+ A short text yields exactly one passage covering all of it, so the common
+ case costs nothing and behaves as before. An empty text yields no passages
+ at all — there is nothing to embed, and a vector of whitespace is a false
+ hit waiting to happen.
+ """
+ body = text.strip()
+ if not body:
+ return []
+ chunk_chars = max(200, int(chunk_chars))
+ overlap_chars = max(0, min(int(overlap_chars), chunk_chars // 2))
+ if len(body) <= chunk_chars:
+ return [Chunk(index=0, text=body, char_start=0, char_end=len(body))]
+
+ chunks: list[Chunk] = []
+ start = 0
+ while start < len(body):
+ limit = min(start + chunk_chars, len(body))
+ end = _cut_at(body, start, limit)
+
+ # Never leave a code fence hanging open: extend to its closing fence
+ # so a passage always contains whole blocks. Bounded by a second
+ # window so one unterminated fence cannot swallow the entire document.
+ if _fence_depth(body[start:end]):
+ close = body.find(_FENCE, end)
+ if close != -1 and close - start <= chunk_chars * 3:
+ end = close + len(_FENCE)
+
+ # A remnant too small to stand alone joins this passage instead.
+ if len(body) - end < _MIN_TAIL_CHARS:
+ end = len(body)
+
+ piece = body[start:end].strip()
+ if piece:
+ chunks.append(
+ Chunk(
+ index=len(chunks),
+ text=piece,
+ char_start=start,
+ char_end=end,
+ )
+ )
+ if end >= len(body):
+ break
+ # Step back by the overlap, but always make forward progress: without
+ # the floor a pathological boundary could return the same cut forever.
+ start = max(end - overlap_chars, start + 1)
+ return chunks
diff --git a/jarvis/ultrawiki/migrations/0001_document_chunk_index.sql b/jarvis/ultrawiki/migrations/0001_document_chunk_index.sql
new file mode 100644
index 0000000000..7b79b505b8
--- /dev/null
+++ b/jarvis/ultrawiki/migrations/0001_document_chunk_index.sql
@@ -0,0 +1,23 @@
+-- Multi-chunk documents: one item may now hold MANY documents of the same
+-- type, one per passage of its text.
+--
+-- Why: the embed stage cut every item at 8 000 characters and wrote exactly
+-- one document per (item, doc_type). A source file, a long thread or a
+-- transcript therefore reached the vector space as its opening paragraph and
+-- nothing else — the rest sat in SQL, unsearchable by meaning. Storing several
+-- passages was not a tuning question but structurally impossible: the
+-- replace-on-(item_id, doc_type) rule meant chunk 2 deleted chunk 1.
+--
+-- `chunk_index` is the passage ordinal (0 for a whole-item document, so every
+-- existing row keeps its meaning under the DEFAULT). The unique index is what
+-- makes "replace this item's passages" an atomic, idempotent operation.
+
+ALTER TABLE uw_documents ADD COLUMN chunk_index INTEGER NOT NULL DEFAULT 0;
+
+-- Byte offsets into the item's body, so a hit can be located in the original
+-- text and a UI can show WHERE in a 200 KB file the answer came from.
+ALTER TABLE uw_documents ADD COLUMN char_start INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE uw_documents ADD COLUMN char_end INTEGER NOT NULL DEFAULT 0;
+
+CREATE UNIQUE INDEX IF NOT EXISTS idx_uw_documents_chunk
+ ON uw_documents(item_id, doc_type, chunk_index);
diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.py
index acb9f825b5..ee94c65296 100644
--- a/jarvis/ultrawiki/pipeline.py
+++ b/jarvis/ultrawiki/pipeline.py
@@ -68,10 +68,14 @@ KEYWORD_BATCH = 200
EMBED_BATCH = 32
DISTILL_BATCH = 4
-#: Character budget per embedded text, mirroring the distillation truncation
-#: in ``jarvis/ultrawiki/distill.py``. An oversized document is a provider
-#: 400/413 that would otherwise retry five times and dead-letter; an embedding
-#: of the first 8000 characters is a far better answer than none.
+#: Character budget per embedded TEXT — now per passage, not per item.
+#:
+#: It used to be a content cap: an item was cut here and everything past it
+#: never reached the vector space, so a 200 KB file was searchable by its
+#: opening paragraph alone. Items are split into passages first
+#: (``jarvis.ultrawiki.chunking``), and this only guards the provider limit
+#: for a single pathological passage. Raising it does not make more content
+#: searchable; the chunker already does that.
MAX_EMBED_CHARS = 8000
#: Loop pacing: quick follow-up while there is work, gentle poll when idle.
@@ -373,10 +377,47 @@ class PipelineWorker:
@classmethod
def _raw_text(cls, item: dict[str, Any]) -> str:
+ """The item's FULL text. No cap — the chunker bounds the passages."""
title = str(item.get("title") or "")
body = str(item.get("body_raw") or "")
text = f"{title}\n\n{body}".strip()
- return cls._cap_embed_input(text or str(item.get("external_id") or ""))
+ return text or str(item.get("external_id") or "")
+
+ @classmethod
+ def _item_chunks(cls, item: dict[str, Any]) -> list[Any]:
+ """The passages of one item, each carrying the item's title.
+
+ Every passage repeats the title: a vector for "line 4 200 of a source
+ file" is unretrievable without knowing which file it is from, and the
+ title is the cheapest possible carrier of that.
+ """
+ from jarvis.ultrawiki.chunking import Chunk, chunk_text # noqa: PLC0415
+
+ title = str(item.get("title") or "").strip()
+ body = str(item.get("body_raw") or "")
+ pieces = chunk_text(body)
+ if not pieces:
+ text = cls._cap_embed_input(cls._raw_text(item))
+ return [Chunk(index=0, text=text, char_start=0, char_end=len(text))]
+ if not title:
+ return [
+ Chunk(
+ index=c.index,
+ text=cls._cap_embed_input(c.text),
+ char_start=c.char_start,
+ char_end=c.char_end,
+ )
+ for c in pieces
+ ]
+ return [
+ Chunk(
+ index=c.index,
+ text=cls._cap_embed_input(f"{title}\n\n{c.text}"),
+ char_start=c.char_start,
+ char_end=c.char_end,
+ )
+ for c in pieces
+ ]
@staticmethod
def _claim_guard(item: dict[str, Any]) -> dict[str, Any]:
@@ -427,7 +468,11 @@ class PipelineWorker:
)
if not items:
return 0
- texts = [self._raw_text(item) for item in items]
+ # One embed input PER PASSAGE, flattened across the claimed items so
+ # the batch call stays a batch call. The offsets map each block of
+ # vectors back to the item it belongs to.
+ per_item = [self._item_chunks(item) for item in items]
+ texts = [chunk.text for chunks in per_item for chunk in chunks]
try:
vectors = await backend.embed(texts, model=model)
if len(vectors) != len(texts):
@@ -448,10 +493,13 @@ class PipelineWorker:
len(items),
exc,
)
- return await self._embed_individually(items, texts, backend, model)
- for item, text, vector in zip(items, texts, vectors, strict=True):
+ return await self._embed_individually(items, per_item, backend, model)
+ offset = 0
+ for item, chunks in zip(items, per_item, strict=True):
+ block = vectors[offset : offset + len(chunks)]
+ offset += len(chunks)
try:
- await self._store_embedded(item, text, vector, model)
+ await self._store_embedded(item, chunks, block, model)
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001 — one poisoned item blocks nothing
@@ -461,17 +509,27 @@ class PipelineWorker:
async def _embed_individually(
self,
items: list[dict[str, Any]],
- texts: list[str],
+ per_item: list[list[Any]],
backend: Any,
model: str,
) -> int:
- """Per-item fallback after a failed batch call (see ``_embed_pass``)."""
- for item, text in zip(items, texts, strict=True):
+ """Per-item fallback after a failed batch call (see ``_embed_pass``).
+
+ Each item is re-embedded with ITS OWN passages only, so a single
+ unembeddable one accrues the attempt while the rest of the batch
+ still lands.
+ """
+ for item, chunks in zip(items, per_item, strict=True):
try:
- vectors = await backend.embed([text], model=model)
- if not vectors:
- raise RuntimeError("backend returned no vector for the text")
- await self._store_embedded(item, text, vectors[0], model)
+ vectors = await backend.embed(
+ [chunk.text for chunk in chunks], model=model
+ )
+ if len(vectors) != len(chunks):
+ raise RuntimeError(
+ f"backend returned {len(vectors)} vectors for "
+ f"{len(chunks)} passages"
+ )
+ await self._store_embedded(item, chunks, vectors, model)
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001 — only this item is charged
@@ -479,24 +537,30 @@ class PipelineWorker:
return len(items)
async def _store_embedded(
- self, item: dict[str, Any], text: str, vector: Any, model: str
+ self, item: dict[str, Any], chunks: list[Any], vectors: Any, model: str
) -> None:
- """RAW document + vector + the guarded ``embedded`` transition.
+ """RAW passages + one vector each + the guarded ``embedded`` transition.
- When the compare-and-set finds the item already reset by a concurrent
- content change, the document just written is stale — harmless, because
- ``add_document`` REPLACES the ``(item_id, doc_type)`` row when the next
- pass re-embeds the new content.
+ Every passage of the item becomes its own document and its own vector,
+ which is what makes text beyond the opening paragraph retrievable at
+ all. The whole set is swapped atomically, so a reader never sees an
+ item holding half its passages.
+
+ When the compare-and-set below finds the item already reset by a
+ concurrent content change, the documents just written are stale —
+ harmless, because ``replace_documents`` swaps the whole set again when
+ the next pass re-embeds the new content.
"""
- doc_id = await self._store.add_document(
+ doc_ids = await self._store.replace_documents(
int(item["id"]),
DocType.RAW,
- text,
+ chunks,
content_hash=str(item.get("content_hash") or ""),
)
- await self._store.store_embedding(
- doc_id, model=model, dim=len(vector), vector=vector
- )
+ for doc_id, vector in zip(doc_ids, vectors, strict=True):
+ await self._store.store_embedding(
+ doc_id, model=model, dim=len(vector), vector=vector
+ )
committed = await self._store.mark_stage_done(
int(item["id"]), ItemState.EMBEDDED, **self._claim_guard(item)
)
diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.py
index 2266548ab5..56429c918e 100644
--- a/jarvis/ultrawiki/store.py
+++ b/jarvis/ultrawiki/store.py
@@ -841,11 +841,12 @@ class UltraStore:
rows = await self._fetchall(
conn,
"SELECT d.id, d.doc_type, d.text_norm, d.distill_json,"
- " d.distill_version, d.created_at,"
+ " d.distill_version, d.created_at, d.chunk_index,"
+ " d.char_start, d.char_end,"
" EXISTS (SELECT 1 FROM uw_embeddings e WHERE e.document_id = d.id)"
" AS has_vector"
" FROM uw_documents d WHERE d.item_id = ?"
- " ORDER BY d.id",
+ " ORDER BY d.doc_type, d.chunk_index, d.id",
(item_id,),
)
# `_fetchall` hands back aiosqlite.Row, which has no .get() — mapping
@@ -1208,6 +1209,73 @@ class UltraStore:
assert row is not None
return int(row[0])
+ async def replace_documents(
+ self,
+ item_id: int,
+ doc_type: DocType | str,
+ chunks: Sequence[Any],
+ *,
+ content_hash: str = "",
+ ) -> list[int]:
+ """Replace ALL documents of one ``(item_id, doc_type)`` with N passages.
+
+ :meth:`add_document` keeps exactly one row per ``(item, type)``, which
+ made a multi-vector item structurally impossible: passage 2 deleted
+ passage 1. That single rule is why an item reached the vector space as
+ its opening 8 000 characters and nothing else.
+
+ ``chunks`` are :class:`jarvis.ultrawiki.chunking.Chunk` objects (or any
+ object carrying ``index``/``text``/``char_start``/``char_end``). The
+ whole set is swapped inside ONE transaction, so a reader never observes
+ an item with half its passages, and a re-run is idempotent.
+
+ Returns the new document ids in passage order, so the caller can pair
+ each with its vector.
+ """
+ kind = DocType(doc_type).value
+ now = _iso_utc()
+ async with self._txn() as conn:
+ old_rows = await self._fetchall(
+ conn,
+ "SELECT id FROM uw_documents WHERE item_id = ? AND doc_type = ?",
+ (item_id, kind),
+ )
+ old_ids = [row["id"] for row in old_rows]
+ if old_ids and self._vec_state is not None and self._vec_state[0]:
+ for chunk in _chunks(old_ids):
+ await conn.execute(
+ f"DELETE FROM uw_vec WHERE rowid IN ({_placeholders(len(chunk))})", # noqa: S608 — placeholders only
+ chunk,
+ )
+ if old_ids:
+ await conn.execute(
+ "DELETE FROM uw_documents WHERE item_id = ? AND doc_type = ?",
+ (item_id, kind),
+ )
+ new_ids: list[int] = []
+ for chunk in chunks:
+ cur = await conn.execute(
+ "INSERT INTO uw_documents (item_id, doc_type, text_norm,"
+ " distill_json, distill_version, content_hash, created_at,"
+ " chunk_index, char_start, char_end)"
+ " VALUES (?, ?, ?, NULL, 0, ?, ?, ?, ?, ?) RETURNING id",
+ (
+ item_id,
+ kind,
+ str(getattr(chunk, "text", "")),
+ content_hash,
+ now,
+ int(getattr(chunk, "index", 0)),
+ int(getattr(chunk, "char_start", 0)),
+ int(getattr(chunk, "char_end", 0)),
+ ),
+ )
+ row = await cur.fetchone()
+ await cur.close()
+ assert row is not None
+ new_ids.append(int(row[0]))
+ return new_ids
+
async def _pinned_space(self) -> tuple[str | None, int | None]:
model = await self.get_meta(META_EMBED_MODEL)
dim_raw = await self.get_meta(META_EMBED_DIM)
@@ -2273,11 +2341,12 @@ class PostgresStore:
rows = await self._fetchall(
conn,
"SELECT d.id, d.doc_type, d.text_norm, d.distill_json,"
- " d.distill_version, d.created_at,"
+ " d.distill_version, d.created_at, d.chunk_index,"
+ " d.char_start, d.char_end,"
" EXISTS (SELECT 1 FROM uw_embeddings e WHERE e.document_id = d.id)"
" AS has_vector"
" FROM uw_documents d WHERE d.item_id = %s"
- " ORDER BY d.id",
+ " ORDER BY d.doc_type, d.chunk_index, d.id",
(item_id,),
)
return [
@@ -2571,6 +2640,46 @@ class PostgresStore:
assert row is not None
return int(row["id"])
+ async def replace_documents(
+ self,
+ item_id: int,
+ doc_type: DocType | str,
+ chunks: Sequence[Any],
+ *,
+ content_hash: str = "",
+ ) -> list[int]:
+ """Postgres twin of :meth:`UltraStore.replace_documents`."""
+ kind = DocType(doc_type).value
+ now = _iso_utc()
+ async with self._txn() as conn:
+ await conn.execute(
+ "DELETE FROM uw_documents WHERE item_id = %s AND doc_type = %s",
+ (item_id, kind),
+ )
+ new_ids: list[int] = []
+ for chunk in chunks:
+ cur = await conn.execute(
+ "INSERT INTO uw_documents (item_id, doc_type, text_norm,"
+ " distill_json, distill_version, content_hash, created_at,"
+ " chunk_index, char_start, char_end)"
+ " VALUES (%s, %s, %s, NULL, 0, %s, %s, %s, %s, %s)"
+ " RETURNING id",
+ (
+ item_id,
+ kind,
+ str(getattr(chunk, "text", "")),
+ content_hash,
+ now,
+ int(getattr(chunk, "index", 0)),
+ int(getattr(chunk, "char_start", 0)),
+ int(getattr(chunk, "char_end", 0)),
+ ),
+ )
+ row = await cur.fetchone()
+ assert row is not None
+ new_ids.append(int(row[0]))
+ return new_ids
+
async def _pinned_space(self) -> tuple[str | None, int | None]:
model = await self.get_meta(META_EMBED_MODEL)
dim_raw = await self.get_meta(META_EMBED_DIM)
diff --git a/tests/unit/ultrawiki/test_chunking.py b/tests/unit/ultrawiki/test_chunking.py
new file mode 100644
index 0000000000..71b5a4435b
--- /dev/null
+++ b/tests/unit/ultrawiki/test_chunking.py
@@ -0,0 +1,126 @@
+"""The passage splitter — the precondition for full-depth ingestion.
+
+Until this existed the embed stage cut every item at 8 000 characters and gave
+it one vector, so a 200 KB file reached the vector space as its opening
+paragraph. These tests pin the properties that make a passage retrievable
+rather than merely present: full coverage, real boundaries, overlap across
+seams, and code blocks that survive intact.
+"""
+
+from __future__ import annotations
+
+from jarvis.ultrawiki.chunking import (
+ DEFAULT_CHUNK_CHARS,
+ chunk_text,
+)
+
+
+def test_a_short_text_is_one_passage_covering_all_of_it():
+ chunks = chunk_text("A single short note.")
+ assert len(chunks) == 1
+ assert chunks[0].text == "A single short note."
+ assert chunks[0].index == 0
+ assert (chunks[0].char_start, chunks[0].char_end) == (0, 20)
+
+
+def test_empty_text_yields_nothing_rather_than_a_blank_vector():
+ """A vector built from whitespace is a false hit waiting to happen."""
+ assert chunk_text("") == []
+ assert chunk_text(" \n\t ") == []
+
+
+def test_every_character_of_a_long_text_lands_in_some_passage():
+ """The whole point: nothing may be silently dropped.
+
+ Reconstructing the text from the passages (accounting for the deliberate
+ overlap) must lose no sentence — that is the property the 8 000-char cap
+ violated for every large item.
+ """
+ paragraphs = [f"Paragraph {i} about topic number {i}." * 4 for i in range(120)]
+ body = "\n\n".join(paragraphs)
+ chunks = chunk_text(body)
+
+ assert len(chunks) > 1
+ joined = "".join(c.text for c in chunks)
+ for i in (0, 37, 60, 119):
+ assert f"Paragraph {i} about topic number {i}." in joined
+ # Offsets must tile the text without leaving a gap.
+ assert chunks[0].char_start == 0
+ assert chunks[-1].char_end == len(body.strip())
+ for previous, nxt in zip(chunks, chunks[1:], strict=False):
+ assert nxt.char_start <= previous.char_end, "a gap would drop text"
+
+
+def test_passages_overlap_so_a_boundary_sentence_is_not_lost():
+ """The sentence that answers a question is regularly on a seam."""
+ body = "\n\n".join(f"Block {i} " + "filler " * 40 for i in range(30))
+ chunks = chunk_text(body)
+ assert len(chunks) > 2
+ overlaps = [
+ previous.char_end - nxt.char_start
+ for previous, nxt in zip(chunks, chunks[1:], strict=False)
+ ]
+ assert all(o > 0 for o in overlaps), overlaps
+
+
+def test_cuts_prefer_a_paragraph_break_over_mid_sentence():
+ body = "\n\n".join("Sentence about widgets. " * 12 for _ in range(20))
+ chunks = chunk_text(body)
+ # A passage that ends mid-word is the failure this avoids.
+ for chunk in chunks[:-1]:
+ assert not chunk.text.endswith("Sen")
+ assert chunk.text == chunk.text.strip()
+
+
+def test_text_with_no_boundaries_at_all_is_still_split():
+ """A minified bundle or a base64 blob legitimately has no seam.
+
+ It must still be chunked — falling back to a hard cut is correct; refusing
+ to split would put the whole blob back into one vector.
+ """
+ body = "x" * (DEFAULT_CHUNK_CHARS * 4)
+ chunks = chunk_text(body)
+ assert len(chunks) >= 3
+ assert all(c.text for c in chunks)
+
+
+def test_a_code_fence_is_never_left_open_in_a_passage():
+ """Half a function retrieves as plausible code that does not do what it says."""
+ code = "```python\n" + "\n".join(f" line_{i}()" for i in range(150)) + "\n```"
+ body = "Intro paragraph.\n\n" + code + "\n\nClosing paragraph."
+ chunks = chunk_text(body)
+ for chunk in chunks:
+ assert chunk.text.count("```") % 2 == 0, chunk.text[:120]
+
+
+def test_a_tiny_remnant_is_merged_rather_than_indexed_alone():
+ """A 40-character passage is noise in the index."""
+ body = ("word " * 500).strip() + "\n\nend."
+ chunks = chunk_text(body)
+ assert all(len(c.text) > 50 for c in chunks)
+
+
+def test_indices_are_sequential_and_start_at_zero():
+ body = "\n\n".join(f"Para {i}. " + "text " * 60 for i in range(25))
+ chunks = chunk_text(body)
+ assert [c.index for c in chunks] == list(range(len(chunks)))
+
+
+def test_the_splitter_always_makes_forward_progress():
+ """A pathological boundary must not loop forever.
+
+ Guarded explicitly because the overlap step-back is what could otherwise
+ return the same cut indefinitely and hang the pipeline on one item.
+ """
+ body = ("a" + "\n") * 5000
+ chunks = chunk_text(body, chunk_chars=200, overlap_chars=100)
+ assert len(chunks) > 5
+ assert chunks[-1].char_end == len(body.strip())
+
+
+def test_overlap_can_never_exceed_half_a_passage():
+ """Otherwise the walk stalls: each step would re-read most of the last."""
+ body = "word " * 4000
+ chunks = chunk_text(body, chunk_chars=500, overlap_chars=100_000)
+ assert len(chunks) > 3
+ assert chunks[-1].char_end == len(body.strip())
diff --git a/tests/unit/ultrawiki/test_pipeline.py b/tests/unit/ultrawiki/test_pipeline.py
index 54a3e4de9d..d8ded21961 100644
--- a/tests/unit/ultrawiki/test_pipeline.py
+++ b/tests/unit/ultrawiki/test_pipeline.py
@@ -358,10 +358,19 @@ async def test_batch_embed_failure_retries_members_individually(store):
assert len(backend.embed_calls) == 1 + count
-async def test_embed_input_is_capped_to_the_provider_budget(store):
- await store.upsert_items(
- "src1", [make_item(1, body="x" * (MAX_EMBED_CHARS * 3))]
+async def test_a_long_item_is_embedded_as_many_passages_not_truncated(store):
+ """The change that makes full-depth ingestion mean anything.
+
+ A long item used to be cut at MAX_EMBED_CHARS and given ONE vector, so
+ everything past the opening paragraph was stored but unsearchable by
+ meaning. It now becomes many passages, each its own document and vector,
+ together covering the whole body — which is the only reason pulling more
+ data changes what a user can retrieve.
+ """
+ body = "\n\n".join(
+ f"Paragraph {i} discussing subject {i}. " * 6 for i in range(200)
)
+ await store.upsert_items("src1", [make_item(1, body=body)])
backend = FakeEmbeddingBackend()
worker = PipelineWorker(
store,
@@ -374,11 +383,66 @@ async def test_embed_input_is_capped_to_the_provider_budget(store):
await worker._keyword_pass() # noqa: SLF001
await worker._embed_pass() # noqa: SLF001
- assert backend.embed_calls
- assert len(backend.embed_calls[0][0]) == MAX_EMBED_CHARS
+ # embed_calls[0] IS the list of texts sent in that batch call.
+ sent = backend.embed_calls[0]
+ assert len(sent) > 5, "a long body must produce many passages"
+ # Each passage stays inside the provider budget…
+ assert all(len(text) <= MAX_EMBED_CHARS for text in sent)
+ # …and text far past the old 8 000-char cut is now genuinely embedded.
+ assert any("Paragraph 199" in text for text in sent)
+ # One document AND one vector per passage, not one per item.
+ docs = await store.item_documents(1)
+ assert len(docs) == len(sent)
+ assert all(doc["has_vector"] for doc in docs)
+ assert [doc["chunk_index"] for doc in docs] == list(range(len(docs)))
assert (await store.counts()).embedded == 1
+async def test_every_passage_carries_the_item_title(store):
+ """A vector for "line 4 200 of a file" is unretrievable without its name."""
+ body = "\n\n".join(f"Section {i}. " + "detail " * 80 for i in range(40))
+ await store.upsert_items("src1", [make_item(1, title="Ledger notes", body=body)])
+ backend = FakeEmbeddingBackend()
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: backend,
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+
+ await worker._keyword_pass() # noqa: SLF001
+ await worker._embed_pass() # noqa: SLF001
+
+ # embed_calls[0] IS the list of texts sent in that batch call.
+ sent = backend.embed_calls[0]
+ assert len(sent) > 1
+ assert all(text.startswith("Ledger notes") for text in sent)
+
+
+async def test_re_embedding_replaces_the_passages_instead_of_adding_more(store):
+ """Otherwise a second pass doubles every item's vectors."""
+ body = "\n\n".join(f"Line {i} " + "word " * 60 for i in range(30))
+ await store.upsert_items("src1", [make_item(1, body=body)])
+ backend = FakeEmbeddingBackend()
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: backend,
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+ await worker._keyword_pass() # noqa: SLF001
+ await worker._embed_pass() # noqa: SLF001
+ first = len(await store.item_documents(1))
+
+ await store.reset_vectors()
+ await worker._keyword_pass() # noqa: SLF001
+ await worker._embed_pass() # noqa: SLF001
+
+ assert len(await store.item_documents(1)) == first
+
+
# ---------------------------------------------------------------------------
# The distillation gate — a keyless install pauses instead of dead-lettering
# ---------------------------------------------------------------------------