Compare commits

..
Author SHA1 Message Date
Trenton H 7f80f4608c Fix: close the temp file descriptor when saving mail as eml 2026-11-26 14:07:12 -08:00
3 changed files with 30 additions and 68 deletions

No files matched your search

@@ -1256,36 +1256,3 @@ class TestIndexPageSize:
assert page_size_of(legacy_page_size_db) == DB_PAGE_SIZE
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")
+27 -33
View File
@@ -4,7 +4,6 @@ import sqlite3
import struct
from collections.abc import Iterator
from collections.abc import Sequence
from contextlib import ExitStack
from contextlib import contextmanager
from pathlib import Path
from types import TracebackType
@@ -213,38 +212,33 @@ class PaperlessSqliteVecVectorStore(BasePydanticVectorStore):
@staticmethod
def _open_connection(db_path: str) -> sqlite3.Connection:
with ExitStack() as stack:
conn = sqlite3.connect(
db_path,
timeout=30,
isolation_level=None, # autocommit; explicit transactions below
)
# Closes the connection (and its WAL/SHM handles) if any setup step
# below raises. pop_all() disarms it once setup has succeeded.
stack.callback(conn.close)
conn.row_factory = sqlite3.Row
conn.enable_load_extension(True) # noqa: FBT003
sqlite_vec.load(conn)
conn.enable_load_extension(False) # noqa: FBT003
conn.execute(f"PRAGMA page_size={DB_PAGE_SIZE}")
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
IndexMetaTable.create(conn)
# vec0 metadata columns only get an efficient lookup path inside a
# KNN (MATCH) query; a plain `WHERE document_id = ?` is a full table
# scan regardless of index size. This plain, indexed table is how
# delete()/upsert_document() find a document's chunk ids without
# that scan.
DocumentChunksTable.create(conn)
# modified used to be a vec0 metadata column, but vec0 only inlines
# TEXT metadata up to 12 bytes -- an ISO timestamp is always longer,
# so every read recompiled and stepped a fresh SQL statement per row.
# 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()
conn = sqlite3.connect(
db_path,
timeout=30,
isolation_level=None, # autocommit; explicit transactions below
)
conn.row_factory = sqlite3.Row
conn.enable_load_extension(True) # noqa: FBT003
sqlite_vec.load(conn)
conn.enable_load_extension(False) # noqa: FBT003
conn.execute(f"PRAGMA page_size={DB_PAGE_SIZE}")
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
IndexMetaTable.create(conn)
# vec0 metadata columns only get an efficient lookup path inside a
# KNN (MATCH) query; a plain `WHERE document_id = ?` is a full table
# scan regardless of index size. This plain, indexed table is how
# delete()/upsert_document() find a document's chunk ids without
# that scan.
DocumentChunksTable.create(conn)
# modified used to be a vec0 metadata column, but vec0 only inlines
# TEXT metadata up to 12 bytes -- an ISO timestamp is always longer,
# so every read recompiled and stepped a fresh SQL statement per row.
# 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)
return conn
@property
+3 -2
View File
@@ -2,6 +2,7 @@ import datetime
import imaplib
import itertools
import logging
import os
import socket
import ssl
import tempfile
@@ -1135,12 +1136,12 @@ class MailAccountHandler(LoggingMixin):
doc_type,
):
settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True)
_, temp_filename = tempfile.mkstemp(
fd, temp_filename = tempfile.mkstemp(
prefix="paperless-mail-",
dir=settings.SCRATCH_DIR,
suffix=".eml",
)
with Path(temp_filename).open("wb") as f:
with os.fdopen(fd, "wb") as f:
# Move "From"-header to beginning of file
# TODO: This ugly workaround is needed because the parser is
# chosen only by the mime_type detected via magic