-
Notifications
You must be signed in to change notification settings - Fork 314
Expand file tree
/
Copy pathtest_parse_task_contract.py
More file actions
837 lines (771 loc) · 29 KB
/
Copy pathtest_parse_task_contract.py
File metadata and controls
837 lines (771 loc) · 29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
from __future__ import annotations
import json
import shutil
import zipfile
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from uuid import uuid4
import pandas as pd
import pytest
from pytest import MonkeyPatch
from sqlalchemy import text
from sqlalchemy.engine import Engine
from support.contract_database import insert_contract_job, insert_contract_user
_REPO_ROOT: Path = Path(__file__).resolve().parents[4]
_FIXTURES_ROOT: Path = _REPO_ROOT / "apps" / "worker" / "tests" / "fixtures"
_SAMPLE_PDF_PATH: Path = _FIXTURES_ROOT / "sample_3pages.pdf"
def _build_pending_file_job_metadata(source_file_name: str) -> dict[str, Any]:
job_metadata: dict[str, Any] = {
"namespace": "worker-contract",
"source_type": "file",
"source_file_name": source_file_name,
"kb_dir": "Default_Root",
}
return job_metadata
def _load_parse_task_modules() -> tuple[Any, Any, Any, Engine, Any, Any, Any]:
import app.core.tasks.kb_tasks as kb_tasks
import app.services.document_parser.parse_service as parse_service
import app.services.storage.sync_storage_service as sync_storage_service
from shared.core.database_sync import get_sync_engine
from shared.services.redis.redis_sync_service import (
SyncJobInfoRedisService,
SyncJobMetadataService,
SyncRedisServiceFactory,
)
return (
kb_tasks,
parse_service,
sync_storage_service,
get_sync_engine(),
SyncJobInfoRedisService,
SyncJobMetadataService,
SyncRedisServiceFactory,
)
def _save_worker_task_cache(
*,
job_id: str,
user_id: str,
s3_key: str,
metadata: dict[str, Any],
sync_job_info_service_cls: Any,
sync_job_metadata_service_cls: Any,
sync_redis_service_factory: Any,
) -> Any:
redis_service = sync_redis_service_factory.get_service()
sync_job_info_service = sync_job_info_service_cls(redis_service)
sync_job_metadata_service = sync_job_metadata_service_cls(redis_service)
sync_job_info_service.save_job_info(
job_id,
{
"job_id": job_id,
"s3_key": s3_key,
"user_id": user_id,
"webhook_enabled": False,
"job_type": "kb_management",
"source_type": "file",
},
)
sync_job_metadata_service.save_metadata(job_id, metadata)
return redis_service
def _find_task_workspaces(root: Path, job_id: str) -> list[Path]:
return sorted(
path
for path in root.iterdir()
if path.is_dir() and path.name.startswith(f"kb_task_{job_id}_")
)
def _bind_parse_task_to_current_module(
monkeypatch: MonkeyPatch,
*,
kb_tasks: Any,
) -> None:
monkeypatch.setitem(
kb_tasks.parse_task._orig_run.__globals__,
"_parse",
kb_tasks._parse,
)
monkeypatch.setattr(kb_tasks.parse_task, "__trace__", None, raising=False)
@pytest.mark.parametrize(
("billing_enabled", "expected_billing_status", "expected_transaction_types"),
[
(True, "charged", ["initial_grant", "usage"]),
(False, "skipped", []),
],
)
def test_should_parse_a_pending_file_job_and_persist_the_published_result_state(
worker_contract_environment: None,
monkeypatch: MonkeyPatch,
tmp_path: Path,
billing_enabled: bool,
expected_billing_status: str,
expected_transaction_types: list[str],
) -> None:
monkeypatch.setenv("BILLING_ENABLED", "true" if billing_enabled else "false")
(
kb_tasks,
parse_service,
sync_storage_service,
engine,
sync_job_info_service_cls,
sync_job_metadata_service_cls,
sync_redis_service_factory,
) = _load_parse_task_modules()
user_id: str = f"worker-user-{uuid4().hex[:12]}"
job_id: str = f"job_parse_success_{uuid4().hex[:12]}"
source_file_name: str = "contract-parse.pdf"
s3_key: str = f"uploads/{job_id}.pdf"
text_content_with_refs: str = (
"chunk-1 embeds [images/page-1.png] and [tables/table-1.html]"
)
captured_artifacts: dict[str, Any] = {}
with engine.begin() as connection:
insert_contract_user(connection, user_id=user_id)
job_metadata = _build_pending_file_job_metadata(source_file_name)
insert_contract_job(
connection,
job_id=job_id,
user_id=user_id,
status="pending",
source_type="file",
s3_key=s3_key,
webhook_enabled=False,
job_metadata=job_metadata,
billing_status="pending",
)
redis_service = _save_worker_task_cache(
job_id=job_id,
user_id=user_id,
s3_key=s3_key,
metadata=job_metadata,
sync_job_info_service_cls=sync_job_info_service_cls,
sync_job_metadata_service_cls=sync_job_metadata_service_cls,
sync_redis_service_factory=sync_redis_service_factory,
)
_bind_parse_task_to_current_module(monkeypatch, kb_tasks=kb_tasks)
monkeypatch.setattr(kb_tasks.settings, "TMP_PATH", str(tmp_path))
monkeypatch.setattr(kb_tasks.settings, "BILLING_ENABLED", billing_enabled)
def fake_verify_s3_file_exists(storage_key: str) -> dict[str, Any]:
return {
"exists": storage_key == s3_key,
"size": _SAMPLE_PDF_PATH.stat().st_size,
}
def fake_generate_download_url(storage_key: str, bucket: str | None) -> dict[str, str]:
return {"download_url": f"https://example.test/{storage_key}"}
monkeypatch.setattr(kb_tasks, "verify_s3_file_exists", fake_verify_s3_file_exists)
monkeypatch.setattr(
sync_storage_service,
"verify_s3_file_exists",
fake_verify_s3_file_exists,
)
monkeypatch.setattr(kb_tasks, "generate_download_url", fake_generate_download_url)
monkeypatch.setattr(
sync_storage_service,
"generate_download_url",
fake_generate_download_url,
)
def fake_download_s3_file_to_temp(
file_url: str, file_ext: str, temp_dir: str
) -> str:
assert file_ext == ".pdf"
downloaded_path = Path(temp_dir) / f"downloaded{file_ext}"
shutil.copy2(_SAMPLE_PDF_PATH, downloaded_path)
return str(downloaded_path)
def fake_checkerboard_inject_parse(**kwargs: Any) -> tuple[str, pd.DataFrame]:
captured_artifacts["parse_kwargs"] = kwargs
output_dir = (
Path(str(kwargs["output_dir"]))
/ str(kwargs["kb_dir"])
/ str(kwargs["internal_output_filename"])
)
images_dir = output_dir / "images"
tables_dir = output_dir / "tables"
images_dir.mkdir(parents=True, exist_ok=True)
tables_dir.mkdir(parents=True, exist_ok=True)
(output_dir / "full.md").write_text("body", encoding="utf-8")
(images_dir / "page-1.png").write_bytes(b"png")
(tables_dir / "table-1.html").write_text("<table></table>", encoding="utf-8")
file_root = str(kwargs["internal_output_filename"])
parsed_rows: list[dict[str, Any]] = [
{
"content": text_content_with_refs,
"path": f"Default_Root/{file_root}/公司研究/自主可控加强,寒武纪或迎来营收快速放量周期",
"type": "text",
"length": len(text_content_with_refs),
"keywords": "",
"summary": "",
"know_id": "kid-1",
"tokens": "",
"connectto": json.dumps(
[
{
"target": "table-1",
"relation": "embeds",
"ref": "[tables/table-1.html]",
}
]
),
"addtime": "now",
"page_nums": "1",
},
{
"content": "chunk-2",
"path": f"Default_Root/{file_root}/相关研报/要点",
"type": "text",
"length": 7,
"keywords": "",
"summary": "",
"know_id": "kid-2",
"tokens": "",
"connectto": "",
"addtime": "now",
"page_nums": "2",
},
{
"content": "image caption",
"path": f"Default_Root/{file_root}/images/page-1.png",
"type": "image",
"length": 13,
"keywords": "",
"summary": "",
"know_id": "image-1",
"tokens": "",
"connectto": "",
"addtime": "now",
"page_nums": "3",
},
{
"content": "table content",
"path": f"Default_Root/{file_root}/tables/table-1.html",
"type": "table",
"length": 13,
"keywords": "",
"summary": "",
"know_id": "table-1",
"tokens": "",
"connectto": "",
"addtime": "now",
"page_nums": "3",
},
]
return str(output_dir), pd.DataFrame(parsed_rows)
class FakeResultStorage:
def upload(self, *, job_id: str, result_dir: str, zip_file_path: str) -> Any:
result_dir_path = Path(result_dir)
zip_path = Path(zip_file_path)
captured_artifacts["result_dir"] = result_dir
captured_artifacts["zip_file_path"] = zip_file_path
captured_artifacts["raw_entries"] = sorted(
path.relative_to(result_dir_path).as_posix()
for path in result_dir_path.rglob("*")
if path.is_file()
)
captured_artifacts["doc_nav"] = json.loads(
(result_dir_path / "doc_nav.json").read_text(encoding="utf-8")
)
with zipfile.ZipFile(zip_path) as zip_file:
captured_artifacts["zip_entries"] = sorted(zip_file.namelist())
captured_artifacts["zip_chunks"] = json.loads(
zip_file.read("chunks.json")
)["chunks"]
return SimpleNamespace(
zip_key=f"results/{job_id}.zip",
raw_prefix=f"results/{job_id}/",
raw_files={},
)
monkeypatch.setattr(kb_tasks, "download_s3_file_to_temp", fake_download_s3_file_to_temp)
monkeypatch.setattr(parse_service, "checkerboard_inject_parse", fake_checkerboard_inject_parse)
monkeypatch.setattr(kb_tasks, "get_result_storage", lambda: FakeResultStorage())
result = kb_tasks.parse_task.run(job_id, user_id, "kb_management")
expected_summary = (
"This document includes the following contents:\n"
"- 公司研究\n"
" - 自主可控加强,寒武纪或迎来营收快速放量周期\n"
"- 相关研报\n"
" - 要点"
)
expected_connect_to = [
{
"target": "image-1",
"relation": "embeds",
"ref": "[images/page-1.png]",
"position": {
"start": text_content_with_refs.index("[images/page-1.png]"),
"end": text_content_with_refs.index("[images/page-1.png]")
+ len("[images/page-1.png]"),
},
},
{
"target": "table-1",
"relation": "embeds",
"ref": "[tables/table-1.html]",
"position": {
"start": text_content_with_refs.index("[tables/table-1.html]"),
"end": text_content_with_refs.index("[tables/table-1.html]")
+ len("[tables/table-1.html]"),
},
},
]
expected_credits_charged = 3 * int(kb_tasks.settings.MICRO_DOLLARS_PER_PAGE)
expected_initial_balance = int(kb_tasks.settings.FREE_PLAN_INITIAL_CREDITS) * 1_000_000
assert result == {
"status": "success",
"job_id": job_id,
"add_dir": None,
"vectors_count": 0,
"contents_count": 4,
"stored_count": 0,
"delivery_mode": "url",
"result_s3_key": f"results/{job_id}.zip",
}
assert captured_artifacts["parse_kwargs"]["filename"] == source_file_name
assert captured_artifacts["parse_kwargs"]["internal_output_filename"] == source_file_name
assert Path(str(captured_artifacts["parse_kwargs"]["file_full_path"])).name == source_file_name
assert captured_artifacts["result_dir"].endswith("Default_Root/contract-parse.pdf")
assert captured_artifacts["doc_nav"]["file_name"] == source_file_name
assert captured_artifacts["doc_nav"]["sections"][0]["title"] == "公司研究"
assert "doc_nav.json" in captured_artifacts["raw_entries"]
assert "hierarchy.json" not in captured_artifacts["raw_entries"]
assert "hierarchy_slim.json" not in captured_artifacts["raw_entries"]
assert "chunks.json" in captured_artifacts["zip_entries"]
assert "full.md" in captured_artifacts["zip_entries"]
assert "doc_nav.json" in captured_artifacts["zip_entries"]
assert "chunks_slim.json" not in captured_artifacts["zip_entries"]
assert "hierarchy.json" not in captured_artifacts["zip_entries"]
assert "hierarchy_slim.json" not in captured_artifacts["zip_entries"]
assert "images/page-1.png" in captured_artifacts["zip_entries"]
assert "tables/table-1.html" in captured_artifacts["zip_entries"]
assert captured_artifacts["zip_chunks"][0]["metadata"]["document_top_summary"] == expected_summary
assert captured_artifacts["zip_chunks"][0]["metadata"]["connect_to"] == expected_connect_to
assert captured_artifacts["zip_chunks"][2]["metadata"]["file_path"] == "images/page-1.png"
assert captured_artifacts["zip_chunks"][3]["metadata"]["file_path"] == "tables/table-1.html"
assert _find_task_workspaces(tmp_path, job_id) == []
progress = redis_service.hgetall(f"task:{job_id}:progress")
assert progress["progress"] == 100
assert progress["message"] == "Task complete!"
assert progress["timestamp"]
metadata = sync_job_metadata_service_cls(redis_service).get_metadata(job_id)
assert metadata is not None
assert metadata["page_count"] == 3
assert metadata["billing_status"] == expected_billing_status
if billing_enabled:
assert metadata["billing_amount_micro_dollars"] == expected_credits_charged
assert metadata["billing_credits"] == expected_credits_charged / 1_000_000
else:
assert metadata["billing_amount_micro_dollars"] == 0
assert metadata["billing_credits"] == 0.0
assert metadata["processing_started_at"]
assert metadata["processing_completed_at"]
assert metadata["processing_duration_ms"] >= 0
with engine.begin() as connection:
job_row = (
connection.execute(
text(
"""
SELECT
status,
billing_status,
page_count,
credits_charged,
error_code,
error_message
FROM jobs
WHERE job_id = :job_id
"""
),
{"job_id": job_id},
)
.mappings()
.one()
)
job_result_row = (
connection.execute(
text(
"""
SELECT delivery_mode, result_s3_key, result_size, inline_payload
FROM job_results
WHERE job_id = :job_id
"""
),
{"job_id": job_id},
)
.mappings()
.one()
)
document_row = (
connection.execute(
text(
"""
SELECT document_id, namespace, status, current_job_result_id, source_file_name
FROM documents
WHERE user_id = :user_id
"""
),
{"user_id": user_id},
)
.mappings()
.one()
)
document_chunks = list(
connection.execute(
text(
"""
SELECT chunk_type, file_path, source_chunk_path, chunk_metadata
FROM document_chunks
WHERE document_id = :document_id
ORDER BY sort_order
"""
),
{"document_id": document_row["document_id"]},
)
.mappings()
.all()
)
graph_node_row = (
connection.execute(
text(
"""
SELECT properties
FROM graph_nodes
WHERE owner_document_id = :document_id
"""
),
{"document_id": document_row["document_id"]},
)
.mappings()
.one()
)
balance_row = (
connection.execute(
text(
"""
SELECT credits_balance
FROM user_balances
WHERE user_id = :user_id
"""
),
{"user_id": user_id},
)
.mappings()
.one_or_none()
)
transaction_types = list(
connection.execute(
text(
"""
SELECT transaction_type
FROM credits_transactions
WHERE user_id = :user_id
ORDER BY created_at ASC
"""
),
{"user_id": user_id},
)
.scalars()
.all()
)
audit_transitions = list(
connection.execute(
text(
"""
SELECT transition_reason, to_state
FROM job_state_audit_logs
WHERE job_id = :job_id
ORDER BY created_at ASC
"""
),
{"job_id": job_id},
)
.mappings()
.all()
)
graph_properties = dict(graph_node_row["properties"])
assert job_row["status"] == "done"
assert job_row["billing_status"] == expected_billing_status
assert job_row["page_count"] == 3
if billing_enabled:
assert job_row["credits_charged"] == expected_credits_charged
else:
assert job_row["credits_charged"] == 0
assert job_row["error_code"] is None
assert job_row["error_message"] is None
assert job_result_row["delivery_mode"] == "url"
assert job_result_row["result_s3_key"] == f"results/{job_id}.zip"
assert job_result_row["result_size"] > 0
assert dict(job_result_row["inline_payload"])["checksum"]
assert document_row["namespace"] == "worker-contract"
assert document_row["status"] == "active"
assert document_row["source_file_name"] == source_file_name
assert document_row["current_job_result_id"]
assert len(document_chunks) == 4
assert document_chunks[0]["chunk_type"] == "text"
assert dict(document_chunks[0]["chunk_metadata"])["document_top_summary"] == expected_summary
assert dict(document_chunks[0]["chunk_metadata"])["connect_to"] == expected_connect_to
assert document_chunks[2]["chunk_type"] == "image"
assert document_chunks[2]["file_path"] == "images/page-1.png"
assert document_chunks[3]["chunk_type"] == "table"
assert document_chunks[3]["file_path"] == "tables/table-1.html"
assert graph_properties["chunks_count"] == 4
assert graph_properties["top_summary"] == expected_summary
if billing_enabled:
assert balance_row is not None
assert (
balance_row["credits_balance"]
== expected_initial_balance - expected_credits_charged
)
else:
assert balance_row is None
assert transaction_types == expected_transaction_types
assert [(row["transition_reason"], row["to_state"]) for row in audit_transitions] == [
("start_processing", "running"),
("mark_completed", "done"),
]
def test_should_skip_parse_task_when_the_job_is_already_terminal(
worker_contract_environment: None,
monkeypatch: MonkeyPatch,
tmp_path: Path,
) -> None:
(
kb_tasks,
parse_service,
sync_storage_service,
engine,
sync_job_info_service_cls,
sync_job_metadata_service_cls,
sync_redis_service_factory,
) = _load_parse_task_modules()
user_id: str = f"worker-user-{uuid4().hex[:12]}"
job_id: str = f"job_parse_skipped_{uuid4().hex[:12]}"
source_file_name: str = "contract-skip.pdf"
s3_key: str = f"uploads/{job_id}.pdf"
with engine.begin() as connection:
insert_contract_user(connection, user_id=user_id)
job_metadata = _build_pending_file_job_metadata(source_file_name)
insert_contract_job(
connection,
job_id=job_id,
user_id=user_id,
s3_key=s3_key,
status="done",
source_type="file",
webhook_enabled=False,
job_metadata=job_metadata,
billing_status="charged",
)
redis_service = _save_worker_task_cache(
job_id=job_id,
user_id=user_id,
s3_key=s3_key,
metadata=job_metadata,
sync_job_info_service_cls=sync_job_info_service_cls,
sync_job_metadata_service_cls=sync_job_metadata_service_cls,
sync_redis_service_factory=sync_redis_service_factory,
)
_bind_parse_task_to_current_module(monkeypatch, kb_tasks=kb_tasks)
monkeypatch.setattr(kb_tasks.settings, "TMP_PATH", str(tmp_path))
def fake_verify_s3_file_exists(storage_key: str) -> dict[str, Any]:
return {"exists": storage_key == s3_key, "size": 1024}
monkeypatch.setattr(kb_tasks, "verify_s3_file_exists", fake_verify_s3_file_exists)
monkeypatch.setattr(
sync_storage_service,
"verify_s3_file_exists",
fake_verify_s3_file_exists,
)
monkeypatch.setattr(
kb_tasks,
"generate_download_url",
lambda *_args, **_kwargs: (_ for _ in ()).throw(
AssertionError("terminal parse task should not request a download URL")
),
)
monkeypatch.setattr(
parse_service,
"checkerboard_inject_parse",
lambda **_kwargs: (_ for _ in ()).throw(
AssertionError("terminal parse task should not invoke the parser")
),
)
result = kb_tasks.parse_task.run(job_id, user_id, "kb_management")
assert result == {
"status": "skipped",
"job_id": job_id,
"reason": "job_already_terminal",
}
assert redis_service.hgetall(f"task:{job_id}:progress") == {}
assert _find_task_workspaces(tmp_path, job_id) == []
with engine.begin() as connection:
job_result_count = int(
connection.execute(
text("SELECT COUNT(*) FROM job_results WHERE job_id = :job_id"),
{"job_id": job_id},
).scalar_one()
)
audit_transition_count = int(
connection.execute(
text(
"SELECT COUNT(*) FROM job_state_audit_logs WHERE job_id = :job_id"
),
{"job_id": job_id},
).scalar_one()
)
assert job_result_count == 0
assert audit_transition_count == 0
def test_should_mark_the_job_failed_and_cleanup_the_workspace_when_parse_execution_raises(
worker_contract_environment: None,
monkeypatch: MonkeyPatch,
tmp_path: Path,
) -> None:
(
kb_tasks,
parse_service,
sync_storage_service,
engine,
sync_job_info_service_cls,
sync_job_metadata_service_cls,
sync_redis_service_factory,
) = _load_parse_task_modules()
user_id: str = f"worker-user-{uuid4().hex[:12]}"
job_id: str = f"job_parse_failure_{uuid4().hex[:12]}"
source_file_name: str = "contract-failure.pdf"
s3_key: str = f"uploads/{job_id}.pdf"
with engine.begin() as connection:
insert_contract_user(connection, user_id=user_id)
job_metadata = _build_pending_file_job_metadata(source_file_name)
insert_contract_job(
connection,
job_id=job_id,
user_id=user_id,
status="pending",
source_type="file",
s3_key=s3_key,
webhook_enabled=False,
job_metadata=job_metadata,
billing_status="pending",
)
_save_worker_task_cache(
job_id=job_id,
user_id=user_id,
s3_key=s3_key,
metadata=job_metadata,
sync_job_info_service_cls=sync_job_info_service_cls,
sync_job_metadata_service_cls=sync_job_metadata_service_cls,
sync_redis_service_factory=sync_redis_service_factory,
)
_bind_parse_task_to_current_module(monkeypatch, kb_tasks=kb_tasks)
monkeypatch.setattr(kb_tasks.settings, "TMP_PATH", str(tmp_path))
def fake_verify_s3_file_exists(storage_key: str) -> dict[str, Any]:
return {
"exists": storage_key == s3_key,
"size": _SAMPLE_PDF_PATH.stat().st_size,
}
def fake_generate_download_url(storage_key: str, bucket: str | None) -> dict[str, str]:
return {"download_url": f"https://example.test/{storage_key}"}
monkeypatch.setattr(kb_tasks, "verify_s3_file_exists", fake_verify_s3_file_exists)
monkeypatch.setattr(
sync_storage_service,
"verify_s3_file_exists",
fake_verify_s3_file_exists,
)
monkeypatch.setattr(kb_tasks, "generate_download_url", fake_generate_download_url)
monkeypatch.setattr(
sync_storage_service,
"generate_download_url",
fake_generate_download_url,
)
def fake_download_s3_file_to_temp(
file_url: str, file_ext: str, temp_dir: str
) -> str:
downloaded_path = Path(temp_dir) / f"downloaded{file_ext}"
shutil.copy2(_SAMPLE_PDF_PATH, downloaded_path)
return str(downloaded_path)
monkeypatch.setattr(kb_tasks, "download_s3_file_to_temp", fake_download_s3_file_to_temp)
monkeypatch.setattr(
parse_service,
"checkerboard_inject_parse",
lambda **_kwargs: (_ for _ in ()).throw(RuntimeError("parse failed")),
)
monkeypatch.setattr(
kb_tasks,
"get_result_storage",
lambda: (_ for _ in ()).throw(
AssertionError("result storage should not run after parser failure")
),
)
result = kb_tasks.parse_task.apply(
args=[job_id, user_id, "kb_management"],
throw=False,
)
assert result.status == "FAILURE"
assert _find_task_workspaces(tmp_path, job_id) == []
expected_credits_charged = 3 * int(kb_tasks.settings.MICRO_DOLLARS_PER_PAGE)
expected_initial_balance = int(kb_tasks.settings.FREE_PLAN_INITIAL_CREDITS) * 1_000_000
with engine.begin() as connection:
job_row = (
connection.execute(
text(
"""
SELECT status, billing_status, page_count, credits_charged, error_code, error_message
FROM jobs
WHERE job_id = :job_id
"""
),
{"job_id": job_id},
)
.mappings()
.one()
)
balance_row = (
connection.execute(
text(
"""
SELECT credits_balance
FROM user_balances
WHERE user_id = :user_id
"""
),
{"user_id": user_id},
)
.mappings()
.one()
)
transaction_types = list(
connection.execute(
text(
"""
SELECT transaction_type
FROM credits_transactions
WHERE user_id = :user_id
ORDER BY created_at ASC
"""
),
{"user_id": user_id},
)
.scalars()
.all()
)
audit_transitions = list(
connection.execute(
text(
"""
SELECT transition_reason, to_state
FROM job_state_audit_logs
WHERE job_id = :job_id
ORDER BY created_at ASC
"""
),
{"job_id": job_id},
)
.mappings()
.all()
)
assert job_row["status"] == "failed"
assert job_row["billing_status"] == "refunded"
assert job_row["page_count"] == 3
assert job_row["credits_charged"] == expected_credits_charged
assert job_row["error_code"] == "UNKNOWN"
assert job_row["error_message"] == "An unexpected error occurred"
assert balance_row["credits_balance"] == expected_initial_balance
assert transaction_types == ["initial_grant", "usage", "refund"]
assert [(row["transition_reason"], row["to_state"]) for row in audit_transitions] == [
("start_processing", "running"),
("mark_failed", "failed"),
]