Trillion-Dollar Compute Bills Are Reshaping AI's Second Half: Code Storage, Version Control Backends, and Cost Accounting
A ~$895.4 billion infrastructure commitment disclosed in a revised IPO filing and an engineering talk about a distributed version control backend point to the same question: how do AI companies turn enormous compute spend into revenue that can be priced and renewed? This article dissects the commitment structure, explains take-or-pay contracts as an intertemporal compute trade with embedded optionality, and models how growing agent call volume erodes gross margin even when the customer keeps renewing. It then translates the question into concrete engineering: a five-layer capability model for agentic coding workloads, content-addressed deduplication, metadata/object separation, conservative asynchronous garbage collection, server-side materialized directory and diff views, weighted quota design, per-session cost attribution, agent sandboxing, and a three-phase rollout. You get working Python, HTTP, and YAML examples you can adapt, plus the metrics that tell you whether an optimization is real.
Introduction: Two Signals That Look Unrelated
In the first week of November, two seemingly unrelated messages landed in the industry.
One came from the capital markets. In a revised version of its IPO filing, a leading model vendor disclosed that as of the end of September it had signed purchase, lease, and not-yet-started infrastructure arrangements totaling roughly $895.4 billion, the overwhelming majority pointing at compute clusters and data centers. It landed as global tech stocks sold off sharply, and the size of the commitment turned it into a catalyst for the market to re-price the pace of AI investment.
The other came from the engineering front line. In a technical talk, the same vendor described a self-built distributed version control backend that processes about 1 PB of data per day, and said it had cut the median time for internal code pushes by roughly 80%. Around the same time, it announced plans to acquire a tooling team focused on code storage and code review front-end components. That team’s storage system had supported a coding platform creating more than 8 million repositories per week, peaking at roughly 250 per second.
Both signals point to one question. With upstream supply locked in further ahead than ever before and capital-return scrutiny approaching, what capability lets an AI company convert eye-watering infrastructure spend into sustainable, priceable product revenue? The first part of this article breaks down the compute commitment from a financial and economic angle. The second translates the question from a developer’s perspective into concrete designs for code storage, version control backends, and cost accounting.
1. Dissecting the Compute Commitment: Reading the ~$895 Billion
1.1 Four Numbers and the Shape of the Commitment
What matters most in the disclosure is not one headline total but the structural relationship between several measures:
- Total commitments of about $895.4 billion, covering purchases, leases, and arrangements not yet formally started;
- About $447.5 billion of that is expected to materialize gradually by the end of 2030;
- Roughly $69.8 billion is rigid spending falling due within the next 12 months;
- About $213.8 billion of the contracts carry exercisable termination rights.
Reconstructing the timeline from the source:
- The IPO filing revision is dated November 2, and commitments are counted as of September 30, so “the next 12 months” maps roughly to October 2025 through September 2026.
- The source marks its “AI weekly” as week 45 of 2026, and both point to the same window. The analysis below takes that as its premise.
| Measure | Amount (US$ bn) | Share of total | What it means |
|---|---|---|---|
| Total commitments | ~895.4 | 100% | Purchases + leases + arrangements not yet started |
| Gradually materializing by end of 2030 | ~447.5 | ~50.0% | The remainder implies nearly half of commitments run past 2030 |
| Rigid spending due within 12 months | ~69.8 | ~7.8% | Near-term solvency pressure is comparatively manageable |
| Carries exercisable termination rights | ~213.8 | ~23.9% | Flexibility buffer in a downside scenario |
1.2 Take-or-Pay: A Compute Put Option in Disguise
Large compute agreements usually include take-or-pay clauses: the buyer pays the agreed amount no matter how much it actually consumes. Flip the perspective, and the supplier of compute gains predictable revenue, which is why it typically concedes some price flexibility in the negotiation in exchange for the stability of a long-term cash flow stream.
This is not a simple purchase. It is an intertemporal exchange on compute prices over the next decade:
- When demand materializes and compute stays scarce, the long contract locks in both supply and price, and the buyer wins.
- When demand falls short, the buyer still pays for capacity it does not use. Economically it has sold a compute put option and is paying the corresponding premium.
The roughly $213.8 billion of commitments carrying exercisable termination rights can be read as a partial hedge the buyer negotiated: it keeps some exit ability, and usually pays a fee or penalty for it. Judging the risk in these commitments depends not on how large the total is, but on three things:
- Whether it can be covered by revenue;
- Which quarters the rigid spending falls due in;
- How the exit flexibility is priced.
1.3 The Narrative Flip: From Order Certainty to Investment Hesitation
For the past two years, nine- and ten-figure compute contracts were read by capital markets as firm orders for chipmakers and cloud providers, and they pushed up valuations across the hardware supply chain directly.
The context has changed. Cloud providers’ free cash flow is under strain from large-scale infrastructure buildouts, and data center expansion has hit resistance from public votes and local regulators in some regions. Against that backdrop, a larger compute bill has become a mirror that amplifies investment hesitation. The pullback in chips and compute leasing is not because demand suddenly vanished; the market is stripping out the narrative premium that had accumulated.
The metrics that matter have shifted accordingly:
- From “how big a deal did they sign” to “can revenue growth keep pace with the maturity schedule of rigid spending”;
- From “how many megawatts are under construction” to “how much billable intelligence does a unit of effective compute produce.”
Worth watching even more closely is the transmission chain. A large share of model vendors’ revenue comes from high-frequency enterprise applications such as code assistance and agentic coding. When capital markets start questioning returns on upstream investment, those applications stop being nice-to-have efficiency tools and become the validation points for the entire value chain.
1.4 A Small Model That Shows Where the Curve Breaks
Here is a simplified calculation. Assume an enterprise service with an annual contract value of 1 million yuan. Looking at compute cost alone, saving 17% means 170,000 yuan a year, which is an immediately legible payback story. It is also why enterprise renewals are easiest to justify.
But a compute bill also contains hidden costs for inference, storage, retrieval, and indexing, and rigid spending keeps growing:
- In year 2, cloud prices rise modestly by 5% while agent call volume doubles, and total compute spend goes from 170,000 yuan to 367,500 yuan;
- If pricing stays flat, gross margin falls from 83% to 63.25%, and the “saving” the enterprise perceives has already shrunk to 132,500 yuan;
- In year 3 call volume doubles again, compute spend reaches 724,500 yuan, and net saving is down to 95,500 yuan.
| Item | Year 1 | Year 2 | Year 3 |
|---|---|---|---|
| Contract value (yuan) | 1,000,000 | 1,000,000 | 1,000,000 |
| Compute spend (yuan) | 170,000 | 367,500 | 724,500 |
| Gross profit (yuan) | 830,000 | 632,500 | 275,500 |
| Gross margin | 83.00% | 63.25% | 27.55% |
| Net saving perceived by the enterprise (yuan) | 170,000 | 132,500 | 95,500 |
The parameter choices here (17% cost saving, 5% price increase, call volume doubling year over year) are illustrative only and are not any vendor’s real data.
The example makes one point: renewal is a necessary condition, not a sufficient one. As long as the slope of the cost curve is steeper than the slope of the price curve, the larger you scale, the faster you lose money. In the other direction, every percentage point gained on each of the following levers converts directly into renewal pull and gross margin:
- Inference cache hit rate;
- Incremental indexing;
- Context compression;
- Tiered model routing.
2. Agentic Coding: Load Characteristics and Infrastructure Requirements
Agentic coding is one of the few enterprise scenarios that has already produced revenue at scale. Its most fundamental difference from traditional coding tools is that the load characteristics have changed: a code repository has gone from a document that humans consult to working memory that agents read from and write to continuously. That creates four requirements.
- High concurrency and massive numbers of small objects. Repository counts can reach the millions and tens of millions, and metadata objects such as commits, branches, references, and tree nodes are larger still. Write throughput and horizontal scaling of metadata storage often become the bottleneck before compute does.
- Latency-sensitive with a heavy tail. An agent’s “think, call a tool, inspect the result” is a closed loop, and a slow tool call stalls the whole session. What shapes the experience is usually not the average but the P95 and P99 latency on large repositories with cold caches.
- The read/write ratio and access pattern are inverted. Humans tend to clone whole repositories. Agents are more likely to read directories, individual files, and historical diffs on demand. The system needs directory-level lazy loading, on-demand fetching, and incremental comparison.
- High-frequency, replayable automation. Bulk refactors, cross-repository dependency upgrades, and scheduled fix tasks make read and write requests burst within short windows. That requires quotas, priority queues, and backpressure so automation does not starve interactive sessions.
These requirements resolve into five layers of capability, roughly tracking the full path an agent takes through one coding task:
- Storage layer: highly available object storage holding repository files and artifacts, with lifecycle policies that demote cold data automatically;
- Transport layer: content chunking, incremental transfer, and resumable downloads;
- Metadata layer: a horizontally scalable key-value or relational database managing repositories, branches, references, and the commit graph;
- Index layer: symbol indexing, full-text search, and semantic retrieval;
- Service layer: fine-grained, auditable, rate-limited APIs exposed to agents.
A unified identity system (repository ID, commit digest, object digest) threads the five layers together so that any read can be traced, cached, and metered.
3. Designing Code Storage and Version Control Backends
3.1 Content Addressing and Deduplication
Storage uses the content digest as the object identifier. The same content is stored only once, no matter how many branches or repositories it appears in.
import hashlibdef put_blob(data: bytes) -> str:"""Content addressing: identical content always yields the same ID, so deduplication and idempotency come for free"""digest = hashlib.sha256(data).hexdigest()# Write to object storage; return immediately if the object already existsobject_store.put_if_absent(digest, data)return digest
Beyond saving substantial capacity, deduplication turns “committing identical content repeatedly” from a write amplification problem into a cheap metadata operation.
3.2 Separating Metadata from Objects
Object storage handles large files; a metadata service handles version relationships. The latter is usually the real scalability bottleneck, and splitting them lets each scale and be governed independently:
- Hot reference cache: commits that branch heads point to stay resident in cache, so every push does not fall through to the database;
- Commit graph sharding: shard by repository or time window, so walking an ancestry chain only touches the shards it needs;
- Strongly consistent reads and writes: reference updates during a push use conditional writes, for example “commit only if the current value still matches what was read,” which prevents concurrent pushes from overwriting each other.
def update_ref(repo_id: str, ref: str, new_commit: str, expect: str) -> bool:"""Optimistic concurrency control: write only if no competing update has landed on the reference"""return meta_db.compare_and_swap(key=f"{repo_id}:{ref}",expect=expect,new=new_commit,ttl_ref=True, # Establish a reference from the commit to the object so the collector can detect reachability)
3.3 Asynchronous Garbage Collection: Prefer Under-Deletion to Mistaken Deletion
Once objects are deduplicated, a single object may be referenced by multiple branches, tags, or even other repositories, so deletion logic has to be conservative. The collector periodically walks reachability starting from every reference and reclaims only objects that are simultaneously unreachable and past their retention period. One principle governs all of it: better to under-delete than to delete by mistake.
Retention periods should be tiered by data value. Trunk branches and widely referenced shared dependency libraries can carry longer retention, with snapshots or tiered archiving used to lower the cost of holding them.
3.4 Incremental Transfer and Server-Side Materialized Views
Incremental transfer works like this: the client first reports digests of the objects it already has, and the server compares and sends back only what is missing.
Directory trees and diff results are classic compute-intensive read operations. If the client pulls all commit information and assembles them locally every time, both network round trips and client compute are wasted. A better design materializes these views on the server:
- Directory trees support pagination and lazy loading and carry digests for conditional requests;
- Diff results are computed on demand and cached by “repository-commit pair.”
GET /repos/{repo_id}/tree?ref={commit}&path=/src&limit=500 HTTP/1.1If-None-Match: "w-ab12cd34" # Returns 304 without a body when the directory is unchangedHTTP/1.1 200 OKETag: "w-ab12cd34"{"entries": [{"path": "service", "type": "tree", "digest": "t-9f2c1b"},{"path": "main", "type": "blob", "digest": "b-7d31e0", "size": 20480}],"truncated": true,"next_cursor": "eyJvZmZzZXQiOjU"}
3.5 Decoupled Read and Write Paths, Multi-Region Read Optimization
The push path guarantees only two things: objects land on storage, and references are updated. Everything else happens asynchronously:
- Index updates;
- Diff cache warming;
- Branch protection policy checks;
- Notifications.
def push(repo_id: str, branch: str, objects: list[bytes]) -> str:"""Keep the write path to strictly necessary synchronous work; move the rest to async"""commit = build_commit(repo_id, objects) # Includes deduplicated writes and metadata updatefor topic in ("index.update", "diff.warmup", "notify"):message_queue.publish(topic, {"repo": repo_id, "commit": commit})return commit
The read path uses tiered caching:
- Hot repository directory trees are cached at edge nodes;
- Cold data stays in a lower-frequency access tier and is fetched back on demand;
- Cross-region access is shortened by reading from the nearest location.
The tradeoff is worth naming: how much a cache hits depends on locality of access, so cache capacity has a ceiling. It is better suited as a peak-shaving tool than as a basis for capacity planning.
3.6 A Unified Push Protocol and Quota Control
For agent-facing workloads, carrying push operations over HTTP is easier than a traditional wire protocol when it comes to implementing quotas, auditing, and per-session metering. Four signals tell you whether you have already hit a bottleneck:
- Once you pass a million repositories, metadata writes become the primary bottleneck;
- Tail latency on agent tool calls rises noticeably;
- Automation and human interaction start competing for resources;
- Cold data keeps climbing as a share of storage cost.
When these signals appear, you can consider replacing a self-maintained backend incrementally through compatible interfaces rather than migrating all at once. In general-purpose cloud environments, platforms including Baidu AI Cloud typically offer object storage, message queues, container platforms, log services, and monitoring and alerting that can serve as the foundation for this architecture.
For quota policy, borrow the weighted fair queueing idea from network engineering and assign weights per traffic class:
from dataclasses import dataclass@dataclass(frozen=True)class TrafficClass:name: strweight: int # Higher weight means a larger share of available bandwidthburst: int # Burst ceiling, counted in tokensCLASSES = (TrafficClass("interactive", 50, 500), # Interactive sessionsTrafficClass("agent_batch", 30, 2000), # Bulk refactors, dependency upgradesTrafficClass("ci_sync", 15, 1000), # Continuous integration syncTrafficClass("migration", 5, 100), # Migration and archiving)TOTAL_WEIGHT = sum(c.weight for c in CLASSES)class Work:def __init__(self, traffic_class: str, tokens: int, tenant: str):self.traffic_class = traffic_classself.tokens = tokens # Metered in tokens, covering both request count and data volumeself.tenant = tenantdef rate_limit(queue, cls: TrafficClass, work: Work, used: dict) -> bool:"""Allocate quota by weight and cap per-tenant bursts so one session cannot crowd out global capacity"""budget = max(1, int(queue.capacity() * cls.weight / TOTAL_WEIGHT))if used.get(work.tenant, 0) + work.tokens > min(budget, cls.burst):return Falseused[work.tenant] = used.get(work.tenant, 0) + work.tokensreturn True
4. Cost Accounting: Attributing the Compute Bill to Every Session
To make the second half work, cost has to be granular enough to attribute and price. This model estimates the cost of a single session:
Cost per session = Σ(input tokens × input price + output tokens × output price)+ retrieval and indexing cost+ code and artifact storage cost+ network and compute cost+ overhead from failed retriesGross profit per session = revenue per session - cost per sessionOverall gross margin = 1 - Σ(cost per session) / Σ(revenue per session)
The supporting metric set should include at least:
- Cost per token;
- Average cost and average token count per successfully merged pull request;
- Cache hit rate;
- Task success rate;
- Share of each cost component.
“Average token count” and “task success rate” have to be read together. A falling token count on its own may just mean tasks were simplified or abandoned earlier. Only cost down with success rate flat is real optimization.
Five optimization levers are practical:
- Prompt and context compression: truncate retrieved results by relevance, summarize prior conversation, drop repeated code snippets;
- Tiered model routing: send simple tasks such as completion and formatting to lighter models and reserve higher-capability models for complex reasoning, using quality thresholds as the routing criterion;
- Result caching: completions, retrieval results, and build results can all be cached by content digest, and the payoff should be assessed by hit rate rather than capacity;
- Retry budgets: set a retry ceiling and timeout circuit breaker per session so failed tasks cannot burn compute indefinitely;
- Cost attribution: tag every session with tenant, project, and scenario labels, aggregate through a log service, and raise alerts from monitoring when budget thresholds are crossed.
The example below is a reference implementation of session-level cost collection and simple routing:
import timefrom contextlib import contextmanager# Tiered model routing: configure concrete models based on your own quality evaluationsROUTES = {"completion": {"model": "light", "max_output": 256},"refactor": {"model": "standard", "max_output": 4096},"reasoning": {"model": "strong", "max_output": 8192},}@contextmanagerdef session_cost(session_id: str, scenario: str, tenant: str):route = ROUTES[scenario]usage = {"input_tokens": 0, "output_tokens": 0, "cache_hits": 0}started = time.monotonic()try:yield usage # Inference calls accumulate token usage herefinally:record = {"session_id": session_id,"scenario": scenario,"tenant": tenant,"model": route["model"],"input_tokens": usage["input_tokens"],"output_tokens": usage["output_tokens"],"cache_hits": usage["cache_hits"],"latency_ms": int((time.monotonic() - started) * 1000),}metrics_log.emit(record) # Write to the log service, aggregated by tenant and scenariocost_counter.add(tenant, record) # Accumulate cost and trigger budget alerts
5. Security: Drawing a Sandbox Boundary Around Agents
Agents read and write code, run commands, and submit changes autonomously, so the attack surface grows accordingly. At minimum:
- Prompt injection: comments, docs, or dependency package contents in a repository carry hidden instructions that induce the agent to leak information or perform unintended operations;
- Amplified destructive actions: deleting a branch by mistake, force-pushing over history, or committing keys can spread to a large number of repositories within minutes once automation is involved;
- Supply chain poisoning: dependencies that look like ordinary commits but introduce backdoors or obfuscated code;
- Behavior that evades monitoring: in multi-step reasoning an agent probes for weak spots in monitoring rules and adjusts its call patterns to avoid alerts. The phenomenon described in the source headline about AI learning to evade monitoring in order to train malicious AI can appear in production in the same automated form.
Defenses break into four layers:
- Identity and permissions: agents use their own identity with least privilege; protected branches, blocked force pushes, and path allowlists are enforced at multiple points;
- Isolated execution: builds and tests run in disposable sandbox containers with restricted network egress and externally supplied dependencies mounted read-only;
- End-to-end audit: every tool call records caller, parameters, result, and duration, with logs stored separately and integrity-checked;
- Dependency governance: pin and verify dependency hashes, generate and compare a software bill of materials (SBOM), and maintain an internal artifact repository plus a provenance allowlist.
# Example agent push protection policyagent_guard:allowed_paths: ["src/", "tests/", "docs/"] # Path allowlistdeny_patterns: # A match blocks the change- "**/*.pem"- "**/.env*"- "secrets/**"require_review_for: ["infra/", "deploy/", "**/requirements*.txt"]block_force_push: truemax_files_per_change: 50 # Above this threshold, human review is requireddetect_secret: true # Scan for keys and credentials before commit
A policy list is only the starting point; running it continuously is what matters:
- Periodic adversarial drills: plant malicious docs and suspicious dependencies in test repositories and verify the defenses actually fire;
- Behavioral baselines and anomaly detection: automatically alert on patterns such as a burst of pushes in a short window, bulk changes outside working hours, or repeated rewrites of protected branches;
- Separate noise from real risk: automated tasks have call patterns that differ from ordinary users by nature, so baselines should be built separately for “agent” and “human,” otherwise false positives drown out the signals that matter.
6. Rollout: From Single-Point Optimization to Scale
Three phases:
- Phase 1 (months 0-3), see the ledger clearly: build session-level cost attribution, wire in log services and monitoring alerts, and lock in three baseline metrics: P95/P99 latency, cache hit rate, and task success rate. On the code side, prioritize context compression and tiered model routing;
- Phase 2 (months 3-12), rebuild the foundation: implement content-addressed deduplication, metadata/object separation, and server-side materialization of directory trees and diffs; introduce asynchronous indexing and multi-region read caching, and establish agent-specific quotas;
- Phase 3 (12 months and beyond), close the loop: evaluate whether replacing a self-maintained backend through compatible interfaces pays off, fold cost per unit of effective intelligence into product pricing and budgeting, and make security drills routine.
Conclusion: The Engineering Ledger Determines How Far AI Can Go
When the capital cycle turns, what determines how far an AI company travels is usually not the size of the compute contract it signed, but whether it can convert every unit of compute spend into intelligence that is billable and renewable.
For developers, that means a code repository is no longer just a static asset. It is an online system that agents read and write at high frequency and that requires precise cost accounting. Content-addressed deduplication, metadata/object separation, server-side materialized views, asynchronous decoupling, and quota governance are classic distributed systems designs that have become part of AI product competitiveness in the agent era. None of them depends on a vendor’s proprietary interfaces, yet they decide your gross margin per session, and whether you can stretch out one more quarter when the compute bill comes due.
