AI Engineering: How to Calculate Compute Costs and Design Code Storage for AI Coding Agents

    This article breaks down two engineering problems that AI coding agents force to the surface: how to reason about rigid, long-term compute commitments, and how to design a code storage layer that survives high-frequency, short-lived, machine-generated repositories. It shows how to separate committed spend from effective output under take-or-pay contracts, how content-addressed storage and mark-and-sweep reclamation keep storage costs bounded, and how on-demand read paths keep agents fast. It closes with a cost-observability model and a practical implementation checklist so teams can prove that each agent session earns back the compute it consumes.

    Evaluating Long-Term Compute Commitments: Rigidity, Expiration Profile, and Termination Rights

    Two seemingly unrelated signals have surfaced in AI engineering recently. On one side, capital markets are repricing long-term compute commitments, data centers, and chip orders. On the other, AI coding agents are creating repositories at high speed and generating massive numbers of micro-commits. Both point to the same constraint: supply-side investment is becoming increasingly rigid, so engineering systems must convert every unit of committed compute into measurable output at higher effective utilization.

    According to public reporting and disclosures, the compute commitments of leading model providers tend to share a few characteristics: large total amounts, long durations, partially rigid spending, and some contracts that come with termination rights. Because disclosure scope, accounting treatment, and verifiable sources differ, this article does not restate specific figures. Instead, it unpacks three key questions from an engineer’s perspective:

    1. Commitment rigidity: Is the money non-negotiable?
      Leasing, purchasing, dedicated compute, resellable capacity, and take-or-pay clauses all materially change the risk profile. Unlike pay-as-you-go, a long-term commitment turns marginal cost into fixed cost. If a contract includes a take-or-pay clause, you pay the agreed amount even when the workload falls short.

    2. Expiration profile: When does the money get spent?
      Rigid spending over the next 12 months determines near-term cash-flow pressure, while multi-year commitments depend on continued optimization of the technical roadmap and inference efficiency. If the cost per token keeps falling, the real pressure from long-dated commitments may be lower than their nominal value.

    3. Exit-ability: Can you cut losses?
      A contract with termination rights is not entirely locked, but it usually requires weighing penalties, compensation costs, and the opportunity cost of giving up a scarce capacity allocation. A compute commitment behaves more like an option curve, “protected on the downside, flexible on the upside,” than a straight line.

    For engineering teams, the key point is this: a long-term commitment locks in supply, but it cannot lock in demand. The response is not to passively accept the bill, but to raise the “effective output per unit of committed compute.”

    Responding to Take-or-Pay: Separate the Bill from Effective Output

    Many cost models mix utilization and cache hit rate together, which leads to a common misconception: that improving utilization automatically lowers the compute bill. In reality, under a take-or-pay long-term commitment, committed spending does not shrink as utilization drops. Utilization affects effective output, idle waste, and cost per task, not the commitment itself.

    So a cost model should distinguish three layers:

    • Committed cost: the total cost that must be paid once the long-term commitment is amortized.
    • Idle waste: waste produced when committed capacity is not actually occupied.
    • Avoidable cost: only when reuse, caching, model routing, or elastic substitution can reduce future renewals, reduce incremental commitments, or replace elastic purchasing can this turn into cash savings.

    Here is a cleaner skeleton for estimating unit cost:

    1. def effective_unit_cost(
    2. hourly_commitment,
    3. committed_hours,
    4. gpu_hours,
    5. utilization,
    6. cache_saving_ratio,
    7. tasks=1000,
    8. adjustable=False,
    9. ):
    10. """
    11. Estimate the effective cost under a long-term commitment.
    12. hourly_commitment: hourly commitment cost after amortizing the long-term contract
    13. committed_hours: take-or-pay committed GPU hours; the bill is based on this and does not vary with utilization
    14. gpu_hours: actual GPU hours used, used to estimate idle waste
    15. utilization: effective workload ratio, used to identify ineffective retries and idle occupancy
    16. cache_saving_ratio: ratio of compute that caching/reuse can reduce
    17. tasks: number of effective tasks in this period
    18. adjustable: whether cash spending can be reduced via renewal, shrinking the commitment, or elastic purchasing
    19. """
    20. if not 0 < utilization <= 1:
    21. raise ValueError("utilization must fall within the (0, 1] range")
    22. committed_cost = hourly_commitment * committed_hours
    23. idle_hours = max(committed_hours - gpu_hours, 0)
    24. idle_waste = hourly_commitment * idle_hours
    25. # Caching savings only reduce cash spending if they cut future commitments or incremental elastic purchasing
    26. avoidable_cost = hourly_commitment * min(gpu_hours, committed_hours) * cache_saving_ratio
    27. adjusted_cost = max(committed_cost - avoidable_cost, 0) if adjustable else committed_cost
    28. return {
    29. "committed_cost_per_1k": committed_cost / (tasks / 1000),
    30. "adjusted_cost_per_1k": adjusted_cost / (tasks / 1000),
    31. "idle_waste": idle_waste,
    32. "utilization": utilization,
    33. }

    This model makes one fact clear: if the contract cannot be reduced, no matter how high the cache hit rate is, it will not automatically reduce the current commitment bill. What caching truly changes is the number of effective tasks, the room for future renewal negotiations, or the need for elastic purchasing.

    For example, with a commitment of 2000 GPU hours, actual usage of 1000 GPU hours, and a unit price of $8 per GPU hour, if adjustable=False, then committed_cost_per_1k will not drop as utilization improves, regardless of how the cache hit rate changes. Only if a future renewal can be reduced can you further compute adjusted_cost_per_1k.

    Engineering paths to raise effective utilization include:

    • Mixed workloads: co-locate training, batch inference, and online inference in the same resource pool to smooth peaks and fill valleys.
    • Preemptible instances and elastic scaling: run non-critical tasks on interruptible resources, and scale online services with real-time load.
    • Efficiency-oriented model selection: route tasks to differently sized models based on task difficulty.
    • Inference cache reuse: stop recomputing identical prefixes, identical queries, and identical tool results.
    • Quantization and graph optimization: reduce memory footprint and compute within an acceptable accuracy range.

    At the same time, engineering teams should build a “resource-to-business” tracking chain: every unit of committed compute should map to a specific business workload, a number of effective tasks, and measurable output.

    Why AI Coding Agents Need a New Code Storage Layer

    Traditional code hosting services are designed primarily around “humans”: developers commit infrequently, branches live for days or weeks, and a single push often carries a large number of history objects. AI coding agents change the write pattern:

    • High-frequency creation: if a task fails, it starts over, and each task creates a brand-new repository from a template or an existing project.
    • Many micro-commits: every small change produces new tree objects and commit records.
    • Short lifecycle: once a session ends, a branch may never be valuable again.
    • Machine-readable: agents need stable APIs, deterministic content addressing, and data structures that can be pulled incrementally.

    These characteristics conflict with the default assumptions of classic version control:

    Dimension Human in the loop Agent-first
    Write frequency Low, batched High, fragmented
    Branch lifecycle Days to weeks Minutes to hours
    Commit semantics Meaningful history Snapshots of a trial-and-error process
    Object reuse Limited Extensive template and common-dependency duplication
    Read pattern Full clone On-demand, incremental, server-side computation

    If you keep the “full clone + local computation” model, a flood of short-lived repositories quickly turns into object storage cost and metadata query pressure. So the code storage layer needs to be restructured around four goals:

    1. Immutable content + mutable references: address file content by content digest, never rewrite it, and treat branches as mutable pointers.
    2. Layered storage: put large content in object storage, metadata in structured storage that supports high concurrency, and add caching for hot data.
    3. Server-side computation: build directory trees, compute diffs, and search files on the storage side so clients fetch only what they need.
    4. Lifecycle governance: reclaim unreferenced objects with mark-and-sweep so storage does not grow without bound.

    Common mistakes: full clones, unreclaimed branches, full front-end rendering

    In practice, common problems include:

    • Full clones: agents pull the entire repository every time they look at code, making traffic and latency unacceptable.
    • Unreclaimed branches: short-lived branches are kept after the session ends, so metadata and object storage keep growing.
    • Full front-end rendering of diffs: pushing very large files or massive numbers of diff blocks directly to the browser causes page jank or failures.
    • Counting storage but not reads: storage gets cheaper, but metadata queries, directory expansion, and diff computation become the new bottleneck.
    • Ignoring security isolation: multi-tenant repositories lack access isolation, and secrets get mistakenly written into repository content.

    Designing Content Addressing and the Metadata Model

    The core idea of content addressing is “write once, reference many times.” In AI-generated code, dependency manifests, lockfiles, common utility functions, and boilerplate templates are highly repetitive. After deduplication, the actual storage increment may be far smaller than the number of repositories.

    1. import hashlib
    2. from typing import Optional
    3. from dataclasses import dataclass, field
    4. class BlobStore:
    5. """Content-addressed storage for immutable content; object keys are derived from content digests."""
    6. def __init__(self, object_storage):
    7. self._os = object_storage
    8. def put(self, data: bytes) -> bytes:
    9. digest = hashlib.sha256(data).digest()
    10. hex_digest = digest.hex()
    11. key = f"blobs/sha256/{hex_digest[:2]}/{hex_digest[2:]}"
    12. self._os.put(key, data)
    13. return digest
    14. def get(self, digest: bytes) -> bytes:
    15. hex_digest = digest.hex()
    16. key = f"blobs/sha256/{hex_digest[:2]}/{hex_digest[2:]}"
    17. return self._os.get(key)
    18. @dataclass
    19. class TreeEntry:
    20. name: str
    21. mode: int
    22. content: Optional[bytes] = None
    23. subtree: tuple = ()
    24. content_sha: Optional[bytes] = None
    25. child_sha: Optional[bytes] = None
    26. @dataclass
    27. class Repository:
    28. blobs: BlobStore
    29. trees: dict = field(default_factory=dict)
    30. refs: dict = field(default_factory=dict)
    31. def _write_tree(self, entries: tuple) -> bytes:
    32. materialized = {}
    33. for entry in entries:
    34. content_sha = None
    35. child_sha = None
    36. if entry.mode == 0o040000: # directory
    37. child_sha = self._write_tree(entry.subtree)
    38. else: # file
    39. content_sha = self.blobs.put(entry.content or b"")
    40. materialized[entry.name] = TreeEntry(
    41. name=entry.name,
    42. mode=entry.mode,
    43. content_sha=content_sha,
    44. child_sha=child_sha,
    45. )
    46. serialized = {
    47. name: (node.mode, node.content_sha, node.child_sha)
    48. for name, node in materialized.items()
    49. }
    50. tree_sha = hashlib.sha256(repr(sorted(serialized.items())).encode()).digest()
    51. self.trees[tree_sha] = materialized
    52. return tree_sha
    53. def commit(
    54. self,
    55. ref: str,
    56. root_entries: tuple,
    57. session_id: str,
    58. expire_at,
    59. now=None,
    60. ) -> bytes:
    61. root_tree = self._write_tree(root_entries)
    62. if now is None:
    63. import datetime as dt
    64. now = dt.datetime.now(dt.timezone.utc)
    65. self.refs[ref] = {
    66. "commit_sha": root_tree,
    67. "root_tree": root_tree,
    68. "parents": [],
    69. "session_id": session_id,
    70. "last_used_at": now,
    71. "expire_at": expire_at,
    72. }
    73. return root_tree

    The corresponding metadata tables can be designed like this:

    1. -- Tree node objects: all entries under the same directory are packed into one snapshot to make whole-layer replacement easy
    2. CREATE TABLE tree_node (
    3. repo_id BIGINT NOT NULL,
    4. tree_sha BYTEA NOT NULL,
    5. parent_sha BYTEA NULL,
    6. name TEXT NOT NULL,
    7. node_type SMALLINT NOT NULL, -- 1 file / 2 directory
    8. content_sha BYTEA NULL,
    9. child_sha BYTEA NULL,
    10. mode INTEGER NOT NULL,
    11. PRIMARY KEY (repo_id, tree_sha, name)
    12. );
    13. -- Repository refs: mutable pointers that point to immutable history objects
    14. CREATE TABLE repo_ref (
    15. repo_id BIGINT NOT NULL,
    16. ref_name TEXT NOT NULL,
    17. commit_sha BYTEA NOT NULL,
    18. parents JSONB NOT NULL,
    19. root_tree BYTEA NOT NULL,
    20. session_id TEXT NULL,
    21. last_used_at TIMESTAMPTZ NOT NULL,
    22. expire_at TIMESTAMPTZ NOT NULL,
    23. PRIMARY KEY (repo_id, ref_name)
    24. );

    Here, repo_ref must include session_id, last_used_at, and expire_at. Otherwise, later lifecycle reclamation cannot tell which references are still in use and which have entered the grace period.

    Implementing Lifecycle Reclamation: Mark-and-Sweep with a Grace Period

    Deleting massive numbers of short-lived references outright can cause accidental deletion, while keeping them forever lets storage cost spiral out of control. Engineering practice usually adopts a two-phase strategy:

    1. After a reference expires, it enters a grace period.
    2. Reclaim only references that receive no new access during the grace period and are unreachable.
    1. import datetime as dt
    2. GRACE = dt.timedelta(hours=48)
    3. def collect_tree(repo: Repository, tree_sha: bytes, acc: set) -> None:
    4. if tree_sha in acc:
    5. return
    6. acc.add(tree_sha)
    7. for node in repo.trees.get(tree_sha, {}).values():
    8. if node.mode == 0o040000 and node.child_sha is not None:
    9. collect_tree(repo, node.child_sha, acc)
    10. elif node.mode != 0o040000 and node.content_sha is not None:
    11. acc.add(node.content_sha)
    12. def sweep_expired_refs(repo: Repository, now: dt.datetime, grace: dt.timedelta = GRACE):
    13. keep_refs = {}
    14. expired_candidates = []
    15. for ref_name, ref in repo.refs.items():
    16. # Keep if not expired, or still accessed within the grace period
    17. if ref["expire_at"] >= now or ref["last_used_at"] >= now - grace:
    18. keep_refs[ref_name] = ref
    19. else:
    20. expired_candidates.append(ref_name)
    21. live_objects = set()
    22. for ref in keep_refs.values():
    23. collect_tree(repo, ref["root_tree"], live_objects)
    24. removed_refs = []
    25. for ref_name in expired_candidates:
    26. repo.refs.pop(ref_name, None)
    27. removed_refs.append(ref_name)
    28. # Keep only reachable tree objects; a real implementation must also hand the content_sha set to object storage for unreachable cleanup
    29. repo.trees = {
    30. sha: nodes for sha, nodes in repo.trees.items() if sha in live_objects
    31. }
    32. return len(removed_refs), len(live_objects)

    The key point in this code: sweep_expired_refs does not delete any arbitrary expired reference. Instead, it first keeps references that are “not expired” or “still accessed within the grace period,” then collects all reachable objects. Only tree objects not in the reachable set get cleaned up.

    Note that reclamation logic is a high-risk operation. It must strictly delete only unreachable objects, and it should be validated with real workloads in a canary environment before going live. Reclamation tasks should run off-peak with rate limiting so they do not affect online reads.

    Designing the Read Path: On-Demand Directory Trees and Diff Comparison

    Once write volume is amplified, the read path must change too. Otherwise, agents pull everything every time they look at code, and both latency and traffic become unacceptable.

    • Directory trees: returning the full listing at once quickly exceeds rendering capacity in a repository with tens of thousands of files. A better approach is to expand on demand, fetching a subdirectory’s entries only the first time it is expanded.
    • Diff comparison: the same content-addressing mechanism naturally supports structured comparison between two directory trees, computing only the parts that changed instead of recomputing the whole repository.

    Below is a minimal diff-rendering implementation based on difflib, emphasizing “degrade rather than fail”:

    1. import difflib
    2. MAX_INLINE_LINES = 2000
    3. MAX_INLINE_BYTES = 256 * 1024
    4. def is_binary(payload: bytes) -> bool:
    5. return b"\x00" in payload[:8192]
    6. def compute_hunks(old_text: str, new_text: str) -> list:
    7. """Minimal difflib-based implementation: return the change hunks the server needs to render."""
    8. old_lines = old_text.splitlines()
    9. new_lines = new_text.splitlines()
    10. matcher = difflib.SequenceMatcher(None, old_lines, new_lines)
    11. hunks = []
    12. for tag, i1, i2, j1, j2 in matcher.get_opcodes():
    13. if tag == "equal":
    14. continue
    15. hunks.append({
    16. "tag": tag,
    17. "deleted": old_lines[i1:i2],
    18. "added": new_lines[j1:j2],
    19. })
    20. return hunks
    21. def render_diff(old: bytes, new: bytes) -> dict:
    22. """Server-side contract for diff display: return only renderable content and summary statistics."""
    23. if is_binary(old) or is_binary(new):
    24. return {"kind": "binary"}
    25. if max(len(old), len(new)) > MAX_INLINE_BYTES:
    26. return {"kind": "oversized"}
    27. old_text = old.decode("utf-8", errors="replace")
    28. new_text = new.decode("utf-8", errors="replace")
    29. hunks = []
    30. budget = 0
    31. total_added = 0
    32. total_deleted = 0
    33. for hunk in compute_hunks(old_text, new_text):
    34. span = len(hunk["deleted"]) + len(hunk["added"])
    35. if budget + span > MAX_INLINE_LINES:
    36. hunks.append({"collapsed": True, "omitted": span})
    37. break
    38. budget += span
    39. total_added += len(hunk["added"])
    40. total_deleted += len(hunk["deleted"])
    41. hunks.append({"collapsed": False, **hunk})
    42. return {
    43. "kind": "text",
    44. "hunks": hunks,
    45. "stats": {
    46. "added": total_added,
    47. "deleted": total_deleted,
    48. },
    49. }

    The core idea here: binary files, oversized files, and extremely long diff blocks each degrade into a summary hint, a truncated display, and a collapsed block, respectively. The user can always see a conclusion rather than facing a spinner or an error.

    Mapped to performance goals, you can validate across four dimensions:

    • First-screen response time for directory expansion.
    • Content size returned by a single diff request.
    • Actual storage increment after content-addressed deduplication.
    • Impact of reclamation tasks on online requests.

    Where the Two Constraints Meet: Bring Compute and Storage Under Cost Observability

    Viewed together, compute bills and code storage point to the same set of engineering practices: every time an agent generates code, it consumes compute, reads repositories, and produces temporary objects. If you cannot observe these processes, you cannot tell whether demand growth is outpacing the expiration of rigid bills.

    From the compute side, large-scale code generation by agents means prompts, context, and generation results contain a lot of duplication, which can yield significant prefix cache hit rates and result reuse. But failed retries, ineffective generation, and context explosion also convert directly into cost.

    From the storage side, the goal of building the storage layer is to make each time an agent “looks at code” a low-cost, deterministic query. This includes loading directory trees on demand, computing diffs server-side, deduplicating content, and tagging references per session so temporary state can be reclaimed when the session ends.

    You can build a minimal cost-tracking structure:

    1. from dataclasses import dataclass
    2. @dataclass
    3. class TaskLedger:
    4. session_id: str
    5. task_id: str
    6. tokens_in: int = 0
    7. tokens_cached: int = 0
    8. tokens_out: int = 0
    9. repo_reads: int = 0 # number of directory tree / file reads
    10. repo_bytes: int = 0 # actual bytes transferred
    11. retries: int = 0
    12. gpu_seconds: float = 0.0
    13. def to_record(self):
    14. return {
    15. "session": self.session_id,
    16. "task": self.task_id,
    17. "tokens": {
    18. "in": self.tokens_in,
    19. "cached": self.tokens_cached,
    20. "out": self.tokens_out,
    21. },
    22. "repo": {
    23. "reads": self.repo_reads,
    24. "bytes": self.repo_bytes,
    25. },
    26. "retries": self.retries,
    27. "gpu_s": self.gpu_seconds,
    28. }

    These structured records can be written uniformly to a logging service, then aggregated and checked for anomalies with monitoring and alerting. For example:

    • Alert when effective utilization of committed capacity falls below 0.6.
    • Alert when the reuse rate drops more than 10% period over period.
    • Alert when bytes read per task double period over period.
    • Alert when the cache hit rate drops sharply.
    • Alert when the retry rate keeps rising.

    Only by correlating each agent session’s compute usage, storage reads, and output results can you answer a core question: is the growth rate of downstream demand outpacing the expiration of rigid bills?

    Implementation Checklist

    • Resource strategy: Is there a credible workload forecast for near-term demand? Does long-dated capacity retain windows for batched confirmation and exit?
    • Cost attribution: Are effective cost per thousand tasks, committed-capacity utilization, and reuse rate observable week over week?
    • Elastic mixing: Are training, batch inference, and online services co-located? Are preemptible resources used for interruptible tasks?
    • Storage model: Is file content immutable and addressed by digest? Is metadata stored separately and able to support high-concurrency queries?
    • Read experience: Do directory trees expand on demand? Are diffs computed server-side with degradation strategies for binary and oversized files?
    • Lifecycle: Are short-lived references bound to sessions with grace-period reclamation? Does reclamation target only unreachable objects and run rate-limited?
    • Security isolation: Is access isolated between multi-tenant repositories? Are secrets managed by a dedicated key management service and never written into repository content?
    • Quality gates: Do AI-generated code pass automated tests, static analysis, and security scanning? Are necessary human review steps still preserved?

    Conclusion

    The enormous compute commitments that capital markets care about and the repository writes per second that developers care about are actually two sides of the same coin. The expansion of compute supply has entered a rigid phase, and what decides the outcome next is not whose commitment is larger, but how fully each commitment can be utilized.

    For individual developers, in a cycle of volatile compute prices or declining costs, the generation efficiency brought by agents may be easier to unlock, but this does not mean efficiency gains happen automatically. For enterprises, the real moat comes from accountable, reusable engineering capability: making the output of every agent session outpace the portion of the bill it consumes.