Custom Bedrock-powered document translation service — document-level preprocessor with lxml validation, part reuse for library pages, auto-scaling ECS worker fleet
The Trinity Beast Infrastructure maintains 45 technical documents. On November 28, 2026, 44 of them were translated into 11 languages, 484 translated files in total; the one guide without translations is Trinity-Beast-Infrastructure-Live.html. The original approach used AWS Translate batch jobs. It worked for simple prose but failed catastrophically on technical documentation.
AWS Translate is a neural machine translation service optimized for general-purpose text. Technical documentation with embedded code, diagrams, and brand terminology exposes its fundamental limitations:
| Failure Mode | Example | Impact |
|---|---|---|
| Translates code blocks | function getName() → función obtenerNombre() | Code no longer executes |
| Translates variable names | api_key → clave_api | Documentation references break |
| Breaks Mermaid diagrams | Translates node labels inside mermaid blocks | Diagrams fail to render |
| Corrupts HTML structure | Merges adjacent elements, drops attributes | Styling and layout break |
| Transliterates brand names | AutoOps → آٹو آپس (Urdu phonetic) | Brand identity lost, search breaks |
| Localizes numeric units | 32 GB → 32 Go (French) | Technical specs become ambiguous |
| Drops version numbers | PostgreSQL 17.7 → PostgreSQL | Version-specific guidance lost |
| Ignores translate attribute | Translates content inside protected zones | Defeats the HTML5 standard mechanism |
With 40 documents × 11 languages, every documentation update triggers a translation cascade. Before the custom engine:
A custom Bedrock-powered translation engine that understands the boundary between human language and machine language. The engine uses defense-in-depth across the full pipeline:
auto, so a wrong guess never puts the wrong language in the prompt. A customer-stated or page-declared source always wins, and detection never raises and never rejects a source. No pivot through English required./admin/translate/complete step. Fire-and-forget from the operator's perspective.Result: A single POST /admin/translate call translates any document from any of the 127 catalog languages into up to 12 target languages per request ("all" means our library's internal 11), each code resolved through the language catalog and its alternate codes. It deploys to S3, invalidates CloudFront, rebuilds the search index, and emails a summary. The source language is the one stated or declared for the document, then a definitive detection, otherwise auto — no pivot through English required.
The translation service is an event-driven pipeline that decouples submission from execution. The operator submits a job; the system handles everything else asynchronously.
Diagram 2.1: End-to-End Pipeline Architecture (v6.0 — BeastTranslate)
flowchart TB
subgraph IN["Entry Points"]
A["POST /admin/translate"]
A2["Customer accept: staged sources, quote job"]
end
subgraph LPO["LPO Server (Go)"]
B["Validate and enqueue: 127-language catalog, up to 12 languages, 42 docs"]
C["Valkey: live state"]
D["Aurora: job row inserted before any send"]
end
subgraph AQ["AWS Queue"]
E["SQS Queue: one message per language"]
end
subgraph BTS["BeastTranslate — Persistent ECS Service"]
direction TB
BT["SQS Long-Poll Loop"]
BT --> SC{"Scale Check"}
SC -->|Single lang| BT2["Process In-Place"]
SC -->|Multi-lang| BT3["Scale Service to N, at most 12"]
BT3 --> BT4["N Containers Poll Same Queue"]
BT4 --> BT5["Each Takes 1 Language Message"]
BT2 --> H00
BT5 --> H00
subgraph TI["Translation Intelligence (Python)"]
direction LR
H00["Language Runtime: catalog row + profile, 15-min cache, snapshot fallback"]
H0["Source Validation"]
H1["Admit, prepare and plan: density check, brand and code protection, part reuse plan"]
H2["Document preprocessor, per part"]
H3["Boundary sentinels TBI-BT"]
H4["Bedrock — 3-Region Failover"]
H5["Part gates: validators, boundary signature, element shift"]
H6["Repair, tag gate, tail gate, splice gate"]
H00 --> H0 --> H1 --> H2 --> H3 --> H4 --> H5 --> H6
end
end
subgraph DEL["Delivery"]
direction LR
I["Worker writes S3"]
J["CloudFront Invalidation (library docs)"]
K["POST /admin/translate/complete: state, search rebuild, email, scale-down"]
end
A2 -->|calls| A
A --> B
B --> C
B --> D
B --> E
E --> BT
H6 --> I
I --> J
I --> K
style IN fill:#1e293b,stroke:#60a5fa,color:#e2e8f0
style LPO fill:#1e293b,stroke:#94a3b8,color:#e2e8f0
style AQ fill:#1e293b,stroke:#a78bfa,color:#e2e8f0
style BTS fill:#1e293b,stroke:#fb923c,color:#e2e8f0
style TI fill:#253347,stroke:#fbbf24,color:#e2e8f0
style DEL fill:#1e293b,stroke:#10b981,color:#e2e8f0
style A fill:#1e3a5f,stroke:#60a5fa,color:#e2e8f0
style A2 fill:#1e3a5f,stroke:#60a5fa,color:#e2e8f0
style B fill:#334155,stroke:#94a3b8,color:#e2e8f0
style C fill:#064e3b,stroke:#10b981,color:#e2e8f0
style D fill:#064e3b,stroke:#10b981,color:#e2e8f0
style E fill:#2e1065,stroke:#a78bfa,color:#e2e8f0
style BT fill:#7c2d12,stroke:#fb923c,color:#e2e8f0
style SC fill:#7c2d12,stroke:#fb923c,color:#e2e8f0
style BT2 fill:#7c2d12,stroke:#fb923c,color:#e2e8f0
style BT3 fill:#7c2d12,stroke:#fb923c,color:#e2e8f0
style BT4 fill:#7c2d12,stroke:#fb923c,color:#e2e8f0
style BT5 fill:#7c2d12,stroke:#fb923c,color:#e2e8f0
style H00 fill:#1e3a5f,stroke:#60a5fa,color:#e2e8f0
style H0 fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style H1 fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style H2 fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style H3 fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style H4 fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style H5 fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style H6 fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style I fill:#064e3b,stroke:#10b981,color:#e2e8f0
style J fill:#064e3b,stroke:#10b981,color:#e2e8f0
style K fill:#064e3b,stroke:#10b981,color:#e2e8f0
linkStyle 0,1,2,3,4,5,6 stroke:#fb923c,stroke-width:2px
linkStyle 7,8,9,10,11,12,13 stroke:#fbbf24,stroke-width:2px
linkStyle 14,15 stroke:#60a5fa,stroke-width:2px
linkStyle 16,17 stroke:#10b981,stroke-width:1.5px
linkStyle 18,19 stroke:#a78bfa,stroke-width:2.5px
linkStyle 20,21,22 stroke:#10b981,stroke-width:2px
Inside the worker, each document and language pair runs fourteen stages in order, as listed in PAIR_STAGES in handler.py. A stage can end the pair early with a rejection or a skip, and an unexpected failure names the stage that raised it in the stage field of its lang_failed event (6.4).
| Stage | What it does |
|---|---|
fetch | Reads the job's options from the message and the English page from S3, keeping the bytes as read beside the text |
source | Resolves the pair's source language, logs lang_started, and rejects the pair (target_is_source) when a definitive detection finds the page already in the target language |
validate | Validates the source and applies its repairs (4.5), keeps snapshots of the authored page for the later gates, and pre-wraps brand terms |
admit | Reads the force and delta options, takes the in-flight lock, checks the pair's failure history and gives the density verdict, which can reject the page as too_dense (6.1) |
prepare | Wraps the job's protected terms and the brand terms, applies the glossary (10.4), protects code elements and makes relative paths absolute before the model sees them |
plan | Runs the pre-scan (14), checks the chunk markers, splits the page into parts and, for a library pair that asks for reuse, plans which parts to reuse (17) |
translate | Sends every part that is not reused to Bedrock by the page's route: chunk markers, pre-scan split or the whole page. Each part's gates and retries (4.2) run inside this stage |
repair | Runs the whole-page integrity check and its repairs: glued terms with their gate, code tags, syntax and structural identity (4.4, 4.7) |
tag_gate | Compares the critical tag counts of the whole page with the enriched source, within per-tag tolerance bands, after stripping code and pre tags the model invented. On an extreme-density page a mismatch can be downgraded to a warning, but never for a lost pre block or a heading |
localize | Sets the page's lang and dir attributes, chooses the output bucket and key, and rewrites stylesheet and asset paths so they work from the language folder |
tail | Repairs span wrappers, strips the preprocessing scaffolding and any placeholder residue, then runs the differential tail gate (Invariant 12), which can stop the write |
splice | Puts each reused part's published bytes back in place, adds the parts manifest, checks the result with the splice gate (17.4) and runs the report-only glossary check |
publish | Checks once more, failing closed, that the job was not cancelled (6.3), then writes the page to its output bucket and key |
record | Charges the pair from the token meter and adds the spend to the daily counters (8.2), records provenance and, when no part was reused, the chunk count, writes the succeeded progress and lang_succeeded, and releases the in-flight lock |
| Component | Type | Runtime | Purpose |
|---|---|---|---|
POST /admin/translate (+ 34 more route registrations, including refund-sweep and the glossary) | Admin API | Go | Job submission, monitoring, control |
trinity-beast-translation-queue | SQS | — | One message per language — workers poll directly |
tbi-translate-worker | ECS Fargate Service | Python 3.11 | Bedrock translation + content protection + validation + S3 write + CF invalidation (no timeout ceiling) |
/admin/translate/complete | LPO Endpoint | Go | Search rebuild + SES notification + state transition + cost computation + scale-down |
translation_jobs | Aurora table | — | Permanent job records (39 columns) |
translation_job_events | Aurora table | — | Granular per-doc/lang audit log |
translation_pair_runs | Aurora table | — | Estimate versus actual for every pair, read by the estimator on every estimate (7.2a) |
translation_glossary_entries | Aurora table | — | Our glossary and every customer's: a preferred translation per source term and target language, read by the server when a job is submitted (10.4) |
Every other compute workload in The Trinity Beast Infrastructure is written in Go. The translation worker is the sole exception, and for good reason:
lxml for HTML parsing — Go's HTML parsers are adequate for simple tasks but lack the XPath and tree-manipulation capabilities needed for the HTML syntax repair (4.7) on complex nested documents.CMD is handler.lambda_handler, but no translate Lambda exists: the ECS task runs task_runner.py.Convention note: All Lambda functions use 1770 MB memory (multiple of 3). The worker runs as an ECS Fargate task (2 vCPU / 6 GB) with no timeout ceiling — large documents translate to completion regardless of processing time.
Some content must reach the translated page exactly as written: code, brand terms, links, numbers, comments, and the tags that one part of a split document opens or closes without a match. The engine lifts that content out of what the model sees and puts it back afterwards, with three mechanisms. The document preprocessor replaces protected elements with placeholders, boundary sentinels carry each part's unmatched tags through the model call, and right before each call the engine swaps every protected term still in the text for a token (3.1). Section 15 describes the preprocessor in full, and the boundary-signature gate that checks the sentinels is in 4.2 and Invariants 22 and 37. Three preparation passes run first and mark more content for protection (3.0).
Three automatic preparation passes run on every document. They need no manual markup. The design principle: they can't break what isn't there.
| Pass | Function | What It Does | Failure Class Eliminated |
|---|---|---|---|
| Brand Term Auto-Wrap | _auto_wrap_brand_terms() | Scans for all 63 protected terms from translation-config.json and wraps each occurrence in <span translate="no">. The preprocessor then lifts each wrapped term into a placeholder (3.1). | Brand transliteration (e.g., The Trinity Beast → ट्रिनिटी बीस्ट) |
| Code Tag Protection | _protect_code_tags() | Upgrades every bare <code> tag to <code translate="no">. The preprocessor then lifts them all into placeholders (3.1). | Code tag mismatch failures (the single largest failure class before v5.0) |
| Path Protection | _fix_paths_absolute() | Converts relative paths (assets/, images/, css/, js/) to absolute URLs before translation. The model passes them through unchanged. | Broken asset references in translated docs |
The prepare stage (2.1) runs these passes, before the plan stage splits the document into parts and before the preprocessor sees any of it. They are deterministic and idempotent, and they cost nothing, because they only change the source HTML locally. When the preprocessor runs, every code tag, brand term and path is already marked for protection.
A pair whose job carries a glossary gets one more pass, step 1.7g, right after the brand-term wrap: an element whose whole text is a glossary source term gets the target written inside a <span translate="no"> wrapper before the preprocessor runs (10.4).
The document preprocessor (translator/preprocessor.py, Section 15) lifts each protected element out of the HTML and leaves an opaque ASCII placeholder in its place, written [QZ_*]. The type code inside it is an opaque Z code, so the model cannot tell what kind of HTML the placeholder stands for. Two earlier formats failed: models corrupted the Unicode brackets of ⟦TYPE_NNN⟧, and they dropped __TBI_TYPE_NNN__ as a code identifier (15.4).
On a split document the worker runs the preprocessor on each part, before the engine's own chunking. The engine's translate() also runs it on the HTML it receives (15.3): the simplified part on the normal path, or the whole page when a page is translated whole. One placeholder counter runs across the whole document, so a placeholder number names the same source position in every part. A part translated in prose mode (4.8) uses only two of its passes, which lift the <pre> blocks and the Type D tables.
After the model call, the postprocessor puts the original bytes back in place of each placeholder (15.5). Before that, the placeholder-survival gate in translator/engine.py counts the placeholders in the response. A response missing more than three is refused and the chunk is translated again. A shortfall of three or fewer goes on to the postprocessor's anchor recovery, which puts the missing elements back (Invariant 17).
A part of a split document can open a tag that a later part closes, or close a tag that an earlier part opened. Since October 6, 2026 the preprocessor replaces each of these unmatched boundary tags with a TBI-BT boundary sentinel: an inert HTML comment that holds the tag's own text, base64-encoded. The comment is lifted into a placeholder like any other comment, so the tag crosses the model call as an opaque token, and it is decoded back into the tag after restoration. The boundary-signature gate (4.2) then checks that the translated part has the same unmatched-tag shape as its source.
The third mechanism runs inside each model call. Right before the call, the engine replaces every protected term (10.1) still left in the chunk's text with a __BT{N}__ token and puts the terms back after it, so a term that the wrapping and lifting above missed still never reaches the model. Prose mode does the same for each fragment (4.8). This per-chunk token is still in use and is separate from the retired sentinel system (3.2).
Before the document preprocessor, the engine protected content chunk by chunk, in eight passes, with __TBP{N}__, __TBO{N}__/__TBC{N}__, __TBN{N}__ and __TBT{N}__ tokens. That system is retired. Its entry point, engine._apply_sentinels, now only logs what the old system would have caught, at info level, and applies nothing (translator/engine.py:1504). It was already a no-op in the worker repository's first commit, on August 27, 2026.
Every translated chunk is validated against the source before acceptance. Validators enforce structural integrity and content preservation — if a translation passes all validators, it is guaranteed to be functionally correct (code works, links resolve, diagrams render).
| Validator | Type | What It Checks | Failure Example |
|---|---|---|---|
check_protected_terms | Hard | Every protected term in source appears in output | "CloudFront" missing from Japanese output |
check_version_numbers | Hard | All version numbers (X.Y.Z) survive translation | "17.7" dropped from PostgreSQL reference |
check_preserve_patterns | Hard | http:// and https:// URLs, matched as plain strings (the email check has been off since June 20, 2026) | A URL altered or dropped |
check_tag_counts | Hard | HTML tag counts match for structural tags | Extra <span> added or <code> dropped |
check_translate_no_zones | Hard | Content inside translate="no" zones unchanged | Protected code block content altered |
Protected term matching: Short uppercase acronyms (≤4 chars like SQS, ECR, S3) use word-boundary matching to avoid false positives where the acronym appears as a substring (e.g., "ECR" inside "SECRET"). Longer terms use plain substring matching.
Implementation (v2.5): The check_tag_counts and check_translate_no_zones validators use character scanning with exact boundary matching — no regex. We control these tags. We know that a tag starts with < and ends with >. The scanner finds complete opening tags by looking for <tagname followed by a boundary character (>, space, tab, newline, or /), then reads to the closing >. This eliminates false positives from partial regex matches and is immune to edge cases where tag names appear as text content (e.g., documenting translate="no" as literal text inside a code tag).
When validation fails, the engine retries with two progressive adjustments:
Underneath every attempt, each Bedrock call has its own size and its own clock. A call asks for an output cap sized from its input: the estimated input tokens × the largest output-to-input ratio measured for the target language × 1.5, never below 4,096 tokens and never above the model's ceiling. The ceiling is limits.max_output_tokens, 131,072 tokens since November 2, 2026, clipped to the maximum Bedrock accepts for each model: 65,536 for Qwen and 128,000 for Claude. Asking for more than a model's maximum is a validation error that is never retried, which is why the clip lives in code. The read timeout is sized from the cap: 60 seconds plus the cap divided by the model's slowest measured speed (35 tokens per second for Qwen, 25 for Claude), rounded up to the minute. A small chunk therefore waits minutes, not an hour, before a stalled call is abandoned.
Only the last attempt of the retry loop asks for the ceiling (since November 2, 2026). Every earlier attempt runs at its own input-sized cap and is never raised, so a reply that starts looping is stopped at that cap instead of spending the whole ceiling on every attempt. The final attempt asks for the model's full ceiling (FINAL-ATTEMPT CEILING in the log), so a legitimately long translation still has room to finish. A call outside the loop, such as a prose-mode call, keeps the older rule: if it stops exactly at its cap it is repeated once at the ceiling (CAP-ESCALATED), at most once per chunk. The SDK's own retries are switched off, so the engine has four retry layers: the validation loop above, the boundary-signature part retry and the element-shift gate below, and the regional failover in §12.
Maximum retries: 5, set per language in translation_language_profiles.max_retries (5 for all 127 languages since November 2, 2026) and read at job start, with the value in translation-config.json, also 5, as the fallback when Aurora is unreachable. A chunk therefore gets up to six attempts. If all attempts fail, a TranslationError is raised with the chunk index, validator detail, and a preview of the problematic chunk.
One more retry sits above the chunk loop. When a translated part fails the boundary-signature gate (its unmatched-tag shape no longer matches its source), the part is translated again, up to 3 attempts in all (limits.boundary_gate_attempts), attempt k running 0.1 × k warmer, before the pair fails. The gate is exactly as strict as before; a bad draw gets another chance. A BOUNDARY SIGNATURE RETRY line means a part was retried, and a pair that still fails after three refusals in a row points at its input rather than the model. Since November 22, 2026 the gate also checks placement (Invariant 37). When a part's signature equals its source's, the gate compares, for each unmatched closer, the elements open at that point with the source's. A closer that moved, such as a container's </div> placed inside the footer's first paragraph, is then a finding captioned part-boundary tags misplaced and is retried within the same three attempts. Since November 28, 2026 the check also covers each unmatched opener, by comparing its position among the part's start tags of the same name with the source's. For example, an opener put back in front of the closing tag of an earlier element with the same name is closed at once and leaves that earlier element open. Such an opener adds an openers misplaced clause to the same finding, after the closers clause when both are found. Placement is the only case where a part that passed the gate before can now fail. The recovery in front of the gate changed on November 22 as well: when the model drops a TBI-BT boundary sentinel whose source gap to the next token holds markup, recovery places it directly before the first tag of that gap, recorded as its bt_anchor, instead of directly before the next surviving token. It does so only when that tag occurs once between the surviving neighbours and the position is safe; otherwise the later recovery passes place it.
The element-shift gate is the last part-level layer (since November 12, 2026, Invariant 35). After a part passes every other gate, it looks for text that slid across element boundaries, such as a bold label holding the sentence after it or a heading holding the end of the paragraph above. It uses the same rule as the post-publish parity-audit, including the two exemptions the audit adopted on November 18, 2026: a bracketed gloss after an English word that the English element also holds, and a short label beside inline code, whose English text is 12 characters or fewer and whose translation is 30 characters or fewer with no Latin letters. A part with a finding is translated again up to limits.shift_gate_retries (2) times: a normal-path part at the next temperature step after the boundary gate's own attempts, and a prose-mode part with each block element's fragments joined on one line (4.8). The attempt with the fewest shifted elements is published, a tie keeps the earlier attempt, and a shift never fails a pair. A retry that fails the boundary gate, or that is further from the source than attempt 1 on any critical tag, Mermaid diagram count or placeholder, is unusable and never published, so a soft finding is never traded for a hard one. A separator the model adds to a prose line that was sent without one is removed and the line accepted. A clean part makes no extra call. The log lines start with the ↔️ arrow and SHIFT GATE, and each part's record carries the attempts (7.2a).
The retry count is per language, and that matters more than it looks. Five retries is what makes the temperature progression above reachable in full — 0.0 on the first attempt, then 0.1 up to 0.5. A language configured with max_retries = 1 only ever sees 0.0 and 0.1, so it gets one jittered attempt rather than five, and a failure it would have escaped on a later pass is recorded as a hard failure instead.
This was live for real. On 2026-08-30 the profiles held 3 for ar, hi, ja, ur and zh, 2 for ru, and 1 for de, es, fr, it and pt. The three languages that had been failing repeatedly on one document were es, pt and it — three of the five with the fewest attempts. A failure called "deterministic" on the strength of two identical runs had in fact only ever been given two sampling paths, not four. All eleven languages were set to 3 the same day, and on November 2, 2026 every one of the 127 languages was raised to 5.
Lesson worth carrying: before concluding a translation failure is deterministic, check how many attempts that language is actually configured for. A knob with a per-language default is a knob that can silently differ from the one you tested.
Validators are classified into two tiers based on what they protect:
| Tier | Tags | Behavior | Rationale |
|---|---|---|---|
| Hard (content-critical) | <code>, <pre>, <a> | Retry → reject on failure | Missing code blocks, broken links, or lost pre-formatted content means the translation is functionally broken |
| Soft (decorative/structural) | <span>, <strong>, <em>, <br> | Log warning, pass through | Missing styling wrappers don't break functionality — the post-translation integrity check repairs them |
This tiered approach eliminates the failure mode where a correctly-translated document is rejected because the model dropped a single decorative <span> wrapper during RTL reordering. The content is correct — only the styling wrapper is missing — and the integrity check restores it automatically.
The ValidationReport aggregates all results and exposes:
.passed — True if zero hard failures.hard_failures — list of blocking issues (content-critical tags).soft_failures — list of warnings (decorative tags — repaired post-translation).summary() — human-readable status stringAfter translation completes and chunks are reassembled, a full-document integrity check runs before the S3 write. This is the defense-in-depth layer — it repairs structural drift that the per-chunk validator intentionally allows through (soft failures).
| Issue | Detection | Repair Action |
|---|---|---|
</br> injection | String scan for invalid closing br tags | Strip all occurrences (never valid HTML) |
| Mermaid content corruption | When the diagram counts match, each block's stripped content is compared with the source block | Replace the block with the source block (logged as Repaired corrupted Mermaid block) |
Missing translate="no" span wrappers | Compare source protected elements to output | Re-wrap bare content with original element tags |
Missing <strong>/<em> wrappers | Same pattern as span recovery | Re-wrap bare content |
The integrity check only repairs translate="no" elements (where content is byte-for-byte identical between source and output). For translated content that lost its wrapper, the check logs the discrepancy but cannot reliably re-wrap (the content has been translated — matching it to the source wrapper requires semantic understanding). The Mermaid repair runs in the repair stage, before the tail steps, so a change a tail step makes inside a diagram is not seen by it.
Design principle: If the translated content is present and correct but the HTML structure is degraded, repair it. Only flag as unrecoverable if content is actually missing or corrupted. The customer sees a clean translation — the repairs happen invisibly.
Before any translation work begins, the source document passes through a validation gate. This catches defects that would cause translation failures or produce broken output — rejecting early saves Bedrock tokens and prevents corrupted translations from reaching S3.
| Category | What It Catches | Auto-Repairable? |
|---|---|---|
| STRUCTURAL | Unclosed tags, malformed HTML, nesting violations | Yes (up to 5 unclosed tags) |
| MERMAID | An empty diagram block (an error); an unrecognized diagram type, mismatched brackets or an odd number of single quotes (warnings: listed in the report, and the document still translates) | No — an empty block is rejected with its location |
| ENCODING | BOM markers, null bytes, mixed encodings | Yes (strip BOM/nulls) |
| SIZE | Document exceeds 500,000 characters (counted on decoded text, not bytes), excessive nesting depth (>30 levels) | No — reject with size info |
| CONFLICT | translate="no" on root element (nothing to translate) | No — reject immediately |
skip_validation: true, so this check never rejects them, though its repairs still apply. Customer documents are already bounded by the separate 300 KB (307,200-byte) cap, enforced by the LPO at the quote and again at the accept re-fetch. The two limits measure different things and are never the same number.pre, code, table, div and section only, up to 5<pre class="mermaid"> block, and warn, without rejecting, when a block does not start with a recognized diagram type, when its opening and closing brackets differ by more than three, or when it holds an odd number of single quotes. Only errors make a source invalid, so a warning tells you what to look at while the translation goes ahead. The type check recognizes the 15 diagram types on its list, the camelCase ones included (sequenceDiagram, classDiagram, stateDiagram, erDiagram, quadrantChart); a type that is not on the list, such as journey, still draws the warning. Until worker 7dd1095 went live on November 7, 2026 it compared those names against a lower-cased line, so every such diagram drew a false warning; the keyword list is now lower-cased too.<body> or <html> element has translate="no"The validator follows a strict philosophy: try to fix it silently, reject early if you can't. Repairable issues (unclosed tags, BOM markers) are fixed in-place — the customer never knows. Unrecoverable issues produce an actionable defect report with the exact location, what's wrong, and how to fix it. For customer quote jobs (skip_validation: true) the repairs run and the rejections do not, because those documents were already checked at the quote and at accept; internal jobs get both.
ValidationResult:
valid: false
rejection_reason: "2 unrecoverable defects found"
defects:
- severity: error
category: MERMAID
location: "Section 5, line 342"
description: "Empty Mermaid block — no diagram content"
suggestion: "Add diagram content or remove the empty <pre class='mermaid'> block"
- severity: error
category: SIZE
location: "Document root"
description: "Document is 626,688 characters (612 KB). Maximum is 500,000 characters (488 KB)."
suggestion: "Split into multiple documents or remove large embedded assets"
Cost savings: A rejected document costs zero Bedrock tokens. Without source validation, a broken document would fail during translation (after burning tokens on partial chunks), produce a corrupted output, and require manual investigation. Source validation catches these cases in <10ms with zero API calls.
Mermaid diagrams are code — they must survive translation byte-for-byte. The integrity check (section 4.4) now includes dedicated diagram verification with automatic recovery.
The integrity check counts Mermaid blocks in the source (<pre class="mermaid">) and compares against the translated output. If any diagrams are missing from the output, the auto-stitch mechanism activates.
When a diagram is missing from the translated output:
<div class="diagram-wrap"> block from source (includes label + pre)The stitched diagram is the English version, which is functionally correct — Mermaid syntax is language-independent. The surrounding prose is already translated, so the reader gets translated explanations with a working diagram.
The _count_tags function now reports diagram count alongside other structural tags:
Tag Inventory (source → output):
• Trinity-Beast-Performance-Report.html
IN: code:75 pre:8 strong:12 em:3 a:6 br:20 diagrams:4
OUT: code:75 pre:8 strong:12 em:3 a:6 br:20 diagrams:4
If a diagram is lost during translation and auto-stitched back, the final count still matches — the stitch happens before the tag inventory is calculated. A mismatch in the diagrams count after stitching indicates a structural issue that needs manual review.
Result: The Performance Report (75 KB, 4 Mermaid diagrams, 18 sections) translates to French with all 4 diagrams intact — 3 survived translation naturally, 1 was auto-stitched from source. The reader sees no difference.
Defense-in-depth: even with perfect preprocessing, models occasionally drop or mangle structural elements. The repair pipeline runs after translation and before final validation, catching anything that slipped through.
_repair_code_tags)Multi-pass repair (up to 6 iterations) that detects dropped <code> wrappers by comparing the translated output against the source document. For each code-tagged value in the source, it searches the output for the bare content and re-wraps it with the original tag. Converges when no more repairs are possible.
| Input (broken) | Output (repaired) |
|---|---|
api_key parameter requires... | <code translate="no">api_key</code> parameter requires... |
the timestamptz column stores... | the <code translate="no">timestamptz</code> column stores... |
The repair function matches content from the source's code tags against the output using exact string matching. It handles both self-closing patterns and open/close pairs. Each pass may reveal new repair opportunities (nested cases), hence the multi-pass design with a convergence check.
_tidy_validate_and_repair)Structural HTML repair using lxml's robust parser. Catches and fixes issues that the model introduces in the HTML structure itself — unclosed tags, nesting violations, mismatched attributes, and malformed output. This is the final safety net before the translated chunk is accepted.
| Issue Detected | Action |
|---|---|
Unclosed <div> or <span> | Auto-close at the correct nesting level |
| Orphaned closing tags | Remove (no matching opener) |
Invalid nesting (e.g., <p> inside <p>) | Restructure to valid hierarchy |
| Malformed attributes | Normalize quotes and spacing |
Parses with lxml's error-recovering parser, etree.HTMLParser(recover=True), so no external binary is needed (lxml is in the container's requirements.txt). It rewrites the HTML only when the parser reports an unfinished tag or a tag name mismatch. It keeps the original when parsing raises an exception, when the repaired HTML is more than 10% shorter than the input, or, for a full document, when the repair would lose the <head> or the closing </html>. There is no BeautifulSoup fallback.
_check_output_integrity)Final gate before a translated chunk is accepted. Compares structural tag counts between source and output — every <code>, <pre>, <strong>, <em>, <a>, <br>, and Mermaid diagram must have matching counts. If counts diverge beyond tolerance, the _recover_missing_wrappers() function attempts targeted restoration before rejecting the chunk.
tag_recovery/ module — v5.1)Different languages exhibit different tag-drop patterns. Arabic and Urdu (RTL) tend to drop trailing <br> tags because their paragraph flow doesn't rely on line breaks the same way English does. Hindi sometimes splits or merges <strong> spans when the translated phrase length differs from English. CJK languages occasionally omit <br> at list boundaries. Latin/Cyrillic languages rarely have issues.
Rather than applying a one-size-fits-all fixer, the tag recovery system dispatches to per-language Python scripts — one file per supported language, each encoding the known behavioral patterns for that script type:
| Module | Language | Known Patterns |
|---|---|---|
tag_recovery/ar.py | Arabic | RTL <br> drops, <strong> reordering around punctuation |
tag_recovery/ur.py | Urdu | RTL <br> drops at list boundaries, <strong> merging |
tag_recovery/hi.py | Hindi | <strong> splitting, <br> drops at danda boundaries |
tag_recovery/ja.py | Japanese | Occasional <br> drop (continuous flow with ideographic period) |
tag_recovery/zh.py | Chinese | Occasional <br> drop at list boundaries |
tag_recovery/es.py | Spanish | Rare — <strong> split on longer phrases |
tag_recovery/pt.py | Portuguese | Rare — similar to Spanish |
tag_recovery/fr.py | French | Rare — restructuring around non-breaking space punctuation |
tag_recovery/de.py | German | Rare — compound word <strong> merges |
tag_recovery/ru.py | Russian | Rare — <br> drop in technical passages |
tag_recovery/it.py | Italian | Rare — similar to Spanish/Portuguese |
Flow: After Bedrock returns a translated chunk, the dispatcher (tag_recovery/__init__.py) counts tags in both source and output using common.py utilities. If counts match, it skips. If they differ, it loads the language-specific fixer and applies deterministic repairs:
count_tags() counts <br>, <strong>, <em>, <code>, <a>, <span>, <pre><br> at sentence boundaries, wrap unwrapped <strong> terms, remove spurious extrasAll operations use direct string comparison — no regex. The convention: tags are structural, deterministic, and countable. Either the bytes are there or they aren't. Each language file is small, focused, and independently extensible as new patterns emerge.
Design principle: Preprocessing is the fortress — strip everything non-prose before the model sees it. Post-processing is defense-in-depth — repair anything that slips through. The goal is zero repairs needed because prep was thorough, but the safety net is always active. The per-language tag recovery system adds surgical precision — each language gets the fixer it needs, not a generic approximation.
When the normal translation path (preprocessor + Bedrock) produces catastrophic code tag loss, the system automatically re-translates the affected part through prose mode — a fundamentally different translation strategy that preserves structural elements by design.
The hint validation system counts <code> tags in each translated part immediately after Bedrock returns. If the drift exceeds tolerance, the fallback fires:
actual_code = count(<code> tags in translated output)
drift = actual_code - hint_code
tolerance = max(3, hint_code × 0.15)
if abs(drift) > tolerance:
→ FALLBACK: re-translate this part via prose mode
<pre translate="no"> blocks from the source part (byte-perfect preservation)extract_prose() walks the DOM and extracts only translatable text fragments, leaving all HTML structure untouchedrebuild_with_translations() inserts translated fragments back into the original DOM skeletonThe normal path sends full HTML to Bedrock — the model must understand and preserve all structural elements while translating. Prose mode inverts this: it never shows the model any HTML. The DOM is the skeleton; only the text content moves through the model. Code tags, pre blocks, spans, and all structural HTML remain in the skeleton untouched — they were never at risk.
The skeleton does not stop text from moving between fragments of one element. A bold label and the sentence after it are two fragments, and the model can merge and re-split them so that the label holds the sentence. When the element-shift gate (4.2) finds that in a prose part, its retry sends the fragments that share one block element, such as a list item, paragraph, table cell or heading, as one line of up to four fragments, with __LS{k}__ markers where one fragment ends and the next begins. The reply is split back on the markers into the original slots before the identity gate and the rebuild, so on one line there is nothing to merge across. A reply line whose markers are missing, repeated, extra or out of order makes the whole retry unusable and the earlier attempt stands. Every part's first attempt is sent exactly as before.
Part 3 of this document has density=high, code=15. On the normal path, Qwen consistently dropped all 15 code tags (drift -15). The fallback re-translates through prose mode — 15/15 code tags preserved, validation passes, job succeeds.
Design principle: The normal path is fast (one Bedrock call per chunk). Prose mode is more reliable but slower (one call per fragment batch). The fallback uses prose mode only when the normal path fails validation — giving you speed in the common case and reliability in the edge case. If both paths fail, the original output is kept and the full-document integrity check handles the final disposition.
Translation execution is handled by BeastTranslate — a persistent ECS Fargate service (tbi-translate-worker-service) that continuously polls the SQS translation queue for jobs. Unlike the previous Step Function → RunTask model (v3.0), BeastTranslate is always-on — no cold starts, no orchestration overhead, instant job pickup.
Diagram 5.1: BeastTranslate Persistent Worker Architecture
flowchart TD
SQS["SQS Translation Queue: one message per language"] --> LP["Long-Poll Loop - 20s wait"]
LP -->|Message received| DM["Deserialize Job Message"]
DM --> EM{"Multi-Language?"}
EM -->|Single lang| RT["Process In-Place"]
EM -->|Multi-lang| BT["Scale Service to N Containers, at most 12"]
BT --> PAR["N Containers Poll Same Queue"]
PAR --> EACH["Each Takes 1 Language Message"]
EACH --> LRT["Load Language Runtime: catalog row + profile, 15-min cache"]
RT --> LRT
LRT --> PROC["Translate All Docs for That Language"]
PROC --> EV["Per-pair events: POST /admin/translate/event/job_id"]
EV --> CC{"Before publish: job cancelled?"}
CC -->|No| PUB["Write to S3"]
CC -->|Yes| CXL["Stop: lang_cancelled, nothing published"]
CC -->|Any job, state unknown| UNK["Fail closed: lang_failed cancel-state-unknown"]
PUB --> LAST{"Last worker of the job?"}
CXL --> LAST
UNK --> LAST
LAST -->|Yes| CMP["POST /admin/translate/complete/job_id"]
LAST -->|No| DONE
CMP --> DONE{"More Messages?"}
DONE -->|Yes| LP
DONE -->|No - queue empty| IDLE["IDLE - Resume Polling"]
IDLE --> LP
subgraph GS["Graceful Shutdown"]
SIG["SIGTERM or SIGINT"] --> FIN["Stop at the next part boundary"]
FIN --> CLEANEX["One lang_cancelled, message kept"]
SIG -->|No boundary within 90 s| DEADL["90 s deadline: one lang_cancelled, then os._exit(0)"]
end
subgraph VH["Visibility Heartbeat"]
HB["Every 5 min"] --> EXTVIS["Extend SQS Visibility"]
EXTVIS --> PREV["Prevent Re-Delivery"]
end
style GS fill:#1e293b,stroke:#c084fc,color:#e2e8f0
style VH fill:#1e293b,stroke:#60a5fa,color:#e2e8f0
style SQS fill:#2e1065,stroke:#a78bfa,color:#e2e8f0
style LP fill:#7c2d12,stroke:#fb923c,color:#e2e8f0
style DM fill:#7c2d12,stroke:#fb923c,color:#e2e8f0
style EM fill:#1e3a5f,stroke:#60a5fa,color:#e2e8f0
style RT fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style BT fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style PAR fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style EACH fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style LRT fill:#1e3a5f,stroke:#60a5fa,color:#e2e8f0
style PROC fill:#92400e,stroke:#fbbf24,color:#e2e8f0
style EV fill:#064e3b,stroke:#10b981,color:#e2e8f0
style CC fill:#7f1d1d,stroke:#f87171,color:#e2e8f0
style PUB fill:#064e3b,stroke:#10b981,color:#e2e8f0
style CXL fill:#3f3f46,stroke:#a1a1aa,color:#e2e8f0
style UNK fill:#7f1d1d,stroke:#f87171,color:#e2e8f0
style LAST fill:#1e293b,stroke:#334155,color:#e2e8f0
style CMP fill:#064e3b,stroke:#10b981,color:#e2e8f0
style DONE fill:#1e293b,stroke:#334155,color:#e2e8f0
style IDLE fill:#1e293b,stroke:#334155,color:#e2e8f0
style SIG fill:#4c1d95,stroke:#c084fc,color:#e2e8f0
style FIN fill:#4c1d95,stroke:#c084fc,color:#e2e8f0
style CLEANEX fill:#4c1d95,stroke:#c084fc,color:#e2e8f0
style DEADL fill:#4c1d95,stroke:#c084fc,color:#e2e8f0
style HB fill:#1e3a5f,stroke:#60a5fa,color:#e2e8f0
style EXTVIS fill:#1e3a5f,stroke:#60a5fa,color:#e2e8f0
style PREV fill:#1e3a5f,stroke:#60a5fa,color:#e2e8f0
linkStyle 0,1 stroke:#a78bfa,stroke-width:2px
linkStyle 11,12,15,18,20 stroke:#10b981,stroke-width:2px
linkStyle 14,17 stroke:#f87171,stroke-width:2px
| Property | Value |
|---|---|
| Service Name | tbi-translate-worker-service |
| Cluster Node | BeastTranslate |
| Image | 211998422884.dkr.ecr.us-east-2.amazonaws.com/tbi-translate-worker:latest |
| Resources | 2 vCPU / 6 GB (per container) |
| Default Desired Count | 1 |
| Max Scale | 12 (one per language of a job; a quote holds at most 12) |
| Runtime | Python 3.11 |
| Entry Point | task_runner.py |
| IAM Role | tbi-translate-role |
| Queue | trinity-beast-translation-queue |
| Log Group | /ecs/tbi-translate-worker |
| Timeout | None — runs to completion |
| Stop Timeout | 120 s (task definition stopTimeout, the Fargate maximum): a worker told to stop is killed if it is still running 120 s later (Graceful Shutdown below) |
| AZ Rebalancing | availabilityZoneRebalancing DISABLED, and it stays off (decision of November 22, 2026): rebalancing stops a busy worker in the middle of a job |
BeastTranslate runs a continuous polling loop. When no jobs exist, it idles — consuming negligible CPU while maintaining a warm connection to SQS. The moment a translation job is submitted, the container picks it up within seconds (no cold start, no orchestration delay).
receive_message(WaitTimeSeconds=20) — blocks for up to 20 seconds waiting for a messagefetch through record (2.1)SQS message visibility timeout to prevent re-delivery during long-running documentsPOST /admin/translate/event/{job_id}, and when the pair ends it posts its estimate-versus-actual record to POST /admin/translate/pair-record/{job_id} (7.2a). Two exits post no record: a pair skipped because it already succeeded in this job (its earlier record stands), and a pair stopped by the 90-second shutdown deadline (the server fills its record from the lang_cancelled event). The last worker of the job calls POST /admin/translate/complete/{job_id}SQS once the job has been processed, including a job with failed pairs. It is kept when the worker is told to stop (Graceful Shutdown below), and a crash leaves it undeleted, so in both cases SQS delivers it againBeastTranslate scales itself automatically — no manual intervention required. The system determines container count from the job's language list at submission time, then scales back to 1 when all work completes.
When a translation job is submitted via POST /admin/translate, the LPO server inspects the langs array:
desired = len(langs) — one container per language for full parallelismtxlimits.MaxLangsPerQuote, the same constant that caps a quote, so a 12-language job never leaves its 12th language waiting for a free containerecs:UpdateService(desiredCount=N) fires immediately after the job is enqueued to SQSWhen a worker completes a job, the finalize step checks for remaining work before scaling down:
GET /admin/translate/queue — checks active and queued job countsecs:UpdateService(desiredCount=1) — scale back to steady-stateThis handles back-to-back batch submissions (e.g., 6 docs + 6 docs) correctly — the first batch to finish won't tear down containers while the second is still running.
| Scenario | Containers | Trigger |
|---|---|---|
| Idle (no jobs) | 1 | Default steady-state — near-zero CPU |
| Small job (1–3 languages) | 1–3 | Auto-scaled at submission: desired = len(langs) |
| Full library (11 languages) | 11 | Auto-scaled at submission — full parallelism |
| Largest customer quote (12 languages) | 12 | Auto-scaled at accept — every language runs at once |
| Post-batch (all jobs done) | 1 | Auto-scaled down by finalize step when queue is empty |
Zero operator involvement. Submit the job, walk away. The infrastructure sizes itself to the workload, processes at maximum parallelism, then shrinks back to 1 idle container. KCC manual commands (translate-scale N) still work as an override but are no longer needed for normal operation.
When ECS stops a worker (scale-down or deployment), it sends SIGTERM and kills the task if it is still running 120 seconds later. The worker treats SIGINT the same way. The first signal sets the worker's shutdown flag and starts a 90-second timer; a second signal does nothing. Then:
lang_cancelled with reason: "worker_shutdown", carrying what its Bedrock calls spent (the pair's token meter), and its pair record says cancelled / worker_shutdown. It writes no progress and publishes nothing.MESSAGE KEPT … SQS will redeliver it) and exits.A part can run longer than the stop timeout, because ceiling calls and gate retries happen inside one part. If the pair has not reached a boundary when the 90-second timer fires, the timer posts the pair's one lang_cancelled from the live meter (reason: "worker_shutdown_deadline"), releases the pair's in-flight lock so the redelivered message is not refused, and calls os._exit(0). Each of those two requests gets 5 seconds to connect and 5 seconds per read, so the worst case is 90 + 10 + 10 = 110 seconds, inside the 120-second stop timeout. The deadline posts no pair record (the server fills it from the event) and does not add the pair to the Valkey daily counters (8.2).
When SQS delivers the message again, the next worker skips every pair that already succeeded in this job (5.2) and translates the interrupted pair from its start, not from the part where it stopped.
The worker runs in persistent polling mode, continuously polling SQS for translation messages. Each message = one language × all docs for that job. Auto-scaling provides parallelism across languages.
Diagram 5.2: BeastTranslate Auto-Scaling — Multi-Language Job Flow
sequenceDiagram
participant Admin as Operator or Customer accept
participant LPO as LPO Server
participant ECS as ECS Service
participant SQS as SQS Queue
participant BT1 as BeastTranslate 1
participant BT2 as BeastTranslate 2-12
rect rgba(96, 165, 250, 0.14)
Admin->>LPO: POST /admin/translate (3 docs x 12 langs)
LPO->>LPO: Insert the job row before any send
LPO->>SQS: 12 messages, one per language (each carries all 3 docs)
LPO->>ECS: UpdateService(desiredCount=12)
LPO->>Admin: 200 OK (job_id, state: queued)
end
Note over ECS: Spins up 11 new containers (one task took 22s on Nov 28, 2026)
Note over BT1: Already polling (always-on)
BT1->>SQS: ReceiveMessage
SQS-->>BT1: One language message (all 3 docs)
BT2->>SQS: ReceiveMessage (competing consumers)
SQS-->>BT2: One language message each
rect rgba(251, 191, 36, 0.12)
par 12 containers process in parallel
BT1->>BT1: es - all 3 docs
BT2->>BT2: fr, de, ru, ja, zh, ar, hi, ur, pt, it, ko
end
end
BT1->>LPO: Per-pair events (lang_started, lang_succeeded, lang_failed)
BT2->>LPO: Last worker: POST /admin/translate/complete/job_id
rect rgba(52, 211, 153, 0.14)
LPO->>LPO: Final state, search rebuild, queue check
LPO->>ECS: UpdateService(desiredCount=1) once the queue is empty
Note over ECS: 11 containers drain gracefully
alt Customer job
LPO->>Admin: Customer completion email, failed pairs go to the refund machine
else Internal job
LPO->>Admin: Ops SNS notification email
end
end
| Failure Mode | Handling | Job State |
|---|---|---|
| A pair fails validation after its retries | The worker records lang_failed for that pair and moves on; the job's other documents and languages keep running | partial |
| Every language of a document fails | Nothing is published for that document. The job ends partial, or failed when no pair at all succeeded | partial / failed |
| A pair runs for a long time | No timeout ceiling. A background heartbeat extends the queue message's visibility every 5 minutes and posts a worker_heartbeat event, so the sweeper never fails a job that is still working | running |
| A worker crashes mid-message | The message is not deleted, so it becomes visible again and is delivered to a worker once more (the pair record keeps the receive count); an in-flight lock keeps two workers off the same pair. Every delivery, first or repeated, asks Aurora before each pair whether it already has a lang_succeeded in this job (one parameterized read, 10-second timeout). A pair that does prints ALREADY SUCCEEDED and returns skipped / already_succeeded at $0, with no event, progress write or pair record. An answer that cannot be read means the pair is translated (fail-open). The check is per job: a pair that succeeded in an earlier job is translated again | running |
| ECS stops a worker (scale-down or deploy) | The pair stops at its next part boundary and posts one lang_cancelled (worker_shutdown) carrying its spend. Nothing is published, the job is not finalized, and the message is kept for redelivery. If no boundary comes within 90 seconds, a deadline posts the same event and exits (Graceful Shutdown, 5.1) | running |
| Operator cancels mid-flight | The job is marked cancelled at once (6.3); each worker stops at its next cancel check, and pages already published stay live | cancelled |
| A job goes silent | The self-healing sweeper (5.4) fails it only when neither it nor any other job has written an event for 15 minutes | failed |
| A pair fails on a customer job | The pair enters the failed-pair refund machine when the job ends: one free retry, then an automatic refund for what is still undelivered. lang_rejected counts as failed for customer jobs | partial / failed |
Per-lang independence: Failure of one (doc, lang) pair never aborts work on the other languages. That holds by construction: each language runs in its own container from its own queue message, and the worker records a failed pair as an event and moves on to the next document instead of raising, so errors are captured as data, not propagated as exceptions.
Simplified June 27, 2026. The EventBridge Pipe, Step Function (tbi-translation-orchestrator), and all translation Lambdas (tbi-translate-init, tbi-translate-deploy, tbi-translate-finalize) have been deleted. The pipeline is now: LPO server → N SQS messages (one per language) → N BeastTranslate containers → POST /admin/translate/complete/{job_id}. Zero orchestration layers. Full pipeline control from the container.
The sweeper runs every 15 minutes on a timer in the LPO server (tx_stuck_job_sweep; every container runs the timer, and an advisory lock lets only one of them sweep at a time), and on demand through POST /admin/translate/sweep. Until October 11, 2026 it ran inside every GET /admin/translate/health call. It moved because a check that only observes the system must never be able to change it, and the health response's swept_jobs now reports what the timer last swept.
It scans all jobs in tx:active (the Valkey SET of active job IDs). Age alone never condemns a job, because a multi-document job legitimately runs far longer than 15 minutes; silence does. For each job older than 15 minutes in queued or running state:
worker_heartbeat event every 5 minutes, because pairs write events only when they start and finishfailed, removed from tx:active, updated in Aurora with its reason, and its pairs closed through the write-back (19.5)All sweep actions are logged to translation_job_events (job_swept) for audit trail.
A second sweeper keeps the promises made to paying customers. It is an LPO timer, tx_failed_refund_sweep, that ticks every 15 minutes (refund.sweep_interval_minutes) and takes a transaction-scoped advisory lock so only one container sweeps at a time. Its step 0 finishes any customer job nobody finalized (TX-FINALIZE-CATCHUP), claiming the job's finalizing phase as a 15-minute lease so a tick that dies is picked up by the next one. The later steps close retry windows, issue refunds that are due, and refund a paid quote whose job never started. Every step is a re-runnable conditional update in Aurora, so a restart never loses or repeats work, and POST /admin/translate/refund-sweep runs one tick on demand.
Result: This eliminates the stuck queue problem permanently — no manual cleanup needed. Jobs that silently fail are automatically detected and marked, keeping the active set accurate and the queue healthy.
The job state now reflects the exact phase of execution:
| Phase | Meaning |
|---|---|
queued | Submitted to SQS, waiting for BeastTranslate to pick up the message (typically <20 seconds) |
running | BeastTranslate received the message, worker translating documents |
deploying | Legacy phase of the retired deploy Lambda. No new job enters it; older rows that still carry it are finished by the catch-up exactly like running |
finalizing | Each worker has invalidated CloudFront for the pages it published, including pairs that had already succeeded in this job, and the last worker called POST /admin/translate/complete/{job_id}; the LPO gathers the results from Aurora, rebuilds the search index and sends the email. For a customer job nobody finalized, the 15-minute refund sweeper claims this phase as a 15-minute lease, so a tick that dies is picked up by the next one |
succeeded / partial / failed | Terminal states — all sub-tasks complete, email notification sent |
This gives real-time visibility into exactly where a job is in the pipeline.
All endpoints require the X-Admin-Key header. They are served by the LPO server (Go) alongside the existing admin routes.
This section covers the 12 endpoints the translation pipeline uses. The glossary endpoints are described in 10.4, and 2.2 gives the full count of routes registered under /admin/translate.
POST /admin/translateSubmits a new translation job. Validates inputs, checks the daily token limit and the kill switch, creates job state in Valkey, inserts the translation_jobs row synchronously (on a detached 60-second context, and under the quote row lock for a customer quote job) before any SQS send, then enqueues one message per language. Before it writes the job row or sends anything, it reads the job's glossary (10.4); if that read fails it answers 500 translate_glossary_load_failed, and nothing is written or sent. first_enqueued_at marks the first successful send, which is what makes a row count as started.
// Request
POST /admin/translate
X-Admin-Key: tbcc-admin-...
X-Idempotency-Key: my-unique-key (optional)
Content-Type: application/json
{
"docs": ["Trinity-Beast-API-Reference.html", "Trinity-Beast-Architecture-Guide.html"],
"langs": "all",
"options": {
"force": false,
"delta": false,
"skip_search_rebuild": false,
"skip_validation": false
}
}
// Response 200
{
"status": "✅ [LPO] [us-east-2] [BeastMain] [/admin/translate] [200]",
"status_code": 200,
"endpoint": "/admin/translate",
"cluster_node": "BeastMain",
"region": "us-east-2",
"language": "en",
"timestamp": "2026-05-16T16:42:00Z",
"data": {
"job_id": "1747407720-a3f8b2c1d4e5",
"state": "queued",
"submitted_at": "2026-05-16T16:42:00Z"
},
"error": ""
}
Validation rules:
docs — required, 1-42 entries (txlimits.MaxDocsPerQuote; more answers 400 translate_max_docs), each must be a valid filename in S3langs — "all" (expands to the internal 11) or an array of 1-12 codes, each resolved through the 127-language catalog and its alternate codes (input shape 2-12 characters) and de-duplicated. An unknown code answers 400 translate_langs_invalidoptions.force (or a top-level force) — bypasses three checks: the in-flight lock (never acquired), the failure history and the too_dense rejection. Since November 28, 2026 it does not bypass the already-succeeded check (5.2). The failure-history check is skipped for every customer job (quote_id), with or without forceoptions.delta (or a top-level delta) — JSON true turns on part reuse for library pairs (17); anything else, including no delta at all, is a full runautoops:bedrock:tokens:input:daily + autoops:bedrock:tokens:output:daily)SQS, and a warning is recorded in the Valkey list tx:warnings when 12 or more are activeGET /admin/translate/status/{job_id}Returns the full job state. Aurora is the primary source — state, timestamps, docs, langs and cost are read from translation_jobs. Real-time per-doc/lang progress is overlaid from Valkey (written per-pair by the worker, too frequent for Aurora writes). If Aurora cannot answer, the status falls back to Valkey. The submit handler inserts the row synchronously before any send (6.1), so this fallback covers an Aurora outage, not a race with the insert.
GET /admin/translate/queueLists all pending and active jobs (state in queued or running).
GET /admin/translate/historyReturns the last 50 completed jobs from translation_jobs in Aurora, ordered by submission date descending. Includes state, docs, succeeded/failed pair counts, cost, and reason. Falls back to the Valkey tx:history list if Aurora is unavailable.
GET /admin/translate/healthSystem health overview:
{
"status": "✅ [LPO] [us-east-2] [BeastMain] [/admin/translate/health] [200]",
"status_code": 200,
"endpoint": "/admin/translate/health",
"cluster_node": "BeastMain",
"region": "us-east-2",
"language": "en",
"timestamp": "2026-05-16T17:30:00Z",
"data": {
"queue_depth": 0,
"active_jobs": 1,
"last_completed_at": "2026-05-16T17:30:00Z",
"last_state": "succeeded",
"daily_spend_usd": "…",
"daily_input_tokens": 284150,
"daily_output_tokens": 312480,
"daily_token_limit": 50000000,
"swept_jobs": 0
},
"error": ""
}
POST /admin/translate/cancel/{job_id}Marks the job cancelled in Aurora first, with a conditional update that only a job not yet finished can win, then in Valkey, and records who cancelled it. Each worker stops at its next cancel check (before a pair starts, before each part, before each boundary-gate retry, before each shift-gate retry, and the fail-closed check before publish), so pages already published stay live and nothing more is published. For a customer's parent job the quote starts its cancel refund. The job's spend and pair actuals are rolled up from its events, and the cancel notification goes out once no pair is still in flight. Returns 404 for an unknown job and 409 if it is already in a terminal state. This is the one cancel path: the customer API and the customer dashboard call the same code.
POST /admin/translate/retry-failed/{job_id}Creates a new job from the failed (doc, lang) pairs of a completed-with-partial job. Returns 409 if the original is still running. A retry runs on the same model as the original job. The handler walks retry_of back to the root job, so even a retry of a retry inherits the first job's model, and writes that model to the new translation_jobs row, the Valkey job hash and the queue message. Before this fix the model was in neither the message nor options, which is why inheriting options alone did not carry it; it now travels at the top level of the message and in options.model. A root job with no recorded model retries on Qwen 3 235B, our standard, never on a fallback.
Inherits the parent job's routing options as of 2026-09-06 — fixed after shipping a wrong deliverable. The handler used to build the retry's options from a bare {"force": true}, discarding everything else the parent job carried. For a customer job that includes quote_id, source_bucket/source_prefix, output_bucket/output_prefix, skip_validation, and execution_mode — the entire routing that sends a translation to the customer's own S3 prefix instead of the internal document library. A retry that dropped those routed the retried pair to the wrong bucket while still reporting succeeded. The handler now reads the parent job's options column from Aurora and inherits it wholesale, overriding only force.
Customer jobs: a retry of a customer job goes through ExecuteCustomerRetry, the same path the customer's Retry button uses. That means one free retry per quote, only the retryable failed pairs, the quote's own agent read from translation_quotes.model / model_by_lang, and translation_jobs.quote_id set on the retry job. An operator can never reopen a pair that was already refunded.
POST /admin/translate/refund-sweepRuns one tick of the failed-pair refund sweeper (5.4) now. Returns {opened, closed_none, due, issued, failed, errors}; 409 translate_refund_sweep_busy when another container holds the lock, 503 translate_refund_sweep_failed when the sweep couldn't run.
POST /admin/translate/sweepManually triggers the self-healing sweeper. Idempotent — safe to call repeatedly.
// Response 200
{
"status": "✅ [LPO] [us-east-2] [BeastMain] [/admin/translate/sweep] [200]",
"status_code": 200,
"endpoint": "/admin/translate/sweep",
"cluster_node": "BeastMain",
"region": "us-east-2",
"language": "en",
"timestamp": "2026-05-16T18:00:00Z",
"data": {
"swept": 1,
"checked": 3,
"results": [
{
"job_id": "1747407720-a3f8b2c1d4e5",
"prior_state": "running",
"submitted_at": "2026-05-16T16:42:00Z",
"sfn_status": "unknown",
"action": "self-healed: worker job stalled (no translation events for 15+ min, and no other job progressing either)"
}
]
},
"error": ""
}
These endpoints are called by the BeastTranslate worker to update Aurora without needing direct database access (the worker runs outside the VPC). Until June 27, 2026 the finalize Lambda called them too; it was deleted with the Step Functions pipeline (5.3).
POST /admin/translate/update/{job_id}Updates job state, progress, cost, and timing fields. Called by the worker after each (doc, lang) translation.
POST /admin/translate/event/{job_id}Records a granular event in the translation_job_events table. Used for audit trail — each doc/lang start, success, failure, retry is logged as a separate event. These outcomes carry more than a status:
lang_rejected with reason: "target_is_source": the worker found, for certain, that the document is already in the target language. It is non-retryable, so the pair is refunded rather than retried.lang_failed with error: "cancel-state-unknown": the before-publish cancel check could not read the job's state after three attempts, so the worker failed closed and published nothing. Since November 7, 2026 every job runs that check, internal and customer alike, because both paths share one process. The known-failure guard ignores this outcome (Invariant 27): it says nothing about the document or the engine, so the next run retries the pair.lang_failed from an unexpected error names the stage that raised it in stage (the log line reads WORKER ERROR … stage=).lang_cancelled with reason: "worker_shutdown" or "worker_shutdown_deadline": the worker was told to stop and the pair was interrupted (5.1). The lang_cancelled of a cancelled job (6.3) carries no reason. The job is not finished, and the redelivered message translates the pair again.lang_skipped with reason: "delta_up_to_date": every part of a library pair was reused, so nothing was translated or published (17.4).lang_succeeded on a library pair also carries parts_total, parts_reused and parts_translated.POST /admin/translate/pair-record/{job_id}Stores the actual half of a pair's estimate-versus-actual record (7.2a). The worker posts once per pair when the pair ends, so a cancelled pair still records what it had at that moment. Two exits post no record: a pair skipped because it already succeeded in this job (its earlier record stands), and a pair stopped by the shutdown deadline (the server fills its record from the lang_cancelled event). The admin key proves who is calling, not what the payload says, so every field is validated: a bad field answers 400 and names the field, an unknown job answers 404 and an oversized body 413. Whether a post replaces the stored actuals is decided by outcome, then by source, then by time: a worker record always replaces one rebuilt from events, a backfill post never replaces a worker record, and a skip never hides a real run. A pair that has no estimate row yet (its seeding was missed) gets a late estimate from the same rules the job's seeding uses.
Fire-and-forget pattern: The update and event endpoints always return 200 regardless of Aurora write outcome. The translation pipeline must never fail because observability data couldn't be written. Errors are logged but never propagated.
The pair-record endpoint answers honestly instead (400, 404, 413, or 503 when Aurora cannot store a valid record), and the worker keeps the same promise on its side: it retries twice on a transport error or a 5xx, and a record it still cannot store prints PAIR RECORD NOT STORED with its reason and never fails the pair. The server then fills that pair's actuals from its events when the job ends.
Aurora is the authoritative record for all translation job state. Valkey serves one specific role: real-time per-pair progress updates during active execution (written too frequently for Aurora). For everything else — job state, history, cost, audit trail — Aurora is read first.
Design principle: Valkey is the price cache, search indexes, and real-time counters. It is not a job ledger. Aurora is the ledger. When you need to know what was translated, when, at what cost, and with what result — query Aurora.
translation_jobs TableOne row per job submission. 39 columns covering the full lifecycle. This table is the ground truth for gap analysis, cost reporting, and audit:
| Column Group | Fields | Purpose |
|---|---|---|
| Identity | id, job_id, idempotency_key | Unique identification and deduplication |
| State | state, submitted_at, started_at, completed_at | Lifecycle tracking — authoritative terminal state |
| Input | docs (JSONB), langs (JSONB), options (JSONB) | What was requested |
| Progress | total_pairs, succeeded_pairs, failed_pairs, progress (JSONB) | Per-doc/lang status map |
| Usage | bedrock_invocations | Model calls per job (the internal cost columns are not published) |
| Execution | errors (JSONB), elapsed_seconds, and the legacy step_function_arn | Traceability and debugging; the Step Functions column stays empty for jobs since June 27, 2026 |
| Deployment | cloudfront_invalidation_ids, search_index_rebuilt, notification_sent | Post-translation actions |
| Lineage | retry_of, reason | Retry chain and submission reason |
| Estimate | est_duration_seconds, estimator_version | How long the job should take from submit until every pair is done, written when the job is created (a customer's original job builds it from the per-pair estimates its quote showed). The status ETA reads it first (19.4) |
| Metadata | submitted_by, created_at, updated_at | Audit trail |
Gap analysis query: To find which documents have never been translated, query SELECT DISTINCT jsonb_array_elements_text(docs) FROM translation_jobs ORDER BY 1 and compare against the S3 document list. Aurora is the only reliable source for this — Valkey keys expire and are lost whenever the cache is cleared.
translation_job_events TableGranular audit log — one row per significant event in a job's lifecycle. Used by the retry-failed handler as the authoritative source of which (doc, lang) pairs failed:
| Column | Type | Example Values |
|---|---|---|
job_id | VARCHAR | 1747407720-a3f8b2c1d4e5 |
event_type | VARCHAR | lang_started, lang_succeeded, lang_failed, lang_skipped, lang_rejected, lang_cancelled, worker_heartbeat, cf_invalidation_failed |
doc | VARCHAR | Trinity-Beast-API-Reference.html |
lang | VARCHAR | ja, ar, es |
detail | JSONB | Cost, chunk count, error message, validator report |
created_at | TIMESTAMP | Event timestamp |
translation_pair_runs Table — Estimate Versus ActualOne row per job, document and language, for every agent and every outcome, internal and customer alike. Each row holds the estimate the server made before the pair ran beside what actually happened. That pairing is the point of the table: the more actuals sit beside estimates, the better the next estimate gets (19.2), and when an estimate misses, the same row carries the facts that explain why. Its columns fall into the five groups below. The TBTS Data Dictionary lists every published column as of November 7, 2026; the glossary column added on November 8 is described in 10.4.
| Column Group | Fields | Purpose |
|---|---|---|
| Identity | job_id, doc, lang, quote_id, is_customer, retry_of, record_origin | Which pair this is. The quote, customer flag and retry link are copied from the job's own row, never from a caller; record_origin is live or backfill |
| Estimate | estimate_origin, estimator_version, est_history_cutoff, est_model_key, est_source_bytes, est_chunks, est_start_offset_seconds, est_processing_seconds, est_input_tokens, est_output_tokens, est_basis | Written by the server before the run: copied from the quote for a customer's original job, computed at submit for every other job, or late when the worker's record arrives first. The history cut-off keeps an estimate from ever reading its own run, and est_basis records the history read and the group behind each figure |
| Measured by the worker | model_key, source_bytes, source_sha256, chunk_markers, split_mode, part_count, chunk_count, density_verdict, density_score | The inputs as the worker found them in the bytes it actually translated |
| Timestamps | job_submitted_at, message_received_at, lang_started_at, published_at, pair_finished_at, and three generated spans | Each stage of the pair. The generated spans split the time a customer waits: queue_wait_seconds (submit to the message's arrival), start_offset_seconds (submit to the pair's start) and processing_seconds (the pair's start to its end) |
| Run facts | outcome, outcome_reason, actual_source, tokens_source, input_tokens, output_tokens, truncations, ceiling_calls, engine_retries, gate_attempts, gate_retried_parts, parts, runs | What happened: the outcome, the tokens and where they were counted (tokens_source), and every retry, truncation and gate attempt. NULL means unknown; 0 means counted, and none happened. On a library pair, a part that shipped its published translation has a parts entry with outcome reused (no call, no spend), a part refused for reuse lists the admission checks that refused it in reuse_refused, and a whole-document repair dropped from a reused part is named in that part's repair_discarded (17.4). Every parts entry also carries the element-shift gate's shift_attempts, shift_counts and shift_chosen (4.2): the attempts made, the shifted elements found in each (null for an unusable attempt) and the attempt published, or 0 and null when the gate did not run |
Who writes what. The server writes the estimate half when the job is created. The worker posts the actual half once per pair when the pair ends (6.4). If that post never arrives, the server fills the pair's actuals from its job events when the job ends, and closes a pair that never ran as not_run. On November 6, 2026 a 60-day backfill rebuilt 2,101 earlier pairs from their events, part telemetry and exact source versions in S3, so the estimator had real history on its first day. The record is permanent and no job purges it, because the history is what the estimates are made of.
Reading a miss. The view translation_pair_estimate_review lines every estimate up against its actual and splits the difference into its parts. A late start with normal processing and a long queue wait is a queue miss; more chunks than estimated is a size miss; a density verdict that changed is a density miss; retried parts and truncations make a retry miss. Each cause points at a different fix, which is why the record keeps them apart.
The translation system uses a deliberate split between Aurora and Valkey based on access pattern:
| Data | Primary Store | Reason |
|---|---|---|
| Job state (queued/running/succeeded/failed) | Aurora | Authoritative terminal state — never expires, queryable, auditable |
| Job history (last 50 completed) | Aurora | Permanent record — survives a cleared cache, supports gap analysis |
| Per-pair progress (es: succeeded, ja: running…) | Valkey | Written per-pair during execution — too frequent for Aurora writes, only needed during active polling |
| Daily spend counter | Valkey | Needs atomic INCRBYFLOAT from every worker, and the nightly sync job resets it to zero at 1:00 AM Eastern (8.2) — Aurora is wrong tool for this |
| Active job set | Valkey | Fast set membership check on every submit — Aurora query would add latency to the hot path |
| Estimate versus actual for every pair | Aurora (translation_pair_runs) | One permanent row per pair, written when the pair is estimated and again when it ends. The estimator reads it on every estimate and never caches it, so quotes and ETAs work the same with Valkey down |
| Glossary entries | Aurora (translation_glossary_entries) | Read once when a job is submitted and carried to the worker in each language's queue message, so the worker makes no read of its own and every pair of the job uses the same copy. Never cached, so the glossary works the same with Valkey down |
translation_jobs row in Aurora synchronously, before any SQS send (6.1)POST /admin/translate/complete/{job_id}, called by the last worker, writes the terminal state — Aurora is updated, Valkey is updated, job removed from active set.translation_job_events for lang_failed events — Aurora is the only reliable source for which pairs failed.Do not rely on Valkey for job state. Valkey keys have no TTL on job hashes and can be flushed, evicted under memory pressure, or simply stale if an update call was lost. Aurora is the record of what happened. Valkey is the window into what is happening right now.
The translation engine calls Bedrock for every chunk of every document in every language, using the customer's chosen agent. Without guardrails, a single typo in a batch submission could trigger hundreds of expensive API calls.
| Layer | Where | Limit | Behavior on Breach |
|---|---|---|---|
| Per-request limits | Admin API (submit handler) | Max 42 docs, max 12 langs; active jobs are not capped (a warning is recorded at 12 or more) | 400 Bad Request (docs/langs); every accepted job is queued in SQS |
| Daily token cap | Admin API (submit handler) | 50M combined tokens/day (autoops:bedrock:tokens:input:daily + autoops:bedrock:tokens:output:daily) | 429 Too Many Requests until the nightly reset at 1:00 AM Eastern |
| Per-pair tracking | Worker task | Increments once per pair, when the pair ends, with what all of its Bedrock calls used, with two exceptions (8.2) | Source of truth for daily counters |
Two parallel counters track daily usage: the day's spend and the day's tokens. Both live in Valkey and start each day at zero when the nightly sync job resets them at 1:00 AM Eastern. Only the token count is checked when work is submitted. There is no daily dollar cap: it was removed on November 8, 2026, so the spend counter is reported and never refuses a job.
autoops:bedrock:spend:daily)INCRBYFLOAT, once per pair when the pair ends, with what every one of its Bedrock calls spent (the pair's token meter)EXPIRE autoops:bedrock:spend:daily 86400 after each increment, so on a busy day the 24-hour TTL keeps renewing and never expires on its own; the nightly reset is what starts each day freshGET /admin/translate/health and GET /public/infrastructure report it as daily_spend_usdautoops:bedrock:tokens:input:daily + autoops:bedrock:tokens:output:daily)INCRBY, once per pair when the pair ends — separate keys for input and output tokenscontrols.daily_token_limit parameter holds 51M, but no check reads it.)Both counters follow the same rule, once per pair when the pair ends, with two exceptions. A pair stopped by the shutdown deadline (5.1) is never added, because the deadline skips the Valkey calls to stay inside the stop timeout; the sync job's nightly month-to-date rebuild still counts it, because it sums the pair's event. A part reuse run whose meter saw no Bedrock call adds $0. A Bedrock call still running when the deadline fires is billed by AWS but never counted.
A pair's cost is recorded twice on purpose, from the same token meter: on its one terminal event (lang_succeeded, lang_cancelled, or the lang_failed that ends the pair) and on its pair record (7.2a). Each roll-up reads exactly one of the two: job cost and the month-to-date rebuild sum the events, and the estimator reads the pair records. The gate-level lang_failed events a pair can write before it ends carry no cost, so no pair is counted twice. A pair interrupted by a shutdown that later succeeds carries both attempts' spend, on its lang_cancelled and on its lang_succeeded, because both were really spent.
Kill switch: setting autoops:bedrock:kill = "1" in Valkey makes the LPO server refuse new work at job submit, task create and customer quote accept. The worker never reads the key, so jobs already running continue; cancelling the job (6.3) is what stops them. Use it, together with a cancel, for emergency cost containment.
Customer price — a flat $3.00 per document-language pair. This is what a customer pays, and it is deliberately simple: one document into one language is one pair at $3.00, so a customer can predict any quote by multiplying pairs × $3.00 without calling the API. The one exception is the Claude Opus 4.8 agent, whose price follows the work: it is priced from the token estimate (19.2), never below $3.00 per pair, and advertised as "From $3.00". Every other agent is a true flat rate. A customer quote returns price only (price_per_pair, total_pairs, total_price, currency); how TBI tracks its own spend is internal and is not published.
The engine is completely agent-agnostic. Any model accessible through Amazon Bedrock's invoke_model API can serve as a translation agent — whether it uses the Anthropic Messages format or the OpenAI-compatible format. The engine auto-detects the provider and constructs the appropriate request/response envelope. We selected these six agents based on three criteria: (1) quality on multilingual document translation, (2) availability across our failover regions (us-east-2, us-east-1, us-west-2), and (3) distinct speed and quality trade-offs that let customers choose the right agent for their workload.
The rates keep themselves honest. The engine tracks its own spend from each agent's Bedrock token rates, stored in the bedrock_pricing rows of Aurora translation_parameters and cached in Valkey tx:params. They used to be typed in by hand, and they drifted. Now the nightly sync job (BeastReconciler) reads every model's rates from the public AWS Price List (pricing:GetProducts, priced for us-east-2), checks each value, and writes any change to Aurora before it copies the table into Valkey; then it confirms both stores agree. It fails safe one model at a time: a fetch error, a missing value, an unknown unit or a jump of more than 3× in one night keeps that model's stored rates and raises a single ops alert, and nothing in it can stop the rest of the nightly job. For a deploy, SYNC_ONLY=bedrock-rates runs just the refresh, the copy and the check, without resetting the day's spend and token counters. The rates themselves are internal and are not published.
| Agent | Tier | Regions |
|---|---|---|
| Qwen3 235B | 💰 Value | east-2, west-2 |
| Mistral Large 3 | 💰 Value | east-2, east-1, west-2 |
| DeepSeek V3 | 💰 Value | east-2, west-2 |
| Claude Haiku 5.5 | ⚡ Standard | All (cross-region) |
| Claude Sonnet 4.6 | 🏆 Premium | All (cross-region) |
| Claude Opus 4.8 | 👑 Elite | All (cross-region) |
Regional failover: if the primary region (us-east-2) returns a timeout or a 5xx, the engine tries the call twice there, five seconds apart, then fails over to the next region in the chain (§12). Every agent uses the same chain, us-east-2, then us-east-1, then us-west-2, and a failover region that does not offer the model is skipped. Anthropic models use cross-region inference profiles (us. prefix) and route automatically. Qwen3 235B is not offered in us-east-1, so its failover goes from east-2 to west-2. The DeepSeek and Mistral region lists in the table were written on October 6, 2026; the engine does not check them.
Customer price per document-language pair:
| Agent | Customer Price |
|---|---|
| Qwen3 235B | $3.00 |
| Mistral Large 3 | $3.00 |
| DeepSeek V3 | $3.00 |
| Claude Haiku 5.5 | $3.00 |
| Claude Sonnet 4.6 | $3.00 |
| Claude Opus 4.8 | From $3.00 |
$3.00 per document-language pair — a true flat rate: every non-Opus agent is priced at a flat $3.00 per pair regardless of document size. Claude Opus 4.8 is the sole exception — its price follows the work and can rise on a large document, so it is priced "From $3.00". The flat rate exists because the value of the result is a professionally translated document, not the cost of the compute, and because a predictable price a customer can compute themselves is worth more to them than precision.
Translation engine metrics are exposed through two public interfaces:
GET /public/infrastructure — includes a translation section with daily spend, active jobs, queue depth, cost-per-pair estimate, and daily token counts (daily_input_tokens, daily_output_tokens, daily_token_limit). Consumed by the daily digest Lambda, nightly sync, and any monitoring dashboard./public/infrastructure every 30 seconds.Email notification timing: The email notification is the absolute LAST step in the pipeline. It fires only after: translation, deployment, search index rebuild, state update, and history push are ALL complete. The email is a comprehensive report including: job summary, translation results, CloudFront invalidation IDs, search index status, and any Bedrock error details. If Bedrock reports validation failures, the specific error messages and validator details are included in the email.
The existing CLI tool (scripts/kcc_helpers/translate_doc.py) continues to work unchanged. A --remote flag routes through the new service instead of running Bedrock locally:
| Flag | Behavior | Use Case |
|---|---|---|
| — | No flag (local): runs the translator engine in-process and calls Bedrock directly from the laptop. translate_doc.py has no --local flag; local is what runs without --remote | Development, debugging, single-doc quick fixes |
--remote | POSTs to /admin/translate, polls /admin/translate/status/{id} every 5s, streams progress to stdout | Production translations, batch operations |
--full | With --remote: every part is translated and a fresh manifest is written. Without it, unchanged parts keep their published translation (17) | An engine fix that must reach unchanged parts; with --force, the recovery after a splice-gate failure (17.4) |
--force | With --remote: bypasses the in-flight lock, the failure history and the too_dense rejection. It does not bypass the already-succeeded check (5.2) | Re-running a pair that failed before on an unchanged document |
The --remote flag produces identical terminal output to local mode — same progress bars, same chunk counters, same completion summary. The operator's workflow doesn't change; only the execution path does.
Local stays the default when --remote is not given; the planned flip of that default to --remote was never made.
The engine's behavior is driven by one config file, tbi-translate-worker/translation-config.json. It ships inside the worker image, so a change to it takes a worker build and deploy. The Go server does not read this file. It keeps its own copies of the two things it needs: the source-language detector's parameters (translate_source_lang.go) and the list of protected terms (translate_replace_apply.go), which a server test compares with the worker's file, so the two change together.
Brand names, product names, AWS services, exchange names, and acronyms that must never be translated or transliterated:
Cross Power Ministries of Pakistan, The Trinity Beast Infrastructure,
The Trinity Beast, Trinity Beast Command Center, Kiro Command Center,
Cory Dean Kalani, Shafiq Bhatti, BeastWebhook, BeastMirror, BeastMain,
BeastLRS, Claude Sonnet 4.6, Bedrock, ElastiCache, EventBridge,
CloudFront, GuardDuty, CloudWatch, CloudTrail, Step Functions,
Crypto.com, Coinbase, Gate.io, Bitstamp, Kraken, Aurora, Valkey,
Stripe, Kiro, Fargate, PostgreSQL, Lambda, Route 53, AutoOps,
TBCC, CPMP, TBI, KCC, OKX, ECR, ECS, ALB, NLB, WAF, SNS, SQS,
SES, VPC, IAM, S3 ...
In addition to the global protected terms list, you can submit document-specific terms via the protected_terms array in the translation request. This is useful for:
POST /admin/translate
{
"docs": ["Trinity-Beast-API-Reference.html"],
"langs": "all",
"protected_terms": ["MyCustomService", "SpecialEndpoint", "ProjectAlpha"]
}
Per-request terms protect that job only. They do not persist across jobs. They reach every pair of the job: the worker's task runner forwards them to the handler that translates each pair. The protected-terms prescan then wraps each term that is not already in the global list in <span translate="no">, matching case-insensitively at word boundaries and keeping the document's own spelling. After translation the engine removes those wrappers exactly as it removes the ones around configured terms. Nothing else in the document is touched: the prescan's identifier, path and URL detection stays off, as it always has in production. The result is the protection you asked for and nothing you did not. A protected term always wins over a glossary entry: an entry whose source is, or contains as a whole word, a protected term is dropped for that pair and counted (10.4).
The config still lists the eight preserve_patterns below, but no engine code reads them: apart from the config key, the name appears only in the validator check_preserve_patterns (4.1). That validator checks http:// and https:// URLs by plain string matching, and its email check has been off since June 20, 2026. The preprocessor lifts URLs, email addresses, memory sizes and percentages into placeholders (15.4, 15.6). It has no pass for cron expressions, IP addresses, ARNs or AWS resource ids: those are protected only when they are written inside code or a translate="no" element.
| Pattern Name | Matches | Example |
|---|---|---|
url | HTTP/HTTPS URLs | https://api.cpmp-site.org/admin/translate |
email | Email addresses | CoryDeanKalani@CPMP-Site.org |
memory_size | Number + memory unit | 1770 MB, 32 GB |
percentage | Number + % | 98.5%, 62% |
cron_expr | Cron expressions | cron(0 11 * * ? *) |
ip_address | IPv4 with optional CIDR | 10.0.1.0/24 |
aws_arn | AWS ARN format | arn:aws:sns:us-east-2:211998422884:tbi-ops-notifications |
aws_resource_id | AWS resource identifiers | vpc-03deaddb7083cd59c, sg-050b617f93b2388f6 |
| Parameter | Value | Purpose |
|---|---|---|
max_chunk_chars | 6000 | Default maximum characters per chunk (Latin scripts: es, pt, fr, de) |
max_chunk_chars_by_lang | — | Per-language overrides for complex scripts, in the table below |
max_retries | 5 | Retry attempts per chunk on validation failure |
request_timeout_seconds | 5220 | The longest read timeout any one Bedrock call gets (87 minutes). Each call's own timeout is sized from its output cap (4.2) and never exceeds this value, which is set high enough that a call at any model's ceiling keeps its full timeout |
max_output_tokens | 131072 | The most output tokens any one call may ask for, held to each model's own maximum in the next row. Inside the retry loop only the last attempt asks for it (4.2) |
max_output_tokens_by_model | {"qwen": 65536, "claude": 128000, "deepseek": 163840, "mistral": 262144, "default": 49152} | Each model's own Bedrock maximum, matched by the first key found in the lowercased model id, else the default entry. A call never asks for more than the lower of this value and the row above, so the ceilings in effect are 65,536 for Qwen, 128,000 for Claude, 131,072 for DeepSeek and Mistral, and 49,152 for any other model |
read_timeout | {"base_seconds": 60, "bucket_seconds": 60, "floor_tokens_per_second": {"qwen": 35, "claude": 25, "default": 30}} | Sizes each call's read timeout from its output cap: 60 seconds plus the cap divided by the model's floor rate in tokens per second, rounded up to a multiple of 60 seconds and never above request_timeout_seconds (4.2, 12.2) |
shift_gate_retries | 2 | How many more times a part whose text slid across element boundaries is translated; the attempt with the fewest shifted elements is published (4.2) |
boundary_gate_attempts | 3 | How many times a part is translated before a boundary-signature finding fails the pair (4.2) |
part_reuse_epoch | 1 | Part of every library page's part fingerprint. Bumping it makes every library page translate in full on its next run (17.6) |
max_code_tags_per_part | 81 | The default limit on code tags per part, for a language with no entry of its own, of its base language or of its tuning language in the next row. The sub-split reads this key; the prescan has a built-in default of the same value (14.3) |
max_code_tags_per_part_by_lang | {"hi": 21, "ur": 21, "ar": 21, "de": 30, "ja": 48, "zh": 48, "ru": 48} | Per-language limits, used in place of the default for the languages listed. A language's limit resolves like every per-language limit (10.3): its own entry, then its base language's, then its tuning language's, then the default. Dutch, for example, takes German's 30, and Korean takes Japanese's 48. The prescan splits a document without chunk markers by them, and for the languages in limits.subsplit_languages (ur, hi, ar) the engine cuts a part over its language's limit into sub-parts and joins them back after translation, so the part count and the markers do not change (14.3) |
Per-language chunk size overrides:
| Languages | Chunk Size (characters) | Rationale |
|---|---|---|
hi, ur, ar | 3000 | Devanagari and Arabic scripts expand significantly during translation. Smaller chunks prevent Bedrock timeouts. |
ja, zh, ru | 4500 | CJK and Cyrillic have moderate expansion. Mid-range chunks balance throughput and reliability. |
es, pt, fr, de, it | 6000 | Latin scripts translate quickly with minimal expansion. This is the default size. |
Every catalog language inherits sensible limits. The table above covers our library's 11 languages. Each of the 127 catalog languages resolves its limits by exact code, then its base_lang, then its tuning_lang, then the default. So fa, ps and sd inherit Urdu's tuning, ko inherits Japanese, Cyrillic languages inherit Russian, and a regional variant such as es-MX follows its base language. The tuning_lang column of the catalog decides it, so a new language is tuned the day it is added.
A glossary entry says: in one target language, translate this source term as this target term. Our own glossary covers our documents, and every customer account can keep its own. Since November 8, 2026 the engine uses an entry in three places and then checks the result. A glossary changes only text the engine was already going to translate, and a pair without one runs exactly as before (Invariant 34, 20.2).
h1–h6 p li dt dd caption figcaption label button summary div span a strong em b i td th) gets the target written inside a <span translate="no"> wrapper, so the model never sees it. The cells of a Type D table are left to item 3. The wrapper travels with the protected-term wrappers and is removed the same way after translation. Matching decodes entities and ignores case and repeated spaces; punctuation must match.engine._invoke appends a REQUIRED TERMINOLOGY block to the system prompt that lists the entries whose source term occurs in that call's text, so the model uses the target and may change its grammatical form. It lists at most limits.glossary_prompt_max_entries entries per call (40), longest source terms first, and counts the rest as not instructed. An entry marked label-only is never listed.What it never touches. The engine never writes a target inside a translate="no" element or one of pre code script style svg math title textarea, into a tag attribute, into the document head, or into Type D cells outside the declared columns, and the instruction tells the model that the entries never apply inside code, URLs or tokens. Protection always wins: an entry whose source is, or contains as a whole word, a configured or job protected term is dropped for that pair and counted, and so is an entry with unsafe text (<, >, a line break, a control character, an engine token shape, or a target that would glue a configured protected term to a letter).
The check (step 3.12, report only). After the tail gate passes and before the S3 write, the engine counts each entry's source term in the source body and its target and other accepted forms in the bytes about to ship, and gives each matched entry a verdict: satisfied, partial or missing. It never changes the bytes and never retries or fails a pair. The worker prints counts only, in two 📘 Glossary lines, and sends the summary with the pair record (6.4); the server stores it in translation_pair_runs.glossary, counts and entry ids only, never terms. A glossary step that fails is recorded there and acts as if it had no entries. The check does not count alt or title text, which the instruction does cover.
Where entries live. One Aurora table, translation_glossary_entries, holds ours (no account) and every customer's. The server reads it once when a job is submitted and puts each language's entries in that language's queue message; a language with no entries gets no glossary key. Ours applies only to jobs without a quote, so it never reaches a customer document, and a customer's applies only to that account's quotes. A retry reads the glossary as it is when the retry starts.
An entry can name the source language it is written in. An entry with a source language applies only to documents in that language, and an entry without one (Any) applies to every document. When a document's source language is unknown or set to auto, only the Any entries apply (decision of November 10, 2026). When an entry for the document's source language and an Any entry have the same source term, the entry for the source language wins.
Limits and the switch are translation_parameters rows in the glossary category (Translation Parameters). The server checks the limits on every write: 200 entries per language, 100 characters per term and 3 other accepted forms per entry. With glossary.enabled at anything but true, the server attaches no entries to new jobs after a params reload, and no entry is deleted.
| Method | Path | What It Does |
|---|---|---|
GET | /admin/translate/glossary?lang= | Lists our entries, optionally for one language, with the count and the live limits |
POST | /admin/translate/glossary | Body {"entries":[…],"dry_run":true,"updated_by":"…"}. Upserts by language and case-folded source term, all or nothing: an invalid entry answers 400 listing every error and writes nothing, and a dry run returns each entry's plan (insert, update or unchanged) and writes nothing |
DELETE | /admin/translate/glossary/{id} | Deletes one of our entries; a customer's entry answers 404 like a missing one |
They need the X-Admin-Key header and answer in English. Customers manage their own glossary with GET and PUT /translate/glossary and their Translation API key (API Reference 15.16).
Single document, all languages:
curl -s -X POST \
-H "X-Admin-Key: $ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{"docs":["Trinity-Beast-API-Reference.html"],"langs":"all"}' \
https://api.cpmp-site.org/admin/translate | jq .
Multiple documents, specific languages:
curl -s -X POST \
-H "X-Admin-Key: $ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{"docs":["Trinity-Beast-API-Reference.html","Trinity-Beast-Architecture-Guide.html"],"langs":["es","pt","fr"]}' \
https://api.cpmp-site.org/admin/translate | jq .
With idempotency key (safe to retry):
curl -s -X POST \
-H "X-Admin-Key: $ADMIN_KEY" \
-H "X-Idempotency-Key: api-ref-2026-05-16" \
-H "Content-Type: application/json" \
-d '{"docs":["Trinity-Beast-API-Reference.html"],"langs":"all"}' \
https://api.cpmp-site.org/admin/translate | jq .
These raw requests carry no delta, so each one translates every part. To reuse unchanged parts, add "options":{"delta":true} to the body (17.5), or submit with translate-pending, translate-task or translate-doc --remote, which ask for reuse by default (--full turns it off).
# Check job status
curl -s -H "X-Admin-Key: $ADMIN_KEY" \
https://api.cpmp-site.org/admin/translate/status/{job_id} | jq .
# View queue
curl -s -H "X-Admin-Key: $ADMIN_KEY" \
https://api.cpmp-site.org/admin/translate/queue | jq .
# System health
curl -s -H "X-Admin-Key: $ADMIN_KEY" \
https://api.cpmp-site.org/admin/translate/health | jq .
# Recent history
curl -s -H "X-Admin-Key: $ADMIN_KEY" \
https://api.cpmp-site.org/admin/translate/history | jq .
| Symptom | Cause | Resolution |
|---|---|---|
Job stuck in queued | Every worker is busy with an earlier job, or the worker service has not scaled up yet | Run bash scripts/kcc.sh translate-worker-status (running containers and queue depth). A queued job waits for a free container; the sweeper leaves it alone while other jobs progress (5.4) |
| 429 on submit | Daily token limit reached (translation_token_limit: 50M combined tokens since the nightly reset) | Wait for the nightly reset at 1:00 AM Eastern (each increment renews the 24-hour TTL, so on a busy day the counters never expire on their own), or reset both counters manually: SET autoops:bedrock:tokens:input:daily 0 and SET autoops:bedrock:tokens:output:daily 0 |
| Partial completion | Some languages failed validation | POST /admin/translate/retry-failed/{id} |
| A pair runs very long | Document too large (many chunks) | Filter the worker log group /ecs/tbi-translate-worker for the job id: each part logs its progress, and the pair record (7.2a) keeps per-part facts |
| Cancel returns 404 | Job only in Aurora, not Valkey | Cancel handler falls back to Aurora — ensure latest code is deployed |
| No email notification | Complete endpoint error or SNS failure | Check LPO container logs for TRANSLATE-COMPLETE entries; verify SNS topic tbi-ops-notifications. When the worker's call to POST /admin/translate/complete/{job_id} gets no answer (a connection error or its 120-second timeout), the worker publishes a basic SNS message of its own to that topic (source translate-worker-fallback) with the job's state and pair counts; an error answer from the endpoint is only logged in /ecs/tbi-translate-worker |
| Search not updated | Search rebuild timed out | Run bash scripts/kcc.sh build-search manually |
Cancel a running job:
curl -s -X POST -H "X-Admin-Key: $ADMIN_KEY" \
https://api.cpmp-site.org/admin/translate/cancel/{job_id}
The job is marked cancelled at once and each worker stops at its next cancel check (6.3). Documents already translated and deployed remain live.
The translation engine implements automatic regional failover to maintain availability during Bedrock service disruptions. This was added after a us-east-2 outage during development exposed the single-region weakness — better to discover this before customers were affected.
When a Bedrock call fails with a service-level error, the engine automatically retries in the next region:
| Priority | Region | Location | Role |
|---|---|---|---|
| 1 | us-east-2 | Ohio | Primary — all normal traffic |
| 2 | us-east-1 | N. Virginia | First fallback |
| 3 | us-west-2 | Oregon | Second fallback |
The failover is transparent to the caller — the translation completes successfully as long as at least one region is available. A log message records when a fallback region was used.
Failover is triggered for service-level errors and timeouts that indicate the region is unavailable or overloaded:
| Error Type | Meaning | Action |
|---|---|---|
ServiceUnavailableException | Bedrock service is down (503) | Retry same region once, then failover |
ThrottlingException | Rate limit or capacity exceeded | Retry same region once, then failover |
ModelStreamErrorException | Model streaming failure | Retry same region once, then failover |
ReadTimeoutError | No response within the call's read timeout. The timeout is sized from the call's output cap as min(request_timeout_seconds, 60 + cap / floor rate), rounded up to a multiple of 60 seconds, so a Qwen call at its 65,536-token ceiling waits up to 1,980 seconds and a Claude call at 128,000 tokens up to 5,220 seconds (4.2, 10.3) | Retry same region once, then failover |
ConnectTimeoutError | Could not establish connection within 10s | Retry same region once, then failover |
InternalServerException, ModelNotReadyException, HTTP 500/502/503/504 | Bedrock internal error or model not yet loaded | Retry same region once, then failover |
EndpointConnectionError, ConnectionClosedError | Network path to the region failed mid-call | Retry same region once, then failover |
Other errors (validation failures, authentication errors, malformed requests) are not retried — they would fail identically everywhere.
Each region gets 2 attempts before the engine moves to the next region. A 5-second backoff between attempts allows transient pressure to clear:
us-east-2 (attempt 1) → timeout → wait 5s →
us-east-2 (attempt 2) → timeout →
us-east-1 (attempt 1) → timeout → wait 5s →
us-east-1 (attempt 2) → timeout →
us-west-2 (attempt 1) → timeout → wait 5s →
us-west-2 (attempt 2) → timeout → FAIL (raise exception)
Total: 6 attempts across 3 regions. In practice, transient spikes clear within 5-10 seconds, so the retry within the same region usually succeeds without needing failover.
Why the chain never includes a Canadian region. The Trinity Beast has a hard rule that no service, Lambda, or Bedrock call ever runs in ca-central-1 or ca-west-1 — no exceptions. This is enforced by construction, not by a runtime check: FAILOVER_REGIONS is a fixed allow-list containing only the three regions in the table above, so a Canadian region simply cannot be selected. An import-time assertion in the same module raises a fatal error if any configured region ever starts with ca-, so a misconfiguration is caught at worker startup rather than discovered mid-failover. The engine has never had a function that redirects a Canadian region to us-east-2 at request time — the earlier belief that one existed described a mechanism the codebase does not contain; the real mechanism is that the list was simply never given anywhere to redirect from.
Regional failover has negligible cost impact:
Resilience benefit: A complete regional outage no longer blocks translations. The May 2026 us-east-2 outage would have caused a 4-hour translation blackout without this feature. With failover, translations continued uninterrupted via us-east-1.
Proper document preparation ensures clean translations with minimal post-processing. This section covers the conventions that help the translation engine produce accurate results.
The <code translate="no"> tag tells the translation engine to preserve content exactly as written. Use it correctly to avoid formatting artifacts in translated documents.
Use <code translate="no"> for technical identifiers that would break if translated:
tbi-ops-notify, BeastMain/admin/translate, /public/infrastructureAWS_REGION, ADMIN_KEY_protect_code_tags(), translate()/var/log/app.log, scripts/kcc.shjob_id, created_atmax_retries, request_timeout_seconds--remote, --forceDo not wrap pure data values in code tags — they should appear as plain text:
<code>1770 MB</code>)<code>60 seconds</code>)<code>98.5%</code>)<code>11 languages</code>)<code>$3.00</code>)<code>17.7</code>)Why this matters: the translation engine's preprocessor protects code-tagged content from translation (3.1). If you wrap "32 GB" in code tags, it survives translation — but so does the monospace formatting, which looks wrong in prose. The engine has a post-processor that strips spurious code wrappers from pure numeric values, but it's better to author correctly from the start.
Ask yourself: "If I changed this value, would the system break?" If yes, use code tags. If no (it's just a number or measurement), leave it as plain text.
| Content | Would changing it break something? | Use code tags? |
|---|---|---|
tbi-ops-notify | Yes — Lambda name | ✅ Yes |
| 1770 MB | No — just a memory size | ❌ No |
/admin/translate | Yes — API endpoint | ✅ Yes |
| $3.00 | No — just a dollar amount | ❌ No |
max_retries | Yes — config key | ✅ Yes |
| 3 retries | No — just a count | ❌ No |
For documents with domain-specific terminology not in the global protected terms list, submit additional terms with the translation request:
POST /admin/translate
{
"docs": ["Customer-Integration-Guide.html"],
"langs": "all",
"protected_terms": [
"CustomerCorp",
"ProjectPhoenix",
"DataSync API",
"IntegrationHub"
]
}
These terms protect this job only. The engine will:
<span translate="no"> during preprocessing (terms that are in the list are wrapped by the brand-term pass, as always)The prescan runs whenever a job supplies terms, on the internal and the customer path alike: the trigger is the presence of terms, never the job type, because both paths share one process.
When the translation engine encounters ambiguous content, it may flag it for human review. This happens in the validation phase when:
Flagged content appears in the job status response under the warnings array:
{
"status": "✅ [LPO] [us-east-2] [BeastMain] [/admin/translate/status/1747407720-a3f8b2c1d4e5] [200]",
"status_code": 200,
"endpoint": "/admin/translate/status/1747407720-a3f8b2c1d4e5",
"cluster_node": "BeastMain",
"region": "us-east-2",
"language": "en",
"timestamp": "2026-05-16T17:45:00Z",
"data": {
"job_id": "1747407720-a3f8b2c1d4e5",
"state": "succeeded",
"warnings": [
"chunk 14 (ja): soft failure — protected term 'DataSync' may have been altered",
"chunk 22 (ar): soft failure — version number format changed from X.Y.Z to X.Y"
]
},
"error": ""
}
Soft failures don't block the translation — the output is still deployed. Review the warnings and manually verify the flagged sections if needed.
Feedback loop: if you consistently see the same term flagged, add it to the global protected terms list, protected_terms in tbi-translate-worker/translation-config.json (10). That is a worker change and takes an image build and deploy. On a published library page, every part in which the brand-term wrap (3.0) finds the new term is translated again the next time the page is translated with reuse on, because the wrap changes that part's processed input (17.1). The model's prompt also carries the protected-term list. For one page, a --full run (9, 17.6) translates every part with the current term list. For the whole library, a bump of limits.part_reuse_epoch (10.3) sends the new list to the parts that do not hold the term, and it makes every library page translate in full. This prevents future warnings and improves translation quality across all documents.
A <!-- TBI-CHUNK --> marker divides a document into parts, and the engine translates each part as its own fragment. Where a marker sits decides what the model is shown, which makes a well-placed marker the cheapest quality improvement in the pipeline: moving one in the English source costs nothing, while the same defect caught after translation costs a failed pair, a republish and a re-translation in every language it touched.
Since November 2026 one tool places every library marker and keeps it correct: bash scripts/kcc.sh marker-place. It judges each existing marker by the part it creates, keeps the markers whose parts pass, moves or removes the ones that fail, adds markers where a part needs one, and changes as few as it can. Its rules are the ones the rest of the pipeline already enforces, now applied in one place:
</div>, and the part opens a div tree at least three deep. Only the last part, which has to close the document, may end on the milder form (WARN): closing tags whose openers live in an earlier part, with any div structure above them.too_dense to challenging), which is why the minimum wins.It reports without writing unless you pass --write, and then it writes atomically and reads the file back. A page on the translation blocklist is inspected and reported, never written. Where no safe boundary exists it reports a residual and never forces a cut.
# Inspect one document (reports only; nothing is written)
bash scripts/kcc.sh marker-place --doc Trinity-Beast-API-Reference.html --json
# Correct every library document in place
bash scripts/kcc.sh marker-place --all --write
A bare file name resolves under the library folder, and an absolute path is read exactly as given, which is how a working copy outside the main checkout is inspected. Exit code 0 means clean, 1 means residuals were reported (expected where a part has no safe cut), and 2 means a usage, I/O or verification failure.
Four more preparation rules hold for every library guide since November 2026:
</div> and any closing tags straight after it, so the diagram's part holds its own closing tags.<!-- /.container --> (since November 22, 2026). It gives that closing tag a unique neighbour, so when the model drops the boundary sentinel that carries the tag, the engine puts the tag back next to the comment (4.2).<nav class="toc">, is allowed in addition to the one after the contents block, so the contents block is a part of its own. That part ends with </nav>, the one allowed exception to the closing-tag rule above. The placer keeps such a marker and never adds one. Only the API Reference uses it: without it, the Arabic, Hindi and Urdu sub-split sent the contents opener to the model as a raw token. Add it to another guide only on the same evidence. This guide has none.doc-publish warns on new or edited bold lead-in labels and never blocks.A standing process, and what its first run did. Keeping the library's markers right is a standing process that Kiro runs: inspect the English library, correct the markers, and publish each corrected English document one at a time. A marker change alters no published page, but under part reuse every part that a marker add, move or removal touches is translated again on the next run (17.6); re-translating stays a separate decision. The first full run, on November 7, 2026, changed marker lines only, in 35 documents; 9 were already right. Across the library, parts went from 539 to 553, parts over the size policy from 53 to 8 (four in Infrastructure Live, which is never translated, and four with no safe cut), empty parts from 9 to 1, tiny parts from 11 to 1, and middle parts with the milder WARN shape from 38 to 0, with no CRITICAL part before or after. The largest part outside Infrastructure Live is now 17,479 bytes.
The same tool is planned to prepare customer documents at the quote. Today it runs on our own library.
Before translation begins, the engine analyzes each document for complexity factors that may cause validation failures. This pre-scan identifies code-heavy sections and recommends whether to proceed, exercise caution, or split the document.
The pre-scan calculates a complexity score for each section based on:
| Factor | Weight | Why It Matters |
|---|---|---|
| Code tags | 1.0 per tag | Each code tag must survive translation intact — more tags = more validation points |
| Code tags in tables | 1.5 per tag | Tables with code examples are harder — model tends to merge or drop tags when reordering |
| Tables | 2.0 per table | Tables with technical content require careful structure preservation |
| Pre blocks | 0.5 per block | Usually have translate="no" — lower risk but still tracked |
| Protected spans | 0.3 per span | Lifted into placeholders by the preprocessor — low risk |
Based on the analysis, the pre-scan returns one of three recommendations:
| Recommendation | Criteria | Action |
|---|---|---|
| PROCEED | Score < 20, no high-density sections | Translate normally — low failure risk |
| CAUTION | Score < 50, ≤ 2 high-density sections | Proceed but monitor — may need retries |
| SPLIT | Score ≥ 50 OR > 3 high-density sections | Consider splitting document before translation |
DOCUMENT TRANSLATION COMPLEXITY ANALYSIS
========================================
Total characters: 81,107
Total sections: 13
Total code tags: 287
Overall complexity score: 415.4
Recommendation: SPLIT
WARNINGS:
⚠️ Document has 287 code tags — high validation failure risk
⚠️ Section 'step-function' has 51 code tags — consider simplifying
⚠️ Section 'observability' has 48 code tags — consider simplifying
HIGH-DENSITY SECTIONS (9):
• architecture: 11 code tags, score 22.7
• sentinel-system: 22 code tags, score 34.5
• step-function: 51 code tags, score 71.1
...
SUGGESTED SPLIT: 4 parts
→ Split after 'validators' (After 3 high-density sections)
→ Split after 'observability' (After 3 high-density sections)
→ Split after 'doc-prep' (After 3 high-density sections)
When the pre-scan recommends splitting, it suggests natural break points at section boundaries. Options for handling complex documents:
Create separate HTML files for each part (e.g., Doc-Part1.html, Doc-Part2.html). Each part translates independently with lower failure risk. Link them together with navigation.
Reduce code tag density in problematic sections:
Submit fewer languages per job (e.g., 3 instead of 11). This reduces concurrent load and allows the model more capacity per translation. Retry failed languages individually.
Complex scripts (Urdu, Arabic, Hindi) struggle with high tag density even when Latin-script languages handle the same chunk fine. The prescan now applies per-language code tag limits — tighter thresholds for scripts where the model is more likely to drop markup:
| Language | Script | Max code Tags per Part |
|---|---|---|
| Default (a language with no entry of its own, of its base language or of its tuning language) | — | 81 |
| Urdu (ur) | Nastaliq | 21 |
| Arabic (ar) | Arabic | 21 |
| Hindi (hi) | Devanagari | 21 |
| German (de) | Latin | 30 |
| Japanese, Chinese, Russian (ja, zh, ru) | CJK / Cyrillic | 48 |
Configuration key: max_code_tags_per_part_by_lang in translation-config.json. When the prescan runs for a specific language, it uses that language's threshold to determine split points. As everywhere, a language's limit resolves like every per-language limit (10.3): its own entry, then its base language's, then its tuning language's, then the default. Dutch, for example, takes German's 30, and Korean takes Japanese's 48. A document that translates as one part for Spanish may automatically split into 2-3 parts for Urdu.
The prescan uses these thresholds, like the 24 KB safety valve (14.4), only for a document without chunk markers, which the engine splits in prescan mode. A document with markers splits on its markers (13.4), and every library guide has them. For the languages in limits.subsplit_languages (Urdu, Hindi and Arabic), the engine also applies the same per-language limit inside every part it translates on the normal path: a part that holds more protected items, such as code tags and placeholders, than the limit is cut into sub-parts, which are translated separately and joined back into the one part, so the part count and the markers do not change.
Result: The Translation Service document (22 code tags in the Architecture section) previously failed for Urdu on every attempt. With the threshold of 18 it had then, the prescan split Architecture and Observability into separate parts, and all 11 languages translated successfully.
This document is an edge case: The Translation Engine documentation itself has 287 code tags and a complexity score of 415 — it's documentation about a translation engine, so it's packed with code examples. Most documents score under 50.
Even when code tag density is low, a single part that exceeds the model's effective output window will be silently truncated — sections at the end of the part simply disappear from the output. The safety valve enforces a hard character limit per part regardless of prescan recommendations.
The Performance Report (75 KB) has 18 sections with moderate code density. The prescan recommended splitting into 3 parts based on code tag thresholds. But Part 1 was 36 KB of prose-heavy content — well under the code tag limit but far beyond the model's output token budget. The model translated the first ~24 KB faithfully, then its output simply stopped. Sections 7-8 (partner-sustained, udp-engine) vanished without any error signal.
# Safety valve: max chars per part (prevents model output truncation)
MAX_CHARS_PER_PART = 24000 # ~6000 tokens, well within max_output_tokens
The splitter now enforces a 24 KB ceiling on every part. If a part exceeds this limit after the prescan-based split, it is further subdivided at the nearest section boundary. This is conservative — Latin scripts could handle ~30 KB, but 24 KB is safe for all languages including RTL and CJK where token efficiency is lower.
| Document | Before (v2.6) | After (v2.8) |
|---|---|---|
| Performance Report (75 KB) | 3 parts (Part 1: 36 KB — truncated) | 4 parts (largest: 22 KB — clean) |
| API Reference (180 KB) | 8 parts (all under 24 KB already) | 8 parts (no change — already safe) |
| Translation Engine (116 KB) | 11 parts (code-density driven) | 11 parts (no change — code splits dominate) |
The safety valve only activates when the prescan's code-tag-based splitting produces oversized parts. For most documents, the code density split already keeps parts well under 24 KB. Neither split applies to a document with chunk markers: it splits on its markers (13.4), so the valve never cuts a library guide.
Result: Performance Report went from dropping 3 entire sections (silent truncation) to a perfect 18/18 sections, 4/4 diagrams, 20/20 <br/> tags across all 11 languages.
The document-level preprocessor is a critical layer that runs before chunking. It extracts complex HTML elements from the document, or from each part of a split document (3.1), replacing them with simple ASCII placeholders. After translation, the postprocessor restores the original elements. This eliminates the "model drops tags" failure mode entirely.
The per-chunk sentinel system, now retired (3.2), worked well for most documents, but complex documents with many <code>, <strong>, and <em> tags exposed a fundamental limitation:
__TBP0__, __TBP1__, etc.)Example failure: A chunk with 27 <code translate="no"> tags consistently failed validation with tag count mismatch (27→23) — the model dropped 4 placeholders despite explicit instructions to preserve them.
Extract ALL problematic elements from the document before chunking. The model never sees these elements — only simple ASCII placeholders that it cannot confuse with HTML structure.
Key insight: The model cannot corrupt what it never sees. By extracting elements at the document level, each chunk has zero complex tags to worry about. The model translates clean prose with obvious markers.
| Pipeline Stage | Before (v2.2) | After (v2.3) |
|---|---|---|
| Document received | 290 code tags | 290 code tags |
| After preprocessing | — | 0 code tags (290 placeholders) |
| Per-chunk sentinels | 20+ placeholders per chunk | 0-2 placeholders per chunk |
| Model cognitive load | High (complex structure) | Low (clean prose) |
| Validation failures | Frequent on complex docs | Rare |
The preprocessor uses a two-phase extraction model that integrates into the translation pipeline as the first step:
Document → PHASE 1 (Density Lift) → PHASE 2 (Individual Extract) → Chunk → Translate → Reassemble → POSTPROCESS → Output
↓ ↓ ↓
Lift entire dense containers Extract remaining code/pre/ Single-pass flat restore
as [QZ_ZK_NNN] placeholders strong/em/numeric individually (no nesting, no iteration)
Original HTML preserved Build manifest mapping from manifest
Phase 1 runs FIRST on the raw DOM. It inspects container elements (tr, li, dd, dt, p, div) and lifts any container whose ratio of protected elements to prose characters exceeds a per-language density threshold. The lifted BLOCK entries store the original HTML byte-for-byte — no nested placeholders inside them.
Phase 2 then runs on whatever Phase 1 didn't lift, extracting individual elements (pre, code, spans, strong/em, a-tags, numeric patterns) the same way as before.
engine.pyOn a split document a normal-path part reaches translate() already preprocessed by the worker (3.1), so step 1 below runs on that simplified part.
def translate(text, target_lang, mode="html", ...):
# Build preprocessor config from language profile
preprocess_config = {"script_family": profile.get("script_family", "latin")}
# Step 1: PREPROCESS — Phase 1 lifts dense blocks, Phase 2 extracts individuals
simplified_html, manifest = preprocess_for_translation(text, preprocess_config)
# Step 2: CHUNK — Split simplified document
head, chunks, tail = chunker.split_document(simplified_html, lang=target_lang)
# Step 3: TRANSLATE — Each chunk through Bedrock
for chunk in chunks:
translated = _translate_chunk(chunk, ...)
# Step 4: REASSEMBLE
reassembled = chunker.reassemble(head, translated_chunks, tail)
# Step 5: POSTPROCESS — Single-pass flat restore (no nesting)
output = postprocess_translation(reassembled, manifest)
The preprocessor extracts elements in a two-phase order. Phase 1 (density lift) runs first on the raw DOM. Phase 2 (individual extraction) runs on whatever Phase 1 didn't lift, processing elements in order of specificity (most specific first) to handle nesting correctly:
| Phase | Pass | Elements Extracted | Placeholder Format |
|---|---|---|---|
| 1 | Density lift | Entire container elements (tr, li, dd, dt, p, div) exceeding density threshold | [QZ_ZK_001] |
| 2 | 1 | <pre translate="no"> blocks | [QZ_ZP_001] |
| 2 | 2 | <code translate="no"> tags | [QZ_ZC_001] |
| 2 | 3 | Other translate="no" elements | [QZ_ZS_001] |
| 2 | 3b | <span class="..."> (structural CSS) | [QZ_ZS_001] |
| 2 | 4 | <strong>, <em>, <b>, <i> tags (short content ≤40 chars) | [QZ_ZB_001], [QZ_ZI_001] |
| 2 | 5 | <a> tags with event handlers | [QZ_ZL_001] |
| 2 | 6 | Numeric patterns (memory sizes, percentages, versions) | [QZ_ZM_001], [QZ_ZN_001], [QZ_ZV_001] |
Placeholders use ASCII square brackets with opaque Z-prefixed type codes. Three previous formats were evaluated and discarded:
⟦TYPE_NNN⟧): models (especially Qwen) corrupt rare Unicode codepoints — U+27E6/U+27E7 became U+27F2 in Arabic output. The model reproduces the inner text but substitutes visually-similar Unicode glyphs for the brackets.__TBI_TYPE_NNN__): models interpret these as Python dunder variables or code identifiers and drop them entirely from the translated output.[TBI_CODE_000]): models read "CODE" and hallucinate <code> tags in the output. The type name provides semantic clues that trigger unwanted generation.The production format uses a two-letter nonsense prefix (QZ) and single-letter opaque type codes that carry no HTML or programming semantics:
[QZ_ZC_000] (square bracket + QZ prefix + Z-code + 3-digit index)QZ — not a brand term, not an HTML tag, not a language code. Zero collision risk.| Z-Code | Element Type | Example Placeholder |
|---|---|---|
| ZC | <code> tags | [QZ_ZC_000] |
| ZP | <pre> blocks | [QZ_ZP_001] |
| ZS | <span> elements | [QZ_ZS_014] |
| ZB | <strong> / <b> tags | [QZ_ZB_021] |
| ZI | <em> / <i> tags | [QZ_ZI_003] |
| ZL | <a> links | [QZ_ZL_007] |
| ZT | Type D tables | [QZ_ZT_000] |
| ZK | Dense blocks (Phase 1 lift) | [QZ_ZK_002] |
| ZQ | Table cells | [QZ_ZQ_005] |
| ZW | Brand terms | [QZ_ZW_033] |
| ZX | HTML comments | [QZ_ZX_000] |
| ZE | Email addresses | [QZ_ZE_001] |
| ZU | Bare URLs | [QZ_ZU_002] |
| ZM | Memory sizes (32 GB) | [QZ_ZM_042] |
| ZN | Percentages (98.5%) | [QZ_ZN_008] |
| ZV | Version numbers (17.7) | [QZ_ZV_004] |
The result: 100% tag preservation across all models and all target languages. The model sees [QZ_ZC_000] and has zero semantic interpretation — it passes the token through unchanged. Postprocessing restores the original HTML from the manifest.
Within Phase 2, the preprocessor handles arbitrary nesting depth by processing innermost elements first. Note: this nesting only occurs for individually-extracted elements — BLOCK entries from Phase 1 are always flat (they contain original HTML, never placeholders).
Source:
<span translate="no"><code translate="no">tbi-ops-notify</code> Lambda</span>
Pass 1: Extract inner code tag
<span translate="no">[QZ_ZC_001] Lambda</span>
Pass 2: Extract outer span
[QZ_ZS_002]
Model sees: [QZ_ZS_002] (one token, no nesting)
When the preprocessor extracts elements from a container (e.g., a table cell), earlier passes leave placeholder text in the parent. Later passes must not be confused by these sibling placeholders — a <code translate="no"> tag in the same table cell as an already-extracted element is still a valid extraction target.
Bug fixed (v2.4): The original _is_inside_placeholder check walked up the DOM tree looking for a placeholder's opening bracket in any parent's text. This caused false positives — if a sibling element had been extracted (leaving [QZ_ZC_042] in the parent's text), the check incorrectly skipped remaining <code translate="no"> tags in the same container. Those unextracted tags then overwhelmed the model during complex-script translation (Hindi, Urdu). Fix: the check now always returns false — if an element still exists in the DOM tree, it wasn't extracted and is a valid target.
Phase 1 of the preprocessor inspects the raw DOM before any individual extraction. It identifies container elements where the ratio of protected elements to prose characters is too high — meaning there's too little translatable text to justify sending the element through the model.
density = protected_elements / max(prose_chars, 1)
Where:
protected_elements = unique count of <code> + translate="no" elements + class spans + <pre> inside the containerprose_chars = character count of visible text content (excluding protected element text)tr, li, dd, dt, p, divThe check uses pure DOM element counting — no regex. This makes it deterministic and immune to content patterns that could fool regex-based approaches.
Thresholds are per-language via the script_family column in the translation_language_profiles Aurora table:
| Script Family | Languages | Density Threshold |
|---|---|---|
| latin | es, fr, de, pt, it | 0.06 |
| cyrillic | ru | 0.05 |
| cjk | ja, zh | 0.03 |
| indic | hi, ur | 0.03 |
| arabic | ar | 0.03 |
density_max_prose column). Containers with more prose than this are never lifted, regardless of density.The translation_language_profiles table stores per-language density configuration:
| Column | Type | Purpose |
|---|---|---|
script_family | varchar | Selects density threshold (latin, cyrillic, cjk, indic, arabic) |
density_lift_threshold | numeric | Override threshold for this language (NULL = use script_family default) |
density_max_prose | integer | Max prose chars for lift eligibility (default 300) |
<tr>
<td><span translate="no">GET</span></td>
<td><code translate="no">/health</code></td>
<td>LPO server health check</td>
</tr>
Protected elements: 2 (span + code)
Prose chars: 25 ("GET" + "/health" excluded, "LPO server health check" counted)
Density: 2 / 25 = 0.08
→ CJK (threshold 0.03): LIFTED as [QZ_ZK_NNN] — density 0.08 > 0.03
→ Latin (threshold 0.06): LIFTED as [QZ_ZK_NNN] — density 0.08 > 0.06
→ If prose were 40+ chars: density drops to 0.05, Latin would KEEP it
ElastiCache doc (ja): 45 blocks lifted, 156/156 code tags survive translation intact. Zero retries.
KCC doc (ja): 82 blocks lifted, 327/327 code tags survive translation intact. Zero retries.
Block lifting eliminates the failure mode where code-heavy table rows overwhelm the model's attention. The model never sees these rows — it translates a single [QZ_ZK_NNN] token (which it passes through unchanged) instead of a complex structure with multiple inline placeholders.
After translation, the postprocessor restores placeholders in a single flat pass in reverse index order (high → low) to prevent prefix collisions. Because Phase 1 (density lift) runs BEFORE Phase 2 (individual extraction), BLOCK entries contain original HTML — never nested placeholders.
[QZ_ZS_002]'s manifest HTML contains [QZ_ZC_001]). Reverse-order restore handles this correctly — restoring index 2 first produces the text containing index 1, then index 1 is restored in the same pass.Translated output contains: [QZ_ZK_003] ... [QZ_ZS_002] ... [QZ_ZC_001]
Single pass (reverse order):
Restore [QZ_ZK_003] → original HTML (no further substitution needed inside)
Restore [QZ_ZS_002] → <span translate="no">[QZ_ZC_001] Lambda</span>
Restore [QZ_ZC_001] → <code translate="no">tbi-ops-notify</code>
Final:
<tr><td>...original row...</td></tr>
<span translate="no"><code translate="no">tbi-ops-notify</code> Lambda</span>
<code translate="no">tbi-ops-notify</code>
Perfect reconstruction — no nesting loops, no iteration.
The manifest maps each placeholder to its original HTML, enabling exact restoration:
{
"[QZ_ZK_003]": {
"type": "BLOCK",
"html": "<tr><td><span translate=\"no\">GET</span></td><td><code translate=\"no\">/health</code></td><td>LPO server health check</td></tr>",
"index": 3
},
"[QZ_ZS_002]": {
"type": "SPAN",
"html": "<span translate=\"no\">[QZ_ZC_001] Lambda</span>",
"index": 2
},
"[QZ_ZC_001]": {
"type": "CODE",
"html": "<code translate=\"no\">tbi-ops-notify</code>",
"index": 1
}
}
Note: BLOCK entries always store pristine HTML (no [QZ_...] tokens inside). Phase 2 entries like SPAN may contain lower-index placeholders from inner elements extracted in a later pass — this is handled naturally by the reverse-order restore.
Result: The Translation Engine document (290 code tags, complexity 423) now translates with 0 retries across all 11 parts. Previously it failed consistently on Part 8 (config section with 27 code tags). Restoration is now a single deterministic pass with zero edge cases.
Pass 5 extracts numeric patterns from the text after HTML element extraction. This protects bare numbers in prose that weren't already inside code or span tags. The model cannot convert, localize, or drop what it never sees.
When translating to complex scripts (Arabic, Hindi, Urdu), the model occasionally:
These transformations break technical accuracy. The numeric extraction pass prevents all of them.
| Pattern Type | Pattern (shown as a regular expression; the engine scans characters) | Examples | Placeholder |
|---|---|---|---|
| Memory sizes | \d+(?:\.\d+)?\s?(?:GB|MB|KB|TB) | 32 GB, 1770 MB, 256 KB | [QZ_ZM_001] |
| Percentages | \d+(?:\.\d+)?% | 98.5%, 62%, 100% | [QZ_ZN_001] |
| Version numbers | \d+\.\d+(?:\.\d+)? | 4.6, 17.7, 2.3.1 | [QZ_ZV_001] |
Numeric extraction runs after HTML element extraction (Passes 1-4). This means:
<code> tags are already protected by Pass 2translate="no" spans are already protected by Pass 3Source:
"The Lambda uses 1770 MB of memory and achieves 98.5% uptime."
After Pass 5:
"The Lambda uses [QZ_ZM_042] of memory and achieves [QZ_ZN_043] uptime."
Model translates prose, placeholders survive intact.
After restoration:
"लैम्ब्डा 1770 MB मेमोरी का उपयोग करता है और 98.5% अपटाइम प्राप्त करता है।"
Technical values preserved exactly — no localization, no conversion.
Result: Translation failures caused by numeric value loss (preserve_memory_size: missing: GB, MB) are now resolved across all 11 languages. Numeric values survive intact regardless of target script.
The numeric extraction pass includes safeguards to prevent extracting numbers that are part of existing placeholder names (e.g., the "001" in [QZ_ZC_001]):
]Without these guards, the numeric scan would corrupt placeholder names by extracting their index numbers, producing a placeholder nested inside another placeholder's name, which the model cannot handle.
Technical documentation is dominated by tables where most columns are technical identifiers (column names, data types, endpoints, parameter keys) and only one or two columns contain translatable prose (descriptions, explanations). Sending these tables through the full translation pipeline is wasteful and risky — the model tends to transliterate technical values or corrupt table structure.
Type D solves this with a surgical approach: extract the entire table before translation, then micro-translate only the declared prose columns via a separate, targeted Bedrock call. The table structure is never modified — only cell text content changes.
When the pair has a glossary (10.4), a collected cell whose whole text is a glossary source term is given the target directly and is not sent to the model; when every collected cell maps, the table needs no model call.
Document authors declare the translation contract directly on the <table> element using two attributes:
| Attribute | Values | Effect |
|---|---|---|
data-tx-headers | "all" | "none" | "0,2,4" | Which header cells (<th>) to translate. "all" translates every header; "none" leaves all English; comma-separated indices target specific columns. |
data-tx-cols | "" | "4" | "0,1,2" | Which body cell columns (<td>) to translate. Empty string means no body cells. Comma-separated zero-based column indices target specific columns. |
<table data-tx-headers="all" data-tx-cols="4">
<thead>
<tr><th>Column</th><th>Data Type</th><th>Default</th><th>Nullable</th><th>Description</th></tr>
</thead>
<tbody>
<tr>
<td><code>user_id</code></td>
<td><code>uuid</code></td>
<td>—</td>
<td>YES</td>
<td>Owner of the key; references users table.</td> <!-- Only this cell gets translated -->
</tr>
</tbody>
</table>
Result in Italian: columns 0–3 remain byte-identical English. Column 4 becomes "Proprietario della chiave; fa riferimento alla tabella users."
Type D tables are handled in three stages that bookend the translation process:
data-tx-headers or data-tx-cols attributes are extracted whole and replaced with [QZ_ZT_NNN] placeholders. The model never sees table HTML.data-tx-headers) and body cells (per data-tx-cols)translate="no"⟪SPLIT⟫ delimitersEfficiency: A 185 KB document with 48 Type D tables (Aurora Data Dictionary) needs a single micro-translate call: all unique description strings are batched into one Bedrock request, so the tables add a small fraction to the work of translating the document.
| Document Type | Typical Markup | Effect |
|---|---|---|
| Data Dictionary | data-tx-cols="4" | Translate Description column only; Column, Type, Default, Nullable stay English |
| API Reference | data-tx-cols="0" | Translate Action/Description column; Endpoint and Params stay English |
| Configuration tables | data-tx-cols="" | Translate headers only; all body content (keys, values, examples) stays English |
| Troubleshooting | data-tx-cols="0,1,2" | Translate all prose columns (Symptom, Cause, Fix) |
Documents with extreme density hints (hint:density=extreme) route through prose mode, which extracts and translates only text fragments from the HTML. Without Type D awareness, prose mode would indiscriminately translate all visible table text — including technical columns that must stay English.
The fix: Phase 0 table extraction runs before prose mode walks the DOM. Prose mode sees only the [QZ_ZT_NNN] placeholder — never the table content. After prose mode rebuilds the document, postprocessing restores the tables and runs micro-translate on the declared columns.
This applies to both the marker-based split path and the auto-split path in handler.py.
Type D micro-translation is non-fatal. If the Bedrock batch call fails or returns a mismatched fragment count, the tables are restored in their original English — no data corruption, no job failure. The document is delivered with English tables rather than corrupted ones.
The translation engine sends email notifications via the AutoOps notification pipeline (tbi-ops-notify Lambda → SES). Notifications are consolidated across batch jobs and include detailed per-document breakdowns.
Each notification email includes:
Subject: [INFO] Translation Complete: 2 docs × 11 langs — 22/22 pairs SUCCEEDED
Batch Summary:
• Jobs: 2
• Documents: 2
• Languages: 11
• Total Pairs: 22
• Succeeded: 22
• Failed: 0
• Final State: SUCCEEDED
• Total Time: 7m 12s
Documents Translated:
• Trinity-Beast-TBI-Translation-Engine.html
✓ Succeeded: es, pt, fr, de, ru, hi, ja, zh, ar, ur, it
• Trinity-Beast-Infrastructure-Overview.html
✓ Succeeded: es, pt, fr, de, ru, hi, ja, zh, ar, ur, it
Deployment:
• CloudFront Invalidations: 2
• All translated files deployed to S3
Search Index:
• Rebuilt successfully (all 11 languages)
Subject: [WARNING] Translation Complete: 1 doc × 11 langs — 10/11 pairs PARTIAL
Documents Translated:
• Complex-Technical-Guide.html
✓ Succeeded: es, pt, fr, de, ru, hi, ja, zh, ar, it
✗ Failed: ur
Error Details:
• Complex-Technical-Guide.html → ur: chunk 14 failed validation after 5 retries
check_tag_counts: expected 27 code tags, found 23
When multiple translation jobs are submitted together (e.g., translating 5 documents), the notification system consolidates them into a single email:
This prevents notification spam when translating multiple documents — you get one comprehensive email covering the entire batch, not 5 separate emails.
When the same document appears in multiple jobs within a batch (e.g., initial run fails Urdu, retry succeeds), the notification resolves duplicate entries into a single final-state view:
Without the resolver, a retry job would show the same document twice — once with the failure and once with the fix — making the notification confusing and the counts misleading.
Every notification includes a Tag Inventory section showing source vs output tag counts per document. This lets you detect at a glance if the model is adding or dropping tags. As of v2.8, the inventory also reports Mermaid diagram counts:
Tag Inventory (source → output):
• Trinity-Beast-Translation-Service.html
IN: code:22 pre:5 strong:8 em:2 a:4 br:3 diagrams:1
OUT: code:22 pre:5 strong:8 em:2 a:4 br:3 diagrams:1
If the model has a bad day and adds a <span> that wasn't in the source, or drops code tags, you'll see the mismatch immediately:
IN: code:23 pre:5 strong:8 diagrams:2
OUT: code:20 pre:4 strong:8 diagrams:1 ← 3 code dropped, 1 diagram lost
Tag counts are logged per-language in Aurora (translation_job_events) with tags_in and tags_out fields. For each document the notification shows the source counts once (Tags IN, taken from the most recent lang_succeeded event that carries them; every language has the same source). It then lists the OUT counts of each language whose counts differ from IN, or says the OUT counts are identical in all languages when none differ.
Recipient: All translation notifications go to CoryDeanKalani@CPMP-Site.org via the unified AutoOps notification pipeline. The sender is CPMP Mission <No-Reply@CPMP-Site.org>.
Documents change often: a new endpoint, a revised architecture, an updated pricing table. When a changed English library page is translated again, the engine keeps the published translation of every part whose inputs did not change and translates only the rest. A library pair (no quote_id, the website bucket as output, a document split on chunk markers) reuses a part when its English bytes and hints, its processed text and glossary context, the model, the source language and limits.part_reuse_epoch are all unchanged. Matching runs only when the queue message's options.delta is JSON true, and the KCC submit commands ask for it by default (17.5). A raw POST /admin/translate without delta translates every part, and a customer pair never reuses. Budget a republish by the parts whose English changed, not by the whole page.
The unit of reuse is a part: the span between two chunk markers (13.4). The engine computes three keys, each the first 16 hex characters of a SHA-256 hash:
src, per part: the English part exactly as fetched from S3, with its marker hints.cond, per part: the processed part the model is sent, with the glossary entries that occur in it.fp, once per page: the model, the source language and limits.part_reuse_epoch.Parts are matched by content, never by number. A new part takes an old part whose src and cond both match, wherever that old part sat on the page, so a match always means byte-identical English, and a moved marker can never make a part ship another part's text. A change of model, source language or epoch changes fp, and the whole page is translated on its next run. A glossary change re-translates only the parts that hold an entry it touches, in that language.
A matched part must also pass admission before any model call. _admit_reused_part in handler.py compares the published part with its raw English part, with no model involved: the same unmatched closer and opener names (the boundary signature), the same count of every critical tag and Mermaid diagram, the same heading sequence, the same element ids, and no more engine token residue than the English holds. A part that fails any check is translated instead, and the pair record names the checks that refused it (7.2a). That way a part damaged before reuse existed is translated again rather than shipped again.
The record of what each published part was made from lives in the translated page itself: one comment line, <!-- TBI-PARTS v1 fp=… n=… parts=… -->, directly before the page's </head>, written by the same S3 put_object as the page. It holds the page's fp, the part count n and one src:cond pair per part, about 1.8 KB at 50 parts and no page text. A record written with the bytes cannot disagree with them after a failed pair, a restore or a corrections apply, so whether a part was already translated from this English is answered from the live page on S3, never from Valkey or Aurora.
</head> and it lies in the first part. A page with a second </head>, even inside a script string, carries no manifest, so every run of it is a full one. The fix belongs in the English: write that string's close tag as <\/head>, which JavaScript reads as the same string.tools/part_manifest_bootstrap.py can label such a page with a legacy manifest once it has proved which English the live page was made from and that only the corrections tool has changed it since. Its fp and every cond are x ("not known"), which only that tool writes; a legacy entry matches on src alone, and the worker writes the current keys the next time it publishes the page.The website bucket (trinity-beast-website-east2) has versioning enabled, and delta-diff reads those versions for analysis (17.5). The engine itself never compares S3 versions of the English, and there is no separate metadata store.
Part reuse needs every translated page to split at the same places as its English, so the markers must come through translation intact. They never reach the model: the plan stage splits the page on its markers, and the translate stage re-inserts each marker, with its hints, when it reassembles the page. Any other HTML comment inside a part is lifted out by the document preprocessor before the model call and stands in the text as a placeholder until restoration puts it back (15.4).
The plan stage makes the reuse plan before any model call: it reads the published page, checks its manifest and fp, matches parts by src and cond, and runs admission on every match. A reused part never reaches the model. Its processed English stands in for it through the whole-document gates and the tail, so no gate that runs on model output runs on it. After the tail gate, the splice stage puts each reused part's published bytes back in place, adds the manifest, and runs the splice gate on the result.
The splice gate's eight checks prove that the page about to ship is the page the gates and the tail approved, with only the reused spans swapped. Checks 1 to 6 cover our own code: the part count, every translated part, every reused part, the bytes between parts, the manifest, and the headings and element ids against the source. Checks 7 and 8 catch a whole-document repair meant for a translated part that landed in a reused part: the critical-tag and Mermaid counts must not change across the splice, and each reused part's stand-in must leave the tail with the unmatched closer and opener names and the counts of its processed English. Any finding fails the pair with Part splice integrity failed (...), nothing is published, and the old page stays live. After a check 7 or 8 failure, the recovery is --full --force on that document and language. A span or integrity repair that lands in a reused part and moves no counted tag is dropped with the stand-in and recorded on that part as repair_discarded (7.2a), and the page ships.
When every part of a pair is reusable, nothing is translated or published: the pair logs lang_skipped with reason delta_up_to_date and costs $0. A reuse check that raises (while splitting the previous page, matching or admitting) never fails the pair: it prints PART REUSE OFF: reuse check failed, and the pair translates in full under a full plan, with a manifest. No Valkey record is involved at any step, and reuse works with every Valkey call failing. The chunk-count cache tx:chunks:{doc} is not written when a part was reused, because the count would then cover only the translated parts.
Diagram 17.1: Part Reuse Flow
flowchart TD
A["fetch: the English from S3"] --> B["plan: split on chunk markers"]
B --> C["Keys: src and cond per part, fp per page"]
C --> D{"options.delta true?"}
D -->|No| FULL["translate: every part"]
D -->|Yes| E["Read the published page"]
E --> F{"Manifest present and fp equal?"}
F -->|No| FULL
F -->|Yes| G["Match parts by src and cond, at any position"]
G --> H["Admission: boundary names, critical tags, headings, ids, residue"]
H --> I{"Every part reusable?"}
I -->|Yes| SKIP["lang_skipped delta_up_to_date: nothing written, no cost"]
I -->|No| PART["translate: only the parts not reused"]
FULL --> GATES["repair, tag_gate, localize, tail"]
PART --> GATES
GATES --> SPL["splice: reused parts back in place, manifest added"]
SPL --> SG{"Splice gate: checks 1-8 clean?"}
SG -->|Yes| PUB["publish: page and manifest in one write"]
SG -->|No| FAIL["Part splice integrity failed: the pair fails, the old page stays"]
style A fill:#1e3a5f,stroke:#60a5fa,color:#e0e0e0
style E fill:#1e3a5f,stroke:#60a5fa,color:#e0e0e0
style G fill:#064e3b,stroke:#10b981,color:#e0e0e0
style SKIP fill:#064e3b,stroke:#10b981,color:#e0e0e0
style FULL fill:#7c2d12,stroke:#f97316,color:#e0e0e0
style PART fill:#7c2d12,stroke:#f97316,color:#e0e0e0
style SG fill:#7f1d1d,stroke:#f87171,color:#e0e0e0
style FAIL fill:#7f1d1d,stroke:#f87171,color:#e0e0e0
style PUB fill:#1e3a5f,stroke:#60a5fa,color:#e0e0e0
The three KCC submit commands, translate-pending, translate-task and translate-doc --remote, send delta: true by default, and each prints whether part reuse is on before the run is confirmed. With --full, the queue message carries delta false: every part is translated and the page gets a fresh manifest. --force is separate and independent: it bypasses the in-flight lock, the failure history and the too_dense rejection (6.1). A raw POST /admin/translate reuses parts only when its body asks for it:
# Reuse unchanged parts (what the KCC submit commands ask for by default)
curl -s -X POST -H "X-Admin-Key: $ADMIN_KEY" -H "Content-Type: application/json" \
-d '{"docs":["Trinity-Beast-API-Reference.html"],"langs":"all","options":{"delta":true}}' \
https://api.cpmp-site.org/admin/translate | jq .
# Without delta, every part is translated
curl -s -X POST -H "X-Admin-Key: $ADMIN_KEY" -H "Content-Type: application/json" \
-d '{"docs":["Trinity-Beast-API-Reference.html"],"langs":"all"}' \
https://api.cpmp-site.org/admin/translate | jq .
Three more commands analyse documents and published pages. None of them submits a translation.
# List available S3 versions
bash scripts/kcc.sh delta-diff Trinity-Beast-API-Reference.html --list-versions
# Compare current vs previous version (auto-detects)
bash scripts/kcc.sh delta-diff Trinity-Beast-API-Reference.html
# Compare against a specific version
bash scripts/kcc.sh delta-diff Trinity-Beast-API-Reference.html --version-id ksYxUBZIUB8Roi2KQYje6ig9R7JesL9z
# Show delta for a specific language
bash scripts/kcc.sh delta-diff Trinity-Beast-API-Reference.html --lang ja
Reads two S3 versions of the English and reports which chunks changed between them. It is analysis only: the engine decides reuse from the manifest, never from S3 versions.
# Validate TBI-CHUNK markers survived translation, for every English page on S3
bash scripts/kcc.sh delta-validate all all
# Validate a specific doc across all languages
bash scripts/kcc.sh delta-validate Trinity-Beast-API-Reference.html all
# Validate a specific doc + language pair
bash scripts/kcc.sh delta-validate Trinity-Beast-API-Reference.html es
Compares the marker count of each translated page with the English on S3 and reports pass or fail per document and language. It counts every marker, bare (<!-- TBI-CHUNK -->) or with hints, and all means every English page on S3. The exit code is 0 when every compared pair kept its markers, and 1 when a translated page lost markers or when no pair was compared at all, which it reports as NOTHING CHECKED.
# Analyze a doc from S3 and suggest TBI-CHUNK marker placement
bash scripts/kcc.sh chunk-size Trinity-Beast-API-Reference.html
# Analyze a local file
bash scripts/kcc.sh chunk-size /path/to/local/doc.html
Scans the document for <section>, <h2>, <h3>, and .category-section boundaries. Reports current chunk sizes (if markers exist), identifies policy violations, and suggests where to insert markers to stay within the 15KB/18KB/12KB policy. Dense sections (high translate="no" density) automatically target the tighter 12KB limit.
With reuse on, publishing a changed English document and re-translating it translates only the parts whose English changed, in every language it goes to; every other part keeps its published translation. Four practical rules follow:
limits.part_reuse_epoch, and why. A new worker build does not invalidate any part by itself, so an engine fix reaches unchanged parts only with --full on the documents concerned, or with an epoch bump for all of them.The document translation engine handles HTML docs (Sections 1–17). A separate system handles the translation of API response messages — the short error and status strings returned in UME envelope responses. This section documents how template variables are protected during that process and why the delimiter choice matters.
On November 28, 2026 the error_messages Aurora table held 3,073 rows: 257 message keys in 12 languages. These messages are served dynamically based on the caller's api_lang preference. Some messages contain template variables that are substituted at runtime with real values (e.g., usage counts, rate limits).
Example message (English):
Monthly query limit reached. You have used [usage] of [limit] allowed queries this month.
At runtime, the Go server substitutes [usage] and [limit] with the user's actual values before returning the response.
Convention: All template variables in translatable messages use [square brackets], never {curly braces}.
Why: Curly braces are universally recognized by AI models as structured data delimiters (JSON, format strings, template literals). When a translation model encounters {usage} in a message, it frequently attempts to:
{{usage}})Square brackets do not trigger this behavior. Models treat [usage] as inline notation — similar to citation markers or editorial annotations — and reliably pass it through unchanged across all 11 target languages.
Implementation:
| Layer | File | Behavior |
|---|---|---|
| Go server (substitution) | internal/handlers/core_errmsg.go | strings.ReplaceAll(msg, "["+k+"]", v) |
| Go server (caller) | internal/handlers/price.go | Passes map[string]string{"usage": "...", "limit": "..."} |
| Aurora (source) | error_messages table | All messages use [variable] syntax |
| Translation tool | scripts/kcc_helpers/translate_messages.py | Wraps [variable] in sentinels before Bedrock translation |
API error messages are translated using the translate-messages KCC command — a lightweight Bedrock pipeline separate from the document translation engine:
error_messages table (18.1)[usage], [limit]) and brand terms are wrapped in sentinel tokens (⟦T1⟧...⟦Tn⟧) before the model sees themtranslation_language_profiles.model_override — so do not read a specific model name here as fixed. This line said "Claude Sonnet 4.6" until 2026-08-30, months after Qwen became the standing choice.[variable] text and brand termserrmsg:{lang}:{key}) on first accessThe entire process is idempotent — running it again overwrites with fresh translations. No S3, no CloudFront, no search index rebuild. Just Aurora + Valkey.
The translate_messages.py helper uses the same sentinel wrap/unwrap pattern as the document translation engine, but at a much smaller scale (single sentences vs. multi-KB chunks):
# Before translation:
"Monthly query limit reached. You have used [usage] of [limit] allowed queries."
→ "Monthly query limit reached. You have used ⟦T1⟧ of ⟦T2⟧ allowed queries."
# After translation (Spanish):
"Límite de consultas mensual alcanzado. Has usado ⟦T1⟧ de ⟦T2⟧ consultas permitidas."
→ "Límite de consultas mensual alcanzado. Has usado [usage] de [limit] consultas permitidas."
Protected items include:
[usage], [limit]translation-config.json (63 terms)Result of the first run, recorded in this guide by October 6, 2026: 21 messages × 11 languages = 231 translations completed with zero failures. Template variables survive intact in every language — the Go server can substitute real values at runtime regardless of the response language.
The ETA system predicts how long a translation job will take from the actual times of every pair already translated, read from Aurora on every estimate. It gives an estimate at the quote, at submission and while a job runs, and once the job has finished it shows the actual time beside the estimate, so anyone can see how close the prediction came.
Every pair writes down what was expected and what happened. The record is translation_pair_runs (7.2a): one row per job, document and language, for every agent and every outcome, internal and customer alike. Internal jobs run far more pairs than customer jobs and run the same code, so recording both gives the estimator the sample size it needs.
On November 7, 2026 the record held 2,126 pairs: 2,101 rebuilt by the 60-day backfill and 25 recorded live, 2,001 of them succeeded. Until November 6, 2026 the ETA came from a per-language calibration hash in Valkey (tx:eta:calibration) that was rebuilt after every job. That hash and its rebuild are retired, and no estimate reads or writes Valkey now.
Every figure is the median of what similar recorded pairs actually did, and every time and token figure is then multiplied by one buffer. The method keeps the shape of the formula it replaced (a start offset plus chunks × seconds per chunk) and takes each number from history instead of a fixed constant:
B = 1 + estimation.history_buffer_pct / 100 (today 1.03)
chunks = source_bytes × median(chunks per byte)
processing_s = chunks × median(seconds per chunk) × B
offset_s = median(start offset of a language) × B
language_s = smallest offset_s of its pairs + Σ processing_s of its documents
delivery_s = max(language_s over the job's languages)
Documents run one after another inside a language's container, so a language takes its start offset plus all of its documents. Languages run in parallel, one container each, so the job takes as long as its slowest language (the bottleneck), which is named in every ETA response.
| Figure | Groups tried, narrowest first |
|---|---|
| Chunks per byte | Same language → all pairs |
| Seconds per chunk | Same language and agent → same agent → same language, any agent → all pairs |
| Input tokens per byte, and the output-to-input ratio | Same language and agent → same agent → same language, any agent → any pair |
| Start offset of a language | All pairs (the first document's start in each recent job and language) |
Each figure takes the narrowest group that holds at least estimation.history_min_samples (9) pairs among its estimation.history_group_rows (90) most recent. The history read is the estimation.history_window_rows (2,700) most recent succeeded pairs; when that window is full, an agent with fewer than 90 pairs in it also gets its own 90 most recent. Token figures come only from pairs whose tokens the engine metered. Only when no group qualifies does a figure take its last resort: 21 seconds per chunk, the document's own chunk estimate, and for the start offset and the token ratios the fixed estimation.* values in the Translation Parameters guide.
There is no schedule and no cache: the estimator reads Aurora on every estimate, so it works the same with Valkey down and is never staler than the last finished pair. It gives one figure, not a range. Every estimate is stored with estimator_version eta-hist-2, so a later method can be compared against the rows this one produced, and est_basis records which group each figure came from. The code also holds a narrower density-verdict group; it stays unused until a document's density is known before the job runs, which is planned.
The same estimate prices Claude Opus 4.8. An Opus pair is priced from the token estimate above, the 3% buffer included, and never below $3.00 per pair. Every other agent is a flat $3.00 per pair, whatever the estimate says. Opus has no recorded pairs of its own yet, so its token figures come from other agents' history, the same language first and then any pair. That is why, on November 7, 2026, an Opus pair priced at $3.00 at every document size up to the 300 KB limit, and it is the intended behaviour: Opus prices will follow real Opus usage as its own history builds.
| Endpoint | Method | Purpose |
|---|---|---|
GET /admin/translate/eta?docs=X&langs=Y | GET | Estimate for a job not yet submitted, from the same estimator the quote uses. A document's chunks come from its latest recorded pair, else from its size |
POST /admin/translate/eta/calibrate | POST | The figures the next estimate would use for each language (the group, its sample count and its median) and the settings in force, read from Aurora on the spot. Nothing is built or cached |
POST /admin/translate (response) | — | Immediate ETA in the submission response |
GET /admin/translate/status/{job_id} | — | Live ETA with elapsed/remaining/percent for running jobs |
POST /translate/quote, GET /translate/quote/{quote_id} | — | The customer's delivery block: the estimated delivery time and, once the job has finished, the actual time |
GET /translate/status/{job_id} | — | The same delivery block, plus the live eta while the job is active |
For running jobs, the status endpoint returns an eta object with real-time progress:
{
"estimated_seconds": 202,
"estimated_low_seconds": 202,
"estimated_high_seconds": 202,
"estimated_formatted": "3m 22s",
"estimated_range": "3m 22s",
"bottleneck_lang": "hi",
"elapsed_seconds": 118,
"remaining_seconds": 84,
"remaining_formatted": "1m 24s",
"percent_complete": 58
}
The estimate is one figure. estimated_low_seconds, estimated_high_seconds and estimated_range stay in the response for older integrations and carry that same figure. Admin responses show the short English form above; a customer's status shows the same times in the customer's own language.
Elapsed time counts from submit, because the estimate includes the wait for a container and the language's start. The estimate used is the job's stored one; failing that, its quote's; failing that, a fresh estimate with the history cut off at the job's submit time. Progress is calculated as elapsed / estimated × 100, capped at 99% until the job actually completes. The remaining time decreases linearly — no smoothing or prediction adjustment mid-flight.
A quote stores the delivery estimate it showed. When the job ends (at completion, at a cancel, in the stuck-job sweep and in the refund sweep), the server writes the actuals back to the quote: the actual delivery time, measured from the original job's submit to its finish, the completion time, and each pair's outcome. Quotes made since November 6, 2026 get this write-back; an older quote has no stored estimate to compare against and is left as it was.
The customer sees both figures: in the delivery block of the quote and status responses, and on the Account Dashboard's job card as Estimated Time and Actual Time, each in the reader's language (all 12 site languages).
The first numbers. Quick Reference in Spanish and Japanese, estimated with no history at all, came out at 260 seconds per pair against actuals of 52 and 65 seconds. Once the backfill gave the estimator real history, the same estimate read 116 and 127 seconds. On November 7, 2026 a Spanish test pair was estimated at 62 seconds of processing and took 55.9.
Design principle: Predict from reality, not theory. Every pair writes down what was expected and what happened, and every estimate reads that record, so estimates improve with each finished pair with no schedule and no tuning. When an estimate misses, the recorded facts say why.
Everything above describes what the engine does. This section describes what it is not allowed to do — a set of invariants, each one earned by an incident, each one enforced at a named point in the code and pinned by a test that fails if the enforcement moves.
They are documented here rather than left in the codebase because a translation pipeline fails in a particular way: quietly, and in the artifact rather than the process. A job reports succeeded, the email says every pair completed, the cost is right, and the published document is wrong. Every invariant below exists because that happened at least once.
Three properties of this system make ordinary testing insufficient, and understanding them is the difference between reading the invariant list as bureaucracy and reading it as hard-won architecture.
The model is stochastic, so the same input can fail once and pass on retry. A defect that appears in one language and not the other ten is not evidence of a language-specific bug — it is the normal shape of model variance. That makes reproduction expensive and makes deterministic guards more valuable than diagnostic ones. Wherever a guard can be made exact, it is worth far more than a guard that is merely usually right.
The pipeline repairs as well as validates, and repair can create defects. There are more than twenty repair, recovery and restore functions between the model's output and the published bytes. Roughly half put back exact source bytes, which is always safe. The other half guess where a wrapper belongs, and a wrong guess is indistinguishable from correct output to anything downstream. The standing direction is to preserve deterministic restoration and prefer hard failure with full diagnostics over heuristic repair.
A check is only as good as the string it reads. This is the subtlest of the three and it produced Invariant 12. A gate can be perfectly correct, pass cleanly, and validate nothing — because the artifact it examined is transformed afterwards. Position in the pipeline is part of a check's correctness, not an implementation detail.
The governing lesson, stated once: a tool that answers is not a tool that is right. Every invariant below is accompanied by a test whose job is to prove the check can actually fail. A green run on an assertion incapable of failing is worse than no assertion, because it carries the authority of a passing test.
Each invariant states an obligation, names where it is enforced, and names the test that would catch its removal. The worker keeps the incident narratives in INVARIANTS.md and in comments beside its code, and it numbers several of these rules differently from this guide, so the table below maps them.
Each row is a guide entry whose number leads to a different rule, or to none, in the worker. The Worker column gives the matching INVARIANTS.md heading, or the number a code comment gives the rule together with that comment's file and line. A dash means the worker gives the rule no number. Every entry not listed (1 to 12, 16, 17 and 34 to 40) has the same number in INVARIANTS.md.
| Guide | Worker | Rule |
|---|---|---|
| 13 | — | No regular expressions in the engine. The regex-audit gate in run_tests.sh enforces it, and INVARIANTS.md uses 13 for the placeholder-residue rule, this guide's 18 |
| 14 | — | A translated prose fragment must land in the slot it was translated for |
| 15 | 15, translator/engine.py:1221 | Two individually correct restorations must not touch with no separator. INVARIANTS.md has no heading 15 |
| 18 | INVARIANTS.md 13 | No engine-minted placeholder residue may appear in the published bytes |
| 19 | — | A chunk without its own document wrapper is still packed to its size limit |
| 20 | 17, translator/prompts.py:57 | A retry after an identified failure must correct that failure. The worker records it as a follow-up to its Invariant 17 |
| 21 | INVARIANTS.md 24 | Text lifted out of the model's view must still be translated and written back. The worker's rule is broader: it also covers table cells, links, lifted blocks and prose fragments |
| 22 | 21, translator/preprocessor.py:59 | A part keeps its source's unmatched-tag shape: the boundary sentinels and the boundary-signature gate |
| 23 | — | A long emphasised passage is protected as two placeholders, so its prose stays translatable |
| 24 | 26, translator/preprocessor.py:383 | A recovered element is never inserted into markup |
| 25 | 28, translator/preprocessor.py:812 | An element's position is its position in the document, not its order of extraction |
| 26 | — | No raw placeholder token may reach a reader through the recovery path |
| 27 | 27, handler.py:6595 | The failure-history guard also asks whether the engine changed |
| 28 | 30, handler.py:3095 | A model-added closing tag may be dropped only when it is provably surplus |
| 29 | 31, translator/validators.py:412 | Glue is judged in rendered text, on both sides of the comparison |
| 30 | — | An authored identifier is repaired or refused, never silently mangled |
Splitting a document into chunks and reassembling it must be a byte-level identity operation on the text. The mechanism that broke this was an unconditional strip of the model's output, which discarded the boundary whitespace a chunk carried at its edges. Two chunks then joined with no space between them, fusing the last word of one to the first word of the next.
Enforced by capturing each chunk's leading and trailing whitespace from the source before translation and reattaching it afterwards, regardless of what the model returned. Pinned by a fuzz harness that walks the full offset space of a chunk boundary with several simulated model behaviours, plus a control proving it detects a deliberately planted defect.
A brand term that survives translation but arrives fused to the neighbouring word — Valkey followed immediately by a translated word with no space — is preserved by every presence check and broken to every reader. Presence and correct placement are different properties, and a substring check answers only the first.
Enforced by a spacing check that compares the full glued run at each occurrence against the glued shapes the source already had, per occurrence rather than per term. The per-occurrence rule matters: the same short term can be a legitimate compound identifier in one place and ordinary prose in another within the same chunk, and a per-term check lets one occurrence's shape license a false verdict for the other.
Calibrated for Arabic, August 2026. The check extends a term's glued run past any adjacent alphanumeric character, and Arabic letters are alphanumeric — so the conjunction wa-, which Arabic orthography always writes bound to the following word, read as a lost space and hard-failed the chunk. Arabic was consequently the only language unable to publish this very document. The exemption is deliberately narrow: exactly one proclitic conjunction, nothing bound on the right, and Arabic only. Urdu uses the same letter but its conjunction is a free-standing word, so the exemption does not extend there.
Why narrow. A blanket "ignore Arabic letters to the left of a term" would have cleared the false positive and hidden every genuine lost space in Arabic and Urdu. Measured across the published corpus, the narrow rule cleared 38 false findings and left the genuine ones — Urdu words fused directly to Latin terms — still flagged. That ratio is the evidence the exemption is correctly sized.
A job's own protected terms. The terms a job supplies (10.1) get the same glue repair and gate as the configured list, with one difference in scope: they are judged only where they sit inside their own <span translate="no"> wrapper. A document-wide scan of arbitrary customer strings judges ordinary words. Measured on 330 real translated pairs, it found 131 false hits for the string api alone, and its repair split "capital" into "c api tal". The configured list can afford the document-wide rule only because it is curated.
Invariant 1's root cause generalised. Every call that trims whitespace from raw model output or extracted text was inventoried and classified. Two share the dangerous shape and are safe only because of a call-order dependency rather than by design — which is precisely the kind of safety that breaks silently when someone reorders code.
Enforced by documentation plus tests that pin the call order those two depend on, so a future reordering trips a test rather than shipping a defect. This one is honest about its own limits: it is a snapshot of the call sites that existed when it was written, not a check that re-derives the inventory.
A marker placed inside an open element splits the document mid-structure, and the resulting fragments are not independently valid HTML. Several tools place markers automatically, so the constraint has to live where the placement happens rather than in a reviewer's judgement. Since November 2026 one tool, the marker placer (13.4), places and maintains every library marker and applies this rule together with the size and part-shape rules.
Enforced by moving a proposed marker to the nearest safe boundary rather than rejecting it, and by a validator that re-implements the server's exact line-recognition rule. The marker rule is stricter than it looks: a marker must sit alone on its own line. A marker glued to an adjacent element passes a naive search and is invisible to the splitter, so the intended boundary silently disappears into the previous chunk.
This document is the hardest case for its own tooling. Because it documents the marker syntax, it contains marker mentions in prose alongside real markers. A substring count over-reports by roughly 40 percent, and a chunk-size calculation keyed to that loose pattern splits real chunks into fragments and therefore understates their size — a false all-clear on the size policy. Any count or size check on this document must apply the marker rule, not a substring match.
A job's reported status is a claim about the job, not about the document. The published artifact is the only authority on whether the published artifact is correct, and it lives on the CDN rather than on any developer's disk.
Enforced by audits that read the live CDN and enumerate from the English document set rather than from a language folder — a distinction that matters because the engine writes translations straight to S3, so a local language folder may not even contain the file that is live. Judged on absolute counts rather than ratios, because a share-of-content ratio flags legitimate short samples and produces noise.
Every extracted element must come back, regardless of which extraction mechanism produced it or why the model failed to echo its token. The incident was an entire thirty-row table dropped whole, because its token sat alone at the start of a chunk with almost no surrounding prose to anchor it.
Enforced by a three-tier recovery in the one function all extracted types funnel through: exact match, then fuzzy match for a garbled token, then anchor recovery for a token dropped outright with no trace to match against. Nothing upstream can guarantee a model never drops an isolated token, so recovery belongs at the point where every type converges rather than in a hope about model behaviour.
A model that loses its place can fill its entire output budget with one character. Two published Urdu documents each served a solid wall of a single glyph where prose should have been — over seven thousand repetitions in each — and both were reported as successful translations.
Enforced by a generation-time guard that rejects a chunk whose output degenerates into a repeated character or a short cycle, detected on run length rather than script. The script-based instinct is wrong here and the measurement proves it: one live case was thousands of Arabic diacritic marks inside Urdu's own script, which a cross-script check structurally cannot see.
Root cause, corrected August 2026: placeholder density per chunk, not chunk size. Both collapsing chunks were comfortably inside the size policy — well under half the ceiling. What they shared was a dense concentration of placeholders relative to translatable prose, which leaves the model too little context between opaque tokens. Isolating the dense region behind its own chunk marker fixed both documents, and the language then succeeded three consecutive times. Chunk size is the wrong lever for this failure.
Restoration replaces a placeholder token with the element it stands for. Any text that merely looks like a token is therefore indistinguishable from a real one and gets overwritten with unrelated lifted HTML.
This document is the reason the invariant exists. It documents the placeholder format and so contains roughly thirty placeholder-shaped literals. One of them was replaced by a real element, silently, with no model involved — reproduced with the model removed from the loop entirely, which is what established the defect as ours rather than the model's.
Enforced by scanning the source for placeholder-shaped literals before generating any token and starting the index above every literal found. Because a single counter is shared across all placeholder types, token equality requires index equality, so clearing the highest reserved index makes a collision arithmetically impossible.
Bounding the replacement to one occurrence was considered and rejected. "The first occurrence" is not reliably the real token, so bounding trades a visible corruption for an ordering-dependent one. That rejection is load-bearing for Invariant 11 below — read them together.
HTML attribute names are case-insensitive; SVG attribute names are not. A general-purpose HTML parser lower-cases attribute names, which turns an inline diagram's coordinate-system declaration into an attribute browsers ignore. The graphic then loses its ability to scale — visibly broken, and invisible to every tag-count check, because the tag is still there and the attribute is still there.
Enforced by extracting inline vector graphics as raw bytes before the parser can normalise them.
Preprocessing enriches the source before translation — wrapping brand terms, marking code elements as non-translatable. Removing that scaffolding afterwards must be bounded by the excess over the authored document, and it must be targeted by content rather than by count.
The defect was an unconditional removal sitting a few lines below a branch that got the same problem right. Because the house convention requires every authored code element to carry the non-translate marker, "remove them all" is precisely backwards for this corpus — almost none of them are scaffolding. On this document the source carried 628 such attributes, preprocessing added 74, and all 702 were destroyed. Every published translation of every document shipped none of them.
Counting is not enough, and this is the instructive part. A count-limited fix preserves the right number of attributes and leaves them on the wrong elements, because a plain replacement takes the first matches and those are the authored ones. It matters beyond tidiness: these pages carry a browser translation widget, so a code element that loses its marker gets its copy-pasteable command translated for the reader. The correct fix records which contents were bare in the authored document and removes the attribute only from those.
Verified by a round trip that is byte-identical to the authored source across all 471 distinct code contents in this document.
There is a third scaffolding source. The protected-terms prescan (10.1) wraps a job's own terms, beside the brand-term wrapping and the code marking, and its wrappers are scaffolding too. The same rule removes them, inside the same excess budget, fed the exact strings the prescan wrapped, case variants included. Fed the supplied terms instead, a case variant would keep its wrapper and ship it.
The term-wrapper strip has been budgeted per term since November 21, 2026, and has chosen which wrappers to remove by position since November 22. It used to spend one budget for the whole page, longest term first from the top, so it removed the author's own wrappers on long names and kept the engine's on short ones: on November 21, 2026 all 11 translations of the ElastiCache Operations Recovery guide carried none of the 28 Valkey wrappers the author wrote and 19 S3 wrappers the author never wrote. Now a term loses only the wrappers it has beyond the author's count of that exact wrapper, never more than the page's excess. A wrapper the author wrote is never stripped; a wrapper nested inside another protected wrapper goes first and the engine's other wrappers next, leftmost first within each group. Published pages keep their old wrapper placement until a part is translated again, because part reuse (17) ships an unchanged part's published bytes.
Restoration must produce a single copy of an element however many times the model echoed its token. The defect was a boolean presence check followed by an unbounded replacement: a boolean cannot distinguish one occurrence from five, and an unbounded replacement expands every one of them into a full copy of the lifted element.
Model doubling is not a hypothesis here. The sentinel system that preceded the current preprocessor carried an explicit pass to collapse duplicated tokens, commented as a bilingual output instinct. That defence was not carried over when content protection moved to the preprocessor, which makes the duplication a regression introduced by that migration rather than a new model behaviour. The current handling deliberately does not inherit the old pass's limitation of only collapsing adjacent duplicates.
Enforced by counting occurrences instead of testing presence: none means missing and still flows to Invariant 6's recovery untouched, one is the normal path, and more than one restores a single copy at the first position, removes the surplus tokens, reports the placeholder and the count, and fails validation.
This depends on Invariant 8 and is unsafe without it. Invariant 8 rejected bounded replacement because a generated token could collide with the document's own literal — and its own fix removed that possibility by reserving the index space. Bounding is sound because Invariant 8 holds. It is a dependency, not an independent fix, and if the reservation guard is ever weakened this becomes silently unsafe again.
Known boundary: this guarantees the element is not duplicated. It does not repair duplicated prose around a doubled token — in a bilingual-doubling event the model may emit a whole passage twice, and restoration cannot adjudicate which copy to keep. The warning says so, and the corpus audits are where that surfaces.
A gate that validates a string the pipeline then transforms has validated nothing. At least one check must observe the artifact as it will be written.
An audit of gate positions found that none of the full-document gates observed the published bytes. All of them ran at one point, and the output was then reassigned seven more times before the write with nothing validating any of it. Two of those reassignments are content transformations acting on wrappers and non-translate markers — exactly the dimension the earlier gates check. So those gates compared two strings, neither of which shipped, and the shipped artifact was then altered in the very dimension they had just validated.
The obvious fix is the wrong one, and it was measured before being attempted. Moving the gates later false-fails. Both sides of the existing comparison carry scaffolding, so its baseline is correct for the position it occupies. Moving the gates and changing their baseline are only safe together; either one alone produces a spurious 13-element mismatch on this document. An earlier draft of the audit called that baseline a defect — that framing was wrong, and acting on it would have introduced the false failure it was trying to prevent.
Enforced by a differential check immediately before the write, which asks only what the final transformations did. That sequence is deterministic code, so its contract is exact — and an exact check is safe there precisely because it cannot be tripped by the stochastic model drift the earlier tolerance-based gate exists to absorb. Four contracts: scaffolding removal may only reduce non-translate markers and never below the authored count; wrapper repair may only add wrappers; path and language rewrites may not change any tag count; and no structural tag may lose or gain count across the sequence.
It fails hard rather than downgrading. The earlier gate's downgrade path exists so stochastic model drift does not discard a paid-for translation — but a finding here cannot come from the model, so it means the engine's own deterministic code misbehaved.
Every string operation in the engine uses direct comparison: membership, equality, find(), character walking, or a real DOM parser. Regular expressions are excluded from the engine entirely — not discouraged, not restricted to non-validation use. Excluded, with the same absolute standing that forbidding omitempty has in the platform's response envelope: the construct does not appear in this codebase, and a reviewer who finds one has found a defect rather than a style disagreement.
This is the only invariant on the list that constrains the source rather than the pipeline, and it is here because every other one kept tracing back to it. A pattern matches characters. Every job in this engine — is this term preserved, is this element intact, did this wrapper survive, is this boundary correct — is a question about meaning. Where those two diverge the pattern still returns an answer, and the answer is silently wrong.
Three failures paid for this rule, each one silent:
It is enforced by a repository audit that walks every engine source file and reports any import of the pattern library or any call into it. Since September 1, 2026 it runs as a gate of the test runner, run_tests.sh, instead of as a leg of the daily audit sweep. It returns a non-zero exit on any finding, so a reintroduction fails the suite and blocks the image build rather than waiting to be noticed (20.4). It was verified in both directions before being trusted — clean across the engine, red on a deliberately induced violation, clean again after reverting it.
The audit reads the parsed syntax tree, not the file's text, and that distinction is the whole reason it works. This codebase documents its direct-comparison functions by naming the pattern each one replaced, so the source is full of accurate prose about patterns. A text search reports every one of those sentences as a violation of the rule they exist to explain. The first inventory attempt was a line-count search: it reported roughly fifty-seven usages across eleven files and was quoted as a measurement. The true count of executable usages was four, in a single file. A language's own parser cannot be misled by a comment, and no count taken any other way should be trusted.
One declared exception. A test may reinstate a retired pattern as a differential oracle — running the old pattern and the new direct-comparison implementation across the entire corpus and asserting identical output. That is how a conversion earns confidence instead of receiving it, and the conversion that closed out this invariant was proven that way across every English source in the library: identical output, four hundred and twenty wrappers rewritten, zero disagreements. A file claiming the exception must declare it with an explicit marker so the exemption is auditable rather than assumed, and the oracle should be retired once the property it proved can be stated directly.
Prose-mode translation sends the model several fragments in one call and gets back a labelled list — fragment 3's translation goes in slot 3, and nothing beyond the model's own label ties the two together. A model that merges two fragments while continuing to count shifts every later fragment one slot into its neighbour's place. The result is well-formed, correctly scripted, and tag-count-identical to the source, because nothing about a shift changes any of the properties those checks measure. It shipped an Arabic section heading reading "the duplicate" and a key card holding the back half of an unrelated sentence, with the job reporting succeeded.
Two deterministic rules, neither needing a model call. Displacement: a unique anchor from fragment N found in a different slot proves the content moved — stated as presence in the wrong place rather than absence from the right one, because absence alone is ambiguous (the model may simply have mangled the identifier) while presence elsewhere is proof. Deletion: a slot left empty while its source fragment was not is content silently dropped, with the writer producing an unremarkable whitespace-only text node.
Coverage was measured against the real corpus rather than assumed, and the number is worth sitting with. Only 2 percent of fragments across the library carry a unique anchor at all, so rule one is individually blind to the other 98 percent. What rescues it is that a shift propagates forward: 82 percent of the positions where a shift could begin have an anchored fragment somewhere downstream of them within the same chunk, which is enough to catch the shift even though the specific fragment that started it carries no anchor of its own. That 82 percent is a per-document ceiling, not the gate's guaranteed rate — three documents in the library carry no anchors whatsoever and sit entirely outside rule one's reach. Rule two needs no anchor and covers deletion completely.
Enforced by a check run before the DOM is touched, on the model's raw labelled response. The engine's own retry path takes one corrective pass at a higher temperature before treating a persistent finding as a hard failure; a caller-side recovery fallback that keeps the original document when a fix cannot be made declines rather than guesses, honouring its own contract instead of shipping a repair it cannot verify.
Known boundary: a swap between two anchor-less fragments sharing a parent is undetectable by this mechanism — it needs semantic comparison, which means another model call, and that tradeoff was declined rather than hidden. The gap is named rather than closed, and the corpus audits are the backstop that can still catch it after publication.
Invariant 11 guarantees one placeholder produces exactly one copy of its element. It says nothing about what happens when two different, individually healthy placeholders happen to land next to each other during restoration. The defect this closes is two distinct product names arriving glued with zero space between them — the same brand term doubled with no separator, from two entirely separate sentences — where neither placeholder was missing, neither was duplicated, and every existing check that looks at one restoration at a time reports it clean.
The model dropped every character of connecting prose between two adjacent-in-output placeholders. The main restoration loop asks "is this token okay" for each entry in isolation and never asks what now sits on either side of a splice it just made. A join is exactly the place that question has to be asked, because a join is the only point where two independently-correct pieces first touch.
Enforced by a guard applied at every splice point in restoration, reused rather than duplicated from the join logic anchor recovery already needed for the same reason. It inserts a single space only when concatenating the two sides bare would present two touching alphanumeric characters to a reader — the same visible-character test, deliberately, that the tail's brand-term glue repair uses, rather than a second independent definition of "glued" that could drift from the first. Japanese and Chinese are exempted, because those scripts legitimately attach a foreign term to adjacent text with no space, and inserting one there would itself be the defect.
Surfaced as a parity-audit regression — three known defects becoming seven overnight — rather than found by reading code, which is the same discipline as Invariant 5: the corpus's actual state is what proved something had changed, not a hunch about what might have.
Every call into Bedrock returns a stop signal distinguishing a response that finished from one cut off for exhausting its output budget. Nothing before this invariant read that signal. A truncated response is real, well-formed text right up to the cutoff — it fails no content check by virtue of being incomplete, because incompleteness is not a property content checks can see. It is a property of how much content exists at all, and a document is missing everything past the cutoff while every tag-count and brand-term check reports what little text arrived as clean.
A published document shipped with its footer and every closing tag cut off entirely. The failing chunk hit the exact same output-token count on all four attempts — a ceiling divided evenly by the retry count, meaning it was not occasionally near the limit, it was pinned to it every single time. The raw response confirmed the real cause directly: the model was cut off mid-reasoning, before writing a single character of the actual translation, and the pipeline shipped what little text existed anyway.
The compounding cause, and why raising the ceiling alone would not have been enough. The model's reasoning-token budget had been configured larger than the total completion ceiling. Reasoning tokens are not a separate allowance — they draw from the exact same pool the output ceiling caps. A configuration where reasoning could alone exceed the total budget meant any chunk dense enough to make the model think at length was one step from guaranteed truncation, independent of how much actual translation text would eventually have been needed. Both halves had to be fixed together: the reasoning budget capped well below the completion ceiling, and the ceiling itself raised and tested directly against the account's real limit rather than the model card's advertised one, which the account rejected outright.
Enforced by reading the provider's real stop signal per model family and treating a truncated attempt as a hard failure that retries through the existing loop rather than falling through to a return — exhausting every retry raises rather than shipping the partial result. An unclosed reasoning block is treated as truncation evidence in its own right, since the step that would otherwise close it deliberately leaves an unclosed one untouched rather than guessing where it should end.
Relationship to Invariant 7: Invariant 7 catches a chunk that degenerates — collapses into a repeated character while still consuming its full budget doing so. This invariant catches a chunk that runs out of budget before finishing, producing clean, non-repeating text that simply stops. Different failure shape, same root category: a completion-time content loss no placeholder-based recovery can see, because there was never a placeholder standing in for the missing content. Nothing was ever generated to recover.
Every placeholder or sentinel format that can reach the model must be named explicitly in its instructions, and those instructions must forbid converting one format into another or inventing a format absent from the input. A chunk that returns fewer placeholders of a given format than it was sent is a hard failure that retries. Since September 7, 2026 a small shortfall is the exception (INVARIANTS.md 18 in the worker): a chunk missing three or fewer [QZ_*] placeholders is not retried and goes on to the postprocessor's anchor recovery, which already repairs that shape safely. Only a larger shortfall fails and retries.
One extraction pass lifts protected content into a placeholder format the rest of the engine treats as opaque — it neither mints that format nor restores it, so nothing verified the tokens came back. Meanwhile the model's instructions named every other placeholder format unconditionally and said nothing about this one. Given tokens it could see and instructions about formats it could not, the model did the plausible thing: it rewrote what it had into what it had been told about, and in doing so satisfied the instructions' own counting rule. From the model's own point of view, it had complied.
Five consecutive identical production failures, and two wrong fixes built against a caption before anyone checked whether the caption was a diagnosis. Every failure reported the same hardcoded finding text naming a specific repair step, because that check's finding string is written once for glue found anywhere across the entire tail — a location hint, not a cause. Two build-and-deploy cycles were spent correcting the step the message named. Both were real, tested fixes to real, if unrelated, defects; neither touched the actual fault, and either one succeeding would have quietly shipped untranslated English into a published document instead of blocking it — which is the failure the block was there to prevent.
What finally solved it was reading the pipeline directly rather than reasoning about it from a symptom three layers downstream. A neighbouring chunk with more placeholders round-tripped perfectly through identical code, which eliminated density, size and structural imbalance as causes in one comparison. The failing chunk sent fifty of its own placeholders and returned zero of them — while returning over fifty tokens in the format the model had been told about, tokens the engine's own minting function had not created. The engine did not produce them. The model did.
Every retry had failed identically because temperature was zero and the input never changed — a deterministic-input fault is precisely the shape a retry cannot fix, the same lesson this engine already carries from the placeholder-residue invariant's own reverted blocking gate.
Enforced by two changes made together, because neither alone was sufficient. The instructions now name the previously-unmentioned format explicitly, forbid converting between formats, and count survival per format rather than globally — closing the cause. And a chunk returning fewer of that format than it was sent is now a hard failure routed into the existing retry loop — inert whenever none were sent, so ordinary chunks are unaffected — catching any recurrence loudly instead of letting it corrupt a document silently. The prompt fix removes the trigger; the gate makes a future instance loud rather than invisible.
Every manifest-driven recovery in this pipeline — Invariant 6's three-tier recovery, the fuzzy match, the anchor recovery — asks one question: did the element I extracted come back? That is the absence side of the question. Nothing asked the presence side: is there placeholder-shaped residue sitting in what is about to ship. A document could restore every manifest entry, pass every gate above, and still publish garbage in its prose, because none of those gates read for a token shape — they read for tag counts and term presence.
The German copy of this very document once shipped four raw sentinels in a single sentence explaining a different subsystem — the same content class this section now documents, published as literal tokens rather than the product names they stood for. A corpus sweep at the time found leaked tokens in over a tenth of all published pairs, across every one of the eleven languages, concentrated in the languages whose scripts already run densest.
Re-translation is not the remedy, and this was proven rather than assumed. Two separate runs of the identical document in the identical language produced different bytes carrying the identical leaked token identifiers. The fault sits in the restore step, not in sampling variance, so spending Bedrock tokens on a fresh translation changes nothing about whether the defect recurs.
Enforced by a check immediately before the write that compares every engine-minted token shape against the English source: anything the source legitimately carries — this document discusses its own sentinel syntax in prose, so it is allowed to contain the shapes it explains — passes, and anything the shipped bytes carry that the source does not is stripped from the bytes and reported as a loud warning rather than blocking the publish. It does not block, deliberately: the prior version did block, and making roughly two dozen documents permanently unpublishable while calling the failure "recoverable" was itself the defect, once the model was shown to fail the exact same way on retry.
Removing a token must not glue two words together either. Until November 12, 2026 the strip dropped the space after any tag when it removed a token, so a token sitting between an inline code path and the word Valkey shipped the two as one word in the rendered text, and the glue check failed an Urdu pair. The strip now keeps the space after an inline tag, and after its removals it asks the glue question again and repairs only glue that the removals created, keeping a repair only when no new glue remains and every earlier finding is untouched.
A companion audit sweeps the already-published corpus for the same shapes, because this gate only stops new residue from shipping — it does nothing for what published before it existed. Neither replaces the other, the same relationship the degeneration guard has with its own corpus audit.
This guide's Invariant 13 is the engine-wide exclusion of regular expressions, and the worker's INVARIANTS.md gives the number 13 to the placeholder-residue gate documented here. Both rules are real and enforced; only the labels differ. The table under Numbering Against the Worker, at the start of 20.2, maps this entry and every other one whose number differs, rather than renumbering either list, because a silently reconciled number erases a real fact for whoever reads the source next.
The chunker's job is to split a document into pieces small enough for reliable translation, and that job does not change just because the piece it was handed is itself already a fragment of a larger one. A caller that hands the chunker a bare slice of body content — no surrounding document — must receive the same size-bounded packing a full document would, not a single unsplit pass-through.
The chunker's entry point locates a document by its opening body tag before deciding how to split it. When that tag is absent — which is exactly the shape of every marker-delimited piece an upstream splitter produces, since a slice of body content never carries its own body tag — the function had one branch left: hand the whole fragment back as a single chunk, no packing applied. That branch was written for what its own comment called an unusual case. It was, in fact, the case every marker-based document hits on every one of its pieces, every time, because the upstream splitter's output is nothing but bare fragments.
The consequence sat quietly underneath a language's own configured size ceiling. A fragment several times over that ceiling went to the model as one uninterrupted chunk, because the layer meant to enforce the ceiling never ran on it — it had already exited through the branch that skips packing entirely. The languages with the tightest ceilings, set tightest because their scripts need the most room per character, were exposed to the largest oversized chunks relative to their own limit.
Enforced by routing the no-wrapper case through the identical marker-check-then-packing logic a full document already receives, rather than exiting early into an unpacked pass-through. A fragment that carries markers still splits on them, deterministically, exactly as before. A fragment that does not is now packed against its target language's real size ceiling, the same discipline every full document already had. Verified against the two live fragments that had been silently exceeding their ceiling by more than double: both now split into multiple correctly-sized pieces, and a fragment already under its ceiling is confirmed to remain a single chunk — the fix adds packing where it was missing without over-splitting where it was never needed.
A retry exists to give the model a genuine second chance, and a second chance that repeats the same generic caution the first attempt already had is not a second chance — on a deterministic model call, an unchanged instruction produces the same error again. When a retry is triggered by a hard failure whose cause is already known and already named, the correction offered on that retry must name the same thing.
A chunk that failed on a specific placeholder-survival violation — the model overwriting one token format with another — was, on retry, handed only the pipeline's general-purpose caution about protected terms and version numbers. That caution says nothing about token formats. The retry consumed a full attempt and a full Bedrock call while asking the model to be more careful about a problem it did not have, leaving the actual problem completely uncorrected.
Enforced by carrying the specific hard-failure name forward from one attempt to the next, and selecting a directed correction that restates the exact rule violated whenever that name matches a defect with a known, nameable cause. The general caution remains the default for every other failure shape, so a retry answers what actually went wrong rather than a fixed script of caution that may or may not apply.
Lifting an element whole to keep the model from mishandling its wrapper is a valid defense against one failure — but if the lifted element's own visible text was the reason to translate it in the first place, the defense has traded one failure for another. An extraction that protects a wrapper by hiding everything inside it, including ordinary prose, must be paired with a step that still translates that prose, or the fix silently becomes the new source of untranslated content.
Short bold and emphasis labels were lifted as complete, single-piece placeholders specifically because the model tended to drop the wrapping tag around them. That defense worked exactly as designed — the wrapper always survived. It also meant the model never received the label's own text as something to translate, so restoration correctly put back exactly what had been lifted: the original English, verbatim, every time. A measurement across a published document found the majority of its bold labels — product tier names, short lead-in phrases — still in English, and every affected label was short enough to match the extraction's own threshold precisely, which is what confirmed the extraction itself as the cause rather than a model shortcoming.
Enforced by the same repair already proven for an identical gap in plain-text links: after restoration, the visible text inside a lifted label is extracted a second time, translated in one small batch call, and patched back into that specific element only. An element whose text comes back unchanged — a protected brand term the model correctly declined to translate — is left exactly as restored, and an element whose only content sits behind its own protection boundary is skipped before any call is made.
A document too large for one model call is split into parts, and a part is almost never internally balanced: a container opened in part 0 may legitimately close in part 6. So "does this part balance" is the wrong question. The right one is whether the part's boundary signature — the list of tags whose partner lives in another part — is identical in the source part and the translated part. A whole-document tag count cannot see this: the counts stay equal while the nesting moves. Measured when it broke, 114 unmatched closers and 109 unmatched openers were dropped across 38 published pairs, and one lost closer ended a layout wrapper 14% into a page so the rest of the document rendered outside it. Every existing gate passed, because the div counts matched the English exactly.
Enforced by encoding each unmatched boundary tag into an inert comment sentinel that carries its own original text, so it survives the model call rather than being hidden from the parser and then handed to the model. Pinned by a same-input, same-position comparison of the two signatures, which has no false-positive mode on a correctly translated part.
A signature compares the names of the unmatched tags and their order, not where each one sits, so since November 22, 2026 equal signatures are checked once more (Invariant 37). For each unmatched closer the gate compares the elements open at that point in the source and in the output, and since November 28, 2026, for each unmatched opener, its position among the part's start tags of the same name. Any difference is a finding that the part retry (4.2) handles like any other.
Protecting an element by replacing it with a single placeholder guarantees its tag survives and guarantees its text is never translated — the model never sees the words. For a short label that trade is acceptable and is repaired afterwards. For a long emphasised passage it is not: the reader gets a paragraph of English inside an otherwise translated page.
Enforced by protecting a long emphasis wrapper as two independent placeholders, one for the opening tag and one for the closing tag, with the prose left visible between them. Corpus exposure for this shape went from 252 affected elements to zero. Pinned by a threshold measured on authored text rather than on the engine's own tokens — the first version of the measurement counted placeholder characters and picked a boundary that protected the wrong things.
When the model drops a placeholder outright, the engine recovers the element by locating a surviving neighbour and inserting the stored content next to it. Locating that neighbour by plain string search over the whole restored document will happily return an offset inside an HTML comment, inside an attribute value, or in the middle of a tag. Reproduced offline at no cost: the anchor was the four-character string 12.2, and the insertion landed inside a comment, so three emphasis labels per language vanished from the page while every tag count still matched.
Enforced by a safe-position gate that refuses any offset not in document text. Unsafe relocations across the corpus went from 44 documents to zero. Pinned by a test asserting no recovered element may be placed inside a comment, an attribute, or a tag.
Rejecting a bad insertion point only moves an element to the next safe wrong place. Closing the harmful shape of Invariant 24 left the position defect intact, and the labels simply moved from a comment into the following heading — visible and wrong, where before they were invisible and wrong. Extraction runs in phases, so a dense block can hold a low index while sitting late in the page: measured, extraction order disagreed with document order for 15,319 of 15,909 tokens across 430 of 443 parts.
Enforced by three changes measured separately, which is the part worth remembering. Assigning a true document-order position and sorting recovery by it moved almost nothing on its own — 611 clean to 612 — and it is the obvious fix. What delivered the improvement was recovering in token space, before substitution, when every anchor is still a unique token rather than content that may appear identically elsewhere. The third was a scope bound plus a requirement that both flanking entries survive, because document order says which entries flank a dropped one but nothing about how far away they are: in one measured case a term inside a title at offset 161 had its next neighbour at offset 5,414, past a stylesheet block and outside the document head.
The same question decides where a dropped boundary sentinel goes (Invariant 37). For a TBI-BT sentinel whose source gap to the next token holds markup, the preprocessor records the first tag of that gap as the sentinel's bt_anchor, and recovery places the dropped sentinel directly before that tag instead of directly before the next token.
The content-anchored recovery pass runs after substitution and inserted its stored markup verbatim. An entry whose stored content held a nested token therefore had that token inserted with no pass left to resolve it, and the page rendered the literal text of an engine placeholder. Invisible to every gate in the pipeline: the tag counts matched, the placeholder genuinely was restored, and a leaked token is ordinary text rather than markup. Measured corpus-wide, 352 of 15,919 recoveries leaked a token; after the fix, none did.
Enforced by resolving nested tokens before insertion, with a bounded depth so a self-reference cannot loop — and by token-space recovery, which avoids the class by construction. Pinned by a test asserting no recovered element leaks a raw token.
The engine records a pair's past failures and refuses to spend tokens repeating one. The question it has to answer is "has anything changed that could make this succeed," and that has two possible answers — the source document, or the engine. It consulted only the first. So immediately after an engine fix, the pairs that most needed re-translating were precisely the ones permanently refused, and silently, because a refusal is terminal.
Enforced by stamping the build time into the image and admitting a retry when either the engine or the source is newer than the recorded failure. Confirmed live: of twelve queued pairs, the seven carrying failure history from a month earlier were all admitted without any manual override. Pinned by a deliberate negative result — the stamp is generated at build time and is absent from a fresh checkout, so the guard warns loudly rather than failing open, and the protection is image-only by design.
One outcome never counts against a pair. The guard ignores a failure recorded as cancel-state-unknown, where the before-publish cancel check could not read the job's state (6.4). Such a failure says nothing about the document or the engine, so the next run retries the pair, while an earlier real failure of the same pair still counts.
Because a long emphasis wrapper reaches the model as two sentinels rather than as tags (Invariant 23), the model sometimes returns both sentinels and a literal closing tag, having inferred that the prose it just translated was emphasised. After restoration there is one closer too many and the boundary-signature gate correctly refuses to publish. The gate was right; what was missing was a repair for the one shape that is safe to fix.
Enforced by a repair that runs before the gate and only ever removes a tag it can prove is redundant. Four conditions must all hold: the part's unmatched openers already match the source; every extra closer is inline emphasis, never a structural container; the opening-tag count for that name is unchanged from the source; and the signature must equal the source's after the deletion, re-measured rather than assumed. The third condition is the proof — eighteen opens and nineteen closes against a source of eighteen and eighteen leaves the nineteenth closer with nothing it could possibly close, whereas seventeen opens means an opener was lost and the extra closer is its symptom, so the repair declines and the gate still rejects. Pinned by a suite weighted toward the refusal cases, because the naive version of this fix passes a test that only checks the live case and would erase the evidence of a lost opener.
Invariant 2 compares a term's glued run against the glued shapes the source already had, which is the correct rule. It was applied to raw markup, and that quietly broke it in both directions. A protected term always sits inside its own protective wrapper, so when the model fuses the next word to it the fusion lands after the closing tag, where a scan over markup stops. And an identifier the author fused on purpose — written by hand with a protective wrapper in the middle of it — reads as new glue on the source side.
So the same check simultaneously invented defects and hid them. It reported a comfortable zero from August to October while 125 genuinely glued terms sat on the published corpus, including German text a reader can simply see. The lesson generalises past this engine: a zero from a check that cannot fail is indistinguishable from a zero from a clean corpus. A half-fix is what made the zero look earned — correcting only the source side still measures zero, which is why the gap survived six weeks after the principle was already written down in the code.
Enforced by reducing both sides to the text a reader sees before any comparison: inline elements vanish with no separator, every other element becomes a single space, so a table-cell boundary stays a word break and cell adjacency invents nothing. Measured before the change rather than after: of the repairs the wider scope enables, 98 restore a real lost space and 9 would have split an authored identifier. Pinned by tests in both directions, including the defect itself so that a revert cannot pass silently.
Seeing more is only an improvement if the repair that follows is right. One live finding class is not a lost space at all but a corrupted name: the model translated the tail of an identifier, so TranslateS3AccessRole shipped as TranslateS3AccessRolle in nine languages. Inserting a space there produces TranslateS3AccessRo lle — measured, that is exactly where the repair's authored-prefix walk lands — which trades a loud, catchable defect for a quiet published one.
Enforced by a refusal rule in the full-document repair: a run whose authored identifier is not intact is reported and left alone, so the gate hard-fails the pair instead of publishing a mangled name. The discriminator is containment rather than a shared prefix, and getting that wrong is easy — an authored compound that survives whole with a translated word glued onto its end is repairable, and a prefix-only rule refuses it. The rule deliberately does not live in the shared position-finding helper, whose verdict must stay identical to the gate's so that a correct scaffolding strip can never hard-fail a paid translation.
And the inverse defect has no check at all. An authored identifier can also be split: BedrockCostForTokens publishes as two words in all nine space-delimited languages, and FlushToElastiCache in one. Every existing check passes it by construction — presence is a substring test, which a split satisfies, and the spacing checks only fire when a run is longer than the term, where a split makes it exactly equal. Both identifiers are now protected terms so the model cannot split them again, and one needed its English markup rewrapped because the protection pass matches within a single text node and could not see an identifier divided by a tag. The missing piece is a gate, and its shape is the mirror of the glue check: an authored run present in the source whose characters appear in the output separated by whitespace. It was found by pre-flighting identifiers before a paid re-translation, which is the finding as much as the defect is.
A glossary (10.4) writes or asks for a target term only in text the engine would otherwise send to the model. It never touches what the source declared: translate="no" elements, code and the other protected elements, tag attributes, the document head, and the cells of a Type D table outside its declared columns. A protected term always wins over a glossary entry, and a pair without a glossary runs exactly as before: the same model requests, events, pair record and published bytes, and no new log line. The need was measured first. Of the 405 hand corrections in our corrections file, 156 are a term rendered with the wrong word or left in English: 109 are an element's whole text and 47 sit inside sentences. The other 249 are text the source keeps English on purpose or a different defect, which a glossary must leave alone.
Enforced by the preparation step, which drops and counts an entry whose source is, or contains as a whole word, a configured or job protected term, and an entry with unsafe text; by the whole-element pass, which writes a target only outside the protected mask, the head and every Type D table, inside the same wrapper the job's protected terms get, so the glue repair, the glue gate and the wrapper and residue strips treat it exactly as they treat those terms; by the Type D direct map, which maps only cells the declared columns already collect; and by the model-call hook, which lists only the call's matched entries and appends nothing when none match. The check after the tail gate only reports: it never changes the bytes, never retries and never fails a pair. Pinned by unit tests for each rule and an end-to-end test with three controls: runs without a glossary must equal a baseline captured on the unchanged engine, in requests, events, pair records and output; a glossary that matches nothing must change none of them; and the applied-glossary assertion must fail when the glossary is removed from the message. The baseline is never regenerated.
The number is the one the worker's INVARIANTS.md gives this rule. That file numbers it 34 because 27, 28, 30, 31 and 33 already name other rules in the worker's repository, so this list goes from 30 to 34. The entries after it, 35 to 40, also carry the worker's numbers.
A translation can keep every element, heading, id and code element of its source while its text slides across element boundaries: a bold label holding the sentence after it, a heading holding the end of the paragraph above. Tag counts, the boundary signature, the heading sequence and the prose identity gate all pass that, because no tag moved. On November 12, 2026 the post-publish audit measured 114 such elements on 48 of 484 published pages, and one plain re-translation round left 79.
It is enforced by the element-shift gate (4.2), which runs on each part after every other gate has accepted it, with a copy of the element-shift rule in parity-audit, because the worker image cannot import the audit's toolchain. A part with a finding is translated again up to twice, the attempt with the fewest shifted elements is published, and a shift never fails a pair. A retry that is worse than attempt 1 on any critical tag, Mermaid diagram count or placeholder is never used. A test pins it: the build runs the engine's copy and the audit on the same real fixtures and fails if their findings differ, and an end-to-end test of the no-worse rule fails with that rule switched off.
Part reuse (17) puts a part's published translation back instead of translating the part again. That is safe only when nothing the part was made from has changed, and only when the bytes put back are bytes the gates approved. It applies to library pairs only (no quote, the website output bucket, the marker path), and matching runs only when the message's delta is JSON true.
It is enforced at three points. A part is matched by its keys: its English bytes and hints, its processed input and glossary context, the model, the source language and limits.part_reuse_epoch (17.1). Admission then checks each published part against its English before any model call: boundary signature, critical tags, headings, ids and residue. After the tail gate, the splice gate fails the pair rather than ship a page whose structure or counts differ from what the gates approved (17.4). A worker change that alters the published bytes for unchanged input must say whether it bumps the epoch. A test pins it: one changed byte of English changes exactly one key, and a mapping by part number, which the content keys replaced, would have reused a part whose English differs.
On the last part of the Kiro Expert Assessment guide the model dropped the token for the container's closing </div> sentinel in 9 languages. Recovery assumed the dropped tag sat immediately before the next surviving token, but the footer's opening tags sat between them, so the </div> landed inside the footer's first paragraph. The boundary-signature gate passed it, because the tag names were unchanged.
It is enforced at two points (4.2). In recovery, a TBI-BT sentinel whose source gap holds markup carries the gap's first tag as its bt_anchor, and a dropped sentinel is placed directly before that tag when the tag is unique there and the position passes the safe-position check (Invariant 24). In the part gate, when a part's signature equals its source's, the open elements at each unmatched closer are compared with the source's, and a difference is a finding that the part retry handles. Measured over 622 single-sentinel drops in the 44 guides, silent misplacements went from 27 to 2, with no finding on an identity translation of all 635 parts or on 6,985 parts of the published pages. A test pins it: the footer shape restores the </div> before the footer, and the same manifest without the anchor reproduces the old misplacement.
Since November 28, 2026 the gate also checks each unmatched opener. One of the two silent drops left was the opening tag that ends Stripe Implementation part 4, the second section start tag in that part. Put back in front of the first section's own closing tag, it was closed at once and left the first section open, while both signatures and both closer stacks stayed equal. The gate now compares each unmatched opener's position among the part's start tags of the same name with the source's, and a difference adds an openers misplaced clause to the same finding. On the same 622 drops that leaves one silent misplacement, the API Reference shape in 20.5, again with no finding on the identity translation or on the published parts. At the current English, after one chunk marker in each of those two guides was moved on November 22, none of 620 drops is silent. A test pins it: the Stripe shape gives one openers misplaced finding while its signatures and closer stacks are equal, and a part with a misplaced closer and a misplaced opener gives one finding that names the closers first.
Not covered by the deployed worker: an opener that moves past siblings of a different name inside the same parent, because it keeps its position among the start tags of its name (20.5), and part reuse admission, which compares the names of the unmatched closers and openers but not where they sit. A part published earlier with a misplaced closer or opener therefore stays reusable until its English or the reuse epoch changes.
On November 21, 2026 ECS stopped a busy worker during AZ rebalancing. Its message was delivered again, and the next worker translated two Portuguese pairs that had already succeeded in that job, so $0.0894 was spent twice. The in-flight lock covers a pair only while it runs.
It is enforced before a pair does any work, on every delivery of a message: one parameterized read asks Aurora whether the job's event log holds a lang_succeeded for this document and language. If it does, the pair is skipped at $0 and writes nothing, no event, no progress and no pair record, because Aurora already holds them (5.2). The check fails open: an unreadable answer translates the pair, because skipping a pair that never succeeded would lose a translation. Since November 28, 2026 force does not bypass it, because every server path that forces a run creates a new job id. It is scoped to the job, so a pair that succeeded in an earlier job runs again (20.5). A test pins it: the same message processed twice makes no Bedrock call the second time and adds no event, pair record, S3 write or progress write.
The same stop on November 21 showed the other half of the problem. The worker's stop handler only set a flag and waited for the whole job, which runs for hours, so ECS killed the task in the middle of a pair at its 120-second stop timeout, and that pair's spend was never recorded.
It is enforced by the shutdown path in 5.1. On SIGTERM or SIGINT the pair stops at its next part boundary, before a part or before a boundary-gate or shift-gate retry. It posts one lang_cancelled (reason worker_shutdown) carrying the token meter's spend and publishes nothing, the job is not finalized, and the message is kept, so SQS delivers it again and the redelivery skips the pairs that already succeeded (Invariant 38). A pair that has translated every part still publishes, because the before-publish check does not look at the stop flag. A 90-second deadline covers a part that runs longer: it posts the same single lang_cancelled from the live meter (worker_shutdown_deadline), releases the in-flight lock and exits, within a 110-second budget inside the 120-second stop timeout. The event type is lang_cancelled because the job's cost roll-up already sums it while the completion count leaves it out, so the job stays open until the redelivered pair ends. A test pins it: a stop during part 1 of 2 sends nothing of part 2, posts exactly one terminal event, publishes nothing and does not finalize the job.
On November 22, 2026 a full run of the suite on a machine with real AWS credentials made 6 paid InvokeModel calls, and on November 6 a test that missed a stub posted a fake pair record to production. The closed local port the runner gave the admin API protected only runs through the runner and did nothing for AWS.
It is enforced by translator/live_guard.py, installed by the first statement of the translator package. Under test it refuses every live AWS request (every boto3 client) and every request made through the requests library, so every admin API call, even with real credentials on the machine. It turns on for a test file run as python -m translator.test_* and whenever TBI_TEST_GUARD=1 is set, which run_tests.sh does for every file; Lambda and ECS match neither, so production runs unchanged. Every refusal is printed and counted, because production code catches the error and a missing fake would otherwise go unseen. Not covered: urllib, raw sockets, and scripts outside the test files, which are deliberately unguarded; the stage tool in 20.2a refuses to start without the guard. A test pins it: a raw AWS call and an admin request are both refused, and with the live switch on, the same request reaches the closed port instead.
The tooling that finally separated a genuine cause from a plausible-looking symptom didn't exist yet when the search for Invariant 17's fault began. Two build-and-deploy cycles were spent chasing a caption because there was no way to see, cheaply, what any single pipeline step had actually done to the document passing through it — Aurora records what was processed, not what happened at the moment it was processed. This is the instrument that fills that gap, and it exists because reasoning from a symptom cost two deploy cycles before it caught the actual defect.
It is deliberately not a new gate, not a new audit leg, and not anything that runs unless asked. Off means zero work, by design. Every entry point returns immediately when the switch is unset, so a normal translation carries no cost from this existing at all — the exact discipline behind not adding anything that recurs on a clock. Turning it on is a single environment variable, and it works identically whether the worker is running locally or inside the ECS container, so the same switch answers the same question wherever the failure actually lives.
| Flag | Effect |
|---|---|
TBI_TRACE_TAIL=1 | Enables tracing. The only switch normally needed. |
TBI_TRACE_DUMP=1 | Additionally writes the full before/after HTML of any step that introduces glue, plus the raw source, to disk. |
TBI_TRACE_DIR | Where trace files are written (default /tmp). |
What it reports, per pipeline step: a glue finding before and after the step, computed with the exact same rule and baseline the real gate uses, so a step that introduces glue is named outright instead of inferred from which step ran most recently. A length delta. And counts of the inline elements that carry this defect class most often — a recovery mechanism that re-injects content as an appended pile shows up here as a count that moves without the surrounding prose moving with it, which is precisely how Invariant 17's root cause was finally identified rather than merely located.
Per translated part, before any placeholder restore runs, it also records how many placeholder tokens of each opaque format were sent to the model against how many came back — the single measurement that distinguished a part the model damaged from a part the engine's own recovery later mishandled, which nothing else in the pipeline records at all.
It cannot break a translation, and that guarantee is structural rather than a promise. Every public function is wrapped so an exception raised inside tracing is caught and reported, never allowed to propagate — a diagnostic capable of failing a paid-for job would be worse than no diagnostic. This is an on-demand instrument, not a scheduled check: it earns its place by having already found a real defect two other approaches missed, and it costs nothing on every day it is not needed.
A second instrument runs one page offline up to any stage (2.1). tools/run_pair_to_stage.py takes the page, the language and --until with any stage but record, and writes what the pair holds after that stage: state.json (the pair's state, or its result when an earlier stage ended it), the source texts, parts/NN.html for each part, output.html once the translate stage has made one, and log.txt with everything the pipeline printed. Every external system is a fake: S3 and the admin API answer from a local harness and the model returns its input, so the tool makes no Bedrock call and no AWS request. It refuses to start unless TBI_TEST_GUARD=1 is set and the live guard (Invariant 40) is active. --list prints the stage names. Without --library the page is written to a local bucket, so it gets no part reuse plan and the splice adds no manifest; every production guide is a library pair, so pass --library to reproduce a reuse-admission or splice problem on a guide. The function underneath, handler.run_pair_until, refuses record, because that stage ends the pair.
env -u AWS_PROFILE AWS_ACCESS_KEY_ID=fake AWS_SECRET_ACCESS_KEY=fake \
AWS_DEFAULT_REGION=us-east-2 AWS_SHARED_CREDENTIALS_FILE=/dev/null \
AWS_CONFIG_FILE=/dev/null TBI_TEST_GUARD=1 LPO_BASE=http://127.0.0.1:9 \
PYTHONPATH=$PWD python3.11 tools/run_pair_to_stage.py \
--html PAGE.html --lang de --until tag_gate --out DIR
... tools/run_pair_to_stage.py --list (prints the stage names)
Diagram 20.1: Where Each Invariant Is Enforced
flowchart TD
P[Pre-build gate: regression suite + engine source audit] --> A
A[Authored document from S3] --> B["Source validation: repairs always, rejects internal jobs only"]
B --> C[Snapshot authored baseline]
C --> D[Enrich: wrap terms, protect code, absolutise paths]
D --> E[Split on chunk markers]
E --> F[Per chunk: extract elements to placeholders]
F --> G[Bedrock translation]
G --> H[Per chunk: restore placeholders]
H --> PG["Part gates and retries"]
PG --> I[Reassemble chunks]
I --> J[Full-document gates]
J --> K[Final transformations]
K --> L[Differential tail gate]
L --> S["Splice reused parts"]
S --> M[Write to S3]
M --> N[Out-of-band corpus audits]
I38["Inv 38: already succeeded in this job? (Aurora)"] --- A
I1[Inv 1 and 3: boundary whitespace] --- E
I4[Inv 4: safe marker position] --- E
I36P["Inv 36: part reuse plan"] --- E
I8[Inv 8: reserve literal indices] --- F
I9[Inv 9: SVG bytes before parsing] --- F
I7[Inv 7: degeneration guard] --- G
I16[Inv 16: truncation gate] --- G
I17[Inv 17: placeholder-format survival] --- G
I39["Inv 39: stop at part boundary"] --- G
I6[Inv 6: three-tier recovery] --- H
I11[Inv 11: one entry one copy] --- H
I14[Inv 14: fragment identity] --- H
I15[Inv 15: adjacent-splice glue guard] --- H
I37["Inv 37: E-1 anchor, E-2 placement"] --- PG
I35["Inv 35: element-shift gate"] --- PG
I2["Inv 2: term spacing, skipped for the 8 word_spaced=false languages"] --- J
X1["Customer job: definitive source equals target, pair skipped, lang_rejected target_is_source"] --- G
X2["Every job: fail-closed cancel check before publish"] --- M
I10[Inv 10: bounded scaffolding removal] --- K
I18[Inv 18: placeholder-residue strip-and-warn] --- L
I12[Inv 12: validate shipped bytes] --- L
I36S["Inv 36: splice gate"] --- S
I5[Inv 5: measure the corpus] --- N
I13[Inv 13: no regex in engine source] --- P
I40["Inv 40: live guard under test"] --- P
style P fill:#064e3b,stroke:#10b981,color:#e0e0e0
style A fill:#1e3a5f,stroke:#60a5fa,color:#e0e0e0
style G fill:#7c2d12,stroke:#f97316,color:#e0e0e0
style PG fill:#3f3f46,stroke:#a1a1aa,color:#e0e0e0
style J fill:#3f3f46,stroke:#a1a1aa,color:#e0e0e0
style K fill:#3f3f46,stroke:#a1a1aa,color:#e0e0e0
style L fill:#064e3b,stroke:#10b981,color:#e0e0e0
style S fill:#064e3b,stroke:#10b981,color:#e0e0e0
style M fill:#1e3a5f,stroke:#60a5fa,color:#e0e0e0
style N fill:#064e3b,stroke:#10b981,color:#e0e0e0
style X1 fill:#92400e,stroke:#fbbf24,color:#e0e0e0
style X2 fill:#7f1d1d,stroke:#f87171,color:#e0e0e0
The diagram makes one thing plain that a list cannot: the invariants cluster where the artifact changes hands. Extraction, generation, restoration and the final transformation sequence are where content is created, replaced or removed, and that is where every enforcement point sits. The out-of-band audits at the end exist because a pipeline cannot certify its own output — only the published bytes can do that. Generation gained two more clusters since this diagram was first drawn: a truncation gate that reads the model's own stop signal, and a format-survival gate watching a class of placeholder the rest of the pipeline treats as opaque. Restoration gained two of its own: a check that a translated fragment landed in the slot it was translated for, and a guard at every splice point ensuring two individually correct restorations don't touch with no separator between them.
Content defects sort into four classes, and the distinction is operational rather than academic: each needs a different detector and a different response. A document can be structurally valid, correctly scripted, free of glued terms, and still be wrong in a way that only one of these four finds.
| Class | What it looks like | Detected by | Correct response |
|---|---|---|---|
| Degeneration | A solid run of one repeated character filling the output budget | Run length on the published bytes, never script identity | Re-translate the document after isolating the dense region behind its own marker |
| Wrong-language prose | A document under one language path whose prose is materially another language | Absolute character counts per script on the published bytes | Re-translate that pair |
| Absence | Structurally valid, coherent, correctly scripted — and an older revision of itself with whole sections missing | Size normalised against each language's own median expansion | Depends on cause — see below |
| Identifier corruption | Structurally valid, correctly scripted, free of glued terms — and naming a resource that does not exist, because the model translated part of an identifier or split one into two words | Comparing a term's full run against the runs the English source authored, in rendered text. A split is invisible to a presence check, which a substring satisfies, and to a spacing check, which only fires on a run longer than the term | Protect the whole identifier as a term so it cannot be divided again, then re-translate. Never "repair" it with a space — see Invariant 30 |
The absence class carries the subtlest trap in the whole detection story. Size must be normalised against each language's own typical expansion, never against English. A language that normally expands to roughly 140 percent of the English source and measures 100 percent is missing content — while looking perfectly healthy to a check that compares against English alone. Comparing against English produced a false all-clear on the first measurement.
And absence has two causes that need opposite responses. A stale revision is fixed by re-translating that document. A term that failed to preserve at otherwise-normal document size is not fixed by re-translation — it recurs, and multi-word terms dominate that bucket. Treating the second as the first burns tokens and changes nothing.
A generation-time guard and an audit are not substitutes for each other. The degeneration guard stops a collapsed chunk from ever publishing. The corpus audit reads what did publish. The guard covers everything translated from now on, the audit covers everything already live, and a job's reported status is not the same claim as the document being correct. Both are required, and neither replaces the other.
The worker deployed on November 28, 2026 carries 103 test files, and the runner, run_tests.sh, adds two gates of its own: the regex audit (Invariant 13) and the collection audit. That makes 105 checks, and all 105 pass. The build refuses to produce an image if any of them fails. That refusal is the point: before it existed, running the suite before a deploy was a discipline someone had to remember rather than a property the tooling enforced. New invariants arrive with their own tests, never as an addition to an existing one, and the suite's growth is the visible record of that discipline holding.
Under test nothing can reach production (Invariant 40): the runner sets TBI_TEST_GUARD=1 for every file, and the live guard then refuses every live AWS request and every admin API request, even with real credentials on the machine. A test file that cannot reach the tests it defines fails the suite (the worker's own Invariant 22, a different rule from this guide's 22). The collection-audit gate fails a file with module-level test functions and no runner block, or with a test function defined after that block, and a runtime check fails a file that exits cleanly having printed nothing.
The runner discovers test files by glob rather than from a list. That is the same "derive it, do not hardcode it" discipline applied elsewhere in this fleet's tooling, and it exists because a hand-maintained list of checks has gone stale here more than once. Adding a test file requires no edit to the runner.
Two properties of these tests are worth stating, because they are what makes the suite trustworthy rather than merely present.
Every fix carries a negative control for the case a naive version would get wrong. Not a test proving the original bug is caught — a test proving the plausible wrong fix is rejected. Several of these were written before the corresponding fix and caught a genuine flaw in the first attempt: the scaffolding removal's count-limited draft preserved the right number of attributes on the wrong elements, and only a control written in advance surfaced it.
Several tests assert that a check can fail. They reproduce the pre-fix behaviour and assert it produces the wrong answer. Without that, a green run cannot distinguish "the fix works" from "these assertions are incapable of failing" — and this codebase has a documented history of checks that returned a clean, confident, wrong answer.
A verification predicate needs verifying too. Four separate measurement errors during this work were caught only by running a control rather than by reasoning: a substring check that matched its own explanatory comment, a fingerprint that occurred three times in the control output and was therefore never evidence of anything, a guard that passed against an empty manifest and proved nothing, and a count asserted from memory that was wrong in both directions. In each case the tool answered confidently. The control is what made the answer trustworthy.
Stating what these guarantees do not cover is part of the guarantee. An overstated boundary is how a clean audit becomes a false all-clear.
<section id="webhook-processing"> came back empty, has been caught since November 28, 2026. The other, API Reference part 48, whose </section> moved past a comment, is still silent. On November 22 one chunk marker in each of those two guides was moved to its section boundary, and the drop test then reported no silent misplacement, but the engine itself still does not detect the API Reference shape.</head>, even inside a script string, carries no parts manifest, so every run of it translates in full (17.2). The fix belongs in the English: write that string's closing tag as <\/head>, which JavaScript reads as the same string.lang_cancelled and on the rerun's own terminal event. With part reuse on, a library pair still reuses the parts that match its published page (17).What this section is really documenting. Every invariant here was found by measuring the published artifact rather than by reading the code — and in several cases the code reading produced a confident wrong answer that the measurement then corrected. Two of them were traced to functions that do not execute at all. The habit that found them is cheap and worth more than any single guard on this list: read the published bytes first, and check whether the code you are reasoning about actually runs.
| Item | Value |
|---|---|
| Model | qwen.qwen3-235b-a22b-2507-v1:0 (Qwen3-235B — all languages) |
| Failover Regions | us-east-2 → us-east-1 → us-west-2 |
| Target Languages | 11 internal: es, pt, fr, de, ru, hi, ja, zh, ar, ur, it · 127-language catalog for customers |
| Worker Runtime | Python 3.11 (ECS Fargate persistent service, auto-scaling 1→12) |
| Finalization | POST /admin/translate/complete/{job_id} (Go, in-process on LPO server) |
| Template Variable Delimiter | [brackets] — never {braces} (models corrupt braces) |
| Worker Resources | 2 vCPU / 6 GB per container (Fargate — no timeout ceiling) |
| Worker Timeout | None (runs to completion) |
| Max Docs per Request | 42 |
| Max Active Jobs | No cap; a warning is recorded at 12 or more active jobs |
| Daily Token Cap | 50M combined tokens (reset nightly at 1:00 AM Eastern) |
| Chunk Size (Latin scripts) | 6000 chars |
| Chunk Size (CJK + Russian) | 4500 chars (ja, zh, ru) |
| Chunk Size (Indic + Arabic) | 3000 chars (hi, ur, ar) |
| Retries per Chunk | 5 |
| Shift Gate Retries | 2 |
| Boundary Gate Attempts | 3 |
| Part Reuse Epoch | 1 |
| Max Part Size | Markers decide library parts: 18 KB, 12 KB when dense (13.4) · 24 KB safety valve for documents without markers only (14.4) |
| MaxConcurrency (per-language) | Unlimited — LPO sends one SQS message per language, auto-scales workers to match |
| ECR Repository | tbi-translate-worker |
| SQS Queue | trinity-beast-translation-queue |
| IAM Role (Worker) | tbi-translate-role |
| Auto-Scaling | Demand-driven: 1 (idle) → N (job submitted, N = language count) → 1 (queue empty) |
| ECS Service | tbi-translate-worker-service (persistent, always-on) |
| Finalization | POST /admin/translate/complete/{job_id} (LPO server endpoint) |
| Valkey Keys | tx:job:{id}, tx:active, tx:history, tx:idempotency:{key}, tx:inflight:{job}:{doc}:{lang} (TTL 1800 s), tx:chunks:{doc}, autoops:bedrock:spend:daily, autoops:bedrock:tokens:input:daily, autoops:bedrock:tokens:output:daily |
| Aurora Tables | translation_jobs, translation_job_events, translation_pair_runs, translation_glossary_entries |
| Part Reuse | Library pairs reuse unchanged parts by default through translate-pending, translate-task and translate-doc --remote; --full translates every part. Record: <!-- TBI-PARTS v1 … --> in each translated page (17) |