mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-06 03:20:39 +08:00
fix(storage): isolate attachment writes and settle document parsing
Local dev repairs for #2244, #2245, #2255, #2426, #2453. Regression checks cover reported symptoms and compatibility boundaries.
This commit is contained in:
@@ -9,6 +9,21 @@ import sys
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
#: How long the tree gets to disappear after the kill signals. Shared by the
|
||||
#: Windows job-object loop and the POSIX group poll so both give up at the same
|
||||
#: point; a test can shorten it instead of waiting out the real deadline.
|
||||
_PROCESS_SETTLE_SECONDS = 5.0
|
||||
|
||||
|
||||
class ProcessTreeNotSettled(RuntimeError):
|
||||
"""The CLI tree outlived the settle deadline.
|
||||
|
||||
A subclass of :class:`RuntimeError`, so callers that already catch broadly
|
||||
keep working unchanged. It exists so the parse can report "cleanup failed"
|
||||
rather than "the parser crashed": the two call for different handling, and
|
||||
only this one means the artifacts may still be in motion (#2426).
|
||||
"""
|
||||
|
||||
|
||||
@contextmanager
|
||||
def cli_process(cmd: list[str], log_path: Path, env: dict[str, str]):
|
||||
@@ -63,12 +78,14 @@ def cli_process(cmd: list[str], log_path: Path, env: dict[str, str]):
|
||||
if process is not None and not assigned:
|
||||
process.kill() # Still suspended; cannot have spawned a child.
|
||||
win32job.TerminateJobObject(job, 1)
|
||||
deadline = time.monotonic() + 5
|
||||
deadline = time.monotonic() + _PROCESS_SETTLE_SECONDS
|
||||
while win32job.QueryInformationJobObject(
|
||||
job, win32job.JobObjectBasicAccountingInformation
|
||||
)["ActiveProcesses"]:
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("MinerU process-tree cleanup did not settle")
|
||||
raise ProcessTreeNotSettled(
|
||||
"MinerU process-tree cleanup did not settle"
|
||||
)
|
||||
time.sleep(0.05)
|
||||
finally:
|
||||
job.Close()
|
||||
@@ -85,10 +102,10 @@ def cli_process(cmd: list[str], log_path: Path, env: dict[str, str]):
|
||||
if process is not None:
|
||||
process.wait(timeout=5)
|
||||
if sys.platform != "win32" and process is not None:
|
||||
deadline = time.monotonic() + 5
|
||||
deadline = time.monotonic() + _PROCESS_SETTLE_SECONDS
|
||||
while _process_group_alive(process.pid):
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("MinerU process-tree cleanup did not settle")
|
||||
raise ProcessTreeNotSettled("MinerU process-tree cleanup did not settle")
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
|
||||
@@ -66,6 +66,11 @@ _LOCAL_FAILURE_MESSAGES: dict[LocalParseReason, str] = {
|
||||
"switch to cloud mode in Settings → MinerU."
|
||||
),
|
||||
LocalParseReason.EXCEPTION: "Local MinerU parsing was interrupted: {detail}",
|
||||
LocalParseReason.CLEANUP_FAILED: (
|
||||
"MinerU finished parsing, but its process tree did not exit within the "
|
||||
"deadline ({detail}). The output was not published because the tree may "
|
||||
"still be writing to it."
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -245,6 +250,7 @@ def _parse_local(
|
||||
LocalParseReason.NONZERO_EXIT,
|
||||
LocalParseReason.NO_ARTIFACTS,
|
||||
LocalParseReason.EXCEPTION,
|
||||
LocalParseReason.CLEANUP_FAILED,
|
||||
}:
|
||||
message += (
|
||||
" Retry restarts this document from the beginning; completed compatible "
|
||||
|
||||
@@ -20,7 +20,7 @@ from uuid import uuid4
|
||||
from deeptutor.services.file_io import atomic_write_json
|
||||
from deeptutor.services.parsing.cache import load_ir
|
||||
|
||||
from ._process import cli_process
|
||||
from ._process import ProcessTreeNotSettled, cli_process
|
||||
from .formats import MINERU_SUPPORTED_FORMATS
|
||||
|
||||
# Minimum seconds between on_output callbacks. MinerU's CLI emits tqdm-style
|
||||
@@ -63,6 +63,12 @@ class LocalParseReason(StrEnum):
|
||||
NONZERO_EXIT = "nonzero_exit"
|
||||
NO_ARTIFACTS = "no_artifacts"
|
||||
EXCEPTION = "exception"
|
||||
#: The parse produced artifacts but its process tree did not settle within
|
||||
#: the deadline, so the attempt is not safe to treat as finished (#2426).
|
||||
#: Kept apart from ``EXCEPTION`` because a caller deciding whether to retry
|
||||
#: needs to tell a wedged teardown apart from a parser crash: the work may
|
||||
#: already be good and only the cleanup in doubt.
|
||||
CLEANUP_FAILED = "cleanup_failed"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -375,6 +381,17 @@ def parse_document_with_mineru_result(
|
||||
result = LocalParseResult.success()
|
||||
return result
|
||||
|
||||
except ProcessTreeNotSettled as e:
|
||||
# The tree outlived the deadline, so whatever it wrote may still be
|
||||
# changing. Publication is withheld either way — the rename sits above
|
||||
# this handler — but the outcome is reported as its own reason rather
|
||||
# than folded into the generic exception bucket (#2426).
|
||||
print(f"✗ MinerU process tree did not settle: {e!s}")
|
||||
result = LocalParseResult.failure(
|
||||
LocalParseReason.CLEANUP_FAILED,
|
||||
f"{type(e).__name__}: {e}",
|
||||
)
|
||||
return result
|
||||
except Exception as e:
|
||||
print(f"✗ Error occurred during parsing: {e!s}")
|
||||
import traceback
|
||||
|
||||
@@ -13,6 +13,7 @@ consumes ``input/*.txt`` regardless of which parser produced the text.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
@@ -82,7 +83,11 @@ async def prepare_input(
|
||||
|
||||
for file_path_str in classification.parser_files:
|
||||
path = Path(file_path_str)
|
||||
text = _extract_parser_text(path)
|
||||
# The parser call is synchronous and can block for a long time
|
||||
# (MinerU cloud polling, local parser subprocess waits), so it runs in
|
||||
# a worker thread — the same offload the LlamaIndex path made in #847 —
|
||||
# keeping the event loop free to advance other coroutines (#2255).
|
||||
text = await asyncio.to_thread(_extract_parser_text, path)
|
||||
written += _write_doc(target_dir, path, text, used, source_for_input)
|
||||
|
||||
for file_path_str in classification.text_files:
|
||||
@@ -101,7 +106,9 @@ async def prepare_input(
|
||||
parse_service = get_parse_service()
|
||||
supports = getattr(parse_service, "supports", lambda _path: False)
|
||||
if supports(path):
|
||||
text = _extract_parser_text(path, parse_service)
|
||||
# Offloaded for the same reason as the parser_files loop above
|
||||
# (#2255, #847): the shared parser's parse() is synchronous.
|
||||
text = await asyncio.to_thread(_extract_parser_text, path, parse_service)
|
||||
written += _write_doc(target_dir, path, text, used, source_for_input)
|
||||
else:
|
||||
logger.warning(
|
||||
|
||||
@@ -33,6 +33,7 @@ import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
from typing import Protocol, runtime_checkable
|
||||
from urllib.parse import quote
|
||||
|
||||
@@ -176,17 +177,17 @@ class LocalDiskAttachmentStore:
|
||||
@staticmethod
|
||||
def _write_sync(target: Path, data: bytes) -> None:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Atomic-ish write: write to .tmp then rename. Avoids exposing a
|
||||
# half-written file via the static handler.
|
||||
tmp = target.with_suffix(target.suffix + ".tmp")
|
||||
# Concurrent uploads must not replace or clean up each other's staging file.
|
||||
tmp: Path | None = None
|
||||
try:
|
||||
with tmp.open("wb") as fh:
|
||||
with tempfile.NamedTemporaryFile(dir=target.parent, delete=False) as fh:
|
||||
tmp = Path(fh.name)
|
||||
fh.write(data)
|
||||
os.replace(tmp, target)
|
||||
finally:
|
||||
if tmp.exists():
|
||||
if tmp is not None:
|
||||
try:
|
||||
tmp.unlink()
|
||||
tmp.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ from datetime import datetime, timezone
|
||||
import errno
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
@@ -223,7 +224,6 @@ class ContentWorkspaceService(WorkspaceCatalogMixin):
|
||||
# though the folder was fine (#2354).
|
||||
probe = output / f".dt-wp-{uuid.uuid4().hex[:12]}"
|
||||
probe.touch(exist_ok=False)
|
||||
probe.unlink()
|
||||
except ValueError as exc:
|
||||
raise WorkspaceError("The workspace outputs folder leaves the workspace.") from exc
|
||||
except OSError as exc:
|
||||
@@ -232,6 +232,14 @@ class ContentWorkspaceService(WorkspaceCatalogMixin):
|
||||
"The workspace path is too long for this system. Choose a shorter folder."
|
||||
) from exc
|
||||
raise WorkspaceError("The workspace outputs folder is not writable.") from exc
|
||||
# A delete guard can reject cleanup after the write already succeeded
|
||||
# (#2453). Do not misreport a usable workspace as unwritable.
|
||||
try:
|
||||
probe.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).warning(
|
||||
"Could not remove workspace write probe %s", probe, exc_info=True
|
||||
)
|
||||
|
||||
def validate(self, path: str | Path | None) -> dict[str, Any]:
|
||||
if path is not None and not str(path).strip():
|
||||
|
||||
@@ -1169,19 +1169,31 @@ def _xlsx_shared_strings(zf: zipfile.ZipFile, filename: str) -> list[str]:
|
||||
return strings
|
||||
|
||||
|
||||
def _xlsx_sheet_names(zf: zipfile.ZipFile, filename: str) -> dict[str, str]:
|
||||
def _xlsx_sheet_names(zf: zipfile.ZipFile, filename: str) -> dict[str, str] | None:
|
||||
"""Resolve worksheet parts and titles in workbook order, when available."""
|
||||
root = _parse_xml_member(zf, "xl/workbook.xml", filename)
|
||||
if root is None:
|
||||
return {}
|
||||
rels = _parse_xml_member(zf, "xl/_rels/workbook.xml.rels", filename)
|
||||
if root is None or rels is None:
|
||||
return None
|
||||
targets = {
|
||||
node.get("Id"): node.get("Target", "")
|
||||
for node in rels
|
||||
if _local_name(node.tag) == "Relationship" and node.get("TargetMode") != "External"
|
||||
}
|
||||
members = set(zf.namelist())
|
||||
out: dict[str, str] = {}
|
||||
index = 1
|
||||
for node in root.iter():
|
||||
if _local_name(node.tag) != "sheet":
|
||||
continue
|
||||
sheet_name = node.attrib.get("name") or f"sheet{index}"
|
||||
sheet_id = node.attrib.get("sheetId") or str(index)
|
||||
out[f"xl/worksheets/sheet{sheet_id}.xml"] = sheet_name
|
||||
index += 1
|
||||
rid = node.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id")
|
||||
target = targets.get(rid, "")
|
||||
if not target:
|
||||
continue
|
||||
member = posixpath.normpath(
|
||||
target.lstrip("/") if target.startswith("/") else f"xl/{target}"
|
||||
)
|
||||
if member in members:
|
||||
out[member] = node.get("name") or f"sheet{len(out) + 1}"
|
||||
return out
|
||||
|
||||
|
||||
@@ -1208,15 +1220,18 @@ def _extract_xlsx_ooxml(data: bytes, filename: str) -> str:
|
||||
with _open_ooxml(data, filename) as zf:
|
||||
shared_strings = _xlsx_shared_strings(zf, filename)
|
||||
sheet_names = _xlsx_sheet_names(zf, filename)
|
||||
sheet_members = sorted(
|
||||
(name for name in zf.namelist() if re.match(r"xl/worksheets/sheet\d+\.xml$", name)),
|
||||
key=lambda name: [
|
||||
int(part) if part.isdigit() else part for part in re.split(r"(\d+)", name)
|
||||
],
|
||||
)
|
||||
if sheet_names is None:
|
||||
# Keep best-effort extraction for archives without workbook metadata.
|
||||
sheet_members = sorted(
|
||||
(name for name in zf.namelist() if re.match(r"xl/worksheets/sheet\d+\.xml$", name)),
|
||||
key=lambda name: [
|
||||
int(part) if part.isdigit() else part for part in re.split(r"(\d+)", name)
|
||||
],
|
||||
)
|
||||
sheet_names = {member: f"sheet{index}" for index, member in enumerate(sheet_members, 1)}
|
||||
|
||||
sheets: list[str] = []
|
||||
for index, member in enumerate(sheet_members, 1):
|
||||
for member, sheet_name in sheet_names.items():
|
||||
root = _parse_xml_member(zf, member, filename)
|
||||
if root is None:
|
||||
continue
|
||||
@@ -1245,7 +1260,6 @@ def _extract_xlsx_ooxml(data: bytes, filename: str) -> str:
|
||||
if row_text.strip():
|
||||
rows.append(row_text)
|
||||
if rows:
|
||||
sheet_name = sheet_names.get(member, f"sheet{index}")
|
||||
sheets.append(f"--- Sheet: {sheet_name} ---\n" + "\n".join(rows))
|
||||
return "\n\n".join(sheets)
|
||||
|
||||
|
||||
@@ -275,3 +275,21 @@ def test_workspace_migration_api_blocks_active_turns_and_keeps_bindings(
|
||||
assert result.status_code == 200
|
||||
assert service.validate_chat_binding(row["workspace_id"]).root == individual
|
||||
assert client.post("/api/settings/workspace/registrations/system-snapshot").status_code == 200
|
||||
|
||||
|
||||
def test_successful_workspace_write_probe_ignores_cleanup_failures(
|
||||
workspace_api, tmp_path, monkeypatch
|
||||
):
|
||||
_, service = workspace_api
|
||||
root = tmp_path / "custom"
|
||||
root.mkdir()
|
||||
original = Path.unlink
|
||||
|
||||
def locked_probe(self, *args, **kwargs):
|
||||
if self.name.startswith(".dt-wp-"):
|
||||
raise RuntimeError("antivirus cleanup hook failed")
|
||||
return original(self, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Path, "unlink", locked_probe)
|
||||
service.set_workspace(root)
|
||||
assert service.current_binding().root == root.resolve()
|
||||
|
||||
@@ -375,6 +375,39 @@ def test_backend_runtime_failure_does_not_claim_missing_install(
|
||||
assert "exit code 9" in str(exc.value)
|
||||
|
||||
|
||||
def test_cleanup_failure_keeps_the_retry_hint(
|
||||
pdf: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A cleanup failure is retained for diagnosis, so it needs the same hint.
|
||||
|
||||
The attempt directory is kept on failure, which is exactly what the hint
|
||||
describes; omitting ``CLEANUP_FAILED`` from the set would make the one
|
||||
reason whose artifacts are most likely still on disk the only one that does
|
||||
not say so (#2426).
|
||||
"""
|
||||
monkeypatch.setattr(
|
||||
mineru_backend,
|
||||
"parse_document_with_mineru_result",
|
||||
lambda *_args, **_kwargs: LocalParseResult(
|
||||
ok=False,
|
||||
reason=LocalParseReason.CLEANUP_FAILED,
|
||||
detail="ProcessTreeNotSettled: did not settle",
|
||||
),
|
||||
)
|
||||
|
||||
with pytest.raises(MinerUError) as exc:
|
||||
mineru_backend.parse_document_to_workdir(
|
||||
pdf, tmp_path / "out", config=MinerUConfig(mode="local")
|
||||
)
|
||||
|
||||
message = str(exc.value)
|
||||
assert exc.value.code == "cleanup_failed"
|
||||
assert "Incomplete output is retained for diagnosis" in message
|
||||
# It must not be reported as a parser crash or a missing install.
|
||||
assert "Ensure MinerU is installed" not in message
|
||||
assert "interrupted" not in message
|
||||
|
||||
|
||||
def test_legacy_bool_helpers_keep_their_contract(
|
||||
pdf: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
|
||||
@@ -264,3 +264,87 @@ def test_cleanup_accepts_zombie_group_reaped_during_snapshot(tmp_path, monkeypat
|
||||
if process is not None:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups")
|
||||
def test_unsettled_tree_is_reported_as_cleanup_failed(tmp_path, monkeypatch):
|
||||
"""A tree that never settles gets its own reason and is not published (#2426).
|
||||
|
||||
The probe is patched rather than the exception: ``_process_group_alive``
|
||||
answering "still alive" is exactly what a wedged tree looks like, so this
|
||||
runs the real settle loop, its real deadline and the real handler in
|
||||
``local.py``. Injecting ``ProcessTreeNotSettled`` from the context manager,
|
||||
as an earlier attempt did, would skip all three.
|
||||
|
||||
Driving it with a real unkillable child is not practical: ``SIGKILL`` cannot
|
||||
be blocked, so a genuine process would settle in practice. The loop is
|
||||
therefore exercised here, and the "can a tree really hang" question stays
|
||||
open — stated in the PR rather than implied by a green test.
|
||||
"""
|
||||
from deeptutor.services.parsing.engines.mineru import _process
|
||||
|
||||
monkeypatch.setattr(_process, "_PROCESS_SETTLE_SECONDS", 0.2)
|
||||
monkeypatch.setattr(_process, "_process_group_alive", lambda _pgid: True)
|
||||
|
||||
result, elapsed = run_fixture(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
"import pathlib,sys; p=pathlib.Path(sys.argv[1]); "
|
||||
"(p/'lesson.md').write_text('# parsed',encoding='utf-8')",
|
||||
idle=10,
|
||||
)
|
||||
|
||||
assert not result.ok
|
||||
assert result.reason is local.LocalParseReason.CLEANUP_FAILED, result.reason
|
||||
assert "ProcessTreeNotSettled" in result.detail
|
||||
# A deliberately short deadline, so the poll ends instead of waiting 5s.
|
||||
assert elapsed < 3
|
||||
# Publication is withheld: the attempt was never renamed into the visible
|
||||
# location, so a late write cannot land in a result a caller already has.
|
||||
assert not (tmp_path / "out" / "lesson").exists()
|
||||
(state_file,) = (tmp_path / "out").glob(".mineru-attempt-*/state.json")
|
||||
assert '"cleanup_failed"' in state_file.read_text()
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups")
|
||||
def test_other_failures_keep_reporting_exception(tmp_path, monkeypatch):
|
||||
"""The new reason is narrow: an unrelated failure is still ``EXCEPTION``."""
|
||||
|
||||
def boom(*_args, **_kwargs):
|
||||
raise ValueError("something else broke")
|
||||
|
||||
# ``local`` binds ``cli_process`` at import, so patch it there rather than
|
||||
# in ``_process``.
|
||||
monkeypatch.setattr(local, "cli_process", boom)
|
||||
|
||||
result, _ = run_fixture(tmp_path, monkeypatch, "import time; time.sleep(0.1)")
|
||||
|
||||
assert not result.ok
|
||||
assert result.reason is local.LocalParseReason.EXCEPTION, result.reason
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups")
|
||||
def test_settled_tree_still_publishes(tmp_path, monkeypatch):
|
||||
"""The normal path is untouched: a settling tree publishes and succeeds."""
|
||||
from deeptutor.services.parsing.engines.mineru import _process
|
||||
|
||||
calls: list[int] = []
|
||||
|
||||
def settles(pgid: int) -> bool:
|
||||
calls.append(pgid)
|
||||
return False # First poll: already empty.
|
||||
|
||||
monkeypatch.setattr(_process, "_process_group_alive", settles)
|
||||
|
||||
result, elapsed = run_fixture(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
"import pathlib,sys; p=pathlib.Path(sys.argv[1]); "
|
||||
"(p/'lesson.md').write_text('# parsed',encoding='utf-8')",
|
||||
idle=10,
|
||||
)
|
||||
|
||||
assert result.ok, result
|
||||
assert calls, "the settle probe must be consulted even when it clears at once"
|
||||
assert (tmp_path / "out" / "lesson" / "lesson.md").read_text() == "# parsed"
|
||||
assert elapsed < 3
|
||||
|
||||
@@ -1310,3 +1310,43 @@ def test_router_graphrag_readiness_does_not_make_a_paid_model_call(monkeypatch)
|
||||
)
|
||||
|
||||
assert knowledge._assert_provider_ready(GRAPHRAG_PROVIDER) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("suffix", [".pdf", ".png"])
|
||||
def test_ingestion_parser_keeps_event_loop_responsive(tmp_path, monkeypatch, suffix):
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
from deeptutor.services import parsing
|
||||
|
||||
source = tmp_path / ("source" + suffix)
|
||||
source.write_bytes(b"synthetic")
|
||||
released = threading.Event()
|
||||
entered = threading.Event()
|
||||
|
||||
class Parser:
|
||||
def supports(self, path):
|
||||
return True
|
||||
|
||||
def parse(self, path):
|
||||
entered.set()
|
||||
assert released.wait(timeout=3), "parser blocked the event loop"
|
||||
return SimpleNamespace(markdown="parsed", blocks=[])
|
||||
|
||||
monkeypatch.setattr(parsing, "get_parse_service", lambda: Parser())
|
||||
|
||||
async def exercise():
|
||||
task = asyncio.create_task(ingestion.prepare_input([str(source)], tmp_path / "kb"))
|
||||
try:
|
||||
for _ in range(100):
|
||||
if entered.is_set():
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
assert entered.is_set()
|
||||
released.set()
|
||||
assert await task == 1
|
||||
finally:
|
||||
released.set()
|
||||
await task
|
||||
|
||||
asyncio.run(exercise())
|
||||
|
||||
75
tests/services/storage/test_attachment_store_writes.py
Normal file
75
tests/services/storage/test_attachment_store_writes.py
Normal file
@@ -0,0 +1,75 @@
|
||||
"""Atomic attachment writes must own their temporary files."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from deeptutor.services.storage import attachment_store
|
||||
from deeptutor.services.storage.attachment_store import LocalDiskAttachmentStore
|
||||
|
||||
|
||||
def test_concurrent_writes_to_same_attachment_publish_complete_bytes(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
target = tmp_path / "session" / "attachment_notes.txt"
|
||||
payloads = (b"first upload" * 1000, b"second upload" * 1000)
|
||||
ready = threading.Barrier(2)
|
||||
rename_lock = threading.Lock()
|
||||
replace = attachment_store.os.replace
|
||||
|
||||
def replace_together(source: Path, destination: Path) -> None:
|
||||
ready.wait(timeout=5)
|
||||
# Prevent overlapping Windows source opens from hiding the old shared-path race.
|
||||
with rename_lock:
|
||||
replace(source, destination)
|
||||
|
||||
monkeypatch.setattr(attachment_store.os, "replace", replace_together)
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
writes = [
|
||||
pool.submit(LocalDiskAttachmentStore._write_sync, target, data) for data in payloads
|
||||
]
|
||||
for write in writes:
|
||||
write.result(timeout=10)
|
||||
|
||||
assert target.read_bytes() in payloads
|
||||
assert list(target.parent.iterdir()) == [target]
|
||||
|
||||
|
||||
def test_failed_replacement_preserves_attachment_and_cleans_temporary_file(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
target = tmp_path / "attachment.txt"
|
||||
target.write_bytes(b"saved attachment")
|
||||
|
||||
def fail_replace(source: Path, destination: Path) -> None:
|
||||
raise PermissionError("attachment is locked")
|
||||
|
||||
monkeypatch.setattr(attachment_store.os, "replace", fail_replace)
|
||||
with pytest.raises(PermissionError, match="attachment is locked"):
|
||||
LocalDiskAttachmentStore._write_sync(target, b"replacement")
|
||||
|
||||
assert target.read_bytes() == b"saved attachment"
|
||||
assert list(tmp_path.iterdir()) == [target]
|
||||
|
||||
|
||||
def test_put_returns_resolvable_url(tmp_path: Path) -> None:
|
||||
import asyncio
|
||||
|
||||
store = LocalDiskAttachmentStore(root=tmp_path)
|
||||
url = asyncio.run(
|
||||
store.put(
|
||||
session_id="session",
|
||||
attachment_id="attachment",
|
||||
filename="学习 notes.txt",
|
||||
data=b"notes",
|
||||
)
|
||||
)
|
||||
|
||||
assert "/files/attachments/session/attachment/" in url
|
||||
path = store.resolve_path(
|
||||
session_id="session", attachment_id="attachment", filename="学习 notes.txt"
|
||||
)
|
||||
assert isinstance(path, Path)
|
||||
assert path.read_bytes() == b"notes"
|
||||
96
tests/utils/test_xlsx_workbook_order.py
Normal file
96
tests/utils/test_xlsx_workbook_order.py
Normal file
@@ -0,0 +1,96 @@
|
||||
"""XLSX fallback extraction follows the workbook, not worksheet filenames."""
|
||||
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
from deeptutor.utils import document_extractor
|
||||
|
||||
|
||||
def _workbook(*, metadata: bool = True, relationships: bool = True, target_mode: str = "") -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w") as archive:
|
||||
archive.writestr(
|
||||
"[Content_Types].xml",
|
||||
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
|
||||
'<Default Extension="xml" ContentType="application/xml"/>'
|
||||
'<Override PartName="/xl/workbook.xml" '
|
||||
'ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
|
||||
"</Types>",
|
||||
)
|
||||
if metadata:
|
||||
archive.writestr(
|
||||
"xl/workbook.xml",
|
||||
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||||
'<sheets><sheet name="Summary" sheetId="42" r:id="rSummary"/>'
|
||||
'<sheet name="Raw data" sheetId="7" r:id="rData"/></sheets></workbook>',
|
||||
)
|
||||
if relationships:
|
||||
archive.writestr(
|
||||
"xl/_rels/workbook.xml.rels",
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
'<Relationship Id="rData" Target="/xl/worksheets/sheet2.xml" '
|
||||
'Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"/>'
|
||||
'<Relationship Id="rSummary" Target="worksheets/summary.xml" '
|
||||
'Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" '
|
||||
f"{target_mode}/>"
|
||||
"</Relationships>",
|
||||
)
|
||||
for member, text in (
|
||||
("sheet1.xml", "Unreferenced worksheet"),
|
||||
("sheet2.xml", "Raw measurements"),
|
||||
("summary.xml", "Study summary"),
|
||||
):
|
||||
archive.writestr(
|
||||
f"xl/worksheets/{member}",
|
||||
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||||
'<sheetData><row r="1"><c r="A1" t="inlineStr">'
|
||||
f"<is><t>{text}</t></is></c></row></sheetData></worksheet>",
|
||||
)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def test_fallback_resolves_sheet_names_and_order_through_relationships(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
from openpyxl import load_workbook
|
||||
|
||||
data = _workbook()
|
||||
workbook = load_workbook(io.BytesIO(data), read_only=True, data_only=True)
|
||||
try:
|
||||
assert workbook.sheetnames == ["Summary", "Raw data"]
|
||||
assert [sheet["A1"].value for sheet in workbook] == ["Study summary", "Raw measurements"]
|
||||
finally:
|
||||
workbook.close()
|
||||
monkeypatch.setattr(document_extractor, "load_workbook", None)
|
||||
|
||||
text = document_extractor.extract_text_from_bytes("study.xlsx", data)
|
||||
|
||||
assert text == (
|
||||
"--- Sheet: Summary ---\nStudy summary\n\n--- Sheet: Raw data ---\nRaw measurements"
|
||||
)
|
||||
|
||||
|
||||
def test_fallback_skips_external_sheet_relationships(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(document_extractor, "load_workbook", None)
|
||||
|
||||
text = document_extractor.extract_text_from_bytes(
|
||||
"study.xlsx", _workbook(target_mode='TargetMode="External"')
|
||||
)
|
||||
|
||||
assert text == "--- Sheet: Raw data ---\nRaw measurements"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing", ["metadata", "relationships"])
|
||||
def test_metadata_free_archives_keep_numeric_sheet_fallback(
|
||||
monkeypatch: pytest.MonkeyPatch, missing: str
|
||||
) -> None:
|
||||
monkeypatch.setattr(document_extractor, "load_workbook", None)
|
||||
|
||||
text = document_extractor.extract_text_from_bytes("study.xlsx", _workbook(**{missing: False}))
|
||||
|
||||
assert text == (
|
||||
"--- Sheet: sheet1 ---\nUnreferenced worksheet\n\n--- Sheet: sheet2 ---\nRaw measurements"
|
||||
)
|
||||
Reference in New Issue
Block a user