Skip to content
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ internal versions are summarized under 0.3.33.
- macOS builds and queries pin OpenMP and MKL to one thread before loading FAISS and torch, including when the shell requests more. (#53)
- Lexical retrieval skips common words capitalized for emphasis, including ROLE, DOSE and LOW. (#39)
- Reappearing papers retain one current metadata record, set of passages and FAISS vector across writer builds, updates and restarts. (#7)
- A later archive linking a PMID and PMCID consolidates the paper records and their file history. Conflicting identifiers or DOIs are reported for review. (#42)

## [0.4.0] - 2026-12-03

Expand Down
8 changes: 6 additions & 2 deletions src/litkit/build/backfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
report_faiss_index,
)
from litkit.index.ids import copy_hnsw_without_ids
from litkit.segments.ingest import mark_duplicate_paper_vectors, remove_obsolete_chunks
from litkit.segments.ingest import mark_duplicate_paper_vectors, remove_obsolete_vectors
from litkit.db import mark_in_index, flush_pending_marks
from litkit.db.schema import get_stage1_mode, paper_embedding_input
from litkit.progress import eprint
Expand Down Expand Up @@ -69,7 +69,11 @@ def backfill_unindexed_vectors(
"""
cur = conn.cursor()
paper_rows = f"SELECT p.id, {paper_embedding_input(conn)} FROM papers p"
remove_obsolete_chunks(conn, chunk_index, chunk_index_path, faiss_lock_path, db_lock_path, FileLock)
if paper_index is not None and paper_index_path is not None:
remove_obsolete_vectors(conn, paper_index, paper_index_path, faiss_lock_path, db_lock_path,
FileLock, "obsolete_paper_vectors")
remove_obsolete_vectors(conn, chunk_index, chunk_index_path, faiss_lock_path, db_lock_path,
FileLock, "obsolete_chunk_vectors")
targets = []
if paper_embedder is not None and paper_index is not None and paper_index_path is not None:
targets.append(("papers", paper_rows, paper_index, paper_index_path, paper_embedder, paper_bs))
Expand Down
42 changes: 38 additions & 4 deletions src/litkit/build/ingest_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
from litkit.build.publication import BatchPublication
from litkit.db.connection import batch_transaction, commit_transaction
from litkit.db.handoff import completed_checkpoint, merged_checkpoints, readable_database
from litkit.db.queries import available_citation_ids
from litkit.db.queries import available_citation_ids, consolidate_owners, linked_owners, record_citation_link
from litkit.db.publication import read_publication
from litkit.db.schema import ensure_in_index_columns, ensure_paper_embedding_column
from litkit.db.sharding import producer_shard_lock
Expand Down Expand Up @@ -287,6 +287,7 @@ def process_tar_files(

replaced_papers: set[int] = set()
replaced_chunks: set[int] = set()
retired_papers: set[int] = set()
revised_shard_papers: set[int] = set()

def flush_batch(tar: str, members: int) -> None:
Expand All @@ -301,6 +302,10 @@ def flush_batch(tar: str, members: int) -> None:
pids, texts, doc_ids = dedupe_papers_with_doc_ids(
paper_ids_buf, paper_texts_buf, paper_doc_ids_buf, keep_last=True
)
if retired_papers:
survivors = [(i, t, d) for i, t, d in zip(pids, texts, doc_ids, strict=True)
if i not in retired_papers]
pids, texts, doc_ids = ([row[k] for row in survivors] for k in range(3))
cids, passages, parents, ords = dedupe_chunks_with_doc_ids(
chunk_ids_buf, chunk_texts_buf, chunk_paper_doc_ids_buf, chunk_ords_buf
)
Expand Down Expand Up @@ -415,6 +420,7 @@ def stage_indexes(paper_dir, chunk_dir):
chunk_ords_buf,
):
buf.clear()
retired_papers.clear()
replaced_papers.clear()
replaced_chunks.clear()
revised_shard_papers.clear()
Expand Down Expand Up @@ -570,6 +576,12 @@ def _render(force: bool = False):

# Content-addressed doc_id: use DB's canonical doc_id when reusing
# an existing paper row.
supplied_link = bool(pmid and pmcid)
local_owners, new_link = linked_owners(cur, pmid, pmcid, meta.get("doi"), merged=merged)
retired = None
if len(local_owners) == 2:
retired = consolidate_owners(cur, local_owners,
queue_vectors=not (faiss_writer or embed_producer))
existing_row = _find_paper(cur, pmcid, pmid, f)
canonical = None
if existing_row is None and merged is not None:
Expand Down Expand Up @@ -603,7 +615,7 @@ def _render(force: bool = False):
else:
canon_doc_id = canonical[0] if canonical and canonical[0] else f
shard_revision = embed_producer and (existing_row is not None or canonical is not None)
if shard_revision:
if shard_revision and not supplied_link:
pmid, pmcid = available_citation_ids(canon_doc_id, pmid, pmcid, cur, merged)
if not existing_row:
cur.execute(
Expand Down Expand Up @@ -638,7 +650,7 @@ def _render(force: bool = False):
(pid,),
).fetchone()
previous_text = prior[0] if prior else None
reuse_embedding = previous_text == ta_ab
reuse_embedding = previous_text == ta_ab and retired is None
old_ids = [row[0] for row in cur.execute(
"SELECT id FROM chunks WHERE paper_id=?", (pid,)
)]
Expand All @@ -655,6 +667,18 @@ def _render(force: bool = False):
cur.execute("CREATE TABLE IF NOT EXISTS obsolete_chunk_vectors (id INTEGER PRIMARY KEY)")
cur.executemany("INSERT OR IGNORE INTO obsolete_chunk_vectors VALUES (?)", ((i,) for i in old_ids))

if new_link:
record_citation_link(cur, pid)
elif merged_has_links and (pmid or pmcid):
# This producer has seen the published link. Its new archive
# can revise the linked paper with either identifier alone.
if merged.execute(
"SELECT 1 FROM papers p JOIN paper_citation_links l ON l.paper_id=p.id "
"WHERE (p.pmid=? AND p.pmid<>'') OR (p.pmcid=? AND p.pmcid<>'')",
(pmid, pmcid),
).fetchone():
record_citation_link(cur, pid)

db_register_file(cur, str(f), pid, st)
# Another shard may have installed a different version
# since this retained shard last embedded the paper.
Expand All @@ -663,7 +687,7 @@ def _render(force: bool = False):
paper_texts_buf.append(ta_ab)
paper_doc_ids_buf.append(canon_doc_id)
if existing_row or shard_revision:
if not shard_revision:
if not shard_revision and not supplied_link:
pmid, pmcid = available_citation_ids(canon_doc_id, pmid, pmcid, cur, merged)
cur.execute(
"UPDATE papers SET title=?, abstract=?, source_path=?, embedding_text=?, "
Expand Down Expand Up @@ -716,6 +740,12 @@ def _render(force: bool = False):
# ---------- END INGEST BODY ----------

conn.execute("RELEASE SAVEPOINT member_sp")
if retired:
loser, obsolete = retired
retired_papers.add(loser)
replaced_papers.add(loser)
replaced_chunks.update(obsolete)
revised_shard_papers.discard(loser)
if existing_row and not reuse_embedding:
# A saved ID alone cannot distinguish two revisions after restart.
replaced_papers.add(pid)
Expand Down Expand Up @@ -786,6 +816,7 @@ def _render(force: bool = False):
)
with owner_lock, ExitStack() as readers:
merged = None
merged_has_links = False
ensure_in_index_columns(conn)
ensure_paper_embedding_column(conn)
paper_output_dir = (
Expand All @@ -810,6 +841,9 @@ def _render(force: bool = False):
has_files = main_db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='files'").fetchone()
if has_files and main_db.execute("SELECT 1 FROM files LIMIT 1").fetchone():
merged = main_db.cursor()
merged_has_links = bool(merged.execute(
"SELECT 1 FROM sqlite_master WHERE name='paper_citation_links'"
).fetchone())
producer_id = chunk_seg_writer.shard_id
publication.bind_producer_outputs(
merged_checkpoints(main_db, producer_id).get(producer_id), main_db
Expand Down
2 changes: 1 addition & 1 deletion src/litkit/build/publication.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def reset_publication(conn: sqlite3.Connection, sqlite_dir: Path, seg_dir: Path)

if read_publication(conn):
conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1")
for table in ("merged_paper_revisions", "obsolete_chunk_vectors"):
for table in ("merged_paper_revisions", "obsolete_chunk_vectors", "obsolete_paper_vectors", "paper_doc_aliases", "paper_citation_links"):
if conn.execute("SELECT 1 FROM sqlite_master WHERE name=?", (table,)).fetchone():
conn.execute(f"DELETE FROM {table}")
if conn.execute("SELECT 1 FROM sqlite_master WHERE name='merged_shard_checkpoints'").fetchone():
Expand Down
8 changes: 8 additions & 0 deletions src/litkit/db/normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
import unicodedata


_DOI_PREFIX_RE = re.compile(r"^(?:https?://(?:dx\.)?doi\.org/|doi:\s*)", re.IGNORECASE)


def normalize_doi(value: str) -> str:
"""Compare bare DOI identifiers with resolver URLs stored by older releases."""
return _DOI_PREFIX_RE.sub("", (value or "").strip()).strip().lower()


def fold_search_dashes(text: str) -> str:
"""Fold dash variants after NFKC and remove discretionary hyphens."""
for dash in "‐‒–—−":
Expand Down
85 changes: 84 additions & 1 deletion src/litkit/db/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import sqlite3
from typing import TYPE_CHECKING
from litkit.db.normalization import normalize_doi
from litkit.progress import eprint

if TYPE_CHECKING:
Expand Down Expand Up @@ -73,6 +74,85 @@ def register_file(
)


def linked_owners(reader, pmid, pmcid, doi=None, *, merged=None):
"""Verify both ends of a supplied link, including owners in the consumer DB.

Return matching local owners (PMCID first) and whether the pair adds a link.
A producer preserves the verified pair for the consumer even when one owner
is still in an unmerged shard.
"""
if not pmid or not pmcid:
return [], False
local = []
records = []
matches = []
for source in (reader, merged):
if source is None:
continue
rows = source.execute(
"SELECT id,doc_id,pmid,pmcid FROM papers WHERE (pmid=? AND pmid<>'') "
"OR (pmcid=? AND pmcid<>'')", (pmid, pmcid),
).fetchall()
if source is reader:
local = rows
records.extend(rows)
if rows:
matches.append((source, rows))

dois = {normalize_doi(doi)} if doi else set()
inconsistent_ids = any((r[2] and r[2] != pmid) or (r[3] and r[3] != pmcid) for r in records)
# A revision can correct a DOI already associated with this exact pair.
# Do not use inconsistent DOIs as evidence for a newly supplied link.
new_link = any(not r[2] or not r[3] for r in records)
if new_link:
for source, rows in matches:
if "doi" in {r[1] for r in source.execute("PRAGMA table_info(papers)")}:
ids = [row[0] for row in rows]
placeholders = ",".join("?" for _ in ids)
dois.update(normalize_doi(value) for value, in source.execute(
f"SELECT doi FROM papers WHERE id IN ({placeholders})", ids,
) if value)
if inconsistent_ids or (new_link and len(dois) > 1):
raise ValueError(f"Conflicting citation metadata for PMID {pmid}, PMCID {pmcid}. "
f"Review the existing paper records {records!r} and DOIs {sorted(dois)!r}.")
return sorted(local, key=lambda r: r[3] != pmcid), new_link


def record_citation_link(cur, pid):
"""Record a verified link so older one-identifier shards remain historical."""
cur.execute("CREATE TABLE IF NOT EXISTS paper_citation_links (paper_id INTEGER PRIMARY KEY)")
cur.execute("INSERT OR IGNORE INTO paper_citation_links VALUES (?)", (pid,))


def consolidate_owners(cur, owners, *, queue_vectors):
"""Move file history to the PMCID owner and retire the PMID-only revision."""
keep, drop = owners
winner, loser = keep[0], drop[0]
obsolete = [r[0] for r in cur.execute("SELECT id FROM chunks WHERE paper_id=?", (loser,))]
cur.execute("CREATE TABLE IF NOT EXISTS paper_doc_aliases (doc_id TEXT PRIMARY KEY, paper_id INTEGER NOT NULL)")
cur.execute("UPDATE paper_doc_aliases SET paper_id=? WHERE paper_id=?", (winner, loser))
if drop[1]:
cur.execute("INSERT OR REPLACE INTO paper_doc_aliases VALUES (?,?)", (drop[1], winner))
cur.execute("UPDATE files SET paper_id=? WHERE paper_id=?", (winner, loser))
if queue_vectors:
cur.execute("CREATE TABLE IF NOT EXISTS obsolete_paper_vectors (id INTEGER PRIMARY KEY)")
cur.execute("INSERT OR IGNORE INTO obsolete_paper_vectors VALUES (?)", (loser,))
cur.execute("CREATE TABLE IF NOT EXISTS obsolete_chunk_vectors (id INTEGER PRIMARY KEY)")
cur.executemany("INSERT OR IGNORE INTO obsolete_chunk_vectors VALUES (?)", ((i,) for i in obsolete))
for table in ("producer_revisions", "merged_paper_revisions", "paper_citation_links"):
if cur.execute("SELECT 1 FROM sqlite_master WHERE name=?", (table,)).fetchone():
cur.execute(f"DELETE FROM {table} WHERE paper_id=?", (loser,))
# Preserve citation metadata supplied by only one earlier archive. A newer
# verified revision can replace these values through the regular update path.
for column in ("doi", "year", "authors", "journal"):
cur.execute(f"UPDATE papers SET {column}=COALESCE(NULLIF({column},''), "
f"(SELECT {column} FROM papers WHERE id=?)) WHERE id=?", (loser, winner))
cur.execute("DELETE FROM chunks WHERE paper_id=?", (loser,))
cur.execute("DELETE FROM papers WHERE id=?", (loser,))
cur.execute("UPDATE papers SET pmid=? WHERE id=?", (drop[2], winner))
return loser, obsolete


def available_citation_ids(doc_id, pmid, pmcid, *readers):
"""Keep an established identifier with its owner when an archive links two records."""
def available(column, value):
Expand Down Expand Up @@ -114,7 +194,10 @@ def preload_paper_id_map(conn: sqlite3.Connection) -> dict[str, int]:
cur = conn.cursor()
# A producer's original doc_id may be an alternate archive path after two
# shards independently encounter the same PMID or PMCID. Canonical IDs win.
cur.execute("""
aliases = ""
if cur.execute("SELECT 1 FROM sqlite_master WHERE name='paper_doc_aliases'").fetchone():
aliases = "SELECT doc_id,paper_id FROM paper_doc_aliases UNION ALL "
cur.execute(aliases + """
SELECT f.path, f.paper_id FROM files f JOIN papers p ON p.id=f.paper_id WHERE f.path<>p.doc_id
UNION ALL SELECT doc_id, id FROM papers
""")
Expand Down
Loading
Loading