← Back to Technical blog

Technical article

Why AI Analytics Must Govern Metrics First: HQL and a Headless Semantic Layer

How a metrics layer uses HQL to govern definitions, permissions, and lineage, then serves trusted context to ChatBI, Data Agents, and business systems through Headless interfaces.

Aug 26, 2026Technical blogHENGSHI8 min read
HQLMetrics LayerHeadless BIChatBIData Agent

Article body

Full article

Finance may calculate revenue from invoices, sales from signed contracts, and operations from collected cash. If ChatBI only sees column names when a user asks, “What was revenue this month?”, it may choose the most similar field and generate valid SQL. A metric definition is what makes the business meaning correct.

A Metric Is an Executable Contract

An enterprise needs to record a metric’s name, calculation, time grain, supported dimensions, data source, owner, and permissions. HQL expresses aggregation, calculation, time, and filter logic in terms close to analytical semantics. An analyst defines “active customer count” once, and dashboards, APIs, and agents refer to the same metric object. If a source table changes, the platform can update the metric implementation while consumers retain a stable name.

The metrics layer also manages synonyms and ambiguity. When business users say “revenue,” “sales revenue,” or another local term, the system matches candidate metrics and narrows them by department, application, and current context. If ambiguity remains, the agent should show the definitions and ask the user to choose before executing a query.

Metric metadata can describe the contract:

name: paid_customer_count
display_name: Paid Customer Count
description: Distinct customers who completed a payment during the period
owner: Sales Operations Data Team
dimensions:
  - region
  - product_line
  - order_date
aliases:
  - paying customers
  - converted customers
permission_policy: sales_metrics_read

This YAML is a metric metadata example. HQL supplies the calculation expression within that contract.

HQL Provides Governed Analytical Freedom

SQL targets tables and columns. HQL targets fields, dimensions, and measures in an analytical model. Users can combine metrics, dimensions, filters, and time windows, and the platform passes the expression to its query engine. Governance can then check dimension compatibility, permissions, and metric dependencies.

A basic aggregation uses a field reference:

SUM({order_amount})

Conditional aggregation makes the business state explicit:

SUM(
  CASE
    WHEN {order_status} = 'completed' THEN {order_amount}
    ELSE 0
  END
)

Active customer count can use a distinct count:

COUNTD(
  CASE
    WHEN {activity_status} = 'active' THEN {customer_id}
  END
)

A monthly revenue view combines the measure SUM({order_amount}) with the month dimension MONTH({order_date}) in a chart or query request. They remain separate HQL expressions; the chart or query defines the grouping instead of embedding it in the measure formula.

Rolling and comparative calculations can use windows. Exact functions and frame boundaries should follow the HQL reference for the deployed version:

AVG(SUM({order_amount})) OVER (
  ORDER BY {order_date}
  ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
)

These expressions still operate inside a specific dataset and permission context. HQL does not replace metric metadata, the data model, or approvals.

Time Semantics Belong in One Place

Year-over-year, month-over-month, rolling seven days, and fiscal year to date all depend on calendar rules. Results become hard to verify when natural month, fiscal month, time zone, backfill policy, and incomplete-period handling are reinvented in each conversation. Teams should place those rules in governed metric definitions and time dimensions, then let agents select existing objects.

A query result should also carry the metric version, data refresh time, filters, date range, and permission principal. The user receives both a number and the definition under which it was calculated.

A Headless Semantic Layer Serves Multiple Entry Points

Enterprise data reaches users through BI portals, CRM, supply-chain systems, mobile applications, APIs, and agents. A Headless semantic layer gives each entry point the same metrics, permissions, and query capabilities through APIs and CLI. Interfaces can change while business definitions remain stable.

ConsumerSemantic-layer capabilityContext to preserve
Dashboards and reportsMetrics, dimensions, filters, formattingMetric version, refresh time
ChatBICandidate metrics, synonyms, query planUser, session, permissions
Data AgentQuery, modeling, and resource-operation contractsPlan, approval, tool receipts
Business-system APIStable metrics and data servicesTenant, application, caller

This architecture also fits ISVs. A software vendor can encode industry metrics in its own product while customers call the same semantic layer through embedded dashboards, ChatBI, or workflows. The ISV controls user experience, and the platform handles calculation, permissions, and governance.

Semantic Context for AI

An agent does not need the complete database schema. It can retrieve a permission-filtered metric catalog first:

{
  "name": "revenue",
  "displayName": "Operating Revenue",
  "definition": "Sum of tax-inclusive amounts for recognized-revenue orders",
  "dimensions": ["region", "product_line", "order_date"],
  "aliases": ["sales revenue", "recognized revenue"],
  "dataType": "currency",
  "owner": "Finance Data Team"
}

When a user asks, “How much did we sell yesterday?”, the agent can offer “operating revenue,” “order count,” and “units sold” as candidates. It generates a query plan only after the user confirms the intended metric. Bounded candidates and explicit clarification are more reliable than guessing a column.

Start With Ten Metrics

Metric governance does not need to cover the entire company at once. A team can choose one operational domain, define ten high-frequency metrics, and complete ownership, definitions, dimensions, time, and permissions. ChatBI can initially answer questions only inside that trusted area.

A compact rollout has four steps:

  1. Review common questions and select ten metrics tied to business decisions.
  2. Ask business and data owners to confirm definitions, dimensions, and calendar rules.
  3. Implement calculations in HQL and compare them with historical reports.
  4. Expose the same metric objects to dashboards, APIs, and agents, then record ambiguity and failed queries.

Each correction should update the metric catalog. As the trusted area grows, agents can take on more analytical and execution tasks.

Quality Checks

CheckRuleResponse
NamingIdentifiers remain stable and portable across environmentsBlock invalid names before publication
Definition conflictSynonymous metrics should not hide different definitionsEscalate to the metric owner
Circular dependencyMetric references must form an acyclic graphBlock publication
Null and division by zeroExpressions define exceptional behaviorAdd explicit conditions or defaults
Data freshnessRefresh time and delay are declaredDisplay freshness to consumers
PermissionsMetric, dimension, and row permissions remain consistentRun multi-role regression tests

Sources and Verification

HENGSHI SENSE

Resources, ecosystem, and implementation stories

Explore how teams design and ship analytics with HENGSHI.

Request a trial

Enterprise deployment, embedded delivery, and trial requests can all be handled quickly.