1462 lines
58 KiB
Python
1462 lines
58 KiB
Python
"""
|
|
tests/test_shipping_notice_intakes_jobs.py
|
|
|
|
用途:验证 Intake 解析 Job 入队、fail/recover、worker 租约与清理调度。
|
|
依赖:pytest、conftest app fixture、MinIO mock、test_shipping_notice_intake_helpers。
|
|
逻辑:由原 test_shipping_notice_intakes.py 按域拆分;建批路径已删除。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
import time
|
|
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,
|
|
ShippingDocumentLayoutVersion,
|
|
ShippingOrderCandidate,
|
|
ShippingOrderDocument,
|
|
ShippingOrderIntake,
|
|
ShippingOrderExtraction,
|
|
ShippingOrderSchema,
|
|
ShippingOrderSchemaVersion,
|
|
ShippingNotice,
|
|
User,
|
|
)
|
|
from app.services.file_assets.service import upload_file_asset
|
|
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
|
from app.services.shipping_notice.business_fingerprint import (
|
|
build_business_fingerprint,
|
|
build_content_fingerprint,
|
|
)
|
|
|
|
from tests.test_shipping_notice_intake_helpers import (
|
|
_make_upload,
|
|
_minimal_pdf_bytes,
|
|
_seed_parsed_intake,
|
|
)
|
|
|
|
pytest_plugins = ['tests.test_shipping_notice_intake_helpers']
|
|
|
|
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 = ShippingOrderIntake(
|
|
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(ShippingOrderIntake)
|
|
.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(ShippingOrderIntake).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 = ShippingOrderIntake(
|
|
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(ShippingOrderIntake).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 = ShippingOrderIntake(
|
|
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(ShippingOrderIntake).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 = ShippingOrderIntake(
|
|
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(ShippingOrderIntake).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 = ShippingOrderIntake(
|
|
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 = ShippingOrderIntake(
|
|
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(ShippingOrderIntake).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_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 = ShippingOrderIntake(
|
|
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(ShippingOrderIntake).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 = ShippingOrderIntake(
|
|
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(ShippingOrderIntake).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
|
|
|
|
import sqlalchemy as sa
|
|
|
|
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 = ShippingOrderIntake(
|
|
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)
|
|
# 历史迁移 helper 仍硬编码 shipping_notice_intakes;模型表已 rename,测试库临时对齐旧名。
|
|
db.session.execute(sa.text(
|
|
'ALTER TABLE shipping_order_intakes RENAME TO shipping_notice_intakes'
|
|
))
|
|
try:
|
|
mig._retarget_intake_parse_job_ids(
|
|
db.session.connection(),
|
|
keep_id=keep_id,
|
|
drop_ids=[drop_id],
|
|
)
|
|
finally:
|
|
db.session.execute(sa.text(
|
|
'ALTER TABLE shipping_notice_intakes RENAME TO shipping_order_intakes'
|
|
))
|
|
db.session.commit()
|
|
|
|
refreshed = db.session.query(ShippingOrderIntake).filter_by(
|
|
intake_no='SNI-MIG-RETARGET'
|
|
).one()
|
|
assert refreshed.parse_job_id == keep_id
|
|
|
|
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(ShippingOrderIntake, 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(ShippingOrderIntake, 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(ShippingOrderIntake, 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_stale_order_extraction_job_requeues_run(app, shipping_user):
|
|
"""订单抽取 Worker 退出后,超时回收须使 Job 和 Run 一起回到可重试状态。"""
|
|
with app.app_context():
|
|
from datetime import timedelta
|
|
|
|
from app.jobs.types import JobType
|
|
from app.models import Job, ShippingOrderProcessingRun
|
|
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
|
|
|
|
run = ShippingOrderProcessingRun(
|
|
run_no='SNER-STALE-RECOVERY',
|
|
user_id=shipping_user.id,
|
|
owner_agent_id=shipping_user.id,
|
|
conversation_id='stale-recovery-test',
|
|
schema_version_id=1,
|
|
input_snapshot_hash='stale-recovery-hash',
|
|
input_snapshot_json={'intakes': []},
|
|
idempotency_key='stale-recovery-idempotency-key',
|
|
status='processing',
|
|
phase='deterministic_parsing',
|
|
)
|
|
db.session.add(run)
|
|
db.session.flush()
|
|
job = Job(
|
|
domain='shipping_notice',
|
|
job_type=JobType.SHIPPING_ORDER_EXTRACTION.value,
|
|
status='running',
|
|
business_ref=run.run_no,
|
|
payload_json={'run_no': run.run_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.commit()
|
|
|
|
count, _ = recover_stale_shipping_notice_jobs()
|
|
assert count >= 1
|
|
db.session.expire_all()
|
|
assert db.session.get(Job, job.id).status == 'queued'
|
|
assert db.session.get(ShippingOrderProcessingRun, run.id).status == 'queued'
|
|
|
|
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 = ShippingOrderDocument(
|
|
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(ShippingOrderIntake, 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(ShippingOrderDocument).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(ShippingOrderIntake, 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(ShippingOrderIntake, 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(ShippingOrderIntake, 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, **_kwargs: 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(ShippingOrderIntake, 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(ShippingOrderIntake, 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(ShippingOrderIntake, 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 = ShippingOrderDocument(
|
|
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(ShippingOrderIntake).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(ShippingOrderDocument).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_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
|
|
|