Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ internal versions are summarized under 0.3.33.
## [Unreleased]

### Added
- Paper and passage results report publication type and retraction status. Search with repeatable `--type` and `--exclude-type` filters. (#58)
- `litkit build-fts` indexes passage text for exact search. The optional index stays current through updates, rebuilds and shard merges. (#56)

### Fixed
Expand Down
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ and `--workspace`; see `litkit <command> --help`.

| Command | Description |
|--------|-------------|
| `litkit search-papers [QUERY]` | Rank papers, or list them by metadata (`--year-from`, `--year-to`, `--author`, `--journal`, `--doi`, `--pmcid`, `--pmid`) |
| `litkit search-papers [QUERY]` | Rank papers, or list them by metadata (repeatable `--type` and `--exclude-type`, `--year-from`, `--year-to`, `--author`, `--journal`, `--doi`, `--pmcid`, `--pmid`) |
| `litkit search-passages QUERY` | `--mode hybrid` (default), `semantic`, or `exact` token search (`G12C`, `SHP-2`, `k_off`); `--section Methods` |
| `litkit chunk-context PAPER ORD` | Chunks `ORD - window .. ORD + window` of one paper (`--window`, default 2) |
| `litkit get-paper PAPER` | Metadata, abstract and ordered chunks (`--section`, `--no-include-tables`) |
Expand All @@ -119,6 +119,14 @@ Without FTS5, exact mode scans the passages. Lexical paper search scans paper
metadata. Hybrid search matches exact tokens within the Stage 1 shortlist.
A DOI or a filename shared by multiple records returns `ambiguous_identifier` with two candidate `paper:N` handles. Use the exact handle from search results, or inspect the candidates to choose a record.
Save a passage’s `evidence_handle` to check its full source text on later reads. Its `evidence:v1:` prefix prevents legacy readers from silently opening an unchecked location. It combines the paper, ordinal and a 96-bit prefix of SHA-256. After a content change, `chunk-context` and `get-paper` return `stale_handle` (exit 5). If the original text moved to exactly one other ordinal in the paper, the error includes a replacement handle. The Python APIs raise `StaleHandleError`. A numeric paper ID also carries a fingerprint of its document metadata so a reassigned row cannot silently change sources. Existing location handles still refer to the current index.
Paper and passage results include the raw JATS `article_type`, normalized `types`
and a `retracted` flag. A retraction notice has type `retraction`; the affected
paper carries the flag. For archives from a text-fetch workspace, pass
`--publication-manifest /path/to/.text-fetch/workspace.json` during ingest to
include source publication types by exact archive member path. After a text-fetch
metadata refresh, rerun the update with the same archive and manifest to refresh
its publication status while reusing the existing embeddings. Rebuild existing
workspaces to populate these fields for previously indexed papers.
The same operations are available in Python as `litkit.retrieval.search_papers`,
`search_passages`, `get_chunk_context` and `get_paper`.

Expand Down
127 changes: 114 additions & 13 deletions src/litkit/build/ingest_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from __future__ import annotations

import hashlib
import json
import os
import sqlite3
Expand All @@ -32,6 +33,7 @@
parallel_iter_tar_articles,
parse_xml_fileobj,
)
from litkit.ingest.publication_types import publication_fields, publication_source
from litkit.ingest import is_uncompressed_tar
from litkit.index import (
make_id_selector,
Expand All @@ -54,7 +56,7 @@
from litkit.db.handoff import completed_checkpoint, merged_checkpoints, readable_database
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.schema import ensure_in_index_columns, ensure_paper_embedding_column, table_columns
from litkit.db.sharding import producer_shard_lock
from litkit.segments.metadata import verify_legacy_shard
from litkit.build.helpers import (
Expand All @@ -75,13 +77,32 @@
)


class _HashingReader:
"""Hash raw XML as the parser consumes a compressed archive member."""

def __init__(self, stream):
self.stream = stream
self.hasher = hashlib.sha256()

def read(self, size=-1):
block = self.stream.read(size)
self.hasher.update(block)
return block

def digest(self):
# A recovering parser can finish before the end of malformed XML.
while self.read(64 * 1024):
pass
return self.hasher.digest()


def iter_tar_articles(
tar_path: Path,
parse_workers: int = 8,
*,
include_tables: bool = False,
max_table_chars: int = DEFAULT_MAX_TABLE_CHARS,
) -> Iterator[tuple[TarMemberMeta | SimpleNamespace, ArticleMeta]]:
) -> Iterator[tuple[TarMemberMeta, ArticleMeta]]:
"""Unified iterator over articles in a tar file.

For uncompressed .tar files (when parse_workers > 1), uses parallel XML parsing.
Expand Down Expand Up @@ -110,18 +131,19 @@ def iter_tar_articles(
# Sequential path for compressed tars (or when parallel disabled)
for tarinfo, fobj in iter_tar_xml_streams(tar_path):
try:
reader = _HashingReader(fobj)
article_meta = parse_xml_fileobj(
fobj,
reader,
tarinfo.name,
include_tables=include_tables,
max_table_chars=max_table_chars,
)
if article_meta is not None:
# Wrap TarInfo in SimpleNamespace for consistent interface
member_meta = SimpleNamespace(
member_meta = TarMemberMeta(
name=tarinfo.name,
size=int(getattr(tarinfo, "size", 0)),
mtime=float(getattr(tarinfo, "mtime", 0.0) or 0.0),
content_sha256=reader.digest(),
)
yield member_meta, article_meta
finally:
Expand Down Expand Up @@ -215,6 +237,7 @@ def process_tar_files(
parse_workers: int,
include_tables: bool = False,
max_table_chars: int = DEFAULT_MAX_TABLE_CHARS,
publication_manifest: Path | None = None,
_producer_locked: bool = False,
) -> tuple[faiss.Index | None, faiss.Index, int, int]:
"""Process tar files and ingest articles into DB and indices.
Expand Down Expand Up @@ -285,16 +308,74 @@ def process_tar_files(
papers_added_total = 0
chunks_added_total = 0

manifest_articles = {}
if publication_manifest is not None:
with Path(publication_manifest).open(encoding="utf-8") as source:
manifest_articles = json.load(source)["articles"]
if not isinstance(manifest_articles, dict):
raise ValueError("Expected text-fetch workspace metadata with an articles mapping")

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

pending_refreshes = 0

def refresh_known_member(path, member, meta, manifest_article):
"""Apply a sidecar change without rewriting text, chunk IDs or vectors."""
nonlocal pending_refreshes, has_refresh_table
source = publication_source(path, member.content_sha256)
select = (
"SELECT p.id, p.article_type, p.publication_types, p.retracted "
"FROM files f JOIN papers p ON p.id=f.paper_id WHERE f.path=? AND p.publication_source=?"
)
local = cur.execute(select, (path, source)).fetchone()
remote = merged.execute(select, (path, source)).fetchone() if merged_has_types else None
if local is None and remote is None:
return
fields = publication_fields(meta, manifest_article)
# A detached shard may already hold a newer, unconsumed refresh.
# Compare against it even when the manifest changes back to the value
# that the main DB still reports.
queued = None
if embed_producer and has_refresh_table:
queued = cur.execute(
"SELECT article_type, types, retracted FROM publication_refreshes "
"WHERE path=? AND source=? AND sequence>?", (path, source, merged_sequence),
).fetchone()
if queued is not None:
if queued == fields:
return
elif all(row is None or row[1:] == fields for row in (local, remote)):
return
if embed_producer:
publication.reserve()
if not conn.in_transaction:
conn.execute("BEGIN")
if local is not None:
cur.execute("UPDATE papers SET article_type=?, publication_types=?, retracted=? WHERE id=?",
(*fields, local[0]))
if embed_producer:
if not has_refresh_table:
cur.execute("CREATE TABLE publication_refreshes (path TEXT PRIMARY KEY, source BLOB NOT NULL, "
"article_type TEXT, types TEXT, retracted INTEGER, sequence INTEGER)")
cur.execute("CREATE INDEX publication_refresh_sequence ON publication_refreshes(sequence)")
has_refresh_table = True
cur.execute("INSERT OR REPLACE INTO publication_refreshes VALUES (?,?,?,?,?,?)",
(path, source, *fields, publication.checkpoint.get("segment_sequence", 0) + 1))
pending_refreshes += 1

def flush_batch(tar: str, members: int) -> None:
nonlocal paper_index, chunk_index, papers_added_total, chunks_added_total
nonlocal paper_index, chunk_index, papers_added_total, chunks_added_total, pending_refreshes
if not (paper_ids_buf or chunk_ids_buf):
if pending_refreshes and embed_producer:
publication.publish(tar, members, lambda paper_dir, chunk_dir: (None, None))
pending_refreshes = 0
return
if publication.token is not None:
publication.discard_uncommitted()
pending_refreshes = 0
commit_transaction(conn)
publication.checkpoint_tar(tar, members)
return
Expand Down Expand Up @@ -423,6 +504,7 @@ def stage_indexes(paper_dir, chunk_dir):
retired_papers.clear()
replaced_papers.clear()
replaced_chunks.clear()
pending_refreshes = 0
revised_shard_papers.clear()

def process_tar(tpath: Path) -> None:
Expand Down Expand Up @@ -516,13 +598,18 @@ def _render(force: bool = False):
include_tables=include_tables,
max_table_chars=max_table_chars,
):
f = f"tar://{tpath}!/{m.name}"
manifest_article = manifest_articles.get(m.name.removeprefix("./"))
if skipped < start_persisted:
if manifest_article is not None and meta is not None:
refresh_known_member(f, m, meta, manifest_article)
if pending_refreshes >= ckpt_every:
flush_batch(str(tpath), start_persisted)
skipped += 1
if skipped == start_persisted:
_render(force=True) # render resume point
continue

f = f"tar://{tpath}!/{m.name}"
st = SimpleNamespace(
st_size=int(getattr(m, "size", 0)),
st_mtime=float(getattr(m, "mtime", 0.0) or 0.0),
Expand All @@ -541,6 +628,10 @@ def _render(force: bool = False):
if not known and merged is not None and db_already_processed(merged, f, st, require_indexed=True):
known = not cur.execute("SELECT 1 FROM files WHERE path=?", (f,)).fetchone()
if known:
if manifest_article is not None and meta is not None:
refresh_known_member(f, m, meta, manifest_article)
if pending_refreshes >= ckpt_every:
flush_batch(str(tpath), processed_count + 1)
processed_count += 1
continue

Expand Down Expand Up @@ -714,9 +805,13 @@ def _render(force: bool = False):
cur.execute("UPDATE papers SET embedding_text=? WHERE id=?", (ta_ab, pid))

bibliography = meta.get("references")
cur.execute("UPDATE papers SET references_json=? WHERE id=?", (
json.dumps(bibliography, ensure_ascii=False) if bibliography is not None else None, pid,
cur.execute("UPDATE papers SET references_json=?, publication_source=?, article_type=?, "
"publication_types=?, retracted=? WHERE id=?", (
json.dumps(bibliography, ensure_ascii=False) if bibliography is not None else None,
publication_source(f, m.content_sha256), *publication_fields(meta, manifest_article), pid,
))
if has_refresh_table:
cur.execute("DELETE FROM publication_refreshes WHERE path=?", (f,))
body = pack_body(meta, chunk_target_chars, chunk_min_chars, chunk_overlap)
abstract_section = "Abstract" if ab else None
abstract_refs = tuple(dict.fromkeys(rid for _, _, rid in meta.get("abstract_citations", [])))
Expand Down Expand Up @@ -803,7 +898,7 @@ def _render(force: bool = False):
persisted_count = processed_count
_render(force=True)

if processed_count != persisted_count or str(tpath) not in ckpt_stream:
if pending_refreshes or processed_count != persisted_count or str(tpath) not in ckpt_stream:
flush_batch(str(tpath), processed_count)
_render(force=True)
_progress_newline(sys.stderr)
Expand All @@ -816,6 +911,11 @@ def _render(force: bool = False):
)
with owner_lock, ExitStack() as readers:
merged = None
merged_has_types = False
merged_sequence = 0
has_refresh_table = bool(conn.execute(
"SELECT 1 FROM sqlite_master WHERE name='publication_refreshes'"
).fetchone())
merged_has_links = False
ensure_in_index_columns(conn)
ensure_paper_embedding_column(conn)
Expand All @@ -841,13 +941,14 @@ 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_types = "publication_source" in table_columns(main_db, "papers")
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
)
receipt = merged_checkpoints(main_db, producer_id).get(producer_id)
merged_sequence = (receipt or {}).get("segment_sequence", 0)
publication.bind_producer_outputs(receipt, main_db)
verify_legacy_shard(
conn, producer_id,
paper_output_dir, chunk_seg_writer.outdir, merged_db=main_db,
Expand Down
9 changes: 9 additions & 0 deletions src/litkit/build/publication.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,15 @@ def _finish(self, directories, tar, members, paper, chunk):
maybe_fsync_dir(target)
maybe_fsync_dir(pending)
sequenced, _, sequence, _ = segment_order(chunk or paper or "")
if self.producer and self.conn.execute(
"SELECT 1 FROM sqlite_master WHERE name='publication_refreshes'"
).fetchone():
# A metadata-only refresh emits no segment filename. Its durable
# sequence must advance on recovery as well as on a clean commit.
latest = self.conn.execute("SELECT MAX(sequence) FROM publication_refreshes").fetchone()[0]
if latest is not None:
sequence = max(latest, sequence or 0)
sequenced = True
if sequenced:
self.checkpoint["segment_sequence"] = max(sequence, self.checkpoint.get("segment_sequence", 0))
self.checkpoint_tar(tar, members)
Expand Down
2 changes: 2 additions & 0 deletions src/litkit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1608,6 +1608,7 @@ def _resolve_build_stage1_mode(*, persist: bool) -> str:
chunk_min_chars=int(getattr(args, "chunk_min_chars", BODY_MIN_CHARS)),
chunk_overlap=int(getattr(args, "chunk_overlap", CHUNK_OVERLAP_CHARS)),
ckpt_shard_id=ckpt_shard_id,
publication_manifest=getattr(args, "publication_manifest", None),
_producer_locked=args.embed_producer,
parse_workers=args.parse_workers,
include_tables=include_tables,
Expand Down Expand Up @@ -1978,6 +1979,7 @@ def main():
"true",
"yes",
)
ap.add_argument("--publication-manifest", type=Path, help="text-fetch .text-fetch/workspace.json for the input archives")
ap.add_argument(
"--include-tables",
action=argparse.BooleanOptionalAction,
Expand Down
13 changes: 11 additions & 2 deletions src/litkit/db/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@
in_index INTEGER DEFAULT 0,
-- Paper vector input when multiple versions share an ID
embedding_text TEXT,
references_json TEXT
references_json TEXT,
publication_source BLOB,
article_type TEXT,
publication_types TEXT,
retracted INTEGER
);
CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
Expand Down Expand Up @@ -89,7 +93,8 @@ def optional_paper_columns(
prefix = f"{alias}." if alias else ""
return {
name: (f"{prefix}{name}" if name in cols else "NULL")
for name in ("doc_id", "source_path", "doi", "year", "authors", "journal", "references_json")
for name in ("doc_id", "source_path", "doi", "year", "authors", "journal", "references_json",
"publication_source", "article_type", "publication_types", "retracted")
}


Expand Down Expand Up @@ -247,6 +252,10 @@ def ensure_paper_embedding_column(conn: sqlite3.Connection) -> None:


_ADDED_COLUMNS = (
("papers", "publication_source", "BLOB"),
("papers", "article_type", "TEXT"),
("papers", "publication_types", "TEXT"),
("papers", "retracted", "INTEGER"),
("papers", "references_json", "TEXT"),
("chunks", "cited_refs", "TEXT"),
("papers", "in_index", "INTEGER DEFAULT 0"),
Expand Down
Loading
Loading