Rewriting a Classic Typesetting Engine in Ten Minutes: Engineering Lessons

    A ten-minute rewrite cannot reproduce a mature typesetting system, but it can produce a useful formula-rendering prototype when the requirements are tightly scoped. This article examines how to define a supported subset, structure a minimal typesetting kernel, use testing to validate AI-generated code, and add quality gates for safe deployment. The focus is not on replacing a complete engine, but on building a verifiable, cacheable, and observable pipeline for converting mathematical formulas into images.

    When research papers, technical blogs, slide decks, and instant messages need to display complex formulas, support for mathematical typesetting varies widely across publishing channels. Pre-rendering formulas as standalone images is a low-cost, compatible engineering compromise.

    That is why the claim that an AI agent can “rewrite a classic typesetting engine from scratch in ten minutes” is so appealing. It looks like both a live-coding stunt and a stress test for modern systems programming languages and large language models. To evaluate the claim properly, however, we must distinguish between two very different goals:

    1. Reimplementing a complete, mature typesetting system.
    2. Building a minimal, usable typesetting kernel under a tightly constrained specification.

    The first is almost impossible within such a time limit. The second has a clear engineering path. This article examines that path through five areas: requirements reduction, kernel architecture, test-driven development, quality gates, and deployment validation.

    1. Define the Problem First: What Can Be Rewritten in Ten Minutes?

    A classic typesetting system is not merely a markup language. It may include conditionals, loops, recursion, macro expansion, and grouping scopes, making it effectively Turing-complete. Mature engines also embody decades of work in font metrics, line and page breaking, mathematical layout, compatibility rules, and ecosystem support.

    Therefore, a “ten-minute rewrite” cannot be an equivalent replacement for the complete system. It should instead be understood as building a runnable prototype for a limited input subset.

    The original use case is specific: a paper contains several important formulas, and those formulas must be extracted from the source document and converted into images that can be used in blogs, presentations, and messaging channels. The requirements can be reduced to four constraints:

    • Process only a subset of mathematical formulas.
    • Support common structures such as fractions, radicals, superscripts, subscripts, Greek letters, delimiters, and simple matrices.
    • Output bitmap images only.
    • Make no compatibility guarantees for extreme macros or complex typesetting.

    With these constraints, the problem changes from “rewrite a complete typesetting language” to “implement a formula-rendering pipeline.”

    This distinction matters. The value of a rapid demonstration is not proving that a mature system can be easily replaced. It is testing an engineering hypothesis: when the requirements are clearly bounded, can an AI agent quickly generate the parsing, layout, rendering, and validation code while exposing hidden semantic risks?

    Ten minutes may be enough to create a prototype skeleton. Production readiness still depends on test coverage, differential validation, and careful handling of edge cases.

    2. The Four-Layer Structure of a Minimal Typesetting Kernel

    A minimal formula-to-image kernel can be divided into four layers: parsing, semantics, layout, and output. Each layer should do only what is necessary and isolate risk through clear interfaces.

    1. Input: formula fragment from a source document + style parameters
    2. Output: bitmap image + warning list
    3. 1. Parsing layer
    4. Lexing: identify control sequences, arguments, groups, and subscript/superscript markers
    5. Syntax analysis: build an expression tree
    6. Macro expansion: support allowlisted macros with recursion-depth and expansion-count limits
    7. 2. Semantic layer
    8. Normalize mathematical atoms: letters, numbers, operators, and delimiters
    9. Normalize structures: fractions, radicals, scripts, and matrices
    10. Font metrics: read character width, height, depth, and italic correction
    11. 3. Layout layer
    12. Build horizontal and vertical boxes
    13. Calculate flexible and minimum spacing
    14. Line breaking: use dynamic programming to minimize badness
    15. Pagination or canvas cropping: apply penalties and widow/orphan controls
    16. 4. Output layer
    17. Generate vector drawing instructions or rasterize directly
    18. Cache results by content hash
    19. Return failed samples and warnings

    The key concern in the parsing layer is not simply whether input can be parsed, but whether failures can be diagnosed. Macro expansion must be bounded by an allowlist, recursion-depth limit, expansion-count limit, and timeout mechanism. Without these controls, a recursive macro could cause a rendering task to run indefinitely.

    The semantic layer should normalize mathematical structures into a finite set of node types. This prevents the layout engine from being overwhelmed by unlimited syntactic variations. The layout layer is where much of the visual quality is determined. Box models, flexible spacing, script placement, fraction-rule thickness, and radical overbar coverage all affect the final appearance.

    The output layer also requires careful cache-key design. At a minimum, the key should include:

    • Formula source
    • Style parameters
    • Font version
    • Renderer version

    Otherwise, changes to fonts or rendering logic may produce stale or contaminated cache results.

    3. Turn Generation Speed into Verifiable Speed with Testing

    AI agents are good at producing code skeletons quickly, but the difficult parts of a typesetting system are semantic details. To turn fast code generation into reliable development speed, testing must come first.

    A practical approach is to build three layers of tests.

    Golden Sample Tests

    Create a set of formulas containing nested fractions, combined superscripts and subscripts, Greek letters, radicals, delimiters, and simple matrices. Confirm the expected output manually.

    After each change, compare:

    • The expression tree
    • Layout-box dimensions
    • The final image’s pixel differences

    Differential Tests

    Render the same formulas through the new kernel and a reference renderer. Compare important measurements, including:

    • Baseline position
    • Character spacing
    • Fraction height
    • Radical width
    • Canvas boundaries

    Fuzz Tests

    Generate random syntax trees and inject deep nesting, repeated scripts, empty groups, and extremely long control sequences. The goal is to verify that the parser:

    • Does not crash
    • Does not expand macros indefinitely
    • Returns clear errors within resource limits

    A quality gate can be expressed with the following pseudocode:

    1. For each formula sample:
    2. Parse and record the expression tree
    3. Lay out and record box-model measurements
    4. Render and record the image hash
    5. If the expression tree differs from the golden sample:
    6. Flag a semantic risk
    7. If key measurements exceed tolerance:
    8. Flag a layout risk
    9. If pixel differences exceed the threshold:
    10. Add the sample to the manual-review queue
    11. If execution exceeds time or memory limits:
    12. Flag a safety risk
    13. Summarize pass rate, failure categories, and the slowest samples

    This workflow turns a “ten-minute generation” exercise into a regression-tested engineering asset. An AI agent can generate the parser, layout engine, and test scripts in parallel, but human review remains important for macro expansion rules, font metrics, and line-breaking cost functions. These areas are especially prone to defects that appear functional in a demo but fail in real use.

    4. From Demonstration to Engineering: Quality Gates and Deployment Validation

    A demonstration only needs to render one formula. An engineering system must render a collection of formulas consistently.

    During deployment validation, rendering tasks can run inside isolated containers with CPU, memory, and execution-time limits. This prevents malicious or abnormal input from exhausting service resources. Results can be cached in object storage by content hash, while failed samples are written to logs and sent to an alert queue.

    For a general cloud deployment, teams may combine container platforms, object storage, and logging services provided by platforms such as Baidu AI Cloud. These are general engineering capabilities for isolating rendering jobs, caching results, and tracking failures; the approach does not depend on a particular API or customized service.

    Font licensing and font-version consistency also require attention. Formula images depend on font metrics. If the font version changes, the cache key must change as well. Otherwise, the same formula may produce different results while appearing to have the same cache identity.

    For multi-channel publishing, standardize canvas margins, background transparency, and scaling factors. This helps prevent inconsistent clarity after different platforms compress or resize the images.

    From a performance perspective, distinguish between cold starts and cache hits. Important metrics include:

    • The slowest formulas
    • Peak memory usage
    • Timeout rate

    Average latency alone is not enough to characterize the system.

    5. Risk Boundaries and Conclusion

    The greatest risk of a rapid rewrite is confusing a subset prototype with a complete replacement. The macro ecosystem, compatibility behavior, and mathematical layout details of a mature typesetting system cannot be fully reproduced in ten minutes.

    A practical approach is to state the support boundaries explicitly:

    • Support only allowlisted formula structures.
    • Do not promise compatibility with complex macro packages.
    • Return clear warnings for unsupported input.
    • Maintain golden-sample regression tests for important formulas.
    • Apply resource limits and timeouts to the rendering service.

    This makes it possible to obtain a useful tool quickly while keeping risk within an acceptable range.

    “Rewriting a classic typesetting engine in ten minutes” is best understood as an engineering experiment. It demonstrates that, with requirement reduction, test-driven development, and parallel implementation support, an AI agent can quickly assemble a minimal typesetting kernel. It also highlights that the real challenge is not code generation itself, but defining boundaries, validating semantics, and controlling operational risk.

    For teams that need to generate formula images at scale, the sensible goal is not a complete rewrite. It is a verifiable, cacheable, and observable formula-rendering pipeline. A rapid prototype can serve a clearly defined use case first, with support expanded gradually as testing and validation improve.