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
44 changes: 37 additions & 7 deletions src/litkit/portable/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import tarfile
import tempfile
from contextlib import closing, contextmanager
from functools import lru_cache
from pathlib import Path, PurePosixPath, PureWindowsPath

import faiss
Expand Down Expand Up @@ -76,12 +77,21 @@ def new_directory(destination):
stage.rename(destination)


@lru_cache(maxsize=2048)
def publisher_archive(name):
"""Compare slash and backslash spellings of the same Windows archive."""
path = PureWindowsPath(name)
return path.as_posix() if path.drive else name


def archive_candidates(uri, recorded):
if not uri.startswith("tar://"):
return []
path = uri.removeprefix("tar://")
candidates = [
(path[: m.start()], path[m.end() :]) for m in re.finditer("!/", path) if m.end() < len(path)
(publisher_archive(path[: m.start()]), path[m.end() :])
for m in re.finditer("!/", path)
if m.end() < len(path)
]
# A directory or an XML member may itself contain the delimiter.
return [
Expand Down Expand Up @@ -371,7 +381,10 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root
records = {}
if db.execute("SELECT 1 FROM sqlite_master WHERE name='build_sources'").fetchone():
for path, sha, size, options in db.execute("SELECT * FROM build_sources"):
records.setdefault(path, []).append((sha, size, json.loads(options)))
versions = records.setdefault(publisher_archive(path), [])
version = sha, size, json.loads(options)
if version not in versions:
versions.append(version)
allowed = tuple(licenses)
predicate = "1"
if allowed:
Expand Down Expand Up @@ -477,15 +490,32 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root
)
),
)
for path, pid in db.execute(
"SELECT f.path,f.paper_id FROM files f JOIN papers p ON p.id=f.paper_id" + where,
for path, pid, current in db.execute(
f"SELECT f.path,f.paper_id,{member} FROM files f JOIN papers p ON p.id=f.paper_id" + where,
allowed,
):
original, member_name = legacy.member(path, archive_candidates(path, records))
catalog.execute(
"INSERT INTO files VALUES (?,?,?,?)",
(source_paths[original], member_name, pid, path),
registered = catalog.execute(
"""INSERT INTO files VALUES (?,?,?,?) ON CONFLICT(source,member) DO UPDATE
SET original=CASE WHEN excluded.original=? THEN excluded.original ELSE files.original END
WHERE files.paper_id=excluded.paper_id""",
(source_paths[original], member_name, pid, path, current),
)
if not registered.rowcount:
raise ValueError(f"Conflicting file owners for {original}!/{member_name}")
# A different separator spelling can make a paper appear to share its
# current member with another owner. Preserve the URI bound to its
# publication fingerprint when the resolved file belongs to that paper.
catalog.execute(
"""UPDATE files SET original=a.current_file
FROM shared_editions e JOIN articles a ON a.id=e.paper_id
WHERE (files.source,files.member,files.paper_id)=(e.source,e.member,e.paper_id)"""
)
catalog.execute(
"""DELETE FROM shared_editions AS e WHERE EXISTS
(SELECT 1 FROM files f WHERE
(f.source,f.member,f.paper_id)=(e.source,e.member,e.paper_id))"""
)
if catalog.execute(
"SELECT id FROM articles EXCEPT SELECT paper_id FROM files "
"EXCEPT SELECT paper_id FROM shared_editions LIMIT 1"
Expand Down
57 changes: 57 additions & 0 deletions tests/integration/test_portable_vectors.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Portable FAISS releases preserve external IDs across machines and source revisions."""

import hashlib
import json
import sqlite3
import tarfile
from contextlib import closing

import faiss
Expand Down Expand Up @@ -254,6 +256,61 @@ def test_archive_names_use_publisher_path_syntax():
assert archive_names([a, c]) == {a: "C/PMC/a/papers.tar", c: "D/PMC/a/papers.tar"}


@pytest.mark.parametrize("recorded", [True, False])
def test_export_restores_mixed_windows_archive_spellings(
tmp_path, portable_source, monkeypatch, recorded
):
from litkit.ingest.publication_types import publication_source
from litkit.portable import articles
from litkit.portable.restore import rebuild_from_vectors

workspace, sources = portable_source
original = r"R:\publisher\papers.tar"
with (
closing(sqlite3.connect(workspace / "sqlite/litkit.sqlite3")) as db,
tarfile.open(sources / "papers.tar") as tar,
):
settings = (
json.loads(db.execute("SELECT settings FROM build_sources").fetchone()[0]) | MODELS
)
if recorded:
db.execute("UPDATE build_sources SET path=?", (original,))
alternate = original.replace("\\", "/")
db.execute(
"INSERT INTO build_sources SELECT ?,sha256,size,settings FROM build_sources",
(alternate,),
)
else:
db.execute("DROP TABLE build_sources")
for path, pid in db.execute("SELECT path,paper_id FROM files").fetchall():
member = path.rsplit("!/", 1)[1]
uri = f"tar://{original}!/{member}"
with tar.extractfile(member) as stream:
sha = hashlib.file_digest(stream, "sha256").digest()
db.execute(
"UPDATE papers SET build_member=?,publication_source=?,retracted=1 WHERE id=?",
(uri, publication_source(uri, sha), pid),
)
db.execute("UPDATE files SET path=? WHERE path=?", (uri.replace("\\", "/"), path))
if member == "one.xml":
db.execute("INSERT INTO files(path,paper_id) VALUES(?,?)", (uri, pid))
db.commit()
release, restored = tmp_path / "release", tmp_path / "restored"
manifest = export_vectors(workspace, release, settings=settings, source_root=sources)
assert [s["name"] for s in manifest["sources"]] == ["papers.tar"]
with closing(sqlite3.connect(release / "mapping.sqlite3")) as db:
assert db.execute("SELECT COUNT(*) FROM shared_editions").fetchone() == (0,)
assert db.execute(
"SELECT COUNT(*) FROM files f JOIN articles a ON a.id=f.paper_id AND a.current_file=f.original"
).fetchone() == (2,)
monkeypatch.setattr(
articles, "load_model", lambda *_: pytest.fail("unchanged editions were re-embedded")
)
assert not any(rebuild_from_vectors(release, sources, restored).values())
with closing(sqlite3.connect(restored / "sqlite/litkit.sqlite3")) as db:
assert db.execute("SELECT retracted FROM papers ORDER BY id").fetchall() == [(1,), (1,)]


@pytest.fixture
def relocated_legacy_archives(tmp_path):
workspace = tmp_path / "workspace"
Expand Down
Loading