Compare commits

..
4 changed files with 97 additions and 39 deletions

No files matched your search

+21 -10
View File
@@ -6,6 +6,7 @@ import zipfile
from collections.abc import Callable from collections.abc import Callable
from pathlib import Path from pathlib import Path
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
from tempfile import mkstemp
from celery import Task from celery import Task
from celery import shared_task from celery import shared_task
@@ -896,25 +897,26 @@ def build_share_link_bundle(bundle_id: int) -> None:
documents = list(bundle.documents.all().order_by("pk")) documents = list(bundle.documents.all().order_by("pk"))
_, temp_zip_path_str = mkstemp(suffix=".zip", dir=settings.SCRATCH_DIR)
temp_zip_path = Path(temp_zip_path_str)
try: try:
strategy_class = ( strategy_class = (
ArchiveOnlyStrategy ArchiveOnlyStrategy
if bundle.file_version == ShareLink.FileVersion.ARCHIVE if bundle.file_version == ShareLink.FileVersion.ARCHIVE
else OriginalsOnlyStrategy else OriginalsOnlyStrategy
) )
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
strategy = strategy_class(zipf)
for document in documents:
strategy.add_document(document)
output_dir = settings.SHARE_LINK_BUNDLE_DIR output_dir = settings.SHARE_LINK_BUNDLE_DIR
output_dir.mkdir(parents=True, exist_ok=True) output_dir.mkdir(parents=True, exist_ok=True)
final_path = (output_dir / f"{bundle.slug}.zip").resolve() final_path = (output_dir / f"{bundle.slug}.zip").resolve()
if final_path.exists():
with TemporaryDirectory(dir=settings.SCRATCH_DIR) as tmp_dir: final_path.unlink()
temp_zip_path = Path(tmp_dir) / "bundle.zip" shutil.move(temp_zip_path, final_path)
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
strategy = strategy_class(zipf)
for document in documents:
strategy.add_document(document)
final_path.unlink(missing_ok=True)
shutil.move(temp_zip_path, final_path)
bundle.file_path = f"{bundle.slug}.zip" bundle.file_path = f"{bundle.slug}.zip"
bundle.size_bytes = final_path.stat().st_size bundle.size_bytes = final_path.stat().st_size
@@ -945,7 +947,16 @@ def build_share_link_bundle(bundle_id: int) -> None:
"timestamp": timezone.now().isoformat(), "timestamp": timezone.now().isoformat(),
} }
bundle.save(update_fields=["status", "last_error"]) bundle.save(update_fields=["status", "last_error"])
try:
temp_zip_path.unlink()
except OSError:
pass
raise raise
finally:
try:
temp_zip_path.unlink(missing_ok=True)
except OSError:
pass
@shared_task @shared_task
+10 -2
View File
@@ -434,9 +434,13 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
"documents.tasks.OriginalsOnlyStrategy.add_document", "documents.tasks.OriginalsOnlyStrategy.add_document",
side_effect=RuntimeError("zip failure"), side_effect=RuntimeError("zip failure"),
), ),
self.assertRaises(RuntimeError), mock.patch("pathlib.Path.unlink") as unlink_mock,
): ):
build_share_link_bundle(bundle.pk) unlink_mock.side_effect = [OSError("unlink"), OSError("unlink-finally")] + [
None,
] * 5
with self.assertRaises(RuntimeError):
build_share_link_bundle(bundle.pk)
bundle.refresh_from_db() bundle.refresh_from_db()
self.assertEqual(bundle.status, ShareLinkBundle.Status.FAILED) self.assertEqual(bundle.status, ShareLinkBundle.Status.FAILED)
@@ -444,6 +448,10 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
assert isinstance(bundle.last_error, dict) assert isinstance(bundle.last_error, dict)
self.assertEqual(bundle.last_error.get("message"), "zip failure") self.assertEqual(bundle.last_error.get("message"), "zip failure")
self.assertEqual(bundle.last_error.get("exception_type"), "RuntimeError") self.assertEqual(bundle.last_error.get("exception_type"), "RuntimeError")
scratch_zips = list(Path(settings.SCRATCH_DIR).glob("*.zip"))
self.assertTrue(scratch_zips)
for path in scratch_zips:
path.unlink(missing_ok=True)
def test_build_share_link_bundle_missing_bundle_noop(self) -> None: def test_build_share_link_bundle_missing_bundle_noop(self) -> None:
# Should not raise when bundle does not exist # Should not raise when bundle does not exist
@@ -1256,3 +1256,36 @@ class TestIndexPageSize:
assert page_size_of(legacy_page_size_db) == DB_PAGE_SIZE assert page_size_of(legacy_page_size_db) == DB_PAGE_SIZE
assert DocumentChunksTable.count(store.client) == 2 assert DocumentChunksTable.count(store.client) == 2
def test_open_connection_closes_connection_when_setup_fails(
tmp_path: Path,
mocker: MockerFixture,
) -> None:
"""
GIVEN a table setup step that fails after the connection was opened
WHEN the store is created
THEN the setup error propagates
AND the connection that was opened is closed, not leaked
"""
opened: list[sqlite3.Connection] = []
real_connect = sqlite3.connect
def recording_connect(*args, **kwargs) -> sqlite3.Connection:
conn = real_connect(*args, **kwargs)
opened.append(conn)
return conn
mocker.patch("paperless_ai.vector_store.sqlite3.connect", recording_connect)
mocker.patch.object(
DocumentMetaTable,
"create",
side_effect=RuntimeError("setup failed"),
)
with pytest.raises(RuntimeError, match="setup failed"):
PaperlessSqliteVecVectorStore(uri=str(tmp_path))
assert len(opened) == 1
with pytest.raises(sqlite3.ProgrammingError):
opened[0].execute("SELECT 1")
+33 -27
View File
@@ -4,6 +4,7 @@ import sqlite3
import struct import struct
from collections.abc import Iterator from collections.abc import Iterator
from collections.abc import Sequence from collections.abc import Sequence
from contextlib import ExitStack
from contextlib import contextmanager from contextlib import contextmanager
from pathlib import Path from pathlib import Path
from types import TracebackType from types import TracebackType
@@ -212,33 +213,38 @@ class PaperlessSqliteVecVectorStore(BasePydanticVectorStore):
@staticmethod @staticmethod
def _open_connection(db_path: str) -> sqlite3.Connection: def _open_connection(db_path: str) -> sqlite3.Connection:
conn = sqlite3.connect( with ExitStack() as stack:
db_path, conn = sqlite3.connect(
timeout=30, db_path,
isolation_level=None, # autocommit; explicit transactions below timeout=30,
) isolation_level=None, # autocommit; explicit transactions below
conn.row_factory = sqlite3.Row )
conn.enable_load_extension(True) # noqa: FBT003 # Closes the connection (and its WAL/SHM handles) if any setup step
sqlite_vec.load(conn) # below raises. pop_all() disarms it once setup has succeeded.
conn.enable_load_extension(False) # noqa: FBT003 stack.callback(conn.close)
conn.execute(f"PRAGMA page_size={DB_PAGE_SIZE}") conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL") conn.enable_load_extension(True) # noqa: FBT003
conn.execute("PRAGMA synchronous=NORMAL") sqlite_vec.load(conn)
IndexMetaTable.create(conn) conn.enable_load_extension(False) # noqa: FBT003
# vec0 metadata columns only get an efficient lookup path inside a conn.execute(f"PRAGMA page_size={DB_PAGE_SIZE}")
# KNN (MATCH) query; a plain `WHERE document_id = ?` is a full table conn.execute("PRAGMA journal_mode=WAL")
# scan regardless of index size. This plain, indexed table is how conn.execute("PRAGMA synchronous=NORMAL")
# delete()/upsert_document() find a document's chunk ids without IndexMetaTable.create(conn)
# that scan. # vec0 metadata columns only get an efficient lookup path inside a
DocumentChunksTable.create(conn) # KNN (MATCH) query; a plain `WHERE document_id = ?` is a full table
# modified used to be a vec0 metadata column, but vec0 only inlines # scan regardless of index size. This plain, indexed table is how
# TEXT metadata up to 12 bytes -- an ISO timestamp is always longer, # delete()/upsert_document() find a document's chunk ids without
# so every read recompiled and stepped a fresh SQL statement per row. # that scan.
# It was never filtered on inside a KNN query either, so it never DocumentChunksTable.create(conn)
# needed to be a vec0 column at all. One row per document here (not # modified used to be a vec0 metadata column, but vec0 only inlines
# per chunk, like document_chunks), since every chunk of a document # TEXT metadata up to 12 bytes -- an ISO timestamp is always longer,
# shares the same modified value -- see get_modified_times(). # so every read recompiled and stepped a fresh SQL statement per row.
DocumentMetaTable.create(conn) # It was never filtered on inside a KNN query either, so it never
# needed to be a vec0 column at all. One row per document here (not
# per chunk, like document_chunks), since every chunk of a document
# shares the same modified value -- see get_modified_times().
DocumentMetaTable.create(conn)
stack.pop_all()
return conn return conn
@property @property