Files
syops/backend/tests/test_shipping_processing_projection.py

840 lines
32 KiB
Python

"""
backend/tests/test_shipping_processing_projection.py
processing OT PDF
Flask/SQLite?create_order_extraction_run?project_conversation_processing?
queued / frozen-failed / completed PDF hash
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.models import ShippingOrderCandidate, ShippingNotice
from app.services.shipping_notice.conversation_processing_projection import (
project_conversation_processing,
)
from app.services.shipping_notice.order_extraction_run_service import (
create_order_extraction_run,
)
from app.services.shipping_notice.order_task_service import (
allocate_user_task_no_for_run,
upsert_order_task_for_candidate_formation,
)
from tests.test_shipping_order_extraction_runs import _seed_run_input
def _ensure_run_order_task(*, run, intake, document) -> None:
"""
Candidate + OT Run.user_task_no?
test_shipping_conversation_processing_api
Candidate ? Run OT order_task
OT
"""
candidate = ShippingOrderCandidate.query.filter_by(
order_extraction_run_id=int(run.id),
).first()
if candidate is None:
candidate = ShippingOrderCandidate(
candidate_no=f'SNC-PROJ-{run.id}',
intake_id=int(intake.id),
primary_document_id=int(document.id),
candidate_key=f'key-proj-{run.id}',
order_extraction_run_id=int(run.id),
is_current_version=True,
candidate_status='provisional',
structured_result_json={},
)
db.session.add(candidate)
db.session.flush()
allocate_user_task_no_for_run(run)
upsert_order_task_for_candidate_formation(
run,
intake_id=int(intake.id),
candidate_id=int(candidate.id),
source_type='direct_pdf',
stage='candidate_created',
)
db.session.commit()
def test_project_conversation_processing_groups_and_dedupes_user_tasks(app):
""" Run OT """
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-A')
run_processing, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
_ensure_run_order_task(run=run_processing, intake=intake, document=document)
_, _, _, intake_fail, document_fail = _seed_run_input(
suffix='PROJ-B',
agent_code='shipping_notice_proj_b',
)
intake_fail.user_id = user.id
intake_fail.conversation_id = session.session_id
db.session.commit()
run_failed, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake_fail.intake_no],
allow_parallel_conversation_runs=True,
)
_ensure_run_order_task(run=run_failed, intake=intake_fail, document=document_fail)
run_failed.status = 'failed'
run_failed.phase = 'failed'
run_failed.input_lifecycle = 'frozen'
run_failed.input_frozen_at = datetime.utcnow()
db.session.commit()
_, _, _, intake_done, document_done = _seed_run_input(
suffix='PROJ-C',
agent_code='shipping_notice_proj_c',
)
intake_done.user_id = user.id
intake_done.conversation_id = session.session_id
db.session.commit()
run_done, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake_done.intake_no],
allow_parallel_conversation_runs=True,
)
_ensure_run_order_task(run=run_done, intake=intake_done, document=document_done)
run_done.status = 'completed'
run_done.phase = 'completed'
run_done.input_lifecycle = 'closed'
db.session.commit()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
focused_task_no=run_failed.user_task_no,
)
assert projection['summary']['total_tasks'] == 3
assert projection['summary']['processing'] >= 1
assert projection['summary']['needs_action'] >= 1
assert projection['summary'].get('completed', 0) >= 1
assert projection['summary']['history'] == 0
assert projection['history'] == []
assert projection['focused_task_no'] == run_failed.user_task_no
processing_nos = {row['user_task_no'] for row in projection['processing']}
needs_nos = {row['user_task_no'] for row in projection['needs_action']}
completed_nos = {row['user_task_no'] for row in projection.get('completed') or []}
assert run_processing.user_task_no in processing_nos
assert run_failed.user_task_no in needs_nos
# completed completed
assert run_done.user_task_no in completed_nos
# OT
all_nos = list(processing_nos | needs_nos | completed_nos)
assert len(all_nos) == len(set(all_nos)) == 3
failed_task = next(
row for row in projection['needs_action']
if row['user_task_no'] == run_failed.user_task_no
)
assert failed_task.get('status_label') == 'failed'
assert 'view_details' in (failed_task.get('available_actions') or [])
primary = failed_task.get('primary_action')
assert primary
# cancel / view_details CTA?BE-01
assert primary not in {'cancel_task', 'cancel_run', 'view_details'}
done_task = next(
row for row in projection['completed']
if row['user_task_no'] == run_done.user_task_no
)
assert done_task.get('status_label') == 'completed'
assert done_task.get('group') == 'completed'
def test_same_attachment_fingerprint_across_ots_keeps_two_cards(app):
"""
BE-02(产品选择 A):不同 user_task_no 即使附件指纹相同,也各出一张卡。
断言:failed OT + processing OT 同 content_hash → 两张卡;total_tasks == 2。
"""
with app.app_context():
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake
from datetime import timedelta
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-MERGE')
older, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
older.status = 'failed'
older.phase = 'failed'
older.input_lifecycle = 'frozen'
older.input_frozen_at = datetime.utcnow()
older.user_task_no = 'OT-OLD-FAIL'
db.session.commit()
second_asset = FileAsset(
asset_no='FA-PROJ-MERGE-2', owner_user_id=user.id,
original_filename=str(document.filename or 'merge.pdf'),
storage_provider='minio', storage_bucket='test',
storage_key=f'temporary/{user.id}/merge-2.pdf',
content_hash=db.session.get(FileAsset, intake.asset_id).content_hash,
file_size=100, mime_type='application/pdf', upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(second_asset)
db.session.flush()
second_intake = ShippingOrderIntake(
intake_no='SNI-PROJ-MERGE-2', asset_id=second_asset.id, user_id=user.id,
conversation_id=session.session_id, upload_batch_id='proj-merge-2',
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
extracted_text='same merge attachment',
expires_at=datetime.utcnow() + timedelta(hours=1),
)
db.session.add(second_intake)
db.session.flush()
db.session.add(ShippingOrderDocument(
intake_id=second_intake.id, asset_id=second_asset.id, document_type='attachment',
attachment_key=str(document.attachment_key or 'merge.pdf'),
filename=str(document.filename or 'merge.pdf'),
content_hash=document.content_hash, classification='order_notice',
parse_status='parsed', extracted_text=document.extracted_text,
))
db.session.commit()
newer, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
upload_batch_id=second_intake.upload_batch_id,
keep_input_open=True,
allow_parallel_conversation_runs=True,
user_task_no='OT-NEW-PROC',
)
newer.status = 'processing'
newer.phase = 'extracting'
db.session.commit()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
shown = projection['processing'] + projection['needs_action']
shown_nos = {row['user_task_no'] for row in shown}
# 跨 OT 同指纹不得折叠:两张独立卡。
assert len(shown) == 2
assert shown_nos == {'OT-OLD-FAIL', 'OT-NEW-PROC'}
assert projection['summary']['total_tasks'] == 2
assert projection['summary']['needs_action'] == 1
assert projection['summary']['processing'] == 1
def test_completed_current_run_hidden_after_viewed(app):
"""UI-04 completed """
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-DONE')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
_ensure_run_order_task(run=run, intake=intake, document=document)
run.status = 'completed'
run.phase = 'completed'
run.input_lifecycle = 'closed'
db.session.commit()
before = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
assert any(row['user_task_no'] == run.user_task_no for row in (before.get('completed') or []))
run.seen_at = datetime.utcnow()
db.session.commit()
after = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
shown = after['processing'] + after['needs_action'] + list(after.get('completed') or [])
assert all(row['user_task_no'] != run.user_task_no for row in shown)
# completed history
history_nos = {row['user_task_no'] for row in (after.get('history') or [])}
assert run.user_task_no in history_nos
assert after['summary']['history'] >= 1
def _set_run_documents(run, documents: list[dict]) -> None:
""" Run documentsPDF """
snapshot = dict(run.input_snapshot_json or {})
intakes = list(snapshot.get('intakes') or [])
if not intakes:
intakes = [{'intake_no': 'SNI-TEST', 'documents': []}]
intakes[0] = dict(intakes[0])
intakes[0]['documents'] = documents
snapshot['intakes'] = intakes
run.input_snapshot_json = snapshot
run.request_snapshot_json = snapshot
def test_single_pdf_task_title_is_none_for_frontend_unified_label(app):
"""BE-05 PDF title None document_names / objects?"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-1PDF')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
_ensure_run_order_task(run=run, intake=intake, document=document)
_set_run_documents(run, [{
'document_id': int(document.id),
'root_document_id': int(document.id),
'document_type': 'attachment',
'filename': 'only.pdf',
'content_hash': 'aaa111',
}])
db.session.commit()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
task = next(
row for row in projection['processing'] + projection['needs_action']
if row['user_task_no'] == run.user_task_no
)
# title?
assert task['title'] is None
assert task['file_count'] == 1
assert task['display_kind'] == 'single_document_task'
assert task.get('document_names') == ['only.pdf']
doc_objects = [obj for obj in (task.get('objects') or []) if obj.get('kind') == 'document']
assert len(doc_objects) == 1
assert doc_objects[0]['filename'] == 'only.pdf'
def test_multi_pdf_task_does_not_use_first_filename_as_title(app):
"""? PDF title file_count=2?objects PDF?"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-2PDF')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
_ensure_run_order_task(run=run, intake=intake, document=document)
_set_run_documents(run, [
{
'document_id': 91,
'root_document_id': 91,
'document_type': 'attachment',
'filename': '4518838152.pdf',
'content_hash': 'hash-a',
},
{
'document_id': 92,
'root_document_id': 92,
'document_type': 'attachment',
'filename': '4518838154.pdf',
'content_hash': 'hash-b',
},
])
db.session.commit()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
task = next(
row for row in projection['processing'] + projection['needs_action']
if row['user_task_no'] == run.user_task_no
)
assert task['title'] is None
assert task['display_kind'] == 'multi_document_task'
assert task['file_count'] == 2
assert task['document_names'] == ['4518838152.pdf', '4518838154.pdf']
doc_objects = [obj for obj in (task.get('objects') or []) if obj.get('kind') == 'document']
assert len(doc_objects) == 2
assert {obj['document_id'] for obj in doc_objects} == {91, 92}
def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app):
"""
BE-03:同 OT 局部重识别——被替代 Run 不另开顶层卡;有效 PDF 仍折叠保留。
断言:同一 user_task_no 仅一张卡;total_tasks == 1;未重识别 PDF 来自源 Run。
"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-PARTIAL-REPARSE')
source, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
_ensure_run_order_task(run=source, intake=intake, document=document)
_set_run_documents(source, [
{
'document_id': 91,
'root_document_id': 91,
'document_type': 'attachment',
'filename': '4518838152.pdf',
'content_hash': 'hash-a',
},
{
'document_id': 92,
'root_document_id': 92,
'document_type': 'attachment',
'filename': '4518838154.pdf',
'content_hash': 'hash-b',
},
])
source.status = 'review_required'
source.phase = 'review_required'
source.input_lifecycle = 'frozen'
source.input_frozen_at = datetime.utcnow()
db.session.commit()
_, _, _, replacement_intake, replacement_document = _seed_run_input(
suffix='PROJ-PARTIAL-REPARSE-NEW',
agent_code='shipping_notice_proj_partial_reparse_new',
)
replacement_intake.user_id = user.id
replacement_intake.conversation_id = session.session_id
db.session.commit()
replacement, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[replacement_intake.intake_no],
allow_parallel_conversation_runs=True,
user_task_no=source.user_task_no,
)
replacement.reparse_of_run_id = source.id
replacement.reparse_reason = 'field_mapping_error'
# 共享 content_hash,确保同 OT 谱系可交叉识别 PDF 身份。
shared_hash = str(document.content_hash or 'hash-partial-shared')
document.content_hash = shared_hash
replacement_document.content_hash = shared_hash
db.session.flush()
_ensure_run_order_task(
run=replacement,
intake=replacement_intake,
document=replacement_document,
)
_set_run_documents(replacement, [{
'document_id': 191,
'root_document_id': 91,
'document_type': 'attachment',
'filename': '4518838152.pdf',
'content_hash': 'hash-a',
}])
source.superseded_by_run_id = replacement.id
source.superseded_at = datetime.utcnow()
db.session.commit()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
all_cards = (
projection['processing']
+ projection['needs_action']
+ list(projection.get('completed') or [])
+ list(projection.get('history') or [])
)
# BE-03:被替代 Run 不另开顶层卡;同 OT 仅一张。
matching = [row for row in all_cards if row['user_task_no'] == source.user_task_no]
assert len(matching) == 1
assert projection['summary']['total_tasks'] == 1
task = matching[0]
assert task['run_no'] == replacement.run_no
doc_objects = [obj for obj in task['objects'] if obj.get('kind') == 'document']
# 局部重识别后:有效 PDF 仍为 2;未触碰 PDF 保留源 Run 版本。
assert task['file_count'] == 2
assert task['title'] is None
assert task['display_kind'] == 'multi_document_task'
assert set(task['document_names']) == {'4518838152.pdf', '4518838154.pdf'}
by_hash = {obj['content_hash']: obj for obj in doc_objects}
assert by_hash['hash-a']['document_id'] == 191
assert by_hash['hash-a']['current_run_no'] == replacement.run_no
assert by_hash['hash-b']['document_id'] == 92
assert by_hash['hash-b']['current_run_no'] == source.run_no
def test_same_filename_different_hash_counts_as_two_pdfs(app):
""" hash?file_count=2"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-NAME')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
_ensure_run_order_task(run=run, intake=intake, document=document)
_set_run_documents(run, [
{
'document_id': 11,
'document_type': 'attachment',
'filename': 'order.pdf',
'content_hash': 'hash-1',
},
{
'document_id': 12,
'document_type': 'attachment',
'filename': 'order.pdf',
'content_hash': 'hash-2',
},
])
db.session.commit()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
task = next(
row for row in projection['processing'] + projection['needs_action']
if row['user_task_no'] == run.user_task_no
)
assert task['file_count'] == 2
assert task['display_kind'] == 'multi_document_task'
def test_same_hash_different_document_id_counts_as_one_pdf(app):
"""? hash document_idfile_count=1?"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-HASH')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
_ensure_run_order_task(run=run, intake=intake, document=document)
_set_run_documents(run, [
{
'document_id': 21,
'root_document_id': 21,
'document_type': 'attachment',
'filename': 'order.pdf',
'content_hash': 'same-hash',
},
{
'document_id': 22,
'root_document_id': 22,
'document_type': 'attachment',
'filename': 'order.pdf',
'content_hash': 'same-hash',
},
])
db.session.commit()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
task = next(
row for row in projection['processing'] + projection['needs_action']
if row['user_task_no'] == run.user_task_no
)
assert task['file_count'] == 1
assert task['display_kind'] == 'single_document_task'
# BE-05: title None hash
assert task['title'] is None
doc_objects = [obj for obj in (task.get('objects') or []) if obj.get('kind') == 'document']
assert len(doc_objects) == 1
assert doc_objects[0]['document_id'] == 22
def test_sparse_snapshot_enriched_by_extraction_units(app):
""" 1 PDF ? Unit 2 multi + file_count=2?"""
from app.models import (
FileAsset,
ShippingOrderDocument,
ShippingOrderProcessingUnit,
)
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SPARSE-U')
asset2 = FileAsset(
asset_no='FA-RUN-PROJ-SPARSE-U-2',
owner_user_id=user.id,
original_filename='second.pdf',
storage_provider='minio',
storage_bucket='test',
storage_key=f'temporary/{user.id}/second.pdf',
content_hash='b' * 64,
file_size=100,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset2)
db.session.flush()
document2 = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset2.id,
document_type='attachment',
attachment_key='second.pdf',
filename='second.pdf',
content_hash='C' * 64,
classification='order_notice',
parse_status='parsed',
extracted_text='PO 2',
)
db.session.add(document2)
db.session.flush()
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
_ensure_run_order_task(run=run, intake=intake, document=document)
# 1
_set_run_documents(run, [{
'document_id': int(document.id),
'root_document_id': int(document.id),
'document_type': 'attachment',
'filename': '4518838152.pdf',
'content_hash': 'hash-only-one',
}])
ensure_order_extraction_plan(run)
plan = run.extraction_plan
assert plan is not None
db.session.add(ShippingOrderProcessingUnit(
plan_id=int(plan.id),
intake_id=int(intake.id),
document_id=int(document2.id),
position=max((int(u.position) for u in plan.units), default=-1) + 1,
unit_type='document_extraction',
document_type='attachment',
content_hash=str(document2.content_hash),
status='review_required',
))
db.session.commit()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
task = next(
row for row in projection['processing'] + projection['needs_action']
if row['user_task_no'] == run.user_task_no
)
assert task['file_count'] == 2
assert task['display_kind'] == 'multi_document_task'
assert task['title'] is None
names = set(task.get('document_names') or [])
assert '4518838152.pdf' in names or str(document.filename) in names
assert 'second.pdf' in names
@pytest.mark.skip(reason='workflow ledger removed')
def test_sparse_snapshot_enriched_by_workflow_items(app):
""" 1 PDF Run 2 ? WorkflowItem multi?"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SPARSE-W')
from app.models import FileAsset, ShippingOrderDocument
asset2 = FileAsset(
asset_no='FA-RUN-PROJ-SPARSE-W-2',
owner_user_id=user.id,
original_filename='peer.pdf',
storage_provider='minio',
storage_bucket='test',
storage_key=f'temporary/{user.id}/peer.pdf',
content_hash='d' * 64,
file_size=100,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset2)
db.session.flush()
document2 = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset2.id,
document_type='attachment',
attachment_key='peer.pdf',
filename='peer.pdf',
content_hash='E' * 64,
classification='order_notice',
parse_status='parsed',
extracted_text='PO peer',
)
db.session.add(document2)
db.session.flush()
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
_set_run_documents(run, [{
'document_id': int(document.id),
'root_document_id': int(document.id),
'document_type': 'attachment',
'filename': '4518838152.pdf',
'content_hash': 'hash-sparse-wf',
}])
workflow = ShippingNoticeWorkflow(
workflow_no=f'WF-SPARSE-{run.run_no}',
conversation_id=session.session_id,
owner_user_id=int(user.id),
status='open',
current_stage='extracting',
)
db.session.add(workflow)
db.session.flush()
for index, doc in enumerate((document, document2)):
db.session.add(ShippingNoticeWorkflowItem(
item_no=f'WFI-SPARSE-{run.run_no}-{index}',
workflow_id=int(workflow.id),
workflow_no=workflow.workflow_no,
conversation_id=session.session_id,
owner_user_id=int(user.id),
root_document_id=int(doc.id),
current_document_id=int(doc.id),
current_run_no=str(run.run_no),
lifecycle_status='pending_review',
current_stage='pending_review',
current_version_no=1,
))
db.session.commit()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
task = next(
row for row in projection['processing'] + projection['needs_action']
if row['user_task_no'] == run.user_task_no
)
assert task['file_count'] == 2
assert task['display_kind'] == 'multi_document_task'
assert task['title'] is None
assert 'peer.pdf' in (task.get('document_names') or [])
def test_primary_action_falls_back_to_focus_task_never_cancel(app, monkeypatch):
"""BE-01: no business entry -> primary_action=focus_task; never cancel/view_details."""
with app.app_context():
from app.services.shipping_notice import conversation_processing_projection as proj_mod
from app.services.shipping_notice import order_extraction_workspace_projection as ws_mod
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-FOCUS')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
_ensure_run_order_task(run=run, intake=intake, document=document)
db.session.commit()
monkeypatch.setattr(
ws_mod,
'_run_available_actions',
lambda _run, _units: ['cancel_run', 'view_details'],
)
primary, actions = proj_mod._resolve_task_actions(run)
assert primary == 'focus_task'
assert 'focus_task' in actions
assert 'view_details' in actions
assert 'cancel_task' in actions or 'cancel_run' in actions
assert primary not in {'cancel_task', 'cancel_run', 'view_details'}
def test_summary_has_more_and_returned_metadata_when_truncated(app):
"""BE-04: after list truncate, summary keeps full counts + has_more/returned."""
with app.app_context():
user, agent, session, intake_a, document_a = _seed_run_input(suffix='PROJ-T0')
run_a, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake_a.intake_no],
keep_input_open=True,
)
_ensure_run_order_task(run=run_a, intake=intake_a, document=document_a)
run_a.status = 'processing'
run_a.phase = 'extracting'
db.session.commit()
for suffix, agent_code in (
('PROJ-T1', 'shipping_notice_proj_t1'),
('PROJ-T2', 'shipping_notice_proj_t2'),
('PROJ-T3', 'shipping_notice_proj_t3'),
):
_, _, _, intake_x, document_x = _seed_run_input(suffix=suffix, agent_code=agent_code)
intake_x.user_id = user.id
intake_x.conversation_id = session.session_id
db.session.commit()
run_x, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake_x.intake_no],
allow_parallel_conversation_runs=True,
keep_input_open=True,
)
_ensure_run_order_task(run=run_x, intake=intake_x, document=document_x)
run_x.status = 'processing'
run_x.phase = 'extracting'
db.session.commit()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
limit=2,
history_limit=1,
)
summary = projection['summary']
returned_active = (
len(projection['needs_action'])
+ len(projection['processing'])
+ len(projection.get('completed') or [])
)
# Assert: full counts stay ahead of returned lists; truncate flags match.
assert summary['total_tasks'] >= 4
assert summary['total_tasks'] >= returned_active
assert summary.get('returned', {}).get('needs_action') == len(projection['needs_action'])
assert summary.get('returned', {}).get('processing') == len(projection['processing'])
assert summary.get('returned', {}).get('completed') == len(projection.get('completed') or [])
assert summary.get('returned', {}).get('history') == len(projection.get('history') or [])
assert summary.get('has_more_active') is True
assert summary.get('truncated', {}).get('active') is True
assert returned_active == 2