Long-Horizon AI Agent Test: Building a Video SaaS in Three Hours
This article reports a hands-on test of a long-horizon coding agent tasked with building a UGC video generation SaaS for cross-border e-commerce from scratch. It explains why this full-stack problem was chosen, how spec-driven development was used to reduce drift across a three-hour run, and the six architecture questions the platform had to answer: row-level security, asynchronous task state machines, idempotency and retry backoff, credit freeze-and-settle billing, token authentication, and observability. It also shares the real issues encountered and practical guidance on where long-running agents fit in a development workflow.
1. Why a Video Generation SaaS Was Chosen as the Test Case
The focus of AI coding tools is shifting. “Can it write code?” used to be measured by whether a model could produce a decent-looking page. Today, three capabilities matter more: agentic behavior, long-horizon task execution, and system engineering. The first two determine whether a model can work for hours without human intervention; the third determines whether it delivers a runnable, extensible, maintainable system rather than a pile of disconnected code snippets.
The task I set was to build, from zero, a user-generated content (UGC) video generation platform for cross-border e-commerce sellers. The problem is naturally complex because it is not a single-page app but a typical full-stack, long-horizon job:
- The frontend needs a mainstream server-rendering framework to handle routing, authentication state, uploads, and polling-based status display.
- The backend needs a high-concurrency API service that handles file validation, task orchestration, and status queries.
- The data layer needs multiple tables for users, assets, tasks, credits, and transactions, with row-level security configured.
- The asynchronous pipeline must address the timeouts and blocking caused by video generation taking several minutes.
- Billing and permissions must cover the full loop: verification-code login, token issuance, credit deduction, and refunds on failure.
The practical motivation was equally direct. Cross-border e-commerce sellers generally do not care how a workflow is assembled; they care about return on investment — the cost per video, how many videos can be produced per day, and whether manual intervention is required. The product goal was therefore defined as “package a complex process into a single click,” which is a direct test of system architecture capability.
2. Methodology: Constraining a Long-Horizon Agent with Spec-Driven Development
The most common reason long-horizon tasks fail is not that the model cannot write code. It is that by minute 40 it has forgotten the interface contract defined at minute 5. To reduce this drift, I used spec-driven development and organized the prompt into three constrained stages:
Stage 1 Research: output target users, core scenarios, feature list, non-functional requirements, and risk list; no codeStage 2 Architecture: output module breakdown, data model, API contracts, state machine, and deployment topology; wait for confirmationStage 3 Development: implement module by module, self-check after each module, and output a change summary
Three points make this constraint effective. First, it enforces serialization so the model does not “write first and think later” with insufficient information. Second, it requires verifiable intermediate artifacts, such as API contracts and a state machine, giving subsequent code a single source of truth. Third, it requires stage-level self-checks, splitting the long task into several verifiable short loops to counter context decay.
3. Architecture Breakdown: Six Questions a Commercial Platform Must Answer
3.1 Data Model and Row-Level Security
In a multi-tenant system, the core risk is unauthorized access. Use the user identifier as the isolation key and enable row-level security in the database so isolation does not depend on the application layer behaving well:
ALTER TABLE video_task ENABLE ROW LEVEL SECURITY;CREATE POLICY task_owner_only ON video_taskUSING (owner_id = current_setting('app.user_id')::uuid);
Assets and tasks are best kept in separate tables. The asset table stores the object storage key, checksum, and status; the task table stores the input snapshot, parameters, status, and error codes. Every monetary and credit change must be written to a transaction table so it is traceable and reconcilable.
3.2 Asynchronous Tasks and State Machine
Video generation is a long-running operation and must never be awaited synchronously. The common pattern: the API only enqueues the job and returns a task identifier; a background consumer picks up the task, calls the generation capability, and writes back the result. The state machine should be kept to six states, with any illegal transition rejected outright:
queued -> running -> succeeded-> failed -> retrying -> running-> canceled
The polling endpoint should return progress, current stage, and estimated time remaining so the frontend can render a progress bar and users do not resubmit.
3.3 Idempotency, Retries, and Backoff
Network jitter and compute queuing are the norm. The submit endpoint should use “user + asset fingerprint + parameter hash” as the idempotency key so duplicate requests return the same task. On the consumer side, failures use exponential backoff retries; once a threshold is exceeded, the task moves to a manual-intervention queue and triggers an alert.
3.4 Credit Deduction and Refunds
Billing must follow a three-phase model — freeze first, settle later, refund on failure — so users are not charged unfairly and the platform does not miss revenue:
def on_task_created(user_id, cost):freeze_credits(user_id, cost) # freezedef on_task_succeeded(task_id):settle_credits(task_id) # settledef on_task_failed(task_id):unfreeze_credits(task_id) # refund
3.5 Authentication and Tokens
Use the common pattern of exchanging a verification code for a short-lived token plus a refresh token for renewal. The token carries only the minimum necessary claims, and permission checks are performed on the server.
3.6 Observability
Logs, metrics, and traces are all required. Build dashboards for task queue time, per-task duration, failure rate, and frozen credit balance, and configure threshold-based alerts.
4. Test Results: Capability Leaps and Real Pitfalls
With normal compute availability, the end-to-end run took about three hours. The architecture and data model stage was the fastest; the asynchronous pipeline and the billing loop took the longest. One clear pattern emerged: once intermediate artifacts were explicitly fixed, the model’s interface deviation in later modules dropped significantly.
The pitfalls clustered in three places. First, the state machine was not constrained early, which produced a logic hole where a failed task was still settled. Second, polling frequency was too high and put pressure on the API; switching to backoff polling with jitter resolved it. Third, object storage uploads lacked frontend direct-upload validation, which produced empty-file tasks; adding checksum and type-allowlist validation fixed it. All three were system-level problems rather than syntax problems, which supports the point that the value of long-horizon tasks lies in engineering completeness.
5. Capability Boundaries and Practical Recommendations
A long-horizon agent is not a replacement for an architect. It is more like a tireless executor: well suited to scaffolding, boilerplate code, filling in tests, and generating documentation; not suited to making autonomous decisions when requirements are vague or compliance constraints are unclear. In practice: write the spec clearly, define acceptance criteria up front, split long tasks into verifiable small loops, and always keep a human review checkpoint. If the runtime is carried by general-purpose capabilities such as object storage, message queues, container platforms, and monitoring and alerting from Baidu AI Cloud, the team can focus more on business modeling and experience design.
