Technical document

Robust and High-Speed Build Foundation with CUE as the Source of Truth for Type Generation Pipeline and Bazel

We explain a design that combines CUE as the source of truth for contracts and constraints, and Bazel as the foundation for generation, validation, and build execution, to reduce inconsistencies and rework across multiple languages and services.
Developer Platform / Codegen & Builds~22 minPublication Date September 22, 2026Update date November 23, 2026
Illustration of a development foundation that generates multiple schemas and code from a single contract definition and validates them with a dependency graph

Summary

Key points of this document

  • 1. The more definitions increase, the more synchronization work becomes central to development
  • 2. What is CUE: Handling Types, Values, and Constraints in the Same World
  • 3. Why CUE as the Source of Truth: Prioritizing Contracts over Source Code

Overview

When APIs, databases, frontends, backends, and MCP Tool Schemas are managed in their respective languages, synchronization checks are required every time specifications change. By making CUE the source of truth for business contracts and placing generation, validation, and builds on Bazel's dependency graph, multiple services can be safely updated while keeping the scope of changes small.

1. The more definitions increase, the more synchronization work becomes central to development

It is not uncommon for API definitions, DB definitions, frontend TypeScript types, backend Go types, and MCP Tool Schemas to be managed in separate files or languages. While different formats themselves are not a problem, if the same business concept is repeatedly described in multiple places, the number of items to check during changes increases.

For example, when adding "Pending" to an order status, it is necessary to update not only the API enumeration value, but also DB constraints, Go switch statements, TypeScript unions, screen displays, and MCP tool input descriptions. If one part is changed but other definitions remain outdated, even if compilation passes, it may be interpreted differently at runtime.

As manual synchronization and verification increase, the burden of consistency checks outweighs the value of specification changes. Furthermore, in environments where multiple AI agents generate code, it becomes difficult to explain later which definition was used as the basis for judgment. Therefore, we adopt the approach of consolidating business contracts and data structures into a single source of truth, and mechanically generating each format from it.

  • The source of truth is not the source code of a specific language, but the contract shared by multiple implementations.
  • API, DB, UI, and agent tool definitions are treated as derived artifacts that can be generated from the same contract.
  • Instead of modifying generated artifacts, we modify the source of truth or explicit transformation definitions and regenerate.

2. What is CUE: Handling Types, Values, and Constraints in the Same World

CUE is a language and tool for describing types and constraints of structured data, fitting data to those constraints, and outputting concrete values. In CUE, both types and values are treated as CUE values. Therefore, instead of handling mere type definition files and actual data with separate mechanisms, both can be integrated and evaluated.

It can express constraints, enumerations, ranges, regular expressions, required/optional fields, default values, and relationships between fields. For example, you can combine contracts that enumerate states, constrain amounts to be non-negative, and define that an end time is after a start time, into a single model. When multiple definitions are unified, contradictory values surface as errors, and consistent constraints are aggregated into a single definition.

cue vetvalidates data such as CUE, JSON, and YAML against constraints.cue exportoutputs evaluation results as concrete data such as JSON and YAML. When outputting to OpenAPI, JSON Schema, Protocol Buffers, SQL, or MCP Tool Schema, conversion definitions or generators tailored to the target format are prepared. This does not mean that CUE automatically converts all formats with the same quality.

General configuration templates focus on replacing variables to create final files. CUE, on the other hand, centers on validation, integrating types and values, constraints and defaults, to evaluate whether a configuration is valid. However, CUE should not be treated as a universal application language. Complex business processes, state transition implementations, communication with external services, and screen behavior should remain in implementation languages like Go or TypeScript.

// Example of defining contracts and constraints in CUE
#Order: {
  id:        string
  status:    "draft" | "confirmed" | "cancelled"
  total:     >=0 & number
  currency:  *"JPY" | "JPY" | "USD"
}

order: #Order & {
  id:     "order-001"
  status: "confirmed"
  total:  1200
}
// Validation and output of concrete values
cue vet ./cue ./data/order.yaml
cue export ./cue -e order --out json > generated/order.json

3. Why CUE as the Source of Truth: Prioritizing Contracts over Source Code

The purpose of Single Source of Truth is not to reduce the number of files. It is to clarify where business contracts are defined and which artifacts are derived from them. While there is a method to generate TypeScript types by making Go types the source of truth, in that case, UI-specific constraints that are difficult to express in Go, and differences between API and DB, would enter the type definition.

By making CUE the higher-level source of truth, specification duplication can be reduced, and changes can be centralized. If the same input is given to generate from the source of truth, the reproducibility of the generated artifacts can also be easily confirmed. Furthermore, constraint violations can be detected before code generation, avoiding the situation where problems are discovered after examining a large amount of generated code.

It also has good compatibility with AI-driven code generation. Instead of letting AI freely design data models and API meanings, implementations are generated according to contracts, naming, and allowed dependency directions defined in CUE. When deploying to multiple customers, applications, or domains, common contracts and extension contracts can be separated, and individual differences can be explicitly shown in the higher-level model.

At this time, there is no need to force everything into CUE. The source of truth is limited to business-shared structures and constraints, while implementation-specific matters such as details of authentication methods, DB indexes, UI state management, and external API retries are left to each implementation. Keeping the boundaries of the source of truth narrow is a condition for avoiding excessive commonization.

  • Source of Truth: Business concepts, fields, constraints, defaults, contract versions, extension points.
  • Derived Artifacts: OpenAPI, JSON Schema, Protocol Buffers, SQL, MCP Tool Schema, types and clients for each language.
  • Hand-written Implementation: Screen behavior, use cases, persistence optimization, processing specific to external systems.

4. Overall Picture of the Type Generation Pipeline

The entry point of the pipeline is requirements and domain definitions. From there, a CUE model is created, andcue vetis used to check syntax, types, and constraints. The validated model is passed tocue exportor a dedicated generator to create OpenAPI, JSON Schema, Protocol Buffers, SQL, and MCP Tool Schema. Since each format has a different purpose, the conversion definitions explicitly state type mappings, mandatory requirements, enumerations, descriptions, and compatibility rules.

Next, Go, TypeScript, gRPC client, sqlc input, and MCP server types and handler stubs are generated. The generated code is combined with hand-written implementations and registered as Bazel targets. The order of generation, static analysis, testing, compilation, and packaging is expressed as Bazel dependencies, not as a script call order.

If implementation differences are found in production, or if a new change request arises, we do not simply fix the generated artifacts or individual implementations on the spot. We return to the requirements or the CUE model and decide whether to adopt it as a contract or to confine it as an implementation detail of a specific service. Designing this feedback loop ensures that knowledge gained from operations flows back into the source of truth.

  • CUE: Defines what should be created and what values are allowed.
  • Generator: Maps the source of truth to the target format. Conversion rules for each format are explicitly managed.
  • Bazel: Manages which inputs execute which targets and which artifacts are produced.
  • Validation/Deployment: Sequentially checks generated differences, contract compliance, and executable artifacts.
Loading diagram...

5. Reasons for Combining CUE and Bazel

CUE is well-suited for evaluating types, values, and constraints, and for converting definitions to other formats. However, if CUE alone is made responsible for managing multi-language compilation, code generation, testing, containerization, and static file packaging as repository-wide dependencies, the responsibility of the execution foundation becomes too large.

Bazel manages a build graph consisting of inputs, rules, outputs, and dependent targets. Starting from CUE generation targets, OpenAPI generation, Go and TypeScript compilation, contract testing, and container image generation can all be placed on a single graph. This is a separation where CUE defines types, and Bazel manages the dependencies and execution of processes that use those definitions.

If the graph is accurate, only changed contracts and their reverse dependencies can be executed. Results obtained from the same inputs and rules can be cached, and independent generation and testing can proceed in parallel. Since the same BUILD definition can be shared between local and CI, problems where procedures vary by environment can also be suppressed.

Achieving reproducible builds requires not only Bazel but also fixed inputs, fixed toolchains, and the elimination of implicit dependencies on networks and time. Bazel is a foundation that makes it easier to translate these prerequisites into execution rules, and it is not magic that automatically corrects errors even if the source of truth or generator is incorrect.

  • CUE: Type definition, constraints, data structures, integration and validation of contracts.
  • Bazel: Dependencies, generation tasks, differential builds, differential tests, caching, parallel execution, artifact generation.
  • Boundary: CUE does not handle the entire build, and Bazel does not define business types or constraints as the source of truth.
// Conceptual example of a Bazel target
cue_export(
    name = "order_schema",
    srcs = ["//contracts:order.cue"],
    outs = ["order.openapi.json"],
)

go_library(
    name = "order_contract_go",
    srcs = [":generated_order_go"],
    deps = [":order_schema"],
)

go_test(
    name = "order_contract_test",
    deps = [":order_contract_go", "//test:contract_harness"],
)

6. Staging Validation in CI/CD

In CI, instead of immediately building all services, we stage the validation into contract validity, generation reproducibility, implementation conformity, and artifact viability. By failing early, we can trace the cause back to the source of truth before having to examine large amounts of code generation or container build logs.

The first stage validates CUE syntax, types, and constraints. The second stage generates schemas and code from CUE, and the third stage, after performing generation that does not dirty the working tree, confirms that there are no differences in Git-managed generated artifacts. While including generated artifacts in Git has the advantage of allowing differences to be reviewed, consistency with the source is always checked in CI.

From the fourth stage onwards, static analysis, tests according to the scope of changes, and contract tests are executed with Bazel. Contract tests verify API input/output, error formats, compatibility, DB boundaries, and MCP tool arguments and results. Conformance conditions that cannot be guaranteed by types alone, such as tenant isolation, authorization, idempotency, and duplicate registration during re-execution, are also placed close to the contract as Bazel test targets.

Finally, binaries, containers, and static files are generated, and before deployment, the target environment's settings, migration, image startup, health checks, and rollback possibility are confirmed. In operations where generated artifacts are not included in Git, CI generates them each time and saves them as artifacts. In either operation, the version of the generator and its source are fixed, and it is verified that the same input produces the same output.

    1. Validation of CUE syntax, types, and constraints
    1. Schema and code generation from CUE
    1. Verification of zero difference after regeneration
    1. Static analysis by Bazel
    1. Unit and integration tests according to the scope of changes
    1. Contract tests for API, DB, and MCP
    1. Conformance tests for tenant isolation, authorization, idempotency, etc.
    1. Generation of binaries, containers, and static files
    1. Pre-deployment configuration, startup, health check, and rollback verification
// Example to ensure generated files are not directly edited
bazel run //contracts:generate_all
git diff --exit-code -- generated/   || { echo "Please regenerate the artifacts from CUE"; exit 1; }

bazel test //contracts/changed:all   --test_output=errors

7. Compatibility with AI Agent Development: Safely Increasing Speed by Constraining Freedom

In environments where AI agents generate a large amount of code, it is more important to converge generated changes to the same contracts and validation rules than to increase the amount of implementation. Instead of letting AI freely design data models and dependencies, we make it follow CUE contracts, generator outputs, and Bazel's allowed dependency directions.

Code generated by AI passes through gates such as Bazel's static analysis, type checking, unit tests, contract tests, and conformance tests. If generated artifacts are directly modified, this is detected by the zero-difference check after regeneration. By controlling dependency directions with Bazel's visibility and target structure, changes that directly depend from the screen to internal DB implementation can be stopped before the review stage.

Changes are divided into small units, and only the changed contract and its scope of impact are diff-tested. In case of failure, it should be possible to identify which CUE contract, which transformation definition, and which Bazel target broke using logs and target labels. This allows specifying the failed boundary when asking the AI to retry, rather than just "fixing it somehow."

Even when parallel agents modify different services, they converge to common sources of truth and build rules. Instead of each agent adding individual types or exceptions, if a contract change is needed, it goes to CUE; if it's implementation-specific, it goes back to the service boundary. Constraining AI's freedom is not to slow it down, but to reduce the scope for human consistency checks later and to enable safe parallelization.

  • Scope entrusted to AI: Implementation according to contracts, testing, creation of transformation definition candidates, local fixes.
  • Scope for human judgment: Meaning of contracts, compatibility, authorization, tenant boundaries, whether to promote exceptions to the source of truth.
  • Mechanical gates: Regeneration diff, Bazel dependency direction, static analysis, diff tests, contract/conformance tests.

8. Benefits and Limitations

The benefits of this configuration are that discrepancies between specifications and implementation can be found early, and duplication of type definitions can be reduced. Having a dependency graph from contracts makes it easier to grasp the scope of change impact, and diff builds and diff tests can shorten daily feedback. Since the generation procedure and inputs are fixed, it becomes easier to explain the premises for maintenance and handover even if the person in charge changes.

On the other hand, the learning cost of CUE cannot be ignored. If used as a replacement for configuration templates without understanding the differences between unification, constraints, defaults, and concrete values, unintended integrations and undetermined values may be overlooked. Trying to model all domains completely from the beginning leads to over-engineering, so start with contracts that change frequently and are shared by multiple services.

Designing transformation rules for each generation target is also necessary. Protocol Buffers field numbers, OpenAPI nullable, JSON Schema additional properties, SQL NULLs and indexes, and MCP Tool Schema input descriptions are not determined by simple type mapping alone. It is necessary to define how much to generalize and what information to hold as format-specific extensions.

Bazel also has introduction and operational costs. BUILD definitions, rules, toolchains, remote caches, and CI permissions need to be set up, and the boundary between generated and handwritten code must also be designed. Implementation-specific circumstances that are difficult to express in CUE will also remain. If incorrect specifications are defined in the source of truth, a large amount of incorrect code will be generated. Automated generation does not eliminate the need for reviews; rather, it organizes the review targets into the source of truth, transformation rules, generation differences, and important handwritten implementations.

  • Benefits: Suppresses discrepancies between specifications and implementation, reduces duplication, and makes change impact and diff builds easier to handle.
  • Benefits: Suitable for parallel development, reproducible generation, maintenance, and handover.
  • Limitations: Requires CUE and Bazel learning/operational costs, transformation rules, and boundary design.
  • Limitations: Incorrect sources of truth increase incorrect generated artifacts, and reviews and conformance checks are still necessary after automatic generation.

9. How to Understand the Relationship with Google

It cannot be definitively stated that CUE is a language adopted company-wide by Google. The CUE language specification and introductory materials explain that CUE was influenced by Google's internal configuration management languages such as GCL and BCL. This indicates a lineage of design philosophy and does not mean that Google's internal systems can be used as is, or that the same operations are publicly available.

Representative public technologies from Google include Protocol Buffers, Bazel, Kubernetes, and CEL. Protocol Buffers are used for structured data serialization and inter-service contracts, Bazel for builds and tests, Kubernetes for managing containerized workloads, and CEL for embeddable expression evaluation. Each is a technology with a different role and should not be treated as a product integrated with CUE.

This configuration does not reproduce Google's internal configuration. It is a design that reconfigures the ideas of declarative contracts, code generation, dependency graphs, and reproducible builds for our own company, centering on CUE and Bazel. Even when adopting Protocol Buffers or Kubernetes, individual decisions are made based on organizational size, existing APIs, operational structure, and team learning costs.

10. Our Company's Adoption Policy

In our company, CUE will be the primary source of truth for domain contracts and constraints. Protocol Buffers, OpenAPI, JSON Schema, SQL, and MCP Tool Schema are derived artifacts from CUE. If additional information is required due to output format considerations, it will be explicitly defined as a transformation definition, and the practice of manually adding to generated artifacts will generally not be adopted.

Bazel will be the execution platform for generation, testing, building, and packaging. CUE validation, various schema generations, Go/TypeScript code generation, gRPC and sqlc processing, contract/conformance tests, and binary/container/static file generation will be targeted and integrated into a dependency graph that can execute only the changed scope.

Generated artifacts will generally not be manually edited. Changes will be made from CUE or explicit transformation definitions, and generation differences, dependencies, and test results will be verified by CI. Differences per customer/application will be managed by separating common and extended contracts, maintaining boundaries so that individual requirements do not unnecessarily pollute common contracts.

This adoption policy also supports future parallel development by AI agents. Even if multiple agents implement simultaneously, changes will converge to the common CUE source of truth and Bazel build rules. Our company's technical philosophy is: "Make declarations the source of truth, automate generation and verification, and safely converge with Bazel."

  • CUE: Domain contracts, types, constraints, defaults, common contracts, and extended contracts.
  • Derived artifacts: Protocol Buffers, OpenAPI, JSON Schema, SQL, MCP Tool Schema, language-specific code.
  • Bazel: Generation, testing, compilation, packaging, incremental execution, caching, parallelization.
  • CI: Regeneration from source of truth, zero difference, dependency direction, contract conformance, artifact validity.

11. Summary: Placing Specifications and Builds in a Single Dependency Graph

Designing with CUE as the source of truth is not just a mechanism to reduce the number of files. It is a design to define business contracts in one place and reproducibly derive multiple schemas and code from there, thereby detecting specification change regressions and inconsistencies in generated artifacts at an early stage.

Combining with Bazel allows treating generation from CUE, static analysis, diff testing, contract/conformance testing, and binary/container generation as processes that follow dependencies. Since only the necessary scope can be targeted for caching and parallel execution, it becomes easier to enhance development speed and robustness on the same foundation.

CUE defines "what should be built," and Bazel manages "which dependencies to follow, how much to verify/generate, and how." If this distinction can be maintained, the combination of CUE and Bazel becomes not just a tool selection, but a development infrastructure design to integrate specifications, generation, verification, and builds into a single dependency graph.

Technical documents

We will continue to increase technical documentation.

We will continue to organize our thoughts on AI, cloud, business app development, requirements definition, and operational design into documents.

Go to technical documentation list