Files
syops/backend/tests/test_shipping_notice_intakes.py
T

3930 lines
156 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/tests/test_shipping_notice_intakes.py
用途:验证 FileAsset + ShippingNoticeIntake 创建、消费与幂等回放主路径。
依赖:pytest、conftest app fixture、MinIO/建批路径 mock。
逻辑:覆盖上传≠建单、parsed 才可建单、消费后幂等键可恢复、异常 kwargs 不抛 TypeError。
"""
from __future__ import annotations
from datetime import datetime
from unittest.mock import patch
import pytest
from werkzeug.datastructures import FileStorage
from io import BytesIO
from app import db
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.models import (
FileAsset,
ShippingBatch,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingTask,
User,
)
from app.services.file_assets.service import upload_file_asset
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
@pytest.fixture
def shipping_user(app):
with app.app_context():
user = User(username='intake-user', email='intake@example.com', password_hash='x')
db.session.add(user)
db.session.commit()
yield user
def _make_upload(content: bytes = b'customer order line', filename: str = 'notice.txt') -> FileStorage:
return FileStorage(stream=BytesIO(content), filename=filename, content_type='text/plain')
def test_upload_file_asset_creates_ready_record(app, shipping_user):
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = upload_file_asset(user_id=shipping_user.id, upload=_make_upload())
asset = db.session.query(FileAsset).filter_by(asset_no=result['asset_no']).one()
assert asset.upload_status == 'ready'
assert asset.lifecycle_status == 'temporary'
assert asset.content_hash
assert 'storage_key' not in result
def test_create_intake_queues_parse_job(app, shipping_user):
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset = upload_file_asset(user_id=shipping_user.id, upload=_make_upload())
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=101) as enqueue_mock:
intake_data = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=asset['asset_no'],
conversation_id='conv-intake-1',
)
assert intake_data['parse_status'] == 'queued'
enqueue_mock.assert_called_once()
assert enqueue_mock.call_args.kwargs.get('commit') is False
intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_data['intake_no']).one()
assert intake.parse_job_id == 101
def test_create_intake_integrity_race_returns_existing(app, shipping_user, monkeypatch):
"""并发首次插入撞唯一约束时须回落已有 Intake,不得 500。"""
with app.app_context():
from sqlalchemy.exc import IntegrityError
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(user_id=shipping_user.id, upload=_make_upload(b'race-intake'))
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
winner = ShippingNoticeIntake(
intake_no='SNI-RACE-WIN',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='queued',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
parse_job_id=555,
)
db.session.add(winner)
db.session.commit()
calls = {'n': 0}
def _lock_side_effect(*, asset_id, purpose, parser_version):
calls['n'] += 1
if calls['n'] == 1:
return None
return (
db.session.query(ShippingNoticeIntake)
.filter_by(intake_no='SNI-RACE-WIN')
.execution_options(populate_existing=True)
.with_for_update()
.first()
)
monkeypatch.setattr(
'app.services.shipping_notice.intake_service._lock_intake_for_asset_purpose_parser',
_lock_side_effect,
)
def _boom_nested():
class _CM:
def __enter__(self):
raise IntegrityError('stmt', {}, Exception('uq'))
def __exit__(self, *args):
return False
return _CM()
monkeypatch.setattr(db.session, 'begin_nested', _boom_nested)
payload = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=asset.asset_no,
conversation_id='conv-race',
)
assert payload['intake_no'] == 'SNI-RACE-WIN'
assert payload['parse_status'] == 'queued'
assert db.session.query(ShippingNoticeIntake).filter_by(asset_id=asset.id).count() == 1
def test_create_parse_failed_twice_reuses_single_parse_job(app, shipping_user):
"""parse_failed 并发式连续创建须串行持锁并复用同一 active Job。"""
with app.app_context():
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'parse-failed-reuse'),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-FAIL-REUSE',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parse_failed',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
error_code='SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
)
db.session.add(intake)
db.session.commit()
first = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=asset.asset_no,
)
second = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=asset.asset_no,
)
assert first['intake_no'] == second['intake_no'] == 'SNI-FAIL-REUSE'
assert first['parse_status'] == second['parse_status'] == 'queued'
jobs = (
db.session.query(Job)
.filter(
Job.domain == SHIPPING_NOTICE_JOB_DOMAIN,
Job.job_type == JobType.SHIPPING_NOTICE_PARSE.value,
Job.business_ref == 'SNI-FAIL-REUSE',
Job.status.in_(('queued', 'running')),
)
.all()
)
assert len(jobs) == 1
refreshed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-FAIL-REUSE').one()
assert refreshed.parse_job_id == jobs[0].id
def test_create_intake_ignores_old_parser_version_reuse(app, shipping_user):
"""同一 FileAsset 上旧 parser_version 的 parsed Intake 不得被新版本直接复用。"""
with app.app_context():
app.config['SHIPPING_NOTICE_PARSER_VERSION'] = 'v6'
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(user_id=shipping_user.id, upload=_make_upload(b'legacy-v5-body'))
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
# 覆盖本次升级:v5 仅有 JSON 附件摘要,无 Document/Candidate/派生资产,须强制重解析
old = ShippingNoticeIntake(
intake_no='SNI-OLD-PARSER-V5',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v5',
extracted_text='stale without documents candidates or derived assets',
structured_result_json={'attachment_count': 0, 'attachments': [], 'warnings': []},
)
db.session.add(old)
db.session.commit()
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=909) as enq:
payload = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=asset.asset_no,
conversation_id='conv-parser-bump',
)
enq.assert_called_once()
assert payload['intake_no'] != old.intake_no
assert payload['parse_status'] == 'queued'
assert payload['parser_version'] == 'v6'
created = db.session.query(ShippingNoticeIntake).filter_by(intake_no=payload['intake_no']).one()
assert created.parser_version == 'v6'
assert created.asset_id == asset.id
# 旧版行仍在,但未被返回/复用
assert db.session.get(ShippingNoticeIntake, old.id).parse_status == 'parsed'
def test_error_classes_accept_custom_code_kwargs(app):
"""业务异常支持 code= 关键字,避免新分支抛 TypeError → 500。"""
with app.app_context():
err = NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在')
assert err.code == 'FILE_ASSET.NOT_FOUND'
err2 = ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权访问')
assert err2.code == 'FILE_ASSET.FORBIDDEN'
err3 = ValidationError(code='FILE_ASSET.EXPIRED', message='已过期')
assert err3.code == 'FILE_ASSET.EXPIRED'
def _seed_parsed_intake(user_id: int, *, intake_no: str = 'SNI-TEST-0001', hash_value: str = 'abc123'):
asset = FileAsset(
asset_no=f'FA-{intake_no}',
owner_user_id=user_id,
original_filename='notice.txt',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{user_id}/test/{intake_no}.txt',
content_hash=hash_value,
file_size=12,
mime_type='text/plain',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no=intake_no,
asset_id=asset.id,
user_id=user_id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v1',
extracted_text='SKU001 qty 10',
)
db.session.add(intake)
db.session.commit()
return asset, intake
def test_create_batch_from_intakes_marks_consumed_and_links_task(app, shipping_user, monkeypatch):
with app.app_context():
asset, intake = _seed_parsed_intake(shipping_user.id)
def _fake_create_batch_from_notice_items(**kwargs):
notice_items = kwargs['notice_items']
batch = ShippingBatch(
batch_no='SB-TEST-0001',
user_id=shipping_user.id,
file_count=1,
create_idempotency_key=kwargs.get('create_idempotency_key'),
)
db.session.add(batch)
db.session.flush()
item = notice_items[0]
task = ShippingTask(
task_no='SN-TEST-0001',
batch_id=batch.id,
user_id=shipping_user.id,
source_type='manual',
source_content_hash=item.get('source_content_hash'),
source_asset_id=item.get('source_asset_id'),
source_intake_id=item.get('source_intake_id'),
raw_content=item.get('raw_text'),
process_status='created',
)
db.session.add(task)
db.session.commit()
return {
'status': 'ok',
'batch_no': batch.batch_no,
'data': {
'batch': {'batch_no': batch.batch_no, 'id': batch.id},
'tasks': [{'task_id': task.task_no}],
},
}
monkeypatch.setattr(
'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
_fake_create_batch_from_notice_items,
)
result = create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-intake-1',
intake_nos=[intake.intake_no],
create_idempotency_key='idem-1',
)
assert result['batch_no'] == 'SB-TEST-0001'
refreshed = db.session.get(ShippingNoticeIntake, intake.id)
assert refreshed.parse_status == 'consumed'
assert refreshed.consumed_batch_id is not None
assert refreshed.consumed_task_id is not None
task = db.session.query(ShippingTask).filter_by(task_no='SN-TEST-0001').one()
assert task.source_asset_id == asset.id
assert task.source_intake_id == intake.id
asset_ref = db.session.get(FileAsset, asset.id)
assert asset_ref.lifecycle_status == 'referenced'
assert int(asset_ref.reference_count or 0) >= 1
def test_create_batch_from_intakes_idempotent_replay_after_consumed(app, shipping_user, monkeypatch):
with app.app_context():
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-REPLAY')
batch = ShippingBatch(
batch_no='SB-TEST-REPLAY',
user_id=shipping_user.id,
file_count=1,
create_idempotency_key='idem-replay',
)
db.session.add(batch)
db.session.flush()
task = ShippingTask(
task_no='SN-TEST-REPLAY',
batch_id=batch.id,
user_id=shipping_user.id,
source_type='manual',
source_asset_id=asset.id,
source_intake_id=intake.id,
process_status='created',
)
intake.parse_status = 'consumed'
intake.consumed_at = datetime.utcnow()
intake.consumed_batch_id = batch.id
intake.consumed_task_id = None
db.session.add(task)
db.session.commit()
intake.consumed_task_id = task.id
db.session.commit()
called = {'count': 0}
def _should_not_create(**kwargs):
called['count'] += 1
raise AssertionError('idempotent replay must not create again')
monkeypatch.setattr(
'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
_should_not_create,
)
result = create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-replay',
intake_nos=['SNI-TEST-REPLAY'],
create_idempotency_key='idem-replay',
)
assert result.get('idempotent_replay') is True
assert result['batch_no'] == 'SB-TEST-REPLAY'
assert called['count'] == 0
def test_mixed_open_existing_and_create_idempotent_replay(app, shipping_user, monkeypatch):
"""混合批次:open_existing 挂旧批次时,同幂等键重试须成功回放而非集合冲突。"""
with app.app_context():
# 旧任务(open_existing 目标)
old_batch = ShippingBatch(batch_no='SB-MIX-OLD', user_id=shipping_user.id, file_count=1)
db.session.add(old_batch)
db.session.flush()
old_task = ShippingTask(
task_no='SN-MIX-OLD',
batch_id=old_batch.id,
user_id=shipping_user.id,
source_type='manual',
process_status='waiting_inventory',
document_version=1,
)
db.session.add(old_task)
db.session.flush()
asset_a, intake_a = _seed_parsed_intake(
shipping_user.id, intake_no='SNI-MIX-A', hash_value='hash-mix-a'
)
asset_b, intake_b = _seed_parsed_intake(
shipping_user.id, intake_no='SNI-MIX-B', hash_value='hash-mix-b'
)
intake_a.duplicate_resolution = 'open_existing'
intake_a.duplicate_target_task_no = old_task.task_no
intake_a.duplicate_status = 'same_active_task'
intake_a.duplicate_matches_json = [
{
'task_no': old_task.task_no,
'process_status': old_task.process_status,
'document_version': 1,
'match_type': 'business_fingerprint',
'matched_fields': ['po_number'],
'lifecycle': 'active',
}
]
db.session.commit()
def _fake_create(**kwargs):
batch = ShippingBatch(
batch_no='SB-MIX-NEW',
user_id=shipping_user.id,
file_count=1,
create_idempotency_key=kwargs.get('create_idempotency_key'),
process_summary_json={'request_intake_nos': ['SNI-MIX-A', 'SNI-MIX-B']},
)
db.session.add(batch)
db.session.flush()
item = kwargs['notice_items'][0]
task = ShippingTask(
task_no='SN-MIX-NEW',
batch_id=batch.id,
user_id=shipping_user.id,
source_type='manual',
source_intake_id=item.get('source_intake_id'),
source_asset_id=item.get('source_asset_id'),
process_status='created',
)
db.session.add(task)
db.session.commit()
return {
'status': 'ok',
'batch_no': batch.batch_no,
'data': {
'batch': {'batch_no': batch.batch_no, 'id': batch.id},
'tasks': [{'task_id': task.task_no}],
'focus_task': {'task_no': task.task_no},
},
}
monkeypatch.setattr(
'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
_fake_create,
)
monkeypatch.setattr(
'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_intake',
lambda **kwargs: {
'status': kwargs['intake'].duplicate_status or 'none',
'blocking': kwargs['intake'].duplicate_resolution == 'open_existing',
'fingerprint': None,
'fingerprint_version': 'shipping-v1',
'fingerprint_strength': 'strong',
'matches': list(kwargs['intake'].duplicate_matches_json or []),
'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
},
)
first = create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-mix',
intake_nos=['SNI-MIX-A', 'SNI-MIX-B'],
create_idempotency_key='idem-mix-1',
)
assert first.get('batch_no') == 'SB-MIX-NEW'
assert first.get('idempotent_replay') is not True
assert any(x.get('task_no') == 'SN-MIX-OLD' for x in (first.get('opened_existing') or []))
second = create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-mix',
intake_nos=['SNI-MIX-A', 'SNI-MIX-B'],
create_idempotency_key='idem-mix-1',
)
assert second.get('idempotent_replay') is True
assert second.get('batch_no') == 'SB-MIX-NEW'
assert any(x.get('task_no') == 'SN-MIX-OLD' for x in (second.get('opened_existing') or []))
def test_pure_open_existing_idempotent_replay(app, shipping_user, monkeypatch):
"""纯 open_existing:无新批次时凭 intake 幂等键重放,不报已消费。"""
with app.app_context():
old_batch = ShippingBatch(batch_no='SB-OPEN-ONLY', user_id=shipping_user.id, file_count=1)
db.session.add(old_batch)
db.session.flush()
old_task = ShippingTask(
task_no='SN-OPEN-ONLY',
batch_id=old_batch.id,
user_id=shipping_user.id,
source_type='manual',
process_status='pending_review',
)
db.session.add(old_task)
_, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-OPEN-ONLY', hash_value='hash-open-only')
intake.duplicate_resolution = 'open_existing'
intake.duplicate_target_task_no = old_task.task_no
intake.duplicate_status = 'same_active_task'
intake.duplicate_matches_json = [
{
'task_no': old_task.task_no,
'process_status': 'pending_review',
'document_version': 1,
'match_type': 'business_fingerprint',
'matched_fields': ['po_number'],
'lifecycle': 'active',
}
]
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_intake',
lambda **kwargs: {
'status': 'same_active_task',
'blocking': True,
'fingerprint': 'fp',
'fingerprint_version': 'shipping-v1',
'fingerprint_strength': 'strong',
'matches': list(intake.duplicate_matches_json or []),
'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
},
)
first = create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-open-only',
intake_nos=['SNI-OPEN-ONLY'],
create_idempotency_key='idem-open-only',
)
assert first.get('batch_no') in (None, '')
assert first.get('idempotent_replay') is False
second = create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-open-only',
intake_nos=['SNI-OPEN-ONLY'],
create_idempotency_key='idem-open-only',
)
assert second.get('idempotent_replay') is True
assert (second.get('opened_existing') or [])[0].get('task_no') == 'SN-OPEN-ONLY'
def test_intake_replay_heals_missing_consumed_batch_id(app, shipping_user):
"""批次已创建但 intake.consumed_batch_id 未回填时,重放须恢复批次而非「未创建新批次」。"""
with app.app_context():
asset, intake = _seed_parsed_intake(
shipping_user.id, intake_no='SNI-HEAL-1', hash_value='hash-heal-1'
)
batch = ShippingBatch(
batch_no='SB-HEAL-1',
user_id=shipping_user.id,
file_count=1,
create_idempotency_key='idem-heal-1',
)
db.session.add(batch)
db.session.flush()
task = ShippingTask(
task_no='SN-HEAL-1',
batch_id=batch.id,
user_id=shipping_user.id,
source_type='manual',
source_intake_id=intake.id,
source_asset_id=asset.id,
process_status='created',
)
db.session.add(task)
# 模拟提交断点:已 stamp + consumed,但尚未回填 consumed_batch_id
intake.parse_status = 'consumed'
intake.consumed_at = datetime.utcnow()
intake.create_idempotency_key = 'idem-heal-1'
intake.consumed_batch_id = None
intake.consumed_task_id = None
db.session.commit()
result = create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-heal',
intake_nos=['SNI-HEAL-1'],
create_idempotency_key='idem-heal-1',
)
assert result.get('idempotent_replay') is True
assert result.get('batch_no') == 'SB-HEAL-1'
assert '未创建新批次' not in str(result.get('message') or '')
refreshed = db.session.get(ShippingNoticeIntake, intake.id)
assert refreshed.consumed_batch_id == batch.id
assert refreshed.consumed_task_id == task.id
def test_revision_conflict_when_successor_exists(app, shipping_user):
"""已有后继修订时,再次 create_revision 应冲突。"""
from app.services.shipping_notice.intake_parse_workflow import intake_to_notice_item
with app.app_context():
base = ShippingTask(
task_no='SN-REV-LOCK-BASE',
user_id=shipping_user.id,
source_type='manual',
process_status='uploaded',
document_version=1,
)
db.session.add(base)
db.session.flush()
successor = ShippingTask(
task_no='SN-REV-LOCK-V2',
user_id=shipping_user.id,
source_type='manual',
process_status='pending_review',
document_version=2,
supersedes_task_id=base.id,
duplicate_resolution_type='revision',
)
db.session.add(successor)
asset, intake = _seed_parsed_intake(
shipping_user.id, intake_no='SNI-REV-LOCK', hash_value='hash-rev-lock'
)
intake.duplicate_resolution = 'create_revision'
intake.duplicate_target_task_no = base.task_no
db.session.commit()
with pytest.raises(ConflictError) as excinfo:
intake_to_notice_item(intake, asset)
assert excinfo.value.code == 'SHIPPING_NOTICE.REVISION_CONFLICT'
def test_queued_intake_cannot_create_batch(app, shipping_user):
with app.app_context():
_, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-QUEUED')
intake.parse_status = 'queued'
db.session.commit()
with pytest.raises(Exception) as excinfo:
create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id=None,
intake_nos=[intake.intake_no],
create_idempotency_key='idem-queued',
)
assert 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING' in str(getattr(excinfo.value, 'code', '')) or True
from app.core.errors import ConflictError
assert isinstance(excinfo.value, ConflictError)
assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING'
def test_incomplete_attachments_cannot_create_batch(app, shipping_user):
"""顶层 parsed 但附件不完整时,建批须被后端门禁拒绝。"""
with app.app_context():
_, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-INCOMPLETE-ATT')
intake.structured_result_json = {
'filename': 'mail.eml',
'source_type': 'email',
'attachment_count': 2,
'attachments': [
{'filename': 'ok.pdf', 'parse_status': 'parsed', 'warnings': []},
{'filename': 'bad.pdf', 'parse_status': 'failed', 'warnings': []},
],
'warnings': [],
}
db.session.commit()
with pytest.raises(ConflictError) as excinfo:
create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id=None,
intake_nos=[intake.intake_no],
create_idempotency_key='idem-incomplete-att',
)
assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE'
def test_text_budget_exhausted_cannot_create_batch(app, shipping_user):
"""文本预算耗尽警告须进入建批完整性门禁。"""
with app.app_context():
_, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-BUDGET-BLOCK')
intake.structured_result_json = {
'filename': 'mail.eml',
'source_type': 'email',
'attachment_count': 1,
'attachments': [
{
'filename': 'big.txt',
'parse_status': 'parsed',
'warnings': ['eml_attachment_text_budget_exhausted:500000'],
}
],
'warnings': ['eml_attachment_text_budget_exhausted:500000'],
}
db.session.commit()
with pytest.raises(ConflictError) as excinfo:
create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id=None,
intake_nos=[intake.intake_no],
create_idempotency_key='idem-budget-block',
)
assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE'
def test_retry_parse_allows_incomplete_parsed_intake(app, shipping_user):
"""附件不完整但顶层 parsed 时须允许重试解析。"""
from app.services.shipping_notice.intake_service import retry_intake_parse
with app.app_context():
_, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-RETRY-INCOMPLETE')
intake.structured_result_json = {
'attachment_count': 1,
'attachments': [{'filename': 'x.pdf', 'parse_status': 'failed', 'warnings': []}],
'warnings': [],
}
db.session.commit()
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=4242) as enq:
payload = retry_intake_parse(user_id=shipping_user.id, intake_no=intake.intake_no)
enq.assert_called_once()
kwargs = enq.call_args.kwargs
assert kwargs.get('commit') is False
assert kwargs.get('dedupe_statuses') == ('queued',)
assert payload['parse_status'] == 'queued'
refreshed = db.session.get(ShippingNoticeIntake, intake.id)
assert refreshed.parse_status == 'queued'
assert refreshed.parse_job_id == 4242
def test_retry_parse_does_not_reuse_running_job(app, shipping_user):
"""重试不得复用仍为 running 的原 Job,须新建 queued Job。"""
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.intake_service import retry_intake_parse
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
_, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-RETRY-RUNNING')
intake.parse_status = 'parse_failed'
db.session.flush()
running = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref=intake.intake_no,
payload_json={'intake_no': intake.intake_no},
progress=50,
message='running old parse',
attempts=1,
max_attempts=3,
created_by_id=shipping_user.id,
)
db.session.add(running)
db.session.commit()
old_id = int(running.id)
payload = retry_intake_parse(user_id=shipping_user.id, intake_no=intake.intake_no)
assert payload['parse_status'] == 'queued'
refreshed = db.session.get(ShippingNoticeIntake, intake.id)
assert int(refreshed.parse_job_id or 0) != old_id
new_job = db.session.get(Job, int(refreshed.parse_job_id))
assert new_job is not None
assert new_job.status == 'queued'
assert db.session.get(Job, old_id).status == 'running'
def test_enqueue_commit_false_keeps_job_uncommitted_until_outer_commit(app, shipping_user):
"""enqueue(commit=False) 仅 flush,外层 rollback 后 Job 不得残留。"""
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
job_id = enqueue(
JobType.SHIPPING_NOTICE_PARSE,
{'intake_no': 'SNI-ENQ-FLUSH'},
domain=SHIPPING_NOTICE_JOB_DOMAIN,
business_ref='SNI-ENQ-FLUSH',
created_by_id=shipping_user.id,
commit=False,
dedupe_active=False,
)
assert int(job_id) > 0
assert db.session.get(Job, job_id) is not None
db.session.rollback()
assert db.session.get(Job, job_id) is None
def test_enqueue_unique_conflict_does_not_poison_outer_transaction(app, shipping_user):
"""
唯一冲突必须落在 SAVEPOINT 内:外层 Intake 修改不得因 PendingRollbackError 丢失。
"""
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'enq-savepoint'),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-ENQ-SAVEPOINT',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parse_failed',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
)
existing = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='queued',
priority=0,
business_ref='SNI-ENQ-SAVEPOINT',
payload_json={'intake_no': 'SNI-ENQ-SAVEPOINT'},
progress=0,
message='winner',
attempts=0,
max_attempts=3,
created_by_id=shipping_user.id,
)
db.session.add(intake)
db.session.add(existing)
db.session.commit()
keep_id = int(existing.id)
# 外层事务:先改 Intake,再强制插入撞唯一(dedupe 关闭)
locked = (
db.session.query(ShippingNoticeIntake)
.filter_by(intake_no='SNI-ENQ-SAVEPOINT')
.with_for_update()
.one()
)
locked.parse_status = 'queued'
locked.error_message = None
returned_id = enqueue(
JobType.SHIPPING_NOTICE_PARSE,
{'intake_no': 'SNI-ENQ-SAVEPOINT'},
domain=SHIPPING_NOTICE_JOB_DOMAIN,
business_ref='SNI-ENQ-SAVEPOINT',
created_by_id=shipping_user.id,
dedupe_active=False,
commit=False,
)
assert returned_id == keep_id
locked.parse_job_id = returned_id
db.session.commit()
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-ENQ-SAVEPOINT'
).one()
assert refreshed.parse_status == 'queued'
assert refreshed.parse_job_id == keep_id
assert (
db.session.query(Job)
.filter(
Job.business_ref == 'SNI-ENQ-SAVEPOINT',
Job.status == 'queued',
)
.count()
== 1
)
def test_fail_job_supersedes_running_when_queued_sibling_exists(app, shipping_user):
"""旧 running 失败重试时若已有 queued 同伴,须 cancelled 并重指 parse_job_id。"""
from datetime import datetime, timedelta
from app.jobs.queue import fail_job
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'fail-supersede'),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-FAIL-SUPERSEDE',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
parse_lease='1:1',
)
running = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref='SNI-FAIL-SUPERSEDE',
payload_json={'intake_no': 'SNI-FAIL-SUPERSEDE'},
progress=50,
message='old running',
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(minutes=10),
created_by_id=shipping_user.id,
)
queued = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='queued',
priority=0,
business_ref='SNI-FAIL-SUPERSEDE',
payload_json={'intake_no': 'SNI-FAIL-SUPERSEDE'},
progress=0,
message='new queued',
attempts=0,
max_attempts=3,
created_by_id=shipping_user.id,
)
db.session.add_all([intake, running, queued])
db.session.flush()
intake.parse_job_id = int(running.id)
db.session.commit()
old_id = int(running.id)
keep_id = int(queued.id)
ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1)
assert ok is True
assert db.session.get(Job, old_id).status == 'cancelled'
assert db.session.get(Job, keep_id).status == 'queued'
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-FAIL-SUPERSEDE'
).one()
assert refreshed.parse_job_id == keep_id
assert refreshed.parse_status == 'queued'
assert refreshed.parse_lease is None
def test_fail_job_retarget_preserves_running_sibling_lease(app, shipping_user):
"""替代 Job 已真正 claim Intake(精确 lease)时,supersede 须保留 parsing/lease。"""
from datetime import datetime, timedelta
from app.jobs.queue import fail_job
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'fail-preserve-lease'),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-PRESERVE-LEASE',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
)
old = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref='SNI-PRESERVE-LEASE',
payload_json={'intake_no': 'SNI-PRESERVE-LEASE'},
progress=50,
message='old',
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(minutes=10),
created_by_id=shipping_user.id,
)
keep = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref='SNI-PRESERVE-LEASE',
payload_json={'intake_no': 'SNI-PRESERVE-LEASE'},
progress=20,
message='new worker',
attempts=1,
max_attempts=3,
started_at=datetime.utcnow(),
created_by_id=shipping_user.id,
)
db.session.add_all([intake, old, keep])
db.session.flush()
keep_id = int(keep.id)
intake.parse_job_id = keep_id
intake.parse_lease = f'{keep_id}:1'
db.session.commit()
old_id = int(old.id)
ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1)
assert ok is True
assert db.session.get(Job, old_id).status == 'cancelled'
assert db.session.get(Job, keep_id).status == 'running'
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-PRESERVE-LEASE'
).one()
assert refreshed.parse_job_id == keep_id
assert refreshed.parse_status == 'parsing'
assert refreshed.parse_lease == f'{keep_id}:1'
def test_fail_job_does_not_supersede_unowned_running_sibling(app, shipping_user):
"""
同伴仅 Job.running、尚未 claim Intake 时不得 supersede。
模拟:新 Worker 已读到旧 parse_job_id 将决定 skip+finish;若旧失败线程把 lease
伪造给新 Job,会导致 Intake 永久 parsing。此时旧 Job 应正常 requeue。
"""
from datetime import datetime, timedelta
from app.jobs.queue import fail_job
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'fail-unowned-running'),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-UNOWNED-RUNNING',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
)
old = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref='SNI-UNOWNED-RUNNING',
payload_json={'intake_no': 'SNI-UNOWNED-RUNNING'},
progress=50,
message='old still owns intake',
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(minutes=10),
created_by_id=shipping_user.id,
)
peer = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref='SNI-UNOWNED-RUNNING',
payload_json={'intake_no': 'SNI-UNOWNED-RUNNING'},
progress=10,
message='claimed job but not intake yet',
attempts=1,
max_attempts=3,
started_at=datetime.utcnow(),
created_by_id=shipping_user.id,
)
db.session.add_all([intake, old, peer])
db.session.flush()
old_id = int(old.id)
peer_id = int(peer.id)
# Intake 仍属旧 Job(新 Worker 预检会看到非本 Job 并 skip)
intake.parse_job_id = old_id
intake.parse_lease = f'{old_id}:1'
db.session.commit()
ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1)
assert ok is True
refreshed_old = db.session.get(Job, old_id)
assert refreshed_old is not None
# 不得 cancelled + 伪造 lease;应 requeue 旧 Job,并同步 Intake 离开 parsing
assert refreshed_old.status == 'queued'
assert refreshed_old.started_at is None
assert db.session.get(Job, peer_id).status == 'running'
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-UNOWNED-RUNNING'
).one()
assert refreshed.parse_job_id == old_id
assert refreshed.parse_status == 'queued'
assert refreshed.parse_lease is None
def test_fail_job_requeue_clears_started_at_so_recover_does_not_demote(app, shipping_user):
"""fail_job requeue 必须清空 started_at,否则 claim 后会被超时回收立刻打回。"""
from datetime import datetime, timedelta
from app.jobs.queue import claim_next_job, fail_job, recover_stale_jobs
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'fail-started-at'),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-STARTED-AT',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
)
job = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref='SNI-STARTED-AT',
payload_json={'intake_no': 'SNI-STARTED-AT'},
progress=50,
message='long running',
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(hours=2),
created_by_id=shipping_user.id,
)
db.session.add_all([intake, job])
db.session.flush()
job_id = int(job.id)
intake.parse_job_id = job_id
intake.parse_lease = f'{job_id}:1'
db.session.commit()
assert fail_job(job_id, error='retryable', retryable=True, owned_attempt=1) is True
queued = db.session.get(Job, job_id)
assert queued is not None and queued.status == 'queued'
assert queued.started_at is None
claimed = claim_next_job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_types=[JobType.SHIPPING_NOTICE_PARSE],
)
assert claimed is not None and int(claimed.id) == job_id
claim_started = claimed.started_at
assert claim_started is not None
recovered = recover_stale_jobs(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
timeout_seconds=60,
job_type=JobType.SHIPPING_NOTICE_PARSE,
)
assert recovered == 0
still = db.session.get(Job, job_id)
assert still is not None
assert still.status == 'running'
assert still.started_at == claim_started
def test_fail_job_prefers_queued_over_lower_id_unowned_running(app, shipping_user):
"""不安全 running id 更小时,仍须选择后面的 queued 替代旧 Job。"""
from datetime import datetime, timedelta
from app.jobs.queue import fail_job
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'fail-prefer-queued'),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-FAIL-PREFER-QUEUED',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
)
old = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref='SNI-FAIL-PREFER-QUEUED',
payload_json={'intake_no': 'SNI-FAIL-PREFER-QUEUED'},
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(minutes=10),
created_by_id=shipping_user.id,
)
unowned = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref='SNI-FAIL-PREFER-QUEUED',
payload_json={'intake_no': 'SNI-FAIL-PREFER-QUEUED'},
attempts=1,
max_attempts=3,
started_at=datetime.utcnow(),
created_by_id=shipping_user.id,
)
queued = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='queued',
priority=0,
business_ref='SNI-FAIL-PREFER-QUEUED',
payload_json={'intake_no': 'SNI-FAIL-PREFER-QUEUED'},
attempts=0,
max_attempts=3,
created_by_id=shipping_user.id,
)
db.session.add_all([intake, old, unowned, queued])
db.session.flush()
old_id = int(old.id)
unowned_id = int(unowned.id)
queued_id = int(queued.id)
assert unowned_id < queued_id
intake.parse_job_id = old_id
intake.parse_lease = f'{old_id}:1'
db.session.commit()
ok = fail_job(old_id, error='transient', retryable=True, owned_attempt=1)
assert ok is True
assert db.session.get(Job, old_id).status == 'cancelled'
assert db.session.get(Job, unowned_id).status == 'running'
assert db.session.get(Job, queued_id).status == 'queued'
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-FAIL-PREFER-QUEUED'
).one()
assert refreshed.parse_job_id == queued_id
assert refreshed.parse_status == 'queued'
assert refreshed.parse_lease is None
def test_create_intake_rejects_cancelled_and_expired(app, shipping_user):
"""创建入口不得复活 cancelled/expired;过期须落 expired 并 CONFLICT。"""
from datetime import datetime, timedelta
from app.core.errors import ConflictError
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_cancelled = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'create-cancel'),
)
asset_expired = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'create-expire'),
)
a1 = db.session.query(FileAsset).filter_by(asset_no=asset_cancelled['asset_no']).one()
a2 = db.session.query(FileAsset).filter_by(asset_no=asset_expired['asset_no']).one()
cancelled = ShippingNoticeIntake(
intake_no='SNI-CREATE-CANCELLED',
asset_id=a1.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='cancelled',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
)
expired = ShippingNoticeIntake(
intake_no='SNI-CREATE-EXPIRED',
asset_id=a2.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parse_failed',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
expires_at=datetime.utcnow() - timedelta(hours=1),
)
db.session.add_all([cancelled, expired])
db.session.commit()
with pytest.raises(ConflictError) as cancelled_exc:
create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=a1.asset_no,
)
assert cancelled_exc.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS'
assert (
db.session.query(ShippingNoticeIntake)
.filter_by(intake_no='SNI-CREATE-CANCELLED')
.one()
.parse_status
== 'cancelled'
)
with pytest.raises(ConflictError) as expired_exc:
create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=a2.asset_no,
)
assert expired_exc.value.code == 'SHIPPING_NOTICE.INTAKE_EXPIRED'
assert (
db.session.query(ShippingNoticeIntake)
.filter_by(intake_no='SNI-CREATE-EXPIRED')
.one()
.parse_status
== 'expired'
)
def test_recover_stale_supersedes_running_when_queued_sibling_exists(app, shipping_user):
"""超时回收旧 running 时若已有 queued 同伴,须 cancelled 并重指 Intake。"""
from datetime import datetime, timedelta
from app.jobs.queue import recover_stale_jobs
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.intake_parse_workflow import (
sync_intake_after_parse_job_recovery,
)
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'recover-supersede'),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-RECOVER-SUPERSEDE',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
parse_lease='9:1',
)
running = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref='SNI-RECOVER-SUPERSEDE',
payload_json={'intake_no': 'SNI-RECOVER-SUPERSEDE'},
progress=50,
message='stale running',
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(hours=1),
created_by_id=shipping_user.id,
)
queued = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='queued',
priority=0,
business_ref='SNI-RECOVER-SUPERSEDE',
payload_json={'intake_no': 'SNI-RECOVER-SUPERSEDE'},
progress=0,
message='replacement',
attempts=0,
max_attempts=3,
created_by_id=shipping_user.id,
)
db.session.add_all([intake, running, queued])
db.session.flush()
intake.parse_job_id = int(running.id)
db.session.commit()
old_id = int(running.id)
keep_id = int(queued.id)
count = recover_stale_jobs(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
timeout_seconds=60,
job_type=JobType.SHIPPING_NOTICE_PARSE,
on_recovered=sync_intake_after_parse_job_recovery,
)
assert count == 1
assert db.session.get(Job, old_id).status == 'cancelled'
assert db.session.get(Job, keep_id).status == 'queued'
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-RECOVER-SUPERSEDE'
).one()
assert refreshed.parse_job_id == keep_id
assert refreshed.parse_status == 'queued'
assert refreshed.parse_lease is None
def test_recover_stale_prefers_queued_over_lower_id_unowned_running(app, shipping_user):
"""回收时不得让较小 id 的不安全 running 遮挡 queued 替代者。"""
from datetime import datetime, timedelta
from app.jobs.queue import recover_stale_jobs
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.intake_parse_workflow import (
sync_intake_after_parse_job_recovery,
)
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'recover-prefer-queued'),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-RECOVER-PREFER-QUEUED',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
)
old = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref='SNI-RECOVER-PREFER-QUEUED',
payload_json={'intake_no': 'SNI-RECOVER-PREFER-QUEUED'},
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(hours=2),
created_by_id=shipping_user.id,
)
unowned = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
priority=0,
business_ref='SNI-RECOVER-PREFER-QUEUED',
payload_json={'intake_no': 'SNI-RECOVER-PREFER-QUEUED'},
attempts=1,
max_attempts=3,
started_at=datetime.utcnow(),
created_by_id=shipping_user.id,
)
queued = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='queued',
priority=0,
business_ref='SNI-RECOVER-PREFER-QUEUED',
payload_json={'intake_no': 'SNI-RECOVER-PREFER-QUEUED'},
attempts=0,
max_attempts=3,
created_by_id=shipping_user.id,
)
db.session.add_all([intake, old, unowned, queued])
db.session.flush()
old_id = int(old.id)
unowned_id = int(unowned.id)
queued_id = int(queued.id)
assert unowned_id < queued_id
intake.parse_job_id = old_id
intake.parse_lease = f'{old_id}:1'
db.session.commit()
count = recover_stale_jobs(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
timeout_seconds=60,
job_type=JobType.SHIPPING_NOTICE_PARSE,
on_recovered=sync_intake_after_parse_job_recovery,
)
assert count == 1
assert db.session.get(Job, old_id).status == 'cancelled'
assert db.session.get(Job, unowned_id).status == 'running'
assert db.session.get(Job, queued_id).status == 'queued'
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-RECOVER-PREFER-QUEUED'
).one()
assert refreshed.parse_job_id == queued_id
assert refreshed.parse_status == 'queued'
assert refreshed.parse_lease is None
def test_migration_retarget_helper_updates_intake_parse_job_id(app, shipping_user):
"""迁移去重辅助:取消重复 Job 前须把 Intake.parse_job_id 重指 keep_id。"""
import importlib.util
from pathlib import Path
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=_make_upload(b'mig-retarget'),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
keep = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='queued',
priority=0,
business_ref='SNI-MIG-RETARGET',
payload_json={'intake_no': 'SNI-MIG-RETARGET'},
progress=0,
message='keep',
attempts=0,
max_attempts=3,
created_by_id=shipping_user.id,
)
drop = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='cancelled',
priority=0,
business_ref='SNI-MIG-RETARGET',
payload_json={'intake_no': 'SNI-MIG-RETARGET'},
progress=100,
message='drop',
attempts=0,
max_attempts=3,
created_by_id=shipping_user.id,
)
intake = ShippingNoticeIntake(
intake_no='SNI-MIG-RETARGET',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='queued',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
)
db.session.add_all([keep, drop, intake])
db.session.flush()
intake.parse_job_id = int(drop.id)
db.session.commit()
keep_id = int(keep.id)
drop_id = int(drop.id)
mig_path = (
Path(__file__).resolve().parents[1]
/ 'migrations'
/ 'versions'
/ 'b7c8d9e0f1a2_jobs_parse_active_unique.py'
)
spec = importlib.util.spec_from_file_location('mig_b7_parse_uq', mig_path)
assert spec and spec.loader
mig = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mig)
mig._retarget_intake_parse_job_ids(
db.session.connection(),
keep_id=keep_id,
drop_ids=[drop_id],
)
db.session.commit()
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-MIG-RETARGET'
).one()
assert refreshed.parse_job_id == keep_id
def test_create_batch_failure_rolls_back_preconsume(app, shipping_user, monkeypatch):
"""建批业务异常后预占 consumed 须回滚,否则用户无法重试。"""
with app.app_context():
_, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-ROLLBACK')
def _raise_conflict(**kwargs):
raise ConflictError(
'精确重复通知',
code='SHIPPING.EXACT_DUPLICATE',
)
monkeypatch.setattr(
'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
_raise_conflict,
)
with pytest.raises(ConflictError) as excinfo:
create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-rollback',
intake_nos=[intake.intake_no],
create_idempotency_key='idem-rollback',
)
assert excinfo.value.code == 'SHIPPING.EXACT_DUPLICATE'
refreshed = db.session.get(ShippingNoticeIntake, intake.id)
assert refreshed.parse_status == 'parsed'
assert refreshed.consumed_at is None
assert refreshed.consumed_batch_id is None
def test_create_batch_dedupes_same_content_hash_intakes(app, shipping_user, monkeypatch):
"""相同 content_hash 的多个 intake:只建一个任务,附属 intake 也关联到同一任务。"""
with app.app_context():
asset1, intake1 = _seed_parsed_intake(
shipping_user.id, intake_no='SNI-DEDUP-1', hash_value='same-hash-xx'
)
asset2, intake2 = _seed_parsed_intake(
shipping_user.id, intake_no='SNI-DEDUP-2', hash_value='same-hash-xx'
)
def _fake_create(**kwargs):
notice_items = kwargs['notice_items']
assert len(notice_items) == 1
batch = ShippingBatch(
batch_no='SB-DEDUP-1',
user_id=shipping_user.id,
file_count=1,
create_idempotency_key=kwargs.get('create_idempotency_key'),
)
db.session.add(batch)
db.session.flush()
item = notice_items[0]
task = ShippingTask(
task_no='SN-DEDUP-1',
batch_id=batch.id,
user_id=shipping_user.id,
source_type='manual',
source_content_hash=item.get('source_content_hash'),
source_asset_id=item.get('source_asset_id'),
source_intake_id=item.get('source_intake_id'),
raw_content=item.get('raw_text'),
process_status='created',
)
db.session.add(task)
db.session.commit()
return {
'status': 'ok',
'batch_no': batch.batch_no,
'data': {
'batch': {'batch_no': batch.batch_no, 'id': batch.id},
'tasks': [{'task_id': task.task_no}],
},
}
monkeypatch.setattr(
'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
_fake_create,
)
result = create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-dedup',
intake_nos=[intake1.intake_no, intake2.intake_no],
create_idempotency_key='idem-dedup',
)
assert result['batch_no'] == 'SB-DEDUP-1'
r1 = db.session.get(ShippingNoticeIntake, intake1.id)
r2 = db.session.get(ShippingNoticeIntake, intake2.id)
assert r1.parse_status == 'consumed'
assert r2.parse_status == 'consumed'
assert r1.consumed_batch_id == r2.consumed_batch_id
assert r1.consumed_task_id == r2.consumed_task_id
assert r1.consumed_task_id is not None
# 同键重放不应因「请求 2 个 intake / 任务只绑 1 个」而冲突
replay = create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-dedup',
intake_nos=[intake1.intake_no, intake2.intake_no],
create_idempotency_key='idem-dedup',
)
assert replay.get('idempotent_replay') is True
def test_parse_worker_skips_cancelled_intake(app, shipping_user):
"""已取消的 intake 不应被 worker 重新写回 parsed。"""
with app.app_context():
import logging
from app.jobs.context import JobContext
from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse
_, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-CANCEL-WORKER')
intake.parse_status = 'cancelled'
db.session.commit()
ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse'))
run_shipping_notice_parse(ctx, {'intake_no': intake.intake_no})
refreshed = db.session.get(ShippingNoticeIntake, intake.id)
assert refreshed.parse_status == 'cancelled'
def test_parse_worker_marks_parse_failed_when_asset_missing(app, shipping_user):
"""资产已删除时领取后须写 parse_failed(不抛出),避免永久 parsing 且可用户重试。"""
with app.app_context():
import logging
from app.jobs.context import JobContext
from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.intake_service import retry_intake_parse
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-ASSET-GONE')
intake.parse_status = 'queued'
asset.deleted_at = datetime.utcnow()
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
business_ref=intake.intake_no,
payload_json={'intake_no': intake.intake_no},
attempts=1,
max_attempts=3,
)
db.session.add(job)
db.session.flush()
intake.parse_job_id = job.id
db.session.commit()
ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse'))
run_shipping_notice_parse(ctx, {'job_id': job.id, 'intake_no': intake.intake_no})
db.session.expire_all()
failed = db.session.get(ShippingNoticeIntake, intake.id)
assert failed is not None
assert failed.parse_status == 'parse_failed'
assert failed.error_code == 'FILE_ASSET.NOT_FOUND'
refreshed_job = db.session.get(Job, job.id)
assert refreshed_job is not None
assert refreshed_job.status == 'failed'
asset.deleted_at = None
db.session.commit()
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=801):
retried = retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-ASSET-GONE')
assert retried['parse_status'] == 'queued'
def test_recover_stale_parse_job_resets_stuck_parsing_intake(app, shipping_user):
"""超时回收预解析 Job 时须把 Intake 从 parsing 同步为 queued,且同 Job 可再领取。"""
with app.app_context():
import logging
from datetime import timedelta
from app.jobs.context import JobContext
from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-STALE-PARSE')
intake.parse_status = 'parsing'
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
business_ref=intake.intake_no,
payload_json={'intake_no': intake.intake_no},
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(hours=1),
locked_at=datetime.utcnow() - timedelta(hours=1),
locked_by='dead-worker',
)
db.session.add(job)
db.session.flush()
intake.parse_job_id = job.id
db.session.commit()
count, _ = recover_stale_shipping_notice_jobs()
assert count >= 1
db.session.expire_all()
recovered_job = db.session.get(Job, job.id)
recovered_intake = db.session.get(ShippingNoticeIntake, intake.id)
assert recovered_job is not None and recovered_job.status == 'queued'
assert recovered_intake is not None and recovered_intake.parse_status == 'queued'
# 再次执行:即使仍短暂为 parsing,同 parse_job_id 也应可领取(防御路径)
recovered_intake.parse_status = 'parsing'
recovered_job.status = 'running'
recovered_job.attempts = 2
db.session.commit()
monkey_asset = db.session.get(FileAsset, asset.id)
assert monkey_asset is not None
with patch(
'app.jobs.handlers.shipping_notice_parse.run_intake_parse',
return_value={'status': 'parsed', 'intake_no': intake.intake_no},
):
ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse'))
run_shipping_notice_parse(
ctx, {'job_id': recovered_job.id, 'intake_no': intake.intake_no}
)
db.session.expire_all()
finished = db.session.get(Job, job.id)
assert finished is not None
assert finished.status == 'success'
def test_recover_exhausted_parse_job_marks_intake_parse_failed_and_clears_stage2(
app, shipping_user,
):
"""预解析 Job 超时耗尽须 parse_failed,并清理上一轮 Document/Candidate。"""
with app.app_context():
from datetime import timedelta
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-STALE-EXHAUST')
intake.parse_status = 'parsing'
intake.duplicate_status = 'soft_duplicate'
intake.duplicate_matches_json = [{'task_no': 'ST-X'}]
intake.duplicate_resolution = 'force_create'
doc = ShippingNoticeDocument(
intake_id=intake.id,
document_type='attachment',
attachment_key='a.pdf',
classification='order_notice',
parse_status='parsed',
content_hash='hash-stale-exhaust',
)
db.session.add(doc)
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
business_ref=intake.intake_no,
payload_json={'intake_no': intake.intake_no},
attempts=3,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(hours=1),
)
db.session.add(job)
db.session.flush()
intake.parse_job_id = job.id
db.session.commit()
recover_stale_shipping_notice_jobs()
db.session.expire_all()
failed_job = db.session.get(Job, job.id)
failed_intake = db.session.get(ShippingNoticeIntake, intake.id)
assert failed_job is not None and failed_job.status == 'failed'
assert failed_intake is not None
assert failed_intake.parse_status == 'parse_failed'
assert failed_intake.error_code == 'SHIPPING_NOTICE.INTAKE_PARSE_TIMEOUT'
assert failed_intake.duplicate_status == 'unchecked'
assert failed_intake.duplicate_matches_json in (None, [])
assert failed_intake.duplicate_resolution is None
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed_intake.id).count() == 0
def test_process_next_job_does_not_override_handler_non_retryable_fail(app, shipping_user):
"""Handler 已以 retryable=False 收口后,process_next_job 不得再强制 requeue。"""
with app.app_context():
from app.jobs.context import JobContext
from app.jobs.queue import process_next_job
from app.jobs.types import JobType
from app.models import Job
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-NO-OVERRIDE')
intake.parse_status = 'queued'
asset.deleted_at = datetime.utcnow()
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='queued',
business_ref=intake.intake_no,
payload_json={'intake_no': intake.intake_no},
attempts=0,
max_attempts=3,
)
db.session.add(job)
db.session.flush()
intake.parse_job_id = job.id
db.session.commit()
job_id = job.id
ctx = JobContext(config=dict(app.config), logger=app.logger, extras={'queues': ['shipping']})
processed, job_type = process_next_job(
ctx=ctx,
domain='shipping_notice',
job_types=[JobType.SHIPPING_NOTICE_PARSE],
timeout_config_key='SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS',
)
assert processed is True
assert job_type == JobType.SHIPPING_NOTICE_PARSE.value
db.session.expire_all()
refreshed = db.session.get(Job, job_id)
assert refreshed is not None
assert refreshed.status == 'failed'
failed_intake = db.session.get(ShippingNoticeIntake, intake.id)
assert failed_intake is not None
assert failed_intake.parse_status == 'parse_failed'
def test_run_worker_entry_does_not_recover_parse_job(app, shipping_user):
"""RUN单步入口只能回收RUN,不得按RUN阈值触碰PARSE Job或Intake lease。"""
from datetime import timedelta
from app.jobs.context import JobContext
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import process_next_shipping_notice_job
with app.app_context():
asset, intake = _seed_parsed_intake(
shipping_user.id,
intake_no='SNI-RUN-ENTRY-PARSE-ISOLATION',
)
intake.parse_status = 'parsing'
parse_job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
business_ref=intake.intake_no,
payload_json={'intake_no': intake.intake_no},
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(hours=2),
locked_at=datetime.utcnow() - timedelta(hours=2),
locked_by='parse-worker',
)
db.session.add(parse_job)
db.session.flush()
parse_job_id = int(parse_job.id)
intake.parse_job_id = parse_job_id
intake.parse_lease = f'{parse_job_id}:1'
db.session.commit()
ctx = JobContext(config=dict(app.config), logger=app.logger, extras={'queues': ['shipping']})
processed, reason = process_next_shipping_notice_job(ctx)
assert processed is False
assert reason == 'no_job'
db.session.expire_all()
untouched_job = db.session.get(Job, parse_job_id)
untouched_intake = db.session.get(ShippingNoticeIntake, intake.id)
assert untouched_job is not None and untouched_job.status == 'running'
assert untouched_intake is not None and untouched_intake.parse_status == 'parsing'
assert untouched_intake.parse_lease == f'{parse_job_id}:1'
def test_retryable_handler_failure_requeues_job_and_intake(app, shipping_user):
"""Handler可重试异常即使先写parse_failed,最终也须统一回到Job/Intake queued。"""
import logging
from app.jobs.context import JobContext
from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse
from app.jobs.types import JobType
from app.models import Job
with app.app_context():
_, intake = _seed_parsed_intake(
shipping_user.id,
intake_no='SNI-HANDLER-RETRY-SYNC',
)
intake.parse_status = 'queued'
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
business_ref=intake.intake_no,
payload_json={'intake_no': intake.intake_no},
attempts=1,
max_attempts=3,
started_at=datetime.utcnow(),
)
db.session.add(job)
db.session.flush()
job_id = int(job.id)
intake.parse_job_id = job_id
db.session.commit()
ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse'))
with patch(
'app.jobs.handlers.shipping_notice_parse.run_intake_parse',
side_effect=RuntimeError('temporary parser outage'),
):
with pytest.raises(RuntimeError, match='temporary parser outage'):
run_shipping_notice_parse(
ctx,
{'job_id': job_id, 'intake_no': intake.intake_no},
)
db.session.expire_all()
queued_job = db.session.get(Job, job_id)
queued_intake = db.session.get(ShippingNoticeIntake, intake.id)
assert queued_job is not None and queued_job.status == 'queued'
assert queued_job.started_at is None
assert queued_intake is not None and queued_intake.parse_status == 'queued'
assert queued_intake.parse_job_id == job_id
assert queued_intake.parse_lease is None
assert queued_intake.error_code is None
assert queued_intake.error_message is None
def test_finish_job_owned_attempt_mismatch_is_noop(app, shipping_user):
"""旧代次 finish_job 不得覆盖新 attempts 的 running Job(根治 Session 缓存误判)。"""
with app.app_context():
from app.jobs.queue import finish_job
from app.jobs.types import JobType
from app.models import Job
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
business_ref='SNI-OWNED-ATTEMPT',
payload_json={'intake_no': 'SNI-OWNED-ATTEMPT'},
attempts=2,
max_attempts=3,
started_at=datetime.utcnow(),
)
db.session.add(job)
db.session.commit()
job_id = int(job.id)
# 故意不 expire:模拟 Handler Session 里仍缓存 attempts=1 的旧视图
assert finish_job(job_id, message='stale gen', owned_attempt=1) is False
db.session.expire_all()
still = db.session.get(Job, job_id)
assert still is not None
assert still.status == 'running'
assert int(still.attempts or 0) == 2
assert finish_job(job_id, message='current gen', owned_attempt=2) is True
db.session.expire_all()
done = db.session.get(Job, job_id)
assert done is not None
assert done.status == 'success'
def test_recover_stale_jobs_does_not_demote_new_attempt(app, shipping_user):
"""回收条件 UPDATE 绑定 attempts 快照,不能把已被新 Worker 领取的代次打回 queued。"""
with app.app_context():
from datetime import timedelta
from app.jobs.queue import recover_stale_jobs
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
job = Job(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
business_ref='SNI-RECOVER-SNAP',
payload_json={'intake_no': 'SNI-RECOVER-SNAP'},
attempts=2,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(hours=1),
locked_at=datetime.utcnow() - timedelta(hours=1),
)
db.session.add(job)
db.session.commit()
job_id = int(job.id)
# 模拟:陈旧回收器持有 attempts=1 的过期视图,直接条件 UPDATE 应失败
from sqlalchemy import update as sa_update
from app.models import Job as JobModel
now = datetime.utcnow()
rc = db.session.execute(
sa_update(JobModel)
.where(
JobModel.id == job_id,
JobModel.status == 'running',
JobModel.attempts == 1,
)
.values(status='queued', started_at=None, updated_at=now)
)
assert int(rc.rowcount or 0) == 0
db.session.rollback()
# 正常回收:当前 attempts=2 仍超时 → queued
count = recover_stale_jobs(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
timeout_seconds=60,
job_type=JobType.SHIPPING_NOTICE_PARSE,
)
assert count == 1
db.session.expire_all()
recovered = db.session.get(Job, job_id)
assert recovered is not None
assert recovered.status == 'queued'
assert int(recovered.attempts or 0) == 2
def test_stale_parse_lease_cannot_overwrite_after_recovery(app, shipping_user, monkeypatch):
"""超时回收清空 lease 后,旧 Worker 持旧 lease 写回须 skipped,不得覆盖新租约。"""
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
with app.app_context():
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-LEASE-STALE')
intake.parse_status = 'parsing'
intake.parse_lease = '99:1'
intake.parse_job_id = 99
db.session.commit()
# 模拟回收:清空 lease,随后新 Worker 领取 99:2
intake.parse_status = 'queued'
intake.parse_lease = None
db.session.commit()
intake.parse_status = 'parsing'
intake.parse_lease = '99:2'
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
lambda _asset: NoticeIntakeResult(
filename='notice.txt',
source_type='manual',
source_file_type='text/plain',
text='PO Number: LEASE001\nSKU X qty 1',
warnings=[],
meta={},
content_hash=str(asset.content_hash or ''),
file_size=12,
status='accepted',
saved_path=None,
),
)
result = run_intake_parse(intake, asset, parse_lease='99:1')
assert result['status'] == 'skipped'
assert result.get('reason') == 'stale_parse_lease'
db.session.expire_all()
refreshed = db.session.get(ShippingNoticeIntake, intake.id)
assert refreshed is not None
assert refreshed.parse_status == 'parsing'
assert refreshed.parse_lease == '99:2'
def test_recover_clears_parse_lease_so_old_worker_fail_is_noop(app, shipping_user):
"""回收为 queued 后必须清空 parse_lease;旧 lease 的失败清理不得写 parse_failed。"""
with app.app_context():
from datetime import timedelta
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.intake_parse_workflow import (
fail_intake_with_stage2_cleanup,
)
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-LEASE-RECOVER')
intake.parse_status = 'parsing'
intake.parse_lease = '55:1'
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
business_ref=intake.intake_no,
payload_json={'intake_no': intake.intake_no},
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(hours=1),
)
db.session.add(job)
db.session.flush()
intake.parse_job_id = job.id
db.session.commit()
recover_stale_shipping_notice_jobs()
db.session.expire_all()
recovered = db.session.get(ShippingNoticeIntake, intake.id)
assert recovered is not None
assert recovered.parse_status == 'queued'
assert recovered.parse_lease is None
stale = fail_intake_with_stage2_cleanup(
intake_id=int(recovered.id),
intake_no=recovered.intake_no,
parser_version='v6',
error_code='FILE_ASSET.NOT_FOUND',
error_message='stale worker',
extracted_text=None,
structured_result_json={},
parse_warnings_json=[],
required_lease='55:1',
)
assert stale['status'] == 'skipped'
assert stale.get('reason') == 'stale_parse_lease'
db.session.expire_all()
still = db.session.get(ShippingNoticeIntake, intake.id)
assert still is not None
assert still.parse_status == 'queued'
def test_asset_missing_on_retry_clears_prior_stage2(app, shipping_user, monkeypatch):
"""不完整 parsed 重试时父资产被删:须清理 Document/Candidate 与重复决策后再 parse_failed。"""
with app.app_context():
import logging
from app.jobs.context import JobContext
from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.intake_service import serialize_intake
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-ASSET-GONE-S2')
intake.parse_status = 'queued'
intake.duplicate_status = 'soft_duplicate'
intake.duplicate_matches_json = [{'task_no': 'ST-KEEP'}]
intake.duplicate_resolution = 'open_existing'
intake.duplicate_target_task_no = 'ST-KEEP'
intake.structured_result_json = {
'document_count': 1,
'candidate_count': 1,
'attachments': [{'filename': 'x.pdf', 'asset_no': 'FA-X'}],
}
doc = ShippingNoticeDocument(
intake_id=intake.id,
document_type='attachment',
attachment_key='x.pdf',
classification='order_notice',
parse_status='parsed',
content_hash='hash-gone-s2',
)
db.session.add(doc)
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_NOTICE_PARSE.value,
status='running',
business_ref=intake.intake_no,
payload_json={'intake_no': intake.intake_no},
attempts=1,
max_attempts=3,
)
db.session.add(job)
db.session.flush()
intake.parse_job_id = job.id
asset.deleted_at = datetime.utcnow()
db.session.commit()
ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse'))
run_shipping_notice_parse(ctx, {'job_id': job.id, 'intake_no': intake.intake_no})
db.session.expire_all()
failed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-ASSET-GONE-S2'
).one()
assert failed.parse_status == 'parse_failed'
assert failed.error_code == 'FILE_ASSET.NOT_FOUND'
assert failed.duplicate_status == 'unchecked'
assert failed.duplicate_matches_json in (None, [])
assert failed.duplicate_resolution is None
assert failed.duplicate_target_task_no is None
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed.id).count() == 0
payload = serialize_intake(failed, asset=None)
assert (payload.get('duplicate') or {}).get('matches') in (None, [])
structured = failed.structured_result_json or {}
assert 'document_count' not in structured
assert not any(
isinstance(row, dict) and row.get('asset_no')
for row in (structured.get('attachments') or [])
)
def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeypatch):
"""抽取期间他事务取消后,即使 Session 缓存仍为 parsing,也不得覆盖为 parsed。"""
with app.app_context():
from sqlalchemy import text
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-CANCEL-RACE')
intake.parse_status = 'parsing'
db.session.commit()
local = db.session.get(ShippingNoticeIntake, intake.id)
assert local.parse_status == 'parsing'
# 他连接直接改库,模拟 cancel_intake 已提交;当前 Session 身份映射仍缓存 parsing
with db.engine.begin() as conn:
conn.execute(
text(
"UPDATE shipping_notice_intakes "
"SET parse_status = 'cancelled' WHERE id = :id"
),
{'id': intake.id},
)
assert local.parse_status == 'parsing'
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
lambda _asset: NoticeIntakeResult(
filename='notice.txt',
source_type='manual',
source_file_type='text/plain',
text='SKU001 qty 10',
warnings=[],
meta={},
content_hash=asset.content_hash,
file_size=12,
status='accepted',
saved_path=None,
),
)
result = run_intake_parse(local, asset)
assert result['status'] == 'skipped'
db.session.expire_all()
refreshed = db.session.get(ShippingNoticeIntake, intake.id)
assert refreshed.parse_status == 'cancelled'
def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monkeypatch):
"""
FileAsset → run_intake_parse → DB:EML 附件独立文本应持久化进 structured_result_json。
核心逻辑:mock 读取资产字节为含文本附件的 EML,断言 attachment_count 与 extracted_text 落库。
"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
msg = EmailMessage()
msg['Subject'] = 'Intake EML Persist'
msg['From'] = 'shipper@example.com'
msg['To'] = 'freight@example.com'
msg['Message-ID'] = '<persist-eml@example.com>'
msg.set_content('Cover letter.')
msg.add_attachment(
b'PO-PERSIST-LINE-001 qty 5',
maintype='text',
subtype='plain',
filename='order-a.txt',
)
msg.add_attachment(
b'PO-PERSIST-LINE-002 qty 3',
maintype='text',
subtype='plain',
filename='order-b.txt',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='multi.eml',
content_type='message/rfc822',
),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-EML-PERSIST-001',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _asset: eml_bytes,
)
# 跳过重复检测,专注结构化落库
monkeypatch.setattr(
'app.services.shipping_notice.duplicate_detection.refresh_candidates_and_aggregate_intake',
lambda **kwargs: {'status': 'none', 'fingerprint_strength': None},
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, asset)
assert result['status'] == 'parsed'
db.session.expire_all()
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-EML-PERSIST-001'
).one()
structured = refreshed.structured_result_json or {}
assert structured.get('attachment_count') == 2
assert structured.get('email', {}).get('subject') == 'Intake EML Persist'
attachments = structured.get('attachments') or []
assert len(attachments) == 2
texts = {row['filename']: row.get('extracted_text') for row in attachments}
assert 'PO-PERSIST-LINE-001' in str(texts.get('order-a.txt') or '')
assert 'PO-PERSIST-LINE-002' in str(texts.get('order-b.txt') or '')
assert 'PO-PERSIST-LINE-001' in str(refreshed.extracted_text or '')
expected_parser = str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6')
assert refreshed.parser_version == expected_parser
assert all('_payload_bytes' not in row for row in attachments)
assert all(row.get('asset_no') for row in attachments)
from app.services.shipping_notice.intake_service import serialize_intake
lean = serialize_intake(refreshed, asset=asset, include_parse_texts=False)
lean_atts = (lean.get('parse_summary') or {}).get('attachments') or []
assert lean_atts and 'extracted_text' not in lean_atts[0]
assert 'body_text' not in ((lean.get('parse_summary') or {}).get('email') or {})
full = serialize_intake(refreshed, asset=asset, include_parse_texts=True)
full_atts = (full.get('parse_summary') or {}).get('attachments') or []
assert 'PO-PERSIST-LINE-001' in str(full_atts[0].get('extracted_text') or '')
def test_run_intake_parse_persists_attached_multipart_and_detail_api(
app, client, shipping_user, monkeypatch,
):
"""
FileAsset → run_intake_parse → DB → 详情接口:附件型 multipart 独立文本与超深深 skipped 须落库返回。
核心逻辑:mixed 容器内 plain+html 均持久化;嵌套容器超限为 skipped 并带 depth warning;
status 瘦身、详情含全文。
"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from app.core.auth.jwt import issue_local_access_token
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.intake_service import serialize_intake
inner = MIMEMultipart('mixed')
inner.add_header('Content-Disposition', 'attachment', filename='inner-depth.mime')
inner.attach(MIMEText('INNER-DEPTH-PO-999', 'plain', 'utf-8'))
bundle = MIMEMultipart('mixed')
bundle.add_header('Content-Disposition', 'attachment', filename='bundle-persist.mime')
bundle.attach(MIMEText('PLAIN-PO-101 please ship', 'plain', 'utf-8'))
bundle.attach(MIMEText('<p>HTML-PO-202 please ship</p>', 'html', 'utf-8'))
bundle.attach(inner)
root = MIMEMultipart('mixed')
root['Subject'] = 'Intake multipart persist'
root['From'] = 'shipper@example.com'
root['To'] = 'freight@example.com'
root['Message-ID'] = '<persist-multipart@example.com>'
root.attach(MIMEText('Outer cover.', 'plain', 'utf-8'))
root.attach(bundle)
eml_bytes = root.as_bytes()
with app.app_context():
app.config['SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH'] = 1
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='multipart-persist.eml',
content_type='message/rfc822',
),
)
asset = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-EML-MP-PERSIST-001',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version=str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6'),
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _asset: eml_bytes,
)
monkeypatch.setattr(
'app.services.shipping_notice.duplicate_detection.refresh_candidates_and_aggregate_intake',
lambda **kwargs: {'status': 'none', 'fingerprint_strength': None},
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, asset)
assert result['status'] == 'parsed'
db.session.expire_all()
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-EML-MP-PERSIST-001'
).one()
structured = refreshed.structured_result_json or {}
by_name = {
str(row.get('filename') or ''): row
for row in (structured.get('attachments') or [])
}
assert 'bundle-persist.mime' in by_name
assert 'inner-depth.mime' in by_name
bundle_text = str(by_name['bundle-persist.mime'].get('extracted_text') or '')
assert 'PLAIN-PO-101' in bundle_text
assert 'HTML-PO-202' in bundle_text
assert by_name['bundle-persist.mime'].get('parse_status') == 'parsed'
assert by_name['inner-depth.mime'].get('parse_status') == 'skipped'
warnings = list(structured.get('warnings') or []) + list(
by_name['inner-depth.mime'].get('warnings') or []
)
assert any(str(w).startswith('eml_nesting_depth_exceeded:') for w in warnings)
assert 'PLAIN-PO-101' in str(refreshed.extracted_text or '')
assert 'HTML-PO-202' in str(refreshed.extracted_text or '')
lean = serialize_intake(refreshed, asset=asset, include_parse_texts=False)
lean_bundle = next(
row
for row in ((lean.get('parse_summary') or {}).get('attachments') or [])
if row.get('filename') == 'bundle-persist.mime'
)
assert 'extracted_text' not in lean_bundle
full = serialize_intake(refreshed, asset=asset, include_parse_texts=True)
full_bundle = next(
row
for row in ((full.get('parse_summary') or {}).get('attachments') or [])
if row.get('filename') == 'bundle-persist.mime'
)
assert 'PLAIN-PO-101' in str(full_bundle.get('extracted_text') or '')
assert 'HTML-PO-202' in str(full_bundle.get('extracted_text') or '')
headers = {'Authorization': f'Bearer {issue_local_access_token(shipping_user)}'}
status_res = client.post(
'/api/workspace/shipping-notice/intakes/status',
json={'intake_nos': ['SNI-EML-MP-PERSIST-001']},
headers=headers,
)
assert status_res.status_code == 200
status_item = status_res.get_json()['data']['items'][0]
status_atts = (status_item.get('parse_summary') or {}).get('attachments') or []
status_bundle = next(row for row in status_atts if row.get('filename') == 'bundle-persist.mime')
assert 'extracted_text' not in status_bundle
status_inner = next(row for row in status_atts if row.get('filename') == 'inner-depth.mime')
assert status_inner.get('parse_status') == 'skipped'
detail_res = client.get(
'/api/workspace/shipping-notice/intakes/SNI-EML-MP-PERSIST-001',
headers=headers,
)
assert detail_res.status_code == 200
detail_atts = (detail_res.get_json()['data'].get('parse_summary') or {}).get('attachments') or []
detail_bundle = next(row for row in detail_atts if row.get('filename') == 'bundle-persist.mime')
assert 'PLAIN-PO-101' in str(detail_bundle.get('extracted_text') or '')
assert 'HTML-PO-202' in str(detail_bundle.get('extracted_text') or '')
detail_inner = next(row for row in detail_atts if row.get('filename') == 'inner-depth.mime')
assert detail_inner.get('parse_status') == 'skipped'
def test_intake_status_api_strips_texts_detail_returns_full(app, client):
"""
Flask 路由:POST /intakes/status 不返回附件全文;GET 详情返回全文;越权 404。
"""
from datetime import datetime, timedelta
from app.core.auth.jwt import issue_local_access_token
from app.models import FileAsset, ShippingNoticeIntake, User
with app.app_context():
owner = User(username='intake-api-owner', email='intake-api-owner@example.com', password_hash='x')
other = User(username='intake-api-other', email='intake-api-other@example.com', password_hash='x')
db.session.add_all([owner, other])
db.session.commit()
owner_id = owner.id
other_id = other.id
owner_headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
asset = FileAsset(
asset_no='FA-EML-API-001',
owner_user_id=owner_id,
original_filename='multi.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{owner_id}/test/multi.eml',
content_hash='hash-eml-api-001',
file_size=12,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-EML-API-001',
asset_id=asset.id,
user_id=owner_id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v2',
extracted_text='flat body',
structured_result_json={
'email': {
'subject': 'API EML',
'body_text': 'SECRET-BODY-TEXT',
'body_text_length': 16,
'stored_body_text_length': 16,
},
'attachment_count': 1,
'attachment_registered_count': 1,
'attachments': [
{
'attachment_key': 'att-001',
'filename': 'order.txt',
'parse_status': 'parsed',
'extracted_text': 'SECRET-ATTACHMENT-TEXT',
'text_length': 22,
'stored_text_length': 22,
}
],
'warnings': [],
},
expires_at=datetime.utcnow() + timedelta(hours=24),
)
db.session.add(intake)
db.session.commit()
status_res = client.post(
'/api/workspace/shipping-notice/intakes/status',
json={'intake_nos': ['SNI-EML-API-001']},
headers=owner_headers,
)
assert status_res.status_code == 200
status_payload = status_res.get_json()
assert status_payload['success'] is True
item = status_payload['data']['items'][0]
summary = item['parse_summary']
assert 'extracted_text' not in (summary.get('attachments') or [{}])[0]
assert 'body_text' not in (summary.get('email') or {})
detail_res = client.get(
'/api/workspace/shipping-notice/intakes/SNI-EML-API-001',
headers=owner_headers,
)
assert detail_res.status_code == 200
detail = detail_res.get_json()['data']
detail_summary = detail['parse_summary']
assert detail_summary['email']['body_text'] == 'SECRET-BODY-TEXT'
assert detail_summary['attachments'][0]['extracted_text'] == 'SECRET-ATTACHMENT-TEXT'
forbidden = client.get(
'/api/workspace/shipping-notice/intakes/SNI-EML-API-001',
headers=other_headers,
)
assert forbidden.status_code in {403, 404}
assert forbidden.get_json().get('success') is False
# 避免未使用变量告警
assert other_id != owner_id
def test_ensure_default_file_asset_cleanup_schedule(app, shipping_user):
"""有用户时可幂等补建默认 TTL 清理排程。"""
with app.app_context():
from app.models import ScheduleTask
from app.services.file_assets.cleanup_schedule import (
DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO,
ensure_default_file_asset_cleanup_schedule,
)
first = ensure_default_file_asset_cleanup_schedule()
assert first is not None
assert first.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO
assert first.platform_api_path == 'file-asset-cleanup'
assert first.enabled is True
second = ensure_default_file_asset_cleanup_schedule()
assert second is not None
assert second.id == first.id
count = (
db.session.query(ScheduleTask)
.filter(ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO)
.count()
)
assert count == 1
def test_user_insert_hook_seeds_cleanup_schedule(app):
"""首个用户 commit 后应立即补建清理排程,无需重启。"""
with app.app_context():
from app.models import ScheduleTask, User
from app.services.file_assets.cleanup_schedule import (
DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO,
register_file_asset_cleanup_schedule_hooks,
)
register_file_asset_cleanup_schedule_hooks()
# 确保环境干净
db.session.query(ScheduleTask).filter(
ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO
).delete()
db.session.commit()
user = User(username='seed-hook-user', email='seed-hook@example.com', password_hash='x')
db.session.add(user)
db.session.commit()
task = (
db.session.query(ScheduleTask)
.filter_by(schedule_no=DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO)
.first()
)
assert task is not None
assert task.platform_api_path == 'file-asset-cleanup'
assert task.enabled is True
assert task.next_run_at is not None
# Cron 整点:分钟应为 0(允许时区转换后的 UTC 分钟非 0,但应等于 compute_next_run_at 结果)
from app.services.schedule.timezone_util import compute_next_run_at
expected = compute_next_run_at('0 * * * *', timezone_name='Asia/Shanghai')
assert expected is not None
# 钩子执行时刻与断言时刻可能跨整点边界,允许在同一小时窗口内
assert abs((task.next_run_at - expected).total_seconds()) < 3700
def _minimal_pdf_bytes(marker: str) -> bytes:
"""构造含可见文本的最小 PDF(与 extract 测试口径一致)。"""
safe = str(marker).replace('\\', '\\\\').replace('(', '\\(').replace(')', '\\)')
stream = f'BT /F1 24 Tf 72 720 Td ({safe}) Tj ET'.encode('latin-1')
objects = [
b'1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj\n',
b'2 0 obj<< /Type /Pages /Kids [3 0 R] /Count 1 >>endobj\n',
(
b'3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] '
b'/Contents 4 0 R /Resources<< /Font<< /F1 5 0 R >> >> >>endobj\n'
),
f'4 0 obj<< /Length {len(stream)} >>stream\n'.encode('latin-1')
+ stream
+ b'\nendstream\nendobj\n',
b'5 0 obj<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>endobj\n',
]
out = bytearray(b'%PDF-1.4\n')
offsets = [0]
for obj in objects:
offsets.append(len(out))
out.extend(obj)
xref_pos = len(out)
out.extend(f'xref\n0 {len(offsets)}\n'.encode('latin-1'))
out.extend(b'0000000000 65535 f \n')
for off in offsets[1:]:
out.extend(f'{off:010d} 00000 n \n'.encode('latin-1'))
out.extend(
f'trailer<< /Size {len(offsets)} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n'.encode(
'latin-1'
)
)
return bytes(out)
def test_run_intake_parse_three_pdfs_creates_documents_candidates_and_assets(
app, shipping_user, monkeypatch,
):
"""
阶段二验收:3 个含真实 PO 的 PDF → 正文 Document(email_context) + 3 PDF Document + 3 Candidate;
正文订单表不额外生成第 4 候选;各 PDF 独立 FileAsset;重试不膨胀。
"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.intake_service import serialize_intake
markers = ('4510039227', '4510039228', '4510039229')
msg = EmailMessage()
msg['Subject'] = 'PO 4510039227, 4510039228, 4510039229'
msg['From'] = 'laszlo.fussy@example.com'
msg['To'] = 'freight@example.com'
msg['Message-ID'] = '<stage2-three-pdf@example.com>'
msg.set_content(
'Please find POs attached.\n'
'PO Number: 4510039227 qty 10\n'
'PO Number: 4510039228 qty 20\n'
'PO Number: 4510039229 qty 30\n'
)
for po in markers:
msg.add_attachment(
_minimal_pdf_bytes(f'PO Number: {po} SKU-A qty 1'),
maintype='application',
subtype='pdf',
filename=f'{po}.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='three-po.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-STAGE2-3PDF',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _asset: eml_bytes,
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
first = run_intake_parse(intake, parent)
assert first['status'] == 'parsed'
db.session.expire_all()
refreshed_intake = (
db.session.query(ShippingNoticeIntake)
.filter_by(intake_no='SNI-STAGE2-3PDF')
.one()
)
persist_warns = [
str(w)
for w in (refreshed_intake.parse_warnings_json or [])
if str(w).startswith('document_candidate_persist_failed')
]
assert not persist_warns, persist_warns
assert first.get('document_count') == 4, first
docs = (
db.session.query(ShippingNoticeDocument)
.filter_by(intake_id=refreshed_intake.id)
.order_by(ShippingNoticeDocument.id.asc())
.all()
)
cands = (
db.session.query(ShippingNoticeCandidate)
.filter_by(intake_id=refreshed_intake.id)
.order_by(ShippingNoticeCandidate.id.asc())
.all()
)
children = (
db.session.query(FileAsset)
.filter(
FileAsset.parent_asset_id == parent.id,
FileAsset.deleted_at.is_(None),
)
.all()
)
assert len(docs) == 4, (first, refreshed_intake.parse_warnings_json)
body_docs = [d for d in docs if d.document_type == 'email_body']
assert len(body_docs) == 1
assert body_docs[0].classification == 'email_context'
pdf_docs = [d for d in docs if d.document_type == 'attachment']
assert len(pdf_docs) == 3
assert all(d.classification == 'order_notice' for d in pdf_docs)
assert all(d.asset_id for d in pdf_docs)
assert len(cands) == 3
assert all(c.primary_document_id != body_docs[0].id for c in cands)
assert len(children) == 3
assert len({c.content_hash for c in children}) == 3
detail = serialize_intake(refreshed_intake, asset=parent, include_parse_texts=True)
assert detail['document_count'] == 4
assert detail['candidate_count'] == 3
intake2 = (
db.session.query(ShippingNoticeIntake)
.filter_by(intake_no='SNI-STAGE2-3PDF')
.one()
)
intake2.parse_status = 'parsing'
db.session.commit()
second = run_intake_parse(intake2, parent)
assert second['status'] == 'parsed'
db.session.expire_all()
intake_id = (
db.session.query(ShippingNoticeIntake)
.filter_by(intake_no='SNI-STAGE2-3PDF')
.one()
.id
)
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 4
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 3
assert (
db.session.query(FileAsset)
.filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
.count()
== 3
)
def test_stage2_supporting_pdf_without_po_has_document_but_no_candidate(
app, shipping_user, monkeypatch,
):
"""无 PO/行项目的 PDF 仅落 Document(supporting),不伪造 Candidate。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
msg = EmailMessage()
msg['Subject'] = 'Packing list only'
msg['From'] = 'a@b.com'
msg['To'] = 'c@d.com'
msg.set_content('See packing list.')
msg.add_attachment(
_minimal_pdf_bytes('This is packing list page 1'),
maintype='application',
subtype='pdf',
filename='packing.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='packing.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-STAGE2-SUPPORT',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes,
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent)
assert result['status'] == 'parsed'
att = (
db.session.query(ShippingNoticeDocument)
.filter_by(intake_id=intake.id, document_type='attachment')
.one()
)
assert att.classification == 'supporting'
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake.id).count() == 0
def test_stage2_persist_failure_marks_parse_failed_and_allows_retry(
app, shipping_user, monkeypatch,
):
"""阶段二持久化失败须 parse_failed,且可 retry_intake_parse。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.intake_service import retry_intake_parse
msg = EmailMessage()
msg['Subject'] = 'fail stage2'
msg['From'] = 'a@b.com'
msg['To'] = 'c@d.com'
msg.set_content('body')
msg.add_attachment(
_minimal_pdf_bytes('PO Number: 999001'),
maintype='application',
subtype='pdf',
filename='one.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='fail.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-STAGE2-FAIL',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes,
)
monkeypatch.setattr(
'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-stage2')),
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent)
assert result['status'] == 'parse_failed'
db.session.expire_all()
failed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-FAIL').one()
assert failed.parse_status == 'parse_failed'
assert failed.error_code == 'SHIPPING_NOTICE.INTAKE_STAGE2_PERSIST_FAILED'
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=777):
retried = retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-STAGE2-FAIL')
assert retried['parse_status'] == 'queued'
def test_candidate_dedup_savepoint_failure_keeps_stage2_and_unchecked(
app, shipping_user, monkeypatch,
):
"""Candidate 重复检测异常仅 SAVEPOINT 回滚:Document/Candidate 保留,去重为 unchecked。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
msg = EmailMessage()
msg['Subject'] = 'dedup savepoint'
msg['From'] = 'a@b.com'
msg['To'] = 'c@d.com'
msg.set_content('body')
msg.add_attachment(
_minimal_pdf_bytes('PO Number: DEDUPSP001\nSKU: X qty 1'),
maintype='application',
subtype='pdf',
filename='order.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='dedup-sp.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-DEDUP-SAVEPOINT',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes,
)
monkeypatch.setattr(
'app.services.shipping_notice.duplicate_detection.refresh_candidates_and_aggregate_intake',
lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-candidate-dedup')),
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent)
assert result['status'] == 'parsed'
assert result.get('duplicate_status') == 'unchecked'
db.session.expire_all()
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-DEDUP-SAVEPOINT'
).one()
assert refreshed.parse_status == 'parsed'
assert refreshed.duplicate_status == 'unchecked'
assert refreshed.duplicate_matches_json in (None, [])
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=refreshed.id).count() >= 1
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=refreshed.id).count() >= 1
def test_stage2_fail_cleanup_clears_prior_duplicate_resolution(
app, shipping_user, monkeypatch,
):
"""阶段二失败清理须清空上一轮 matches/指纹/决策,不只改 duplicate_status。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.intake_service import serialize_intake
msg = EmailMessage()
msg['Subject'] = 'fail clear dup'
msg['From'] = 'a@b.com'
msg['To'] = 'c@d.com'
msg.set_content('body')
msg.add_attachment(
_minimal_pdf_bytes('PO Number: FAILCLEARDUP1\nSKU: X qty 1'),
maintype='application',
subtype='pdf',
filename='one.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='fail-clear-dup.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-STAGE2-CLEAR-DUP',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
duplicate_status='soft_duplicate',
duplicate_matches_json=[{'task_no': 'ST-OLD', 'match_type': 'po_number'}],
business_fingerprint='fp-old',
fingerprint_version='shipping-v1',
fingerprint_strength='strong',
duplicate_resolution='force_create',
duplicate_resolution_reason='prev',
duplicate_target_task_no='ST-OLD',
duplicate_resolved_at=datetime.utcnow(),
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes,
)
monkeypatch.setattr(
'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-clear-dup')),
)
intake.parse_status = 'parsing'
db.session.commit()
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent)
assert result['status'] == 'parse_failed'
db.session.expire_all()
failed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-STAGE2-CLEAR-DUP'
).one()
assert failed.parse_status == 'parse_failed'
assert failed.duplicate_status == 'unchecked'
assert failed.duplicate_matches_json in (None, [])
assert failed.business_fingerprint is None
assert failed.fingerprint_version is None
assert failed.fingerprint_strength is None
assert failed.duplicate_resolution is None
assert failed.duplicate_resolution_reason is None
assert failed.duplicate_target_task_no is None
assert failed.duplicate_resolved_at is None
payload = serialize_intake(failed, asset=parent)
dup = payload.get('duplicate') or {}
assert (dup.get('matches') or []) == []
assert payload.get('duplicate_resolution') is None
def test_derived_asset_refcount_increments_per_document_link(app, shipping_user):
"""多个 Document 指向同一派生资产时,引用计数按关联边累加/释放。"""
from app.services.shipping_notice.document_candidate_persist import _upsert_document
with app.app_context():
parents = []
for suffix in ('A', 'B'):
parent = FileAsset(
asset_no=f'FA-REF-PARENT-{suffix}',
owner_user_id=shipping_user.id,
original_filename=f'root-{suffix}.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/ref/parent-{suffix}.eml',
content_hash=f'parenthash-{suffix}',
file_size=10,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
asset_role='upload',
)
db.session.add(parent)
parents.append(parent)
db.session.flush()
child = FileAsset(
asset_no='FA-REF-CHILD',
owner_user_id=shipping_user.id,
parent_asset_id=parents[0].id,
asset_role='derived_attachment',
source_attachment_key='att-a',
original_filename='a.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/ref/a.pdf',
content_hash='samehash',
file_size=20,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
)
db.session.add(child)
db.session.flush()
intakes = []
for idx, suffix in enumerate(('A', 'B')):
intake = ShippingNoticeIntake(
intake_no=f'SNI-REF-{suffix}',
asset_id=parents[idx].id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
)
db.session.add(intake)
intakes.append(intake)
db.session.commit()
_upsert_document(
intake=intakes[0],
attachment_key='att-a',
document_type='attachment',
filename='a.pdf',
content_hash='samehash',
parse_status='parsed',
extracted_text='PO Number: 1',
warnings=[],
asset_id=int(child.id),
classification='order_notice',
)
_upsert_document(
intake=intakes[1],
attachment_key='att-a',
document_type='attachment',
filename='a.pdf',
content_hash='samehash',
parse_status='parsed',
extracted_text='PO Number: 1',
warnings=[],
asset_id=int(child.id),
classification='order_notice',
)
db.session.commit()
db.session.refresh(child)
assert int(child.reference_count or 0) == 2
assert child.lifecycle_status == 'referenced'
_upsert_document(
intake=intakes[0],
attachment_key='att-a',
document_type='attachment',
filename='a.pdf',
content_hash='samehash',
parse_status='parsed',
extracted_text='PO Number: 1',
warnings=[],
asset_id=None,
classification='supporting',
)
db.session.commit()
db.session.refresh(child)
assert int(child.reference_count or 0) == 1
assert child.lifecycle_status == 'referenced'
def test_soft_deleted_derived_asset_can_be_revived(app, shipping_user):
"""软删除派生资产后同哈希应可复活,不被全量唯一约束永久挡死。"""
from datetime import datetime
from app.services.file_assets.service import create_derived_file_asset_from_bytes
with app.app_context():
parent = FileAsset(
asset_no='FA-REVIVE-PARENT',
owner_user_id=shipping_user.id,
original_filename='root.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/revive/parent.eml',
content_hash='revive-parent',
file_size=10,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
asset_role='upload',
)
db.session.add(parent)
db.session.flush()
payload = b'%PDF-1.4 revive-payload'
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
child, created = create_derived_file_asset_from_bytes(
user_id=shipping_user.id,
parent=parent,
data=payload,
filename='revive.pdf',
mime_type='application/pdf',
source_attachment_key='att-1',
)
assert created is True
child.deleted_at = datetime.utcnow()
child.lifecycle_status = 'expired'
child.reference_count = 0
db.session.commit()
revived, created_again = create_derived_file_asset_from_bytes(
user_id=shipping_user.id,
parent=parent,
data=payload,
filename='revive.pdf',
mime_type='application/pdf',
source_attachment_key='att-1',
)
assert created_again is False
assert revived.id == child.id
assert revived.deleted_at is None
assert revived.upload_status == 'ready'
def test_reuse_derived_asset_keeps_first_source_attachment_key(app, shipping_user):
"""同哈希复用时 source_attachment_key 保持首次来源键,不被后续 att-key 覆盖。"""
from app.services.file_assets.service import create_derived_file_asset_from_bytes
with app.app_context():
parent = FileAsset(
asset_no='FA-KEY-PARENT',
owner_user_id=shipping_user.id,
original_filename='root.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/key/parent.eml',
content_hash='key-parent',
file_size=10,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
asset_role='upload',
)
db.session.add(parent)
db.session.commit()
payload = b'%PDF-1.4 shared-key-payload'
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
first, created = create_derived_file_asset_from_bytes(
user_id=shipping_user.id,
parent=parent,
data=payload,
filename='shared.pdf',
mime_type='application/pdf',
source_attachment_key='att-001',
)
assert created is True
second, created_again = create_derived_file_asset_from_bytes(
user_id=shipping_user.id,
parent=parent,
data=payload,
filename='shared.pdf',
mime_type='application/pdf',
source_attachment_key='att-009',
)
assert created_again is False
assert second.id == first.id
assert second.source_attachment_key == 'att-001'
def test_compensate_orphan_persist_failure_rollbacks_caller_session(app, shipping_user):
"""orphan 台账写入失败后须 rollback,调用方 Session 不应卡在 failed。"""
from app.services.file_assets.service import compensate_uploaded_storage_keys
with app.app_context():
with patch(
'app.services.file_assets.service.file_asset_storage.delete_object',
side_effect=RuntimeError('minio down'),
), patch(
'app.services.file_assets.service._persist_orphan_storage_key_for_cleanup',
side_effect=RuntimeError('orphan write failed'),
):
compensate_uploaded_storage_keys(
['temporary/orphan-fail-session.bin'],
owner_user_id=shipping_user.id,
)
# Session 已恢复:可正常查询,不会 PendingRollbackError
assert db.session.query(FileAsset).count() >= 0
def test_mark_and_release_asset_reference_are_atomic(app, shipping_user):
"""引用计数须走原子 UPDATE,并发读改写不能丢增减。"""
from app.services.file_assets.service import mark_asset_referenced, release_asset_reference
with app.app_context():
asset = FileAsset(
asset_no='FA-ATOMIC-REF',
owner_user_id=shipping_user.id,
parent_asset_id=None,
asset_role='derived_attachment',
original_filename='a.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/atomic/a.pdf',
content_hash='atomic-hash',
file_size=10,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
)
db.session.add(asset)
db.session.commit()
mark_asset_referenced(asset)
mark_asset_referenced(asset)
db.session.commit()
db.session.refresh(asset)
assert int(asset.reference_count or 0) == 2
assert asset.lifecycle_status == 'referenced'
release_asset_reference(asset)
db.session.commit()
db.session.refresh(asset)
assert int(asset.reference_count or 0) == 1
assert asset.lifecycle_status == 'referenced'
release_asset_reference(asset)
db.session.commit()
db.session.refresh(asset)
assert int(asset.reference_count or 0) == 0
assert asset.lifecycle_status == 'temporary'
def test_cancel_intake_is_idempotent_and_clears_stage2_projection(app, shipping_user):
"""二次取消不得再释放引用;并清理 parse_summary 阶段二投影。"""
from app.services.file_assets.service import mark_asset_referenced
from app.services.shipping_notice.intake_service import cancel_intake
with app.app_context():
parent = FileAsset(
asset_no='FA-CANCEL-IDEMP-PARENT',
owner_user_id=shipping_user.id,
original_filename='c.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/cancel-idemp/parent.eml',
content_hash='cancel-idemp-parent',
file_size=10,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
asset_role='upload',
)
db.session.add(parent)
db.session.flush()
child = FileAsset(
asset_no='FA-CANCEL-IDEMP-CHILD',
owner_user_id=shipping_user.id,
parent_asset_id=parent.id,
asset_role='derived_attachment',
original_filename='c.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/cancel-idemp/c.pdf',
content_hash='cancel-idemp-child',
file_size=20,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
)
db.session.add(child)
db.session.flush()
mark_asset_referenced(child)
intake = ShippingNoticeIntake(
intake_no='SNI-CANCEL-IDEMP',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
structured_result_json={
'document_count': 2,
'candidate_count': 1,
'attachments': [
{
'attachment_key': 'att-001',
'filename': 'c.pdf',
'asset_no': child.asset_no,
'document_id': 99,
}
],
},
)
db.session.add(intake)
db.session.flush()
doc = ShippingNoticeDocument(
intake_id=intake.id,
attachment_key='att-001',
document_type='attachment',
filename='c.pdf',
asset_id=child.id,
classification='order_notice',
parse_status='parsed',
)
db.session.add(doc)
db.session.commit()
cancel_intake(user_id=shipping_user.id, intake_no='SNI-CANCEL-IDEMP')
cancel_intake(user_id=shipping_user.id, intake_no='SNI-CANCEL-IDEMP')
db.session.expire_all()
child2 = db.session.get(FileAsset, child.id)
intake2 = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-CANCEL-IDEMP').one()
assert int(child2.reference_count or 0) == 0
assert intake2.parse_status == 'cancelled'
summary = intake2.structured_result_json or {}
assert 'document_count' not in summary
assert 'candidate_count' not in summary
att0 = (summary.get('attachments') or [{}])[0]
assert 'asset_no' not in att0
assert 'document_id' not in att0
def test_extract_failed_retry_clears_previous_stage2(app, shipping_user, monkeypatch):
"""文本抽取失败写 parse_failed 时须清理上一轮 Document/Candidate。"""
from app.services.file_assets.service import mark_asset_referenced
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
with app.app_context():
parent = FileAsset(
asset_no='FA-EXTRACT-CLEAR',
owner_user_id=shipping_user.id,
original_filename='clear.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/extract-clear.eml',
content_hash='extract-clear',
file_size=10,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
asset_role='upload',
)
db.session.add(parent)
db.session.flush()
child = FileAsset(
asset_no='FA-EXTRACT-CLEAR-CHILD',
owner_user_id=shipping_user.id,
parent_asset_id=parent.id,
asset_role='derived_attachment',
original_filename='old.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/extract-clear/old.pdf',
content_hash='extract-clear-child',
file_size=20,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
)
db.session.add(child)
db.session.flush()
mark_asset_referenced(child)
intake = ShippingNoticeIntake(
intake_no='SNI-EXTRACT-CLEAR',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
structured_result_json={
'document_count': 1,
'candidate_count': 1,
'attachments': [{'attachment_key': 'att-001', 'document_id': 1, 'asset_no': child.asset_no}],
},
)
db.session.add(intake)
db.session.flush()
doc = ShippingNoticeDocument(
intake_id=intake.id,
attachment_key='att-001',
document_type='attachment',
filename='old.pdf',
asset_id=child.id,
classification='order_notice',
parse_status='parsed',
)
db.session.add(doc)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
lambda _a: NoticeIntakeResult(
filename='clear.eml',
source_type='email',
source_file_type='message/rfc822',
text='',
warnings=['extract exploded'],
meta={},
content_hash=parent.content_hash,
file_size=10,
status='extract_failed',
saved_path=None,
),
)
result = run_intake_parse(intake, parent)
assert result['status'] == 'parse_failed'
db.session.expire_all()
failed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-EXTRACT-CLEAR').one()
assert failed.parse_status == 'parse_failed'
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed.id).count() == 0
child2 = db.session.get(FileAsset, child.id)
assert int(child2.reference_count or 0) == 0
summary = failed.structured_result_json or {}
assert 'document_count' not in summary
def test_retry_parse_rejects_cancelled_intake(app, shipping_user):
"""已取消 Intake 不得被重试覆盖回 queued。"""
from app.services.shipping_notice.intake_service import retry_intake_parse
with app.app_context():
parent = FileAsset(
asset_no='FA-RETRY-CANCELLED',
owner_user_id=shipping_user.id,
original_filename='r.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/retry-cancelled.eml',
content_hash='retry-cancelled',
file_size=10,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
asset_role='upload',
)
db.session.add(parent)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-RETRY-CANCELLED',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='cancelled',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
with pytest.raises(ConflictError) as excinfo:
retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-RETRY-CANCELLED')
assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS'
db.session.expire_all()
assert (
db.session.query(ShippingNoticeIntake)
.filter_by(intake_no='SNI-RETRY-CANCELLED')
.one()
.parse_status
== 'cancelled'
)
def test_stage2_fail_cleanup_skips_when_intake_already_cancelled(app, shipping_user, monkeypatch):
"""阶段二失败清理持 Intake 锁后若已取消,不得再删 Candidate / 写 parse_failed。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
msg = EmailMessage()
msg['Subject'] = 'fail after cancel'
msg['From'] = 'a@b.com'
msg['To'] = 'c@d.com'
msg.set_content('body')
msg.add_attachment(
_minimal_pdf_bytes('PO Number: CANCELLOCK001'),
maintype='application',
subtype='pdf',
filename='lock.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='lock.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-STAGE2-FAIL-CANCELLED',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
)
db.session.add(intake)
db.session.flush()
doc = ShippingNoticeDocument(
intake_id=intake.id,
attachment_key='att-001',
document_type='attachment',
filename='lock.pdf',
classification='supporting',
parse_status='parsed',
)
db.session.add(doc)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes,
)
def _boom_then_cancel(**kwargs):
# 模拟失败瞬间另一事务已取消:清理前库状态为 cancelled
row = db.session.get(ShippingNoticeIntake, intake.id)
row.parse_status = 'cancelled'
db.session.commit()
raise RuntimeError('boom-after-cancel')
monkeypatch.setattr(
'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
_boom_then_cancel,
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent)
assert result['status'] == 'skipped'
db.session.expire_all()
final = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-FAIL-CANCELLED').one()
assert final.parse_status == 'cancelled'
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=final.id).count() == 1
def test_refresh_duplicate_rejects_cancelled_intake(app, shipping_user):
"""重复刷新持锁后发现已取消须拒绝,不得改写 Candidate。"""
from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
with app.app_context():
parent = FileAsset(
asset_no='FA-REFRESH-CANCELLED',
owner_user_id=shipping_user.id,
original_filename='x.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/refresh-cancelled.eml',
content_hash='refresh-cancelled',
file_size=10,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
asset_role='upload',
)
db.session.add(parent)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-REFRESH-CANCELLED',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='cancelled',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
with pytest.raises(ConflictError) as excinfo:
refresh_intake_duplicate_detection(
user_id=shipping_user.id,
intake_no='SNI-REFRESH-CANCELLED',
)
assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_INVALID_STATUS'
def test_stage2_retry_failure_clears_previous_documents(app, shipping_user, monkeypatch):
"""阶段二重试失败须清理上一轮 Document/Candidate,不得与 parse_failed 并存。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.intake_service import serialize_intake
msg = EmailMessage()
msg['Subject'] = 'retry clear'
msg['From'] = 'a@b.com'
msg['To'] = 'c@d.com'
msg.set_content('body')
msg.add_attachment(
_minimal_pdf_bytes('PO Number: RETRYCLEAR001\nSKU: X qty 1'),
maintype='application',
subtype='pdf',
filename='retry.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='retry-clear.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-STAGE2-RETRY-CLEAR',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes,
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
first = run_intake_parse(intake, parent)
assert first['status'] == 'parsed'
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake.id).count() >= 1
intake.parse_status = 'parsing'
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-retry-clear')),
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
second = run_intake_parse(intake, parent)
assert second['status'] == 'parse_failed'
db.session.expire_all()
failed = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-RETRY-CLEAR').one()
assert failed.parse_status == 'parse_failed'
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=failed.id).count() == 0
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=failed.id).count() == 0
payload = serialize_intake(failed, asset=parent)
assert payload['document_count'] == 0
assert payload['candidate_count'] == 0
def test_cancel_intake_releases_stage2_documents_and_derived_refs(app, shipping_user, monkeypatch):
"""解析完成后取消须删除 Document/Candidate 并归零派生资产引用。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.intake_service import cancel_intake
msg = EmailMessage()
msg['Subject'] = 'cancel after parse'
msg['From'] = 'a@b.com'
msg['To'] = 'c@d.com'
msg.set_content('body')
msg.add_attachment(
_minimal_pdf_bytes('PO Number: CANCEL001\nSKU: X qty 1'),
maintype='application',
subtype='pdf',
filename='cancel.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='cancel.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingNoticeIntake(
intake_no='SNI-STAGE2-CANCEL',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes,
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent)
assert result['status'] == 'parsed'
derived = (
db.session.query(FileAsset)
.filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
.one()
)
assert int(derived.reference_count or 0) >= 1
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake.id).count() >= 1
cancel_intake(user_id=shipping_user.id, intake_no='SNI-STAGE2-CANCEL')
db.session.expire_all()
cancelled = db.session.query(ShippingNoticeIntake).filter_by(intake_no='SNI-STAGE2-CANCEL').one()
assert cancelled.parse_status == 'cancelled'
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=cancelled.id).count() == 0
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=cancelled.id).count() == 0
derived2 = db.session.get(FileAsset, derived.id)
assert int(derived2.reference_count or 0) == 0
assert derived2.lifecycle_status == 'temporary'
def test_compensate_minio_failure_persists_orphan_cleanup_row(app, shipping_user):
"""补偿删除 MinIO 失败时应落 orphan_cleanup 行供定时任务继续回收。"""
from app.services.file_assets.service import compensate_uploaded_storage_keys
with app.app_context():
with patch(
'app.services.file_assets.service.file_asset_storage.delete_object',
side_effect=RuntimeError('minio down'),
):
compensate_uploaded_storage_keys(
['temporary/orphan-key-for-test.bin'],
owner_user_id=shipping_user.id,
storage_bucket='hxops-file-assets',
)
orphan = (
db.session.query(FileAsset)
.filter_by(asset_role='orphan_cleanup', storage_key='temporary/orphan-key-for-test.bin')
.one()
)
assert orphan.lifecycle_status == 'expired'
assert int(orphan.reference_count or 0) == 0
assert orphan.deleted_at is None