The agent said revenue grew 12%, accounting said 4%: OpenAI and the battle at the semantic layer

The agent said revenue grew 12%, accounting said 4%: OpenAI and the battle at the semantic layer

Table of Contents

In November, the agent in Slack answers cleanly: revenue this month is up 12% versus last month. You carry that number into the meeting. The accountant opens the report, and the number is 4%.

Nobody edited a number, nobody typed anything wrong. The agent ran correctly, the query ran correctly, the warehouse did not drop a row. The 12% figure is gross revenue by order creation date, minus cancelled orders, before refunds, including unpaid orders. The 4% figure is recognized revenue by delivery date, fully netted. Both numbers are correct. One of them is answering the wrong question.

That is where OpenAI is stepping in. According to The Decoder, citing The Information, they are building an internal data platform called Athena, described as a semantic layer: a consistent definition layer for business metrics like revenue or customer count. At least one customer found that the data analysis agent in ChatGPT Work was not accurate enough. The product is early, with no timeline and no pricing.

1. The agent does not lie, it answers a different question

“Revenue” is not a concept. It is a family of concepts: gross, net, MRR, ARR, booked, recognized, collected, deferred. Each one has its own formula, and each one is correct in one context. People inside a company learn that difference over years of arguing in meeting rooms.

The agent has no such history. It has a schema.

You hand it a table with 60 columns: amt_ttl_pre_dsc, amt_net, rev_rec, created_at, status_cd. No comments, no docs, nobody to explain. The LLM reads the column names and reasons from them. amt_ttl_pre_dsc sounds like “amount total, before discount”. It writes SUM(amt_ttl_pre_dsc) and calls that revenue. The query runs in 200ms, no exception is thrown. This is the worst kind of wrong: wrong with an exit code of 0.

The problem sits in the spec, not in the model. Put GPT-5, Claude or Gemini on that same schema and you still get an educated guess back. Changing the model does not fix this, because the missing information is not inside the model.

The BIRD benchmark (NeurIPS 2023) quantifies that gap. 12,751 question-SQL pairs, 95 real databases, 33.4 GB total, spread across 37 professional domains. ChatGPT reaches 40.08% execution accuracy. Humans reach 92.96%.

40.08% sounds like a dumb model. A closer look says otherwise. BIRD names three challenges: dirty values in the database, external knowledge needed to understand the question against the data, and the efficiency of the generated SQL. The second one is not “the model is bad at writing SQL”, it is “the model is missing context that does not exist in the database”. A significant share of that 53 point gap lives right there, and no model can make up for knowledge nobody ever wrote down.

2. What a semantic layer actually is

Strip away the marketing and a semantic layer is a config file with a strict schema, plus a compiler. Four concepts are enough.

Entity is the thing and its join key. order joins customer through customer_id, declared once. Dimension is the axis you slice numbers by, time or categorical (order_date, region). Measure is the row level measurement, not yet aggregated: amount, discount_pct. Metric is an aggregated measure with a name and a definition: net_revenue = SUM(amount * (1 - discount_pct)).

The agent asks “net revenue by region in October”, the compiler emits SQL with the right join, filter and formula. The agent does not need to know which table joins which, and it has no right to know. Take the example from the Snowflake docs: gross revenue may live in the column amt_ttl_pre_dsc, while net revenue is always SUM(gross_revenue * (1 - discount)). A column name says nothing about semantics, the definition does.

With dbt Semantic Layer / MetricFlow, the semantic model is declared in YAML attached to a dbt model, covering entities (primary, foreign, unique, natural, used as join keys), dimensions (time or categorical), measures, and simple metrics. agg_time_dimension is mandatory, because without it “this month” is undefined. MetricFlow builds a semantic graph and then compiles the query into SQL.

With Cube, the agent does not query the warehouse directly. It queries the semantic layer through Semantic SQL: a Postgres-compatible interface extended with the MEASURE function. Every query goes through the runtime, gets validated against the data model, and gets deterministic access policies applied before it reaches the warehouse. Cube also has pre-aggregations: rollup tables declared in the model, refreshed in the background, stored in Cube Store. And it exposes an MCP server for agents.

The common thread: the definition lives outside the LLM, and it is enforced by code, not by instruction.

3. Three ways to implement it, two kinds of guarantee

Warehouse-native. Snowflake Semantic Views are schema level objects containing logical tables (customer, order, supplier), relationships through join keys, row level facts, metrics as aggregations of facts, dimensions as categorical. Cortex Agents read the definition and generate SQL against physical tables. Win: no extra service, no extra network hop, permissions follow the warehouse. Cost: locked to one warehouse.

External. dbt MetricFlow and Cube sit outside the warehouse, run on multiple engines, have git history and CI. Win: the definition is code, reviewable, revertible. Cost: one more system to operate, one more network hop, one more place that can drift from the real data.

Prompt. You write 300 lines of “revenue is defined as follows” into the system prompt. Popular because it is free and done in 10 minutes. Also the worst option: the model may read it, may skip it, may read it and still pick a different column because the context is long. You cannot measure the compliance rate.

The first two are deterministic: same question, same metric, same SQL. The third is probabilistic, and worse because it does not fail loudly.

flowchart TD
  Q["Question: revenue this month?"] --> P["Prompt stuffed with definitions"]
  P --> L["LLM writes SQL on its own"]
  L --> R1["Result changes between runs"]
  Q --> S["Semantic layer"]
  S --> C["Compiler over declared metrics"]
  C --> R2["Same input, same SQL"]

A semantic layer does not make the agent smarter. It makes the agent need to be less smart, and the second thing is far easier to reach.

4. Why OpenAI is stepping in: switching cost

Changing a model: edit the base URL, edit the API key, edit the model name in config. If the code already uses an OpenAI-compatible interface, that is one afternoon, and the risk is a different output format, a different tool call, a different price. A few days and you are done.

Changing a semantic layer: change the definition of the numbers for the whole company. Dashboards, board reports, ML pipelines, alerts all reference those metrics. Changing the meaning of net_revenue changes the past: last quarter’s report can no longer be compared with this one. Nobody wants to do it, so nobody does.

According to The Information, OpenAI uses Athena to build agents that collect, document and update business rules, so other agents do not have to start from scratch every time. Read that sentence closely: they are not selling the definition layer, they are selling the process of accumulating it. Every time an agent figures out “this column is actually…” and writes it down, that asset lives in Athena, not in your repo.

This is a land grab at the contract layer, not the model layer. Snowflake and Databricks already have their own semantic layers, and all three are betting on the same thing: sell a model and the customer can switch, sell a definition and they cannot.

Hyrum’s Law: with enough users, every observable behavior of a system becomes a contract, including behavior nobody wrote on purpose. A semantic layer is that law packaged as a product. You do not have to force people onto the right definition, you only have to make it the only thing that can be queried. The rest happens on its own, including the parts you did not design.

5. Three boundaries: warehouse, semantic, agent

flowchart TD
  subgraph "Warehouse"
    w_orders[("orders fact table")]
  end
  subgraph "Semantic service"
    s_reg["Registry"]
    s_comp["Compiler"]
  end
  subgraph "Agent"
    a_loop["LLM + tool loop"]
  end
  a_loop -->|"MCP: metric name + filters"| s_reg
  s_reg --> s_comp
  s_comp -->|"SQL, 2-8ms inside the VPC"| w_orders

Physical boundary: how many network hops, which hop can time out. A semantic service in-process with the agent makes the hop disappear, but you lose the ability to share definitions. Split it into its own service and you can share, in exchange for 2 to 8ms per query inside the same VPC, plus timeouts, plus retries.

Schema boundary: who owns the definition. If the warehouse team owns it, the semantic layer deploys in step with the warehouse, but the data team has to queue up. If the data team owns it, it becomes an independent service with its own SLA, but the warehouse team can change a column without telling anyone. If the platform team owns it, there is one more thing to staff 24/7.

Permission boundary: what the agent may ask. Not “the agent may read the orders table”, but “which metrics may the agent ask for, sliced by which dimensions”. This is where deterministic access policy earns its keep: a policy applied at the semantic layer blocks even the queries the agent will think of in the future.

6. Let the agent pick a metric, do not let it write SQL

The rule: the smaller the surface the agent touches, the fewer ways it can be wrong. Instead of letting the agent generate free-form SQL, expose a registry. The agent calls query_metric(name, filters, group_by), choosing from registered metrics and declared dimensions. No SELECT *, no subqueries, no improvised JOIN.

The version below is minimal, stdlib only, no external dependencies. It runs, and gofmt is clean.

package main

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"sort"
	"strings"
	"sync"
)

// Metric is one row in the registry. Expr is a warehouse side expression,
// never a whole query. Agg is the only aggregate the registry will compile.
type Metric struct {
	Name       string
	Expr       string
	Agg        string
	Dimensions []string
}

// Query is the entire surface the agent may ask: metric name, filters on
// declared dimensions, group by on declared dimensions.
type Query struct {
	Metric  string
	Filters map[string]string
	GroupBy []string
}

// Statement separates SQL from arguments. No string concatenation, no manual escaping.
type Statement struct {
	SQL     string
	Args    []any
	Version string
}

var allowedAggs = map[string]string{
	"sum":            "SUM(%s)",
	"avg":            "AVG(%s)",
	"min":            "MIN(%s)",
	"max":            "MAX(%s)",
	"count_distinct": "COUNT(DISTINCT %s)",
}

// The denylist is deliberately crude. A false positive is a column rename,
// a false negative is a production incident.
var banned = []string{
	";", "--", "/*", "*/", "union", "select", "insert", "update",
	"delete", "drop", "alter", "grant", "copy", "pg_", "information_schema",
}

func isIdent(s string) bool {
	if s == "" {
		return false
	}
	for i, r := range s {
		switch {
		case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r == '_':
		case r >= '0' && r <= '9':
			if i == 0 {
				return false
			}
		default:
			return false
		}
	}
	return true
}

// isExpr only lets through letters, digits, dots, arithmetic operators and
// parentheses. No quotes, no comments, no keywords. Needing CASE WHEN inside
// Expr means you should materialize a column, do not stuff logic into a metric
// definition.
func isExpr(s string) bool {
	depth := 0
	for _, r := range s {
		switch {
		case r == '(':
			depth++
		case r == ')':
			depth--
			if depth < 0 {
				return false
			}
		case r == ' ', r == '.', r == '_', r == '*', r == '+', r == '-', r == '/', r == '%', r == ',':
		case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
		default:
			return false
		}
	}
	return depth == 0 && strings.TrimSpace(s) != ""
}

func sourceOf(expr string) (string, error) {
	i := strings.Index(expr, ".")
	if i <= 0 {
		return "", errors.New("expr must be table.column")
	}
	table := expr[:i]
	if !isIdent(table) {
		return "", fmt.Errorf("table %q is not a valid identifier", table)
	}
	return table, nil
}

func (m Metric) Validate() error {
	if !isIdent(m.Name) {
		return fmt.Errorf("metric %q: invalid name", m.Name)
	}
	if _, ok := allowedAggs[m.Agg]; !ok {
		return fmt.Errorf("metric %q: agg %q is not supported", m.Name, m.Agg)
	}
	if !isExpr(m.Expr) {
		return fmt.Errorf("metric %q: expr contains characters outside the grammar", m.Name)
	}
	if _, err := sourceOf(m.Expr); err != nil {
		return fmt.Errorf("metric %q: %w", m.Name, err)
	}
	low := strings.ToLower(m.Expr)
	for _, b := range banned {
		if strings.Contains(low, b) {
			return fmt.Errorf("metric %q: expr contains %q", m.Name, b)
		}
	}
	seen := make(map[string]bool, len(m.Dimensions))
	for _, d := range m.Dimensions {
		if !isIdent(d) {
			return fmt.Errorf("metric %q: dimension %q is not a valid identifier", m.Name, d)
		}
		if seen[d] {
			return fmt.Errorf("metric %q: dimension %q is duplicated", m.Name, d)
		}
		seen[d] = true
	}
	return nil
}

// Version is a content hash of the definition. Change one character in Expr
// and the version changes, so an old report can still be traced back to the
// formula that produced it.
func (m Metric) Version() string {
	dims := append([]string(nil), m.Dimensions...)
	sort.Strings(dims)
	sum := sha256.Sum256([]byte(m.Name + "|" + m.Agg + "|" + m.Expr + "|" + strings.Join(dims, ",")))
	return hex.EncodeToString(sum[:])[:12]
}

type Registry struct {
	mu      sync.RWMutex
	metrics map[string]Metric
}

func NewRegistry() *Registry {
	return &Registry{metrics: make(map[string]Metric)}
}

func (r *Registry) Register(m Metric) (string, error) {
	if err := m.Validate(); err != nil {
		return "", err
	}
	r.mu.Lock()
	defer r.mu.Unlock()
	r.metrics[m.Name] = m
	return m.Version(), nil
}

func (r *Registry) Compile(ctx context.Context, q Query) (Statement, error) {
	if err := ctx.Err(); err != nil {
		return Statement{}, err
	}
	r.mu.RLock()
	m, ok := r.metrics[q.Metric]
	r.mu.RUnlock()
	if !ok {
		return Statement{}, fmt.Errorf("metric %q: not in registry", q.Metric)
	}
	declared := make(map[string]bool, len(m.Dimensions))
	for _, d := range m.Dimensions {
		declared[d] = true
	}
	for _, d := range q.GroupBy {
		if !declared[d] {
			return Statement{}, fmt.Errorf("dimension %q: not declared for metric %q", d, m.Name)
		}
	}
	keys := make([]string, 0, len(q.Filters))
	for k := range q.Filters {
		if !declared[k] {
			return Statement{}, fmt.Errorf("filter %q: not declared for metric %q", k, m.Name)
		}
		keys = append(keys, k)
	}
	sort.Strings(keys)
	where := make([]string, 0, len(keys))
	args := make([]any, 0, len(keys))
	for i, k := range keys {
		where = append(where, fmt.Sprintf("%s = $%d", k, i+1))
		args = append(args, q.Filters[k])
	}
	src, err := sourceOf(m.Expr)
	if err != nil {
		return Statement{}, fmt.Errorf("metric %q: %w", m.Name, err)
	}
	selects := append([]string(nil), q.GroupBy...)
	selects = append(selects, fmt.Sprintf(allowedAggs[m.Agg], m.Expr)+" AS "+m.Name)
	sql := "SELECT " + strings.Join(selects, ", ") + " FROM " + src
	if len(where) > 0 {
		sql += " WHERE " + strings.Join(where, " AND ")
	}
	if len(q.GroupBy) > 0 {
		sql += " GROUP BY " + strings.Join(q.GroupBy, ", ")
		sql += " ORDER BY " + strings.Join(q.GroupBy, ", ")
	}
	return Statement{SQL: sql, Args: args, Version: m.Version()}, nil
}

// ToolSpec describes the registry in MCP format. The agent only sees metric
// names and dimensions, never Expr, never the SQL dialect underneath.
func (r *Registry) ToolSpec() string {
	r.mu.RLock()
	defer r.mu.RUnlock()
	names := make([]string, 0, len(r.metrics))
	dims := make(map[string]bool)
	for name, m := range r.metrics {
		names = append(names, name)
		for _, d := range m.Dimensions {
			dims[d] = true
		}
	}
	sort.Strings(names)
	enum := make([]string, len(names))
	for i, n := range names {
		enum[i] = fmt.Sprintf("%q", n)
	}
	dimEnum := make([]string, 0, len(dims))
	for d := range dims {
		dimEnum = append(dimEnum, fmt.Sprintf("%q", d))
	}
	sort.Strings(dimEnum)
	return fmt.Sprintf(
		`{"name":"query_metric","description":"Run a registered metric, never raw SQL","inputSchema":{"type":"object","properties":{"metric":{"type":"string","enum":[%s]},"group_by":{"type":"array","items":{"type":"string","enum":[%s]}}},"required":["metric"]}}`,
		strings.Join(enum, ","), strings.Join(dimEnum, ","),
	)
}

func main() {
	reg := NewRegistry()
	gross := Metric{
		Name:       "gross_revenue",
		Expr:       "orders.amt_ttl_pre_dsc",
		Agg:        "sum",
		Dimensions: []string{"order_date", "region"},
	}
	net := Metric{
		Name:       "net_revenue",
		Expr:       "orders.amt_ttl_pre_dsc * (1 - orders.dsc_pct)",
		Agg:        "sum",
		Dimensions: []string{"order_date", "region"},
	}
	for _, m := range []Metric{gross, net} {
		v, err := reg.Register(m)
		if err != nil {
			fmt.Println("register:", err)
			continue
		}
		fmt.Printf("registered %-14s version=%s\n", m.Name, v)
	}

	// Expr with a subquery, sent from somewhere: blocked at validate, never
	// reaches the warehouse.
	bad := Metric{Name: "revenue_guess", Expr: "orders.amt (SELECT 1)", Agg: "sum"}
	if _, err := reg.Register(bad); err != nil {
		fmt.Println("rejected:", err)
	}

	st, err := reg.Compile(context.Background(), Query{
		Metric:  "net_revenue",
		Filters: map[string]string{"region": "hcm"},
		GroupBy: []string{"order_date"},
	})
	if err != nil {
		fmt.Println("compile:", err)
		return
	}
	fmt.Println("sql:", st.SQL)
	fmt.Println("args:", st.Args, "version:", st.Version)

	// Same input, same output. No LLM in between.
	again, _ := reg.Compile(context.Background(), Query{
		Metric:  "net_revenue",
		Filters: map[string]string{"region": "hcm"},
		GroupBy: []string{"order_date"},
	})
	fmt.Println("stable:", again.SQL == st.SQL)
	fmt.Println("tool:", reg.ToolSpec())
}

isExpr only lets through letters, digits, dots, arithmetic operators and parentheses. Needing CASE WHEN inside Expr means you should materialize a column, do not stuff logic into a metric definition. The smaller the grammar, the fewer ways the agent can go wrong, and compile errors are far easier to read than a 200 line query that still runs.

sourceOf pulls the table out of Expr itself (orders.amt_ttl_pre_dsc means FROM orders), so the agent cannot pass a table name and cannot change the data source. Dropping a parameter from the API entirely is cheaper than validating it.

Compile emits $1, $2 placeholders and returns Args separately, so filter values never touch the SQL text. Version is the sha256 of name|agg|expr|dims: change one character in the formula and the version changes, and you log it with every result. ToolSpec exposes only metric names and dimensions, never Expr, table names or dialect.

Output when run (tool spec line trimmed):

registered gross_revenue  version=0cabbe11c4bf
registered net_revenue    version=a61fc0084165
rejected: metric "revenue_guess": expr contains "select"
sql: SELECT order_date, SUM(orders.amt_ttl_pre_dsc * (1 - orders.dsc_pct)) AS net_revenue FROM orders WHERE region = $1 GROUP BY order_date ORDER BY order_date
args: [hcm] version: a61fc0084165
stable: true

The rejected line is the most important part: an Expr with a subquery gets blocked before it reaches the warehouse. The agent does not “write SQL” in any sense, it picks a metric and passes arguments.

This code has no join graph, no time grain, no lineage. It is enough to make the point: the hard part is not the code, it is getting three departments to agree on what net_revenue means.

7. The price of a single definition

You have a second schema to maintain. The warehouse schema changes, the semantic model has to follow. Every column rename is a red CI run, and that is the good case. The bad case is a column that does not get renamed, only redefined: amount goes from pre-tax to post-tax. No test catches that, only users do.

It becomes a people bottleneck. Conway’s Law does not ask your opinion: org structure crawls into metric structure. Three departments with three revenue definitions give you two endings. One person owns it, the other two are annoyed. Or three parallel metrics (revenue, revenue_v2, revenue_finance) and the agent is guessing again. The latter is worse than before you built the semantic layer, because now there is one more layer to be wrong in.

Drift between the definition and the real data. The semantic model says dsc_pct runs from 0 to 1. In reality 0.15% of rows store 15 instead of 0.15 because of one import from an old system, and nobody notices until a report is off by 100x. The semantic layer does not create that bug, but it makes the bug harder to see, because everyone trusts that the definition is already right.

Pre-aggregation makes numbers stale. Cube refreshes rollups in the background, which is great for dashboards. For an agent asking about 10 minutes ago, the number may be 15 minutes old and nobody told it. You have to decide which metrics may lag, by how much, and whether the agent needs to know. The right answer is yes, and it has to be in the response.

The political cost of “a single definition”. All three departments are right in their own way: Finance needs recognized, Sales needs booked, Product needs activated. No definition is wrong, a single definition is just not enough. A good semantic layer does not merge three into one, it names all three and says exactly where they differ. Merging carelessly is the fastest way to lose trust, and no compiler rescues trust that is already gone.

Tip

Do not build a semantic layer when you have fewer than 30 to 50 metrics. A YAML file in the repo, one CI job validating the schema, one 200 line compiler is enough. Your problem at that point is naming discipline, not infrastructure.

8. Measure execution accuracy, do not measure vibes

The most common way to measure is to open a chat, ask a few questions, and call it done when the answer “sounds reasonable”. That measures exactly one thing: the model’s prose ability. What you need to measure is execution accuracy: run the SQL the agent generated against the real database, compare the result with a human written reference query, and only count it correct if the whole result set matches. BIRD does exactly that, which is why the 40.08% number is worth trusting.

Golden question set. A few hundred real questions, written by real users, with reference queries and verified results. Do not invent test questions yourself, because you will unconsciously write easy ones. Tag each question with the metric it uses.

A harness that runs in CI. Every time the semantic model changes, run the whole set. Report two numbers: overall execution accuracy and the delta per metric. A metric that drops 5 points means someone just changed its definition.

Shadow mode. Run the agent in parallel with the old reports for a few weeks, show it to nobody, only log it. Every mismatch is a definition nobody wrote down. The cheapest way to find business rules nobody ever told you.

Canary per metric, and log every query. Turn a new metric on for 5% of traffic first. Log every SQL the agent generates, along with the metric version. When an incident hits, you need to be able to answer “what exactly did the agent run at 14:03 that day”.

BIRD is heading the same way. In its November 9, 2026 update, BIRD describes LiveSQLBench 2.0 in development, extending evaluation to “understanding business context and semantic modeling: how agents extract and reconcile business knowledge from documents, wikis and historical queries, anchor it to the database schema, then build and validate reusable semantic models”. Read that line next to BIRD 2023 and the shift shows: from “writing correct SQL” to “understanding the correct definition”.

After a semantic layer, the agent answers: net revenue for November, recognized by delivery date, refunds deducted, version a61fc0084165. The number matches accounting. You still have to check, because this is the first time it answered a hard question right.

The question I want to leave you with: in your system, which metric has three definitions and nobody knows which one is winning? If you can answer that right now, you do not need Athena yet. If you have to open three dashboards to check, you have needed it for a long time.

Share :

Related Posts

From KISS and SOLID to Idempotency: Demystifying Classic Software Engineering Terms for Go Backend

From KISS and SOLID to Idempotency: Demystifying Classic Software Engineering Terms for Go Backend

If you have ever sat through a backend interview or a technical design session for a new service, you know the feeling: the room quickly descends into buzzword bingo. Acronyms fly from every direction: KISS, DRY, YAGNI, the five letters of SOLID, quickly followed by Idempotency, Backpressure, and Circuit Breaker.

Read More
Hyrum's Law in Go: When an Error String Becomes an Immutable API Contract

Hyrum's Law in Go: When an Error String Becomes an Immutable API Contract

Some comments in the Go standard library make you close the laptop for a minute. Not because they are hard to understand, but because they are brutally honest about something most of us prefer to ignore.

Read More
MCP and 40 Years of Distributed Systems: When AI Agents Repeat the RPC Mistakes

MCP and 40 Years of Distributed Systems: When AI Agents Repeat the RPC Mistakes

In late July 2025, Julien Simon published an argument nobody in the AI tooling bubble wanted to hear: the Model Context Protocol ignores forty years of hard-won distributed systems lessons. The Hacker News thread pulled 409 points and 227 comments. Most people agreed, a few pushed back, and nearly everyone missed the detail that actually matters: MCP is not a new protocol. It is JSON-RPC 2.0, which makes it a grandchild of Sun RPC from 1984.

Read More