Long-Horizon AI Agent Test: Building a Video SaaS in Three Hours

    This article reports a hands-on test of long-horizon AI coding agents that built a commercial short-video SaaS platform in about three hours. It explains why agentic capability, long-horizon task execution, and system engineering matter more than UI polish, and how spec-driven development (SDD) keeps the model from drifting across a large context. The core system covers a six-layer architecture, a four-table relational data model with row-level security, idempotent task submission, an append-only credit ledger, an asynchronous video task state machine with retry and cost control, and a practical acceptance checklist. Readers will find SQL and pseudocode examples, common failure modes, and lessons on where long tasks actually break.

    1. Background: Why Long-Horizon Capability Matters More Than a Nice-Looking Page

    Recent discussion of next-generation AI coding has shifted away from “can it generate a good-looking page” toward three more engineering-oriented dimensions: agentic capability, long-horizon tasks, and system engineering. None of these terms is abstract. Agentic capability means the model can autonomously call tools, read and write files, run commands, and evaluate results. Long-horizon means the model can hold its goal steady across a context span of tens of thousands of tokens. System engineering means the model understands “non-code” constraints such as databases, queues, authentication, and billing.

    The hard part of building a real commercial system has never been the amount of code in a single file. It is the coupling of constraints: the database schema determines the permission model, the permission model determines API design, and API design in turn affects the granularity of the task queue. Human teams keep these constraints in sync through documentation and review. A long-horizon agent has to anchor itself with explicit specification files. That is exactly why this test chose spec-driven development (SDD).

    The target was a short-video product-marketing asset generation platform: a user uploads a product image and selling-point text, and the system automatically generates a vertical short video, renders it asynchronously, lets the user poll for the result, and charges credits. This subject was chosen because it compresses “AI capability” and a “commercial loop” into one verifiable system. Cross-border e-commerce sellers do not care how the workflow is orchestrated; they care about cost per video, daily output capacity, and the number of steps required. For technology choices, this article uses only generic category descriptions: a relational database, object storage, a message queue, a container platform, logging, and monitoring and alerting. No specific vendor product is bound.

    2. Method First: Using Spec Files to Fight Context Drift

    The typical failure mode of a long task is not “one wrong line” but “chapter three forgot the agreement made in chapter two.” So the first job of the prompt is to produce a specification, not code. I split the prompt into a three-stage process constraint:

    1. Stage 1 Research: List the target system's roles, core use cases, and non-functional
    2. metrics (concurrency, latency, cost). Output open questions. Do not write implementation code.
    3. Stage 2 Architecture: Output module breakdown, draft data model DDL, state machine, API list,
    4. and failure mode table. Wait for confirmation before entering the next stage.
    5. Stage 3 Development: Commit in small steps in the order data layer -> auth -> task orchestration
    6. -> billing -> frontend. After each step, run build and tests; if they fail, fix first and continue.
    7. Global constraints: Do not introduce unspecified external dependencies; all time-consuming
    8. operations must be asynchronous; all write APIs must be idempotent.

    Three design choices in this structure are key. First, a “human confirmation gate” is set between stages to stop the model from inventing requirements when information is insufficient. Second, non-functional metrics are moved to the front, because daily output capacity and cost per video directly determine queue and concurrency strategy. Third, requiring verification at every step turns a long task into a chain of short tasks, which reduces context pressure.

    3. Architecture Breakdown: A Six-Layer Skeleton for a Commercial System

    In the architecture stage, I asked for a “constraint table” rather than “technology preference.” The resulting skeleton can be summarized in six layers.

    The access layer handles authentication and rate limiting. It uses phone-number verification-code login to exchange for a short-lived access token; the token carries a user identifier and expiration time, and the gateway applies rate limits to prevent the verification-code endpoint from being abused. The data layer uses a relational database as the single source of truth, with four core entities: users, assets, video tasks, and credit ledger entries. The task orchestration layer separates time-consuming operations such as rendering from the request path. The storage layer uses object storage for images and finished videos, while the database stores only reference keys and metadata. The billing layer uses credits as a common unit of measure, pulling “cost” out of the code and turning it into a configurable parameter. The observability layer covers task backlog, failure rate, and per-video duration with logs, metrics, and alerts.

    The most important point here: a time-consuming operation must never complete synchronously inside an HTTP request. A common anti-pattern is to call the generation capability directly inside the API and wait for the return, which leads to gateway timeouts, duplicate user submissions, and doubled cost.

    4. Data Model and Row-Level Security

    The data layer is the foundation of the whole system. The four core tables have the following responsibilities:

    1. users(id, phone, created_at)
    2. assets(id, user_id, storage_key, kind, created_at)
    3. video_tasks(id, user_id, asset_id, status, cost_credits,
    4. error_code, idempotency_key, created_at, updated_at)
    5. credit_ledger(id, user_id, delta, reason, task_id, created_at)

    Three design points. First, video_tasks.idempotency_key has a unique index, and together with ON CONFLICT DO NOTHING it makes submission idempotent, so repeated user clicks do not create a second task. Second, credit_ledger is append-only; the credit balance is derived by summing the ledger, which avoids lost updates from concurrent updates to the same row. Charging and task creation are placed in the same transaction to guarantee “either both succeed or both roll back.” Third, row-level security (RLS) uses user_id as the policy key, so unauthorized queries are blocked at the database layer instead of relying on hand-written filters in every API:

    1. ALTER TABLE video_tasks ENABLE ROW LEVEL SECURITY;
    2. CREATE POLICY own_tasks ON video_tasks
    3. USING (user_id = current_setting('app.user_id')::uuid);

    Note that RLS introduces a connection-reuse problem: session variables in the connection pool must be reset at the start of every request, otherwise a serious privilege issue occurs where “user A reads user B’s data.” This was explicitly listed as a must-check item in the prompt.

    5. Asynchronous Tasks: State Machine, Retry, and Cost Control

    Keep the video task state machine minimal: queued -> running -> succeeded | failed. A failure can fall back to queued, but it must carry a retry count. There are two common scheduling implementations: one relies on the message queue’s delay and redelivery capabilities; the other uses a database table plus scheduled scanning for lightweight polling. The former has better throughput; the latter is easier to debug early on. In practice, use the latter to validate the loop first and then switch.

    Four failure modes must be built in and written into the table during the architecture stage: upstream generation service rate limiting, non-compliant asset format, render timeout, and insufficient credits. Each failure maps to a clear error code and user-visible message to avoid “unknown error” on the frontend. The retry strategy uses exponential backoff with an upper limit; beyond the limit, the task moves to a manual-intervention queue to prevent infinite retries from burning cost.

    The core of cost control is to make unit price configurable and to pre-deduct before submitting a task and settle or roll back at the task’s terminal state:

    1. # Pseudocode: pre-deduct + settle
    2. with tx():
    3. task = insert_task(idempotency_key=key) # idempotent
    4. if not task: return ALREADY_EXISTS
    5. if not deduct_credits(user, cost, task.id): # charge in the same transaction
    6. task.status = 'failed'; return NO_CREDIT
    7. # terminal callback
    8. settle(task.id, ok=result.success) # confirm on success, refund credits on failure

    6. Post-Mortem: Where Long Tasks Actually Break

    In the test, problems concentrated in four areas. First, convention drift under long context: in the later development phase, the model began inventing field names. The fix was to solidify the DDL and API list into files and require reading them first in every step’s prompt. Second, missing verification led to “looks like it runs,” so build and tests were made mandatory at every step. Third, concurrency and transaction boundaries were blurred: charging and task creation were split into two writes, causing lost credits. Fourth, observability was missing: failed tasks had no error code, and troubleshooting meant digging through logs. In addition, tight compute capacity during peak hours significantly lengthened the overall duration, so cutting a large task into small steps that can resume from a breakpoint is a practical strategy against uncertainty.

    7. Acceptance Checklist: The Minimum Bar from Demo to Commercial

    Before delivery, check each item: does a repeated submission produce only one task; is unauthorized access blocked by the database; are credits rolled back on failure; is there an alert for task backlog; are cost per video and daily output capacity given as explicit numbers; are all time-consuming paths asynchronous; does the frontend have a clear interaction after the token expires. Only when these seven items pass is the system ready for external trial.

    8. Conclusion

    This test shows that progress in AI coding is not only better code generation quality, but better ability to “keep the specification consistent” during long-horizon tasks. The real leverage is to write requirements as verifiable specs, write system constraints as explicit tables, and turn every step into a small, rollback-able delivery. With this method, a small team can build a system skeleton in hours that used to require multiple people collaborating. This is also the value of cloud services such as Baidu AI Cloud continuing to invest in common capabilities like container platforms, message queues, object storage, and monitoring and alerting: it lets developers focus on specs and the business loop instead of repeatedly building infrastructure.