Skip to content
All articles

How AVA Uses OSI to Align Dashboard and AI Agent Metrics

Use a coffee retailer’s orders and refunds to define shared business metrics and verify the results in SQL.

At the monthly business review, the BI dashboard reports ¥5,000 in net sales and puts the Mini Program Store at the top of the refund-rate ranking, at 20%. A colleague asks the AI agent the same question. It reports ¥6,700 in net sales, puts the Tmall Flagship Store at the top with a 16.67% refund rate, and ranks the Douyin Shop ahead of the Mini Program Store in net sales.

Net sales differ by 34%. The two answers also point to different channels to investigate first and disagree about which channel ranks second in net sales.

Both queries can run successfully. The difference comes from business rules the agent could only guess at from the table definitions and a few prompt instructions. The dashboard already knows which orders count, which date determines the reporting month, and how to handle multiple refunds for one order.

AntV AVA is an open-source data analysis and visualization framework for JavaScript applications and AI agents. It connects to data sources, provides the agent with data structure, statistics, and business definitions, and runs queries through an execution engine. AVA business semantics documentation

AVA's model structure is based on the Open Semantic Interchange (OSI) specification for exchanging semantic definitions. The project entered the Apache Incubator under the name Apache Ossie (incubating) and publishes the YAML format used here to record the business rules. Apache Ossie project announcement

The dashboard and the agent can work from the same definitions. With DuckDB, both can use the same API to run SQL.

text
Apache Ossie YAML → parse to an object → ava.semantic() → query generation context
 
AI agent   Natural language + query context → ava.translate() → generated SQL
Dashboard  Fixed configuration → SQL reviewed against the business rules
 
Both can call ava.query(SQL) → query engine → data source and results
  1. Business teams can review the rules. The YAML records how each metric is defined, which records count, and how to assign them to a reporting period.
  2. Applications can validate the definitions and run queries. The Ossie JSON Schema checks the document structure. When AVA saves a definition, it checks the object structure, duplicate names, and references in keys and relationships. The engine runs SQL that implements the rules.
  3. Readers can verify the results. An application can keep the metric definitions and the SQL it actually ran, so readers can trace the figures back to the underlying rows and recompute them.

The example below uses eight orders. You can check every result by hand.


Eight orders reveal four ways business metrics can disagree

Suppose we are analyzing online sales for Qingbei Coffee, a specialty coffee brand. Its warehouse has three tables. All amounts are in Chinese yuan.

1. Channel dimension table analytics.dim_channels (one row per channel)

channel_idchannel_namechannel_group
ch_miniMini Program StoreDirect sales
ch_tmallTmall Flagship StoreThird-party marketplace
ch_douyinDouyin ShopThird-party marketplace

2. Order fact table analytics.dwd_orders (one row per order)

order_idchannel_idcreated_atpaid_atorder_statusis_test_ordergross_amountdiscount_amountshipping_fee
O001ch_mini04-02 10:0004-02 10:05paidfalse100010020
O002ch_mini03-31 23:5504-01 00:05paidfalse60000
O003ch_tmall04-10 14:0004-10 14:02paidfalse20002000
O004ch_tmall04-28 20:0004-28 20:10paidfalse1200015
O005ch_mini04-15 09:0004-15 09:01paidtrue50000
O006ch_douyin04-18 16:00NULLcancelledfalse8001000
O007ch_douyin04-20 11:0004-20 11:05paidfalse1000010
O008ch_douyin04-30 23:5005-01 00:03paidfalse50000

All dates are in 2026.

3. Refund fact table analytics.dwd_refunds (one row per refund, with multiple partial refunds possible per order)

refund_idorder_idrefunded_atrefund_statusrefund_amount
R001O00104-04 12:00completed100
R002O00104-06 15:30completed200
R003O00304-12 09:00pending300
R004O00405-02 10:00completed200

Ask a question a sales team might need to answer. “What were paid merchandise sales, net sales, and the refund rate by channel in April 2026?”

Given just the three table definitions, a text-to-SQL agent might produce this query.

sql
SELECT
  c.channel_name,
  SUM(o.gross_amount - o.discount_amount) AS paid_gmv,
  SUM(o.gross_amount - o.discount_amount) - SUM(COALESCE(r.refund_amount, 0)) AS net_revenue,
  SUM(COALESCE(r.refund_amount, 0)) * 1.0 / SUM(o.gross_amount - o.discount_amount) AS refund_rate
FROM analytics.dwd_orders o
JOIN analytics.dim_channels c ON o.channel_id = c.channel_id
LEFT JOIN analytics.dwd_refunds r ON o.order_id = r.order_id
WHERE o.created_at >= '2026-04-01' AND o.created_at < '2026-05-01'
GROUP BY c.channel_name;

Compare its results with the dashboard's business rules and you get the mismatch from the review meeting. Both versions calculate the overall refund rate by dividing total refunds by total paid merchandise sales.

ChannelPaid merchandise sales (dashboard / agent)Net sales (dashboard / agent)Refund rate (dashboard / agent)
Tmall Flagship Store3,000 / 3,0002,800 / 2,5006.67% / 16.67%
Mini Program Store1,500 / 2,3001,200 / 2,00020.00% / 13.04%
Douyin Shop1,000 / 2,2001,000 / 2,2000.00% / 0.00%
All channels5,500 / 7,5005,000 / 6,7009.09% / 10.67%
  1. Grain and join fan-out. One order can have many refunds. Order O001 has two partial refunds, R001 and R002. A direct LEFT JOIN repeats the ¥900 order amount in two rows, inflating paid merchandise sales by ¥900. Combined with the test order and the date filter, this drops the Mini Program Store's refund rate from 20.00% to 13.04%.
  2. Which records and amounts count. Count orders with order_status = 'paid' and is_test_order = false, and refunds with refund_status = 'completed'. Calculate paid merchandise sales as gross_amount - discount_amount, excluding shipping_fee. The agent's query includes test order O005, cancelled order O006, and pending refund R003.
  3. Which date defines the reporting month. Use payment time, paid_at. Order O002 was placed on March 31 and paid on April 1, so it belongs to April. Order O008 was placed on April 30 and paid on May 1, so it belongs to May. Order O004 was paid on April 28 and refund R004 was completed on May 2. Include the refund in April when measuring the performance of April's paid orders. This keeps the numerator and denominator tied to the same orders.
  4. Join paths and missing values. The Douyin Shop's valid order O007 has no refund rows. After the LEFT JOIN, coalesce the missing refund amount to zero before subtracting it. When a period has no valid orders, protect the average order value and refund-rate calculations from a zero denominator.

You could put all four rules in a system prompt. As metrics and status codes change, the same rules would still need to be updated in dashboard SQL, warehouse scripts, and every relevant agent prompt. A shared semantic model gives the team one place to review the definitions and makes them easier to validate.


Put the rules in an Apache Ossie semantic model

The Qingbei Coffee example uses the Apache Ossie 0.3.0.dev0 development specification. Core specification · JSON Schema

One Ossie YAML document describes one semantic model. It records where the data comes from, what each row represents, how datasets relate, and how to calculate metrics. Apache Ossie

  • Semantic model. At the document root, version identifies the specification version, name identifies the model, and datasets contains at least one dataset. This model is named qingbei_coffee_sales. Relationships and model-scoped metrics also appear at the root.
  • Datasets. datasets describes business entities such as orders, refunds, and channels. A dataset's source points to an underlying table, view, or query. For example, orders reads analytics.dwd_orders, and primary_key: [order_id] identifies each order row.
  • Fields. fields defines row-level attributes for grouping, filtering, and calculating metrics. The order_status field reads a source column, and paid_goods_amount uses expression.sql to calculate the amount paid for merchandise on one order.
  • Metrics. metrics defines calculations such as sums, averages, and ratios. The orders dataset defines paid_gmv to sum the merchandise amounts from valid paid orders. At the model root, net_revenue uses AGG(dataset.metric) to reference metrics from the orders and refunds datasets.
  • Dimensions. Dimensions give you ways to group or filter the data, such as by channel and time. Use channels.channel_name to group by channel. On orders.paid_at, dimension.is_time: true marks the field as a time dimension.
  • Relationships. relationships declares many-to-one links. from identifies the many side and to identifies the one side. from_columns and to_columns pair their fields in order. Multiple refund rows can use order_id to link to the same order.

Models, datasets, fields, metrics, and relationships can carry ai_context. Use instructions for usage guidance, synonyms for the terms people use, and examples for common questions or field values. That gives the agent more context when generating a query.

This excerpt shows how net_revenue references paid merchandise sales and completed refunds.

yaml
# Excerpt showing how a model-scoped metric references dataset-scoped metrics
datasets:
  - name: orders
    source: analytics.dwd_orders
    primary_key: [order_id]
    metrics:
      - name: paid_gmv
        datatype: Decimal
        expression:
          sql: COALESCE(SUM(CASE WHEN order_status = 'paid' AND NOT is_test_order THEN paid_goods_amount ELSE 0 END), 0)
  - name: refunds
    source: analytics.dwd_refunds
    primary_key: [refund_id]
    metrics:
      - name: completed_refund_amount
        datatype: Decimal
        expression:
          sql: COALESCE(SUM(CASE WHEN refund_status = 'completed' THEN refund_amount ELSE 0 END), 0)
 
metrics:
  - name: net_revenue
    datatype: Decimal
    expression:
      sql: AGG(orders.paid_gmv) - COALESCE(AGG(refunds.completed_refund_amount), 0)

The full model includes all fields, dimensions, relationships, six metrics, and the ai_context used in the example.

Show the full Apache Ossie 0.3.0.dev0 YAML for qingbei_coffee_sales
yaml
version: "0.3.0.dev0"
name: qingbei_coffee_sales
description: >
  Semantic model for online sales and refunds at Qingbei Coffee.
  Defines paid merchandise sales, average order value, completed refunds, net sales, and the refund rate for dashboards and AI agents.
ai_context:
  instructions: >
    1. Filter sales and order quality by orders.paid_at (payment time) by default, unless the user explicitly asks for order time or refund time.
    2. Attribute net sales and the refund rate to the order's payment period. Include all completed refunds for valid orders paid in that period, even if the refund completes in a later month.
    3. A valid order has order_status = 'paid' and is_test_order = false.
       Apply these conditions in the SQL and use the same valid orders when joining refunds.
  synonyms:
    - Qingbei Coffee sales model
    - Omnichannel online sales model
    - Sales and refunds model
  examples:
    - What were paid merchandise sales, average order value, net sales, and the refund rate by channel in April 2026?
    - Compare net sales and refund rates for direct sales and third-party marketplaces in April 2026.
 
datasets:
  - name: channels
    source: analytics.dim_channels
    primary_key:
      - channel_id
    description: Online channel dimension table with one row per sales channel and its channel group.
    ai_context:
      instructions: Use the orders_to_channels relationship to group sales and refunds by channel or channel group.
      synonyms:
        - Channel dimension
        - Sales channel table
      examples:
        - Break down April net sales by channel.
        - Compare refund rates for direct sales and third-party marketplaces.
    fields:
      - name: channel_id
        expression:
          sql: channel_id
        datatype: String
        description: Unique sales channel ID (primary key).
        dimension:
          is_time: false
      - name: channel_name
        expression:
          sql: channel_name
        datatype: String
        description: Channel display name, such as Mini Program Store, Tmall Flagship Store, or Douyin Shop.
        dimension:
          is_time: false
        ai_context:
          instructions: Group or filter by channel_name when the user asks for a channel breakdown or names a particular store.
          synonyms:
            - Channel
            - Channel name
            - Store channel
          examples:
            - Mini Program Store
            - Tmall Flagship Store
            - Douyin Shop
      - name: channel_group
        expression:
          sql: channel_group
        datatype: String
        description: Channel group, either Direct sales or Third-party marketplace.
        dimension:
          is_time: false
        ai_context:
          instructions: Group or filter by channel_group when comparing direct sales with third-party marketplaces.
          synonyms:
            - Channel group
            - Channel type
            - Marketplace classification
          examples:
            - Direct sales
            - Third-party marketplace
 
  - name: orders
    source: analytics.dwd_orders
    primary_key:
      - order_id
    description: Online order fact table with one row per order, including order and payment times, status, and amounts.
    ai_context:
      instructions: >
        This dataset has one row per order. Joining directly to refund rows and summing repeats the order amount when an order has multiple partial refunds.
        Aggregate order amounts and refund amounts separately when applying the model-level definitions for net sales and refund rate.
      synonyms:
        - Orders table
        - Order details
        - Sales order fact table
      examples:
        - Show valid paid orders and paid merchandise sales by channel in April 2026.
        - Show April average order value by channel.
    fields:
      - name: order_id
        expression:
          sql: order_id
        datatype: String
        description: Unique order ID (primary key).
        dimension:
          is_time: false
      - name: channel_id
        expression:
          sql: channel_id
        datatype: String
        description: Sales channel ID for the order, which references channels.channel_id.
        dimension:
          is_time: false
      - name: created_at
        expression:
          sql: created_at
        datatype: DateTime
        description: Time the customer placed the order.
        dimension:
          is_time: true
        ai_context:
          instructions: Use only when the user asks to report by order creation time. Use paid_at for standard sales, GMV, and net sales analysis.
          synonyms:
            - Order creation time
            - Order placement time
          examples:
            - Count April orders by the time they were placed.
      - name: paid_at
        expression:
          sql: paid_at
        datatype: DateTime
        description: Payment completion time. Unpaid and cancelled orders have NULL.
        dimension:
          is_time: true
        ai_context:
          instructions: Default date for sales, average order value, net sales, and refund rate. For a month, use an inclusive start and exclusive end, such as >= '2026-04-01 00:00:00' and < '2026-05-01 00:00:00'.
          synonyms:
            - Payment time
            - Payment completion time
            - Paid date
          examples:
            - Net sales by channel in April 2026.
            - Paid merchandise sales from April 1 to April 30, 2026.
      - name: order_status
        expression:
          sql: order_status
        datatype: String
        description: Order status, with values paid, unpaid, and cancelled.
        dimension:
          is_time: false
        ai_context:
          instructions: Order metrics use order_status = 'paid'. Apply the same condition to valid order details and refunds for those orders.
          synonyms:
            - Order status
            - Payment status
          examples:
            - paid
            - unpaid
            - cancelled
      - name: is_test_order
        expression:
          sql: is_test_order
        datatype: Boolean
        description: Internal test order flag. True indicates a test order and false indicates a customer order.
        dimension:
          is_time: false
        ai_context:
          instructions: Exclude records with is_test_order = true from business reporting.
          synonyms:
            - Test order flag
            - Is test order
          examples:
            - "false"
            - "true"
      - name: gross_amount
        expression:
          sql: gross_amount
        datatype: Decimal
        description: Total list price of merchandise in the order in yuan before discounts, excluding shipping.
      - name: discount_amount
        expression:
          sql: discount_amount
        datatype: Decimal
        description: Total amount of order discounts, coupons, and other promotions in yuan.
      - name: shipping_fee
        expression:
          sql: shipping_fee
        datatype: Decimal
        description: Shipping charge paid by the customer in yuan. Paid merchandise sales exclude this amount.
      - name: paid_goods_amount
        expression:
          sql: gross_amount - discount_amount
        datatype: Decimal
        description: Amount paid for merchandise on one order in yuan, calculated as list price minus discounts and excluding shipping.
    metrics:
      - name: paid_order_count
        description: Count of distinct paid orders with order_status = 'paid' and is_test_order = false.
        datatype: Integer
        expression:
          sql: COUNT(DISTINCT CASE WHEN order_status = 'paid' AND NOT is_test_order THEN order_id END)
        ai_context:
          instructions: Use orders.paid_at for the reporting period by default. Exclude cancelled and test orders.
          synonyms:
            - Valid paid order count
            - Paid orders
            - Valid order volume
            - Completed order count
          examples:
            - How many valid paid orders did each channel have in April 2026?
            - How many paid orders did the Mini Program Store have in April?
      - name: paid_gmv
        description: Total merchandise list price minus discounts in yuan for valid paid orders, before refunds and excluding shipping.
        datatype: Decimal
        expression:
          sql: COALESCE(SUM(CASE WHEN order_status = 'paid' AND NOT is_test_order THEN paid_goods_amount ELSE 0 END), 0)
        ai_context:
          instructions: Use for paid sales or sales before refunds. Filter on orders.paid_at by default. Use the model-level net_revenue metric for net sales.
          synonyms:
            - Paid merchandise sales
            - Paid sales
            - Paid merchandise value
            - Paid GMV
          examples:
            - What were paid merchandise sales by channel in April 2026?
            - What was the total paid GMV across all channels in April?
      - name: avg_order_value
        description: Paid merchandise sales (paid_gmv) divided by the valid paid order count (paid_order_count), in yuan per order. Returns NULL when there are no valid orders.
        datatype: Decimal
        expression:
          sql: >
            COALESCE(SUM(CASE WHEN order_status = 'paid' AND NOT is_test_order THEN paid_goods_amount ELSE 0 END), 0)
            / NULLIF(COUNT(DISTINCT CASE WHEN order_status = 'paid' AND NOT is_test_order THEN order_id END), 0)
        ai_context:
          instructions: Use for the average amount paid for merchandise on one valid order. The formula handles a zero denominator.
          synonyms:
            - Average valid order value
            - Average order value
            - Average paid amount per order
            - AOV
          examples:
            - Which channel had the highest average order value in April 2026?
            - Show the average paid amount per order for each channel in April.
 
  - name: refunds
    source: analytics.dwd_refunds
    primary_key:
      - refund_id
    description: Refund fact table with one row per refund. An order can have multiple partial refunds.
    ai_context:
      instructions: >
        This dataset has a many-to-one relationship to orders (refunds.order_id -> orders.order_id).
        Include refunds with refund_status = 'completed'. Pending and rejected refunds are excluded.
      synonyms:
        - Refunds table
        - Customer refund records
      examples:
        - What was the completed refund amount for orders paid in April 2026?
    fields:
      - name: refund_id
        expression:
          sql: refund_id
        datatype: String
        description: Unique refund ID (primary key).
        dimension:
          is_time: false
      - name: order_id
        expression:
          sql: order_id
        datatype: String
        description: Original order ID, a foreign key to orders.order_id.
        dimension:
          is_time: false
      - name: refunded_at
        expression:
          sql: refunded_at
        datatype: DateTime
        description: Refund processing time. For a completed refund, this is when the payment was sent.
        dimension:
          is_time: true
        ai_context:
          instructions: Use refund time when the user asks about actual cash outflows by refund date. For a month's order net sales or refund rate, filter orders.paid_at.
          synonyms:
            - Refund time
            - Refund completion time
          examples:
            - How much was refunded in May based on refund completion date?
      - name: refund_status
        expression:
          sql: refund_status
        datatype: String
        description: Refund status, with values completed, pending, and rejected.
        dimension:
          is_time: false
        ai_context:
          instructions: Refund metrics include refund_status = 'completed'. Pending and rejected refunds do not reduce net sales.
          synonyms:
            - Refund status
            - After-sales status
          examples:
            - completed
            - pending
            - rejected
      - name: refund_amount
        expression:
          sql: refund_amount
        datatype: Decimal
        description: Merchandise refund amount in yuan for one refund record.
    metrics:
      - name: completed_refund_amount
        description: Total merchandise refunds in yuan where refund_status = 'completed'. Pending and rejected refunds are excluded. An empty result contributes zero.
        datatype: Decimal
        expression:
          sql: COALESCE(SUM(CASE WHEN refund_status = 'completed' THEN refund_amount ELSE 0 END), 0)
        ai_context:
          instructions: When grouping by order dimensions or filtering on orders.paid_at, include all completed refunds for that set of valid orders, including refunds completed in a later month. Treat groups with no refunds as zero.
          synonyms:
            - Completed refund amount
            - Eligible refund amount
            - Refund amount
            - Actual refunds
          examples:
            - What were completed refunds by channel for orders paid in April 2026?
            - How much was refunded for the Mini Program Store's April orders?
 
relationships:
  - name: orders_to_channels
    from: orders
    to: channels
    from_columns:
      - channel_id
    to_columns:
      - channel_id
    ai_context:
      instructions: >
        Orders link many-to-one to the sales channel dimension.
        Use this relationship to join channels when reporting by channel_name or channel_group.
      synonyms:
        - Orders by channel
      examples:
        - Show April paid merchandise sales and net sales by channel.
 
  - name: refunds_to_orders
    from: refunds
    to: orders
    from_columns:
      - order_id
    to_columns:
      - order_id
    ai_context:
      instructions: >
        Refunds link many-to-one to the order fact table. Use this relationship to tie refunds to valid paid orders when calculating refund amounts, net sales, and the refund rate by order payment period.
        Aggregate orders and refunds separately before combining them. Limit the refunds to the same set of valid orders.
      synonyms:
        - Refunds by original order
      examples:
        - Calculate net sales and the refund rate by channel for orders paid in April.
 
metrics:
  - name: net_revenue
    description: >
      Net sales in yuan equal paid merchandise sales (orders.paid_gmv) minus completed refunds (refunds.completed_refund_amount) for the same valid orders.
      Attribute refunds to the order's payment period and treat missing refunds as zero.
    datatype: Decimal
    expression:
      sql: AGG(orders.paid_gmv) - COALESCE(AGG(refunds.completed_refund_amount), 0)
    ai_context:
      instructions: >
        Model-level metric across orders and refunds. Filter by orders.paid_at by default and sum refunds only for the same valid paid orders.
        Aggregate order amounts and refund amounts separately to avoid repeating an order amount for multiple refunds.
      synonyms:
        - Net sales
        - Net revenue
        - Sales after refunds
        - Net GMV
      examples:
        - What were net sales by channel in April 2026?
        - Which channel had the highest net sales in April?
 
  - name: refund_rate
    description: >
      Completed refunds (refunds.completed_refund_amount) divided by paid merchandise sales (orders.paid_gmv) for the same valid orders.
      Returns a decimal ratio, such as 0.2000 for 20.00%, or NULL when paid merchandise sales are zero.
    datatype: Float
    expression:
      sql: 1.0 * COALESCE(AGG(refunds.completed_refund_amount), 0) / NULLIF(AGG(orders.paid_gmv), 0)
    ai_context:
      instructions: >
        Model-level ratio across datasets. Filter orders.paid_at by default so completed refunds and paid merchandise sales come from the same valid paid orders.
      synonyms:
        - Refund rate
        - Merchandise refund rate
        - Refund amount rate
      examples:
        - How did the channels rank by refund rate in April 2026?
        - Which channel had the highest refund rate?

Business and product teams can review description, expression.sql, and ai_context together. They can confirm that paid merchandise sales exclude shipping, that test and cancelled orders are excluded, and that only completed refunds count. They can also check that even when a refund happens in a later month, it follows the original order's payment date.


Share the model between a dashboard and an AI agent

After calling ava.source() to load the data, use the yaml package to parse the file. Put the model fields in the models array and save it with ava.semantic(). The standalone document's version field stays outside the AVA model object.

javascript
import { readFile } from 'node:fs/promises';
import { parse } from 'yaml';
 
const { version, ...model } = parse(await readFile('qingbei-coffee-sales.yml', 'utf8'));
await ava.semantic(undefined, () => ({ models: [model] }));

The dashboard can run SQL reviewed against the model. When an agent asks a question in natural language, AVA provides the model as context for query generation. With DuckDB, ava.translate() returns SQL. Both callers can execute SQL with ava.query().

Map a question to metrics, dimensions, and filters

Suppose someone asks “Show me April 2026 paid merchandise sales, average order value, net sales, and the refund rate for each channel.”

AVA supplies the metrics, dimensions, ai_context, and available data statistics as query generation context. The definition helps the agent make three decisions.

  • Match metrics. The synonyms and descriptions point to orders.paid_gmv, orders.avg_order_value, net_revenue, and refund_rate, with orders.paid_order_count and refunds.completed_refund_amount supporting the calculations.
  • Choose a grouping. “For each channel” points to channels.channel_name. The orders_to_channels relationship describes how to make the join.
  • Apply filters. The model and the orders.paid_at instructions put April in the range ['2026-04-01 00:00:00', '2026-05-01 00:00:00'). The generated SQL must also apply the rules that exclude test orders, cancelled orders, and pending refunds.

An application that wants the dashboard and agent to share a structured interface can define a JSON request like this and map it to reviewed SQL. AVA's query() takes an executable query string.

json
{
  "model": "qingbei_coffee_sales",
  "dimensions": ["channels.channel_name"],
  "metrics": [
    "orders.paid_order_count",
    "orders.paid_gmv",
    "orders.avg_order_value",
    "refunds.completed_refund_amount",
    "net_revenue",
    "refund_rate"
  ],
  "filters": [
    { "field": "orders.paid_at", "operator": ">=", "value": "2026-04-01 00:00:00" },
    { "field": "orders.paid_at", "operator": "<", "value": "2026-05-01 00:00:00" },
    { "field": "orders.order_status", "operator": "=", "value": "paid" },
    { "field": "orders.is_test_order", "operator": "=", "value": false }
  ],
  "orderBy": [{ "metric": "net_revenue", "direction": "DESC" }]
}

Write SQL that prevents double-counting

The primary keys, relationships, and metric scopes show that orders and refunds have different grains. This DuckDB query uses common table expressions (CTEs) to aggregate the orders and refunds separately. It limits refunds to the same valid orders through the refunds_to_orders relationship. That keeps the payment for O001 from being counted twice and keeps refunds for test or cancelled orders out of the results. Run the SQL with ava.query().

sql
WITH valid_orders AS (
  SELECT
    o.order_id,
    o.channel_id,
    (o.gross_amount - o.discount_amount) AS paid_goods_amount
  FROM analytics.dwd_orders AS o
  WHERE o.order_status = 'paid'
    AND NOT o.is_test_order
    AND o.paid_at >= TIMESTAMP '2026-04-01 00:00:00'
    AND o.paid_at < TIMESTAMP '2026-05-01 00:00:00'
),
orders_agg AS (
  SELECT
    vo.channel_id,
    COUNT(DISTINCT vo.order_id) AS paid_order_count,
    COALESCE(SUM(vo.paid_goods_amount), 0) AS paid_gmv
  FROM valid_orders AS vo
  GROUP BY vo.channel_id
),
refunds_agg AS (
  SELECT
    vo.channel_id,
    COALESCE(
      SUM(CASE WHEN r.refund_status = 'completed' THEN r.refund_amount ELSE 0 END),
      0
    ) AS completed_refund_amount
  FROM analytics.dwd_refunds AS r
  INNER JOIN valid_orders AS vo ON r.order_id = vo.order_id
  GROUP BY vo.channel_id
)
SELECT
  c.channel_name,
  oa.paid_order_count,
  oa.paid_gmv,
  ROUND(oa.paid_gmv / NULLIF(oa.paid_order_count, 0), 2) AS avg_order_value,
  COALESCE(ra.completed_refund_amount, 0) AS completed_refund_amount,
  oa.paid_gmv - COALESCE(ra.completed_refund_amount, 0) AS net_revenue,
  ROUND(
    CAST(COALESCE(ra.completed_refund_amount, 0) AS DOUBLE) / NULLIF(oa.paid_gmv, 0),
    4
  ) AS refund_rate
FROM orders_agg AS oa
INNER JOIN analytics.dim_channels AS c ON oa.channel_id = c.channel_id
LEFT JOIN refunds_agg AS ra ON oa.channel_id = ra.channel_id
ORDER BY net_revenue DESC;

Verify a result in three steps

The application can display the relevant definitions and the executed SQL with the results. When ava.analyze() includes the optional sql field, the application can read the statement from it.

  1. Check the metric definition. The application can show the YAML description and expression next to a metric so readers can verify the reporting date and which records count.
  2. Read the executed SQL. In the example above, the CTEs show that order amounts and refund amounts are aggregated separately.
  3. Check the underlying rows. To verify the Mini Program Store's 20% refund rate, use the same filters to inspect the records. April has two valid orders for that channel, O001 (¥900) and O002 (¥600), for a total of ¥1,500. The two completed refunds, R001 (¥100) and R002 (¥200), total ¥300. The refund rate is 300 / 1,500 = 20.00%.

Validate the model before relying on it

Storing the model as YAML lets you validate the definitions and test the expected results as part of the same code review.

Check the structure and references

Before merging, check the document against the Apache Ossie 0.3.0.dev0 JSON Schema and save the model object with AVA's semantic() method. Review the expressions and physical tables separately. Ossie JSON Schema

  • Document structure and required fields. JSON Schema checks the document root, version, and required fields. A metric needs name and expression. If present, description, datatype, and ai_context are checked for the expected structure and types.
  • Key and relationship references. On save, AVA checks for duplicate names and verifies that primary_key, from, to, from_columns, and to_columns refer to declared fields or datasets as appropriate.
  • Expressions and scope. Review the expressions against OSSIE_SQL_2026 or use a separate validator. Check that dataset-scoped metrics use fields in scope and that model-scoped AGG(dataset.metric) references point to defined dataset metrics.
  • Physical sources. Use ava.schema() to compare the model with the actual tables and columns. Test primary-key uniqueness against the warehouse data.

Test the numbers with sample data

Run the query with the three channels, eight orders, and four refunds from this example as a test fixture in CI. DuckDB or a local SQL engine can check the following cases.

  • Fan-out. Count ¥900 for O001 even though it has two partial refunds. The Mini Program Store's refund rate should be 20.00%.
  • Payment dates and refund attribution. Include O002 in April and leave O008 for May. Refund R004, completed on May 2, reduces April net sales for Tmall.
  • Record and amount exclusions. Exclude test order O005, cancelled order O006, pending refund R003, and all shipping charges.
  • Missing values and division by zero. The Douyin Shop has no refunds, so completed_refund_amount is 0 and net_revenue is 1,000. A month with no orders, such as June 2026, returns zero rows when grouped by channel. For an all-channel summary of that month, avg_order_value and refund_rate are NULL.

Assert the results below. For the all-channel average order value, divide total paid merchandise sales by the total number of valid paid orders. For the all-channel refund rate, divide total completed refunds by total paid merchandise sales.

ChannelValid paid orders (paid_order_count)Paid merchandise sales (paid_gmv)Average order value (avg_order_value)Completed refunds (completed_refund_amount)Net sales (net_revenue)Refund rate (refund_rate)
Tmall Flagship Store23,000.001,500.00200.002,800.000.0667 (6.67%)
Mini Program Store21,500.00750.00300.001,200.000.2000 (20.00%)
Douyin Shop11,000.001,000.000.001,000.000.0000 (0.00%)
All channels55,500.001,100.00500.005,000.000.0909 (9.09%)

When a rule changes, update the YAML, affected shared SQL, and expected test results in the same pull request. After review and CI, deploy the same definitions and queries to the dashboard and the agent.


Start with the metrics people disagree on

Bringing AI agents into business reviews requires metric definitions that the business team can read and the application can use to guide queries. With OSI in AVA, the team can move those rules out of scattered BI configuration, analyst notes, and agent prompts into a versioned model with tests.

Start with three metrics your team often has to reconcile. Write down their rules in an Ossie model and check the SQL against a small dataset you can verify by hand. AVA business semantics documentation · Ossie core specification · Ossie JSON Schema