Spaces:
Running on Zero

File size: 7,839 Bytes
ca82a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cdd95e
 
ca82a2f
 
 
 
 
 
426b73a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca82a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cdd95e
 
 
ca82a2f
 
 
 
 
2cdd95e
ca82a2f
 
 
 
 
2cdd95e
ca82a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
"""
test_async_serving_local.py
===========================
Full asynchronous serving test suite designed for local execution outside
the restricted Windows terminal sandbox.

Runs without skips:
  1. ExtractionService Bounded asyncio.Queue + Single Background Worker loop
  2. Queue Saturation HTTP 429 handling
  3. FastAPI /extract and /jobs/{id} HTTP polling flow
  4. Shadow Mode field-level diff calculation and background execution

How to run locally:
  pytest tests/test_async_serving_local.py -v
"""

import asyncio
import os
import sys
import time
import pytest
from fastapi.testclient import TestClient

from app.adapters.extraction_adapter import ExtractionAdapter
from app.server import app, extraction_service
from app.services.extraction_service import ExtractionService


def test_local_extraction_service_queue_and_worker():
    """
    Validates end-to-end async queue processing:
    - Service starts background worker
    - Job is submitted and receives 202 Accepted + job_id
    - Worker picks up job, executes extraction, and sets status to 'completed'
    - Verifies 'extractionSource' is recorded
    """
    async def _run():
        service = ExtractionService(max_queue_size=5)
        await service.start()
        try:
            sample_resume = (
                b"SARAH CONNOR\n"
                b"Lead Systems Engineer | sarah@cyberdyne.org | +1-415-555-0199\n"
                b"EXPERIENCE\n"
                b"Principal Infrastructure Architect (Kubernetes / Go) | Tech Corp | Jan 2021 - Present\n"
                b"SKILLS\n"
                b"Go, Kubernetes, Docker, Python, AWS\n"
            )

            code, resp = await service.submit_job(sample_resume, "sarah_resume.txt", "text/plain")
            assert code == 202
            assert "job_id" in resp
            job_id = resp["job_id"]

            # Poll for worker completion (up to 15 seconds)
            for _ in range(75):
                await asyncio.sleep(0.2)
                job = service.get_job(job_id)
                if job and job["status"] in ("completed", "failed"):
                    break

            job = service.get_job(job_id)
            assert job is not None
            assert job["status"] == "completed", f"Job failed: {job.get('error')}"
            assert job["result"] is not None
            assert "candidateName" in job["result"]
            assert job.get("extractionSource") in ("slm", "fallback", "legacy")
            assert job["result"].get("extractionSource") in ("slm", "fallback", "legacy")
        finally:
            await service.stop()

    asyncio.run(_run())


def test_local_extraction_service_auto_starts_worker_on_submit():
    """
    Validates that if submit_job is called without prior service.start(),
    ensure_worker() automatically spins up the background worker on the active loop
    and processes the pending job to 'completed'.
    """
    async def _run():
        fresh_service = ExtractionService(max_queue_size=5)
        # Note: We deliberately do NOT call fresh_service.start()
        sample_resume = (
            b"MICHAEL SCOTT\n"
            b"Regional Manager | michael@dundermifflin.com | +1-570-555-0100\n"
            b"EXPERIENCE\n"
            b"Regional Manager - Dunder Mifflin Paper Company | 2005 - 2013\n"
            b"SKILLS\n"
            b"Sales, Negotiation, Management\n"
        )
        code, resp = await fresh_service.submit_job(sample_resume, "michael.txt", "text/plain")
        assert code == 202
        job_id = resp["job_id"]

        # Verify worker was started automatically
        assert fresh_service.running is True
        assert fresh_service.worker_task is not None

        # Wait for worker to finish
        for _ in range(50):
            await asyncio.sleep(0.1)
            job = fresh_service.get_job(job_id)
            if job and job["status"] in ("completed", "failed"):
                break

        job = fresh_service.get_job(job_id)
        assert job is not None
        assert job["status"] == "completed", f"Job remained stuck or failed: {job}"
        assert job["result"]["candidateName"] == "Michael Scott"
        await fresh_service.stop()

    asyncio.run(_run())


def test_local_extraction_service_queue_capacity_429():
    """
    Validates that when the bounded queue is filled to capacity,
    subsequent requests are rejected immediately with HTTP 429 Too Many Requests.
    """
    async def _run():
        small_service = ExtractionService(max_queue_size=2)
        # Intentionally do not start worker so jobs accumulate
        code1, _ = await small_service.submit_job(b"Resume 1", "res1.txt")
        code2, _ = await small_service.submit_job(b"Resume 2", "res2.txt")
        code3, resp3 = await small_service.submit_job(b"Resume 3", "res3.txt")

        assert code1 == 202
        assert code2 == 202
        assert code3 == 429
        assert "capacity" in resp3["error"].lower()

    asyncio.run(_run())


def test_local_fastapi_extract_and_poll_endpoints():
    """
    Validates full HTTP API flow using FastAPI TestClient:
    - POST /extract -> returns 200 (cache hit) or 202 (enqueued)
    - GET /jobs/{job_id} -> returns job status and payload
    - GET /jobs/{bad_id} -> returns 404
    """
    with TestClient(app) as client:
        files = {
            "file": ("dev_cv.txt", b"Jane Doe\nStaff Engineer\njane.doe@example.com", "text/plain")
        }
        # Pass dev-mode header; ENVIRONMENT defaults to development so the guard is skipped
        headers = {"X-ATS-Internal-Secret": "dev"}
        res = client.post("/extract", files=files, headers=headers)
        assert res.status_code in (200, 202)
        data = res.json()
        assert "job_id" in data
        job_id = data["job_id"]

        poll_res = client.get(f"/jobs/{job_id}", headers=headers)
        assert poll_res.status_code == 200
        poll_data = poll_res.json()
        assert poll_data["job_id"] == job_id
        assert poll_data["status"] in ("pending", "processing", "completed")

        bad_res = client.get("/jobs/non_existent_uuid_99999", headers=headers)
        assert bad_res.status_code == 404


def test_local_shadow_mode_diff_logging(monkeypatch):
    """
    Validates Shadow Mode:
    - When EXTRACTION_SHADOW_MODE=true, alternate extractor runs in background
    - Computes field-level differences (skills Jaccard, experience delta, title match)
    - Emits structured diff logs without disrupting or delaying the primary output
    """
    monkeypatch.setenv("EXTRACTION_SHADOW_MODE", "true")
    monkeypatch.setenv("USE_NEW_EXTRACTOR", "false")

    class MockSLMService:
        def _infer_llm(self, text):
            return {
                "candidateName": "Jane Doe",
                "jobTitle": "Lead Engineer (Python / Distributed Systems)",
                "email": "jane.doe@example.com",
                "phone": "+1-415-555-0100",
                "skills": ["Python", "Distributed Systems", "Kubernetes"],
                "workExperience": [
                    {"title": "Lead Engineer", "dates": "Jan 2020 - Jan 2024", "duration_years": 4.0}
                ]
            }

    adapter = ExtractionAdapter(extraction_service=MockSLMService())
    assert adapter.is_shadow_mode_enabled is True

    resume_text = (
        "Jane Doe\n"
        "Lead Engineer | jane.doe@example.com | +1-415-555-0100\n"
        "Skills: Python, Go, Docker\n"
    )

    primary_res = adapter.extract(resume_text)
    assert primary_res["extractionSource"] == "legacy"

    # Allow daemon background thread to finish
    time.sleep(0.5)

    assert adapter.latest_shadow_diff is not None
    diff = adapter.latest_shadow_diff
    assert diff["primary"] == "legacy"
    assert diff["shadow"] == "slm"
    assert diff["nameMatch"] is True
    assert "skillsJaccard" in diff