Skip to content

feat(pipeline): chunk, validate and retry id-keyed translation - #12

Merged
anthonyma94 merged 13 commits into
masterfrom
card/translate
Dec 5, 2026
Merged

anthonyma94 merged 13 commits into
masterfrom
card/translate

Conversation

@anthony-hermes

@anthony-hermes anthony-hermes Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

What

Lane 04, the translate stage: chunk, client and validator. Satisfies XL4.1, XL4.2, XL4.3, XL4.4, XL4.6 and XL4.7.

  • chunk_segments slices segments into chunks of twenty, ids untouched, and refuses a repeated or empty id list (XL4.1).
  • validate_translation checks one answer against the exact requested id set with a pydantic model: missing, extra, renumbered, non-canonical key, non-string, blank and non-object answers are all rejected with a message a retry can use (XL4.2, XL4.3).
  • translate_segments asks once, retries once with that message appended, then asks for each unresolved id alone. An id that still fails keeps its source text, gets the untranslated QA flag, the chunk is recorded with its ids and error, and the job continues (XL4.6).
  • translated.json is rewritten atomically after every chunk with the chunk index and attempt per line, so a killed job resumes from the file.
  • openai_client.py is the network edge: ChatClient seam, OpenAIChatClient over the OpenAI SDK at a caller-chosen base URL (a /v1 prefix reaches the SDK unchanged and the SDK posts to /v1/chat/completions), always response_format: json_object. OpenAITranslator composes the prompt from the language profiles and parses the answer.
  • TranslationUnit is id and text only; no request or answer carries a time (XL4.4).

Tests

38 named tests in tests/pipeline/test_translate.py, no network: FakeTranslator for the chunk, retry and fallback paths, a scripted ChatClient for the prompt and JSON handling, and a stub SDK factory for the base URL.

Acceptance:

pytest -q tests/pipeline/test_translate.py && make check     # exit 0

Base branch

Stacked on card/languages-prompt (#8) because this stage composes its prompt with prompt.py and loads rules from the profiles. Retarget to master when #8 merges.

Language rules and cue numbers live in TOML files, and the prompt that carries them is built in one place.

- ko.toml and en.toml follow the design shape: identity, role fragments and the five cue numbers, with the English no-em-dash rule in en.toml rather than the base text.
- profile.py validates every file with pydantic, refuses a pair that lacks either file, and refuses a source without source_rules or a target without target_rules so no rule is dropped silently.
- prompt.py composes base rules, source fragment, target fragment, context, glossary and previous lines in that fixed order, omitting empty optional sections and capping previous lines at three.
Twenty cues per request, an answer keyed by the string form of the segment id, and a
retry that hands the validator's own complaint back to the model.

- translate.py chunks the segment list without touching ids, rejects a repeated id,
  validates every answer against the exact id set with a pydantic model (missing, extra,
  renumbered, non-canonical, non-string and blank values all named), retries once with
  that message in the request, then asks for each unresolved id alone.
- A line that still cannot be translated keeps its source text and carries an
  "untranslated" QA flag; the chunk is recorded with its ids and error, and the job
  continues to the next chunk.
- translated.json is rewritten atomically after every chunk, with the chunk index and
  attempt that produced each line.
- openai_client.py speaks the chat-completions shape against a caller-chosen base URL
  through a ChatClient seam, always asking for json_object; an answer that is not a JSON
  object is a rejection so the retry carries the parser's complaint, while an unreachable
  endpoint is a request failure retried without a correction.
- 38 tests, no network: a scripted chat client and a stub SDK factory cover the client,
  and tests/fakes.FakeTranslator covers the chunk, retry and fallback paths.
@anthony-hermes
anthony-hermes Bot requested a review from anthonyma94 as a code owner December 4, 2026 01:01
Base automatically changed from card/languages-prompt to master December 4, 2026 23:58
Master's #8 rewrote the languages lane, so the add/add conflicts in
languages/__init__.py, languages/profile.py, pipeline/prompt.py and their tests
resolve to master's versions; this branch's earlier language implementation is
superseded and the flat en.toml/ko.toml copies are removed.

The translation code is kept. openai_client.py now compares the request language
against profile.tag instead of the removed profile.code. make check passes.
@anthony-hermes
anthony-hermes Bot added this pull request to stack #21 December 5, 2026 00:17
@anthony-hermes

anthony-hermes Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the test feedback in 89e1222.

Deleted (asserted a constant against itself)

  • test_the_chunk_size_is_twenty (CHUNK_SIZE == 20). The product rule is already asserted by test_forty_five_segments_split_into_20_20_5..., which drives the public default and fails if the default changes.
  • test_translation_units_carry_no_time_field (exact dataclass field set). Adding an unrelated field broke it without changing behavior.
  • assert JSON_OBJECT == {"type": "json_object"} inside the json_object test, which already asserts the value that reaches the client.

Rewritten (behavior, not structure)

  • No-time test: the wire payload must be exactly id to text, and no field name on the request or on a unit may be a time name. Adding previous_lines or a retry field stays green; a time field fails.
  • Partial write: instead of len(translations) == 20, the file mid-run must hold exactly the ids of the one finished chunk and fewer than all 25.
  • Base URL: asserts base_url and api_key arrive unchanged (including the /v1 path) rather than exact dict equality on the factory kwargs, which broke on any SDK option the client starts passing.

Evidence

  • PATH=.../.venv/bin:$PATH make check exit 0, 288 cases, 36 test functions (was 38).
  • Mutation check: setting CHUNK_SIZE = 25 fails 5 tests, so the behavior assertions still bite after the removals.

@anthony-hermes

anthony-hermes Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up in 04f2a14.

You were right that the dependency was wider than one test. Under CHUNK_SIZE = 25, five tests failed, and four of them had no business caring about the default:

  • test_the_job_continues_after_a_failed_chunk used 45 cues and a broken id at 25, which only lands in a later chunk when the size is 20.
  • test_each_chunk_is_written_to_translated_json_as_it_finishes and test_the_second_chunk_carries_the_previous_three_finished_lines used 25 cues to get two chunks out of the default.
  • test_calls_are_counted_across_chunks expected three calls from 45 cues.

All four now pass chunk_size=10 explicitly, so they own their boundaries and the default can move without touching them.

One test still asserts twenty: test_forty_five_segments_split_into_20_20_5_and_cover_every_id_once, which drives the public default with 45 cues. That is the XL4.1 rule (twenty cues per request) asserted through behavior, and it is the only test pinned to the default now.

Evidence: CHUNK_SIZE = 25 fails exactly that one test and nothing else (checked with bytecode cleared, after the earlier stale .pyc scare); make check exit 0 on the restored tree, 288 cases.

@anthony-hermes

anthony-hermes Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Dropped in 9f99406. The 45-cue test now passes size=10 and asserts 10/10/10/10/5, so it covers chunking behavior without touching the default. Setting CHUNK_SIZE = 25 now passes all 288 cases, which is the check that nothing depends on twenty.

The rule still lives in docs/spec/04-translate.md (XL4.1) and in the production constant; it is no longer duplicated as a test expectation.

@anthony-hermes

anthony-hermes Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Moved in b2df19f.

  • tests/pipeline/test_openai_client.py now owns everything about openai_client.py: prompt composition, the id-to-text payload, feedback rendering, JSON parse failures, the language-pair guard, and the four SDK-boundary tests. Twelve tests, driven by a scripted ChatClient and a stub SDK factory.
  • tests/pipeline/test_translate.py is down to 24 tests and no longer imports openai_client at all. It drives FakeTranslator and a local raising translator for the dead-endpoint case.
  • Dropped test_a_request_and_its_response_contain_no_time_field. The request half is now test_the_user_message_is_exactly_id_to_text in the client file. The response half asserted something the validator already forbids, twice over: an answer with a start_ms key is rejected as a non-canonical id, and a time inside a value is rejected as a non-string. Both are already covered in the validator table.

make check exit 0, 288 cases; CI green on b2df19f.

@anthony-hermes

anthony-hermes Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Consolidated in 00f4e9d.

One handler, one test. The validator raised ResponseRejected through a single catch in _ask_chunk, so the eight functions that differed only in message text are now one case table (test_an_answer_outside_the_id_set_is_rejected_with_the_reason_the_retry_needs, 8 cases, including the start_ms case that the dropped XL4.4 test was reaching for). The three chunk_segments refusals are one table (6 cases). Tests that stay separate assert a different handling or a different artifact: a rejection retries with feedback, a transport error retries without, an extra id never reaches the file.

Where the two exceptions do differ, in _ask_chunk:

  • ResponseRejected sets feedback=reason, because the model can fix a missing or extra id when told which.
  • RequestFailed sets feedback="", because nothing was wrong with the prompt.

Both retry once and both fall back per id, so the feedback field is the only difference, and test_a_transport_error_is_retried_without_inventing_a_correction asserts it.

On fake answers: they prove an invariant (nothing outside the exact id set can reach translated.json), not what a model does. Hallucination rate is a live measurement, not a unit test; that is the sweep I offered earlier, and it belongs outside make check.

make check exit 0, 292 cases; 16 test functions in test_translate.py, 12 in test_openai_client.py; CI green on 00f4e9d.

@anthony-hermes

anthony-hermes Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Trimmed in 25d4fc3: 28 test functions to 20, 292 cases to 281, all green.

Cut because nothing a user can observe differs:

  • exact chunk sizes [10,10,10,10,5] and chunk indexes: the invariant is "no cue lost, none duplicated, at most the size asked for", which still runs.
  • refusal cases for size=0, size=True, a non-Segment and a non-sequence: programmer guards, unreachable from the app. A user can reach an empty transcript or a duplicate id, and those two stay.
  • renumbered-id and non-canonical-"01" validator cases: same code branch as "missing" and as the start_ms case.
  • the attempt-number JSON test: attempt: 2 is resume metadata, not output; the recovered text is now asserted in the retry test.
  • the fallback request-shape test: only the failing id re-asked is a cost detail, not output.
  • the call-count test: calls is diagnostic.
  • the language-pair guard and blank-base_url tests: raises with no handling behind them.
  • prompt structure assertions (## Base rules, em-dash): test_prompt.py owns composition, and em-dash pins shipped TOML content.

Merged rather than cut: extra-id and non-string now one table (both prove a bad answer cannot reach the file); the two SDK failures one table; the two non-object answers one table.

Kept because a user hits the difference: every id once per chunk, recovery after one retry, a bad answer never reaching the file, a permanently failed id keeping its source text with the untranslated flag, the job continuing past a failed chunk, a dead endpoint finishing, each chunk written as it ends, the lookbehind carrying the previous three lines, context and feedback reaching the prompt, /v1 passing through to the SDK.

Mutation check: accepting an extra id in the validator fails the suite (DID NOT RAISE ResponseRejected on the unexpected-ids case). make check exit 0; CI green on 25d4fc3.

@anthony-hermes

anthony-hermes Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in febfa9b. You were right: StubSDK was a fake I wrote, so the test proved my fake accepted the arguments.

The three client tests now run the real openai.OpenAI (3.63.0) with only its HTTP transport replaced, via httpx2.MockTransport. The factory forwards base_url, api_key and timeout from OpenAIChatClient, so the URL assertion covers our pass-through and the SDK's joining, not a stub's.

What the tests now prove:

  • the real SDK builds POST http://127.0.0.1:8080/v1/chat/completions from the base URL with its prefix
  • the body it serialises carries model, messages and response_format as given
  • a 401 from the server surfaces as RequestFailed, not a traceback
  • an empty completion is a RequestFailed naming the empty answer

Mutation proof: stripping /v1 from the base URL handed to the SDK fails test_the_sdk_posts_to_the_base_url_with_its_path_prefix. With the old stub, that mutant passed, because the stub never used the base URL.

No socket opens; make check exit 0, 10 tests in test_openai_client.py, CI green on febfa9b. One coupling worth naming: httpx2 is openai's own HTTP library, so an openai release that swaps it again breaks this test loudly at import rather than silently.

@anthony-hermes

anthony-hermes Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

a144ca2, on the same point.

test_a_bad_answer_never_reaches_translated_json now asserts that the chunk was actually rejected and which ids failed, instead of only checking the file contents. Without that, a fake whose extra mode silently stopped adding an id would let the test pass while proving nothing. The fake's modes are now load-bearing for the lane test, which is the reason the lane test does not need a test of the fake.

The SDK stub is gone from the assertions entirely: httpx2.MockTransport only carries bytes, and the asserts read the real client's request URL and body.

make check exit 0, CI green.

@anthonyma94
anthonyma94 merged commit bf1cbb0 into master Dec 5, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant