Rayfin

Semantic models

Run DAX against a Fabric semantic model from a Rayfin app and handle typed table results, row limits, request timeouts, and connector diagnostics.

Run DAX against an existing Fabric semantic model when your app needs measures or model logic that already lives in Power BI. The fabric-semanticmodel connector is a Category B function-bridge connector: it exposes executeQuery, uses delegated authentication only, and is pinned to an adapter version (version: "1" today).

Note

fabric-semanticmodel is delegated-only, so rayfin up rejects auth.type: application. Each deployed app query runs as the signed-in user.

To let users ask questions in natural language instead of running DAX you write, use the Fabric IQ connector.

Keep the generated schema

npx rayfin connector add --type fabric-semanticmodel writes rayfin/connectors/<name>/schema.ts. The file is complete for this connector type: it exports the phantom marker used in AppConnectorsSchema and a generic connectorConfig that tells the client which runtime to use. Connector names are lowercase because connector add normalizes --name before writing files.

rayfin/connectors/salesmodel/schema.ts
// @generated — do not edit.

// Connector: salesmodel (fabric-semanticmodel)

import type { ConnectorConfig } from '@microsoft/rayfin-connectors';
import type { FabricSemanticModel } from '@microsoft/rayfin-connector-fabric-semanticmodel';

/**
 * Typed connector schema for "salesmodel" (fabric-semanticmodel).
 * Plug into your AppConnectorsSchema in your RayfinClient setup.
 */
export type SalesmodelSchema = FabricSemanticModel<'executeQuery'>;

export const connectorConfig = {
  connector: 'fabric-semanticmodel',
} as const satisfies ConnectorConfig;

Do not hand-edit this file. If the connector points at the wrong semantic model, re-add it under the same name; connector add always regenerates this file:

npx rayfin connector add --type fabric-semanticmodel --workspace-id <workspace-id> --item-id <semantic-model-item-id> --name salesmodel --yes

The workspace and item IDs belong under the connector's config: entry in rayfin/rayfin.yml; the app never sends them from the browser.

Register the runtime

Changed in 2.0

Register fabricSemanticModel() in the runtime map of connectorsService before calling the connector. The runtime decodes the Arrow response and normalizes the operation output; without it, executeQuery does not return the shape its TypeScript marker promises. See Wiring connectors into your app for the full client setup.

src/services/rayfinClient.ts
import { RayfinClient } from '@microsoft/rayfin-client';
import { browserSession } from '@microsoft/rayfin-auth';
import { dataService } from '@microsoft/rayfin-data';
import { connectorsService } from '@microsoft/rayfin-connectors';
import { fabricSemanticModel } from '@microsoft/rayfin-connector-fabric-semanticmodel';
import type { AppSchema } from '../../rayfin/data/schema';
import {
  connectorConfig as salesmodelConfig,
  type SalesmodelSchema,
} from '../../rayfin/connectors/salesmodel/schema';

type AppConnectorsSchema = {
  salesmodel: SalesmodelSchema;
};

export const rayfinClient = RayfinClient.create({
  baseUrl: import.meta.env.VITE_RAYFIN_API_URL,
  publishableKey: import.meta.env.VITE_RAYFIN_PUBLISHABLE_KEY,
  auth: browserSession({ storage: true }),
  services: {
    data: dataService<AppSchema>(),
    connectors: connectorsService<AppConnectorsSchema>({
      configs: { salesmodel: salesmodelConfig },
      runtime: { salesmodel: fabricSemanticModel() },
    }),
  },
});

export type AppClient = typeof rayfinClient;

The key must match the connector name in rayfin/rayfin.yml, the AppConnectorsSchema property, the configs map, and the runtime map.

Call executeQuery

executeQuery accepts a DAX query and resolves to an already-normalized SemanticModelQueryResult. Do not call toQueryResult on it again; branch on result.status directly.

src/features/sales/loadSalesByRegion.ts
import { rayfinClient } from '../../services/rayfinClient';

export async function loadSalesByRegion() {
  const result = await rayfinClient.connectors.salesmodel.executeQuery({
    query: `
EVALUATE
SUMMARIZECOLUMNS(
  'Sales'[Region],
  "Total Sales", [Total Sales]
)
`,
    resultSetRowCountLimit: 500,
  });

  if (result.status === 'error') {
    throw new Error(
      result.error.recoveryHint
        ? `${result.error.message} ${result.error.recoveryHint}`
        : result.error.message
    );
  }

  return result.table.rows.map((row) => {
    const record = Object.fromEntries(
      result.table.columns.map((column, index) => [column.name, row[index]])
    );

    return {
      region: String(record['Sales[Region]'] ?? ''),
      totalSales: Number(record['[Total Sales]'] ?? 0),
      requestId: result.requestId,
    };
  });
}

Set a request timeout

Changed in 2.0

executeQuery waits up to 5 minutes for a response — the deadline the backend enforces for connector calls — instead of the client's generic 30-second timeout, so slow DAX queries are no longer aborted in the browser while the backend is still serving them. Pass { timeoutMs } as the second argument to give up sooner:

src/features/sales/loadTopSales.ts
import { rayfinClient } from '../../services/rayfinClient';

export function loadTopSales() {
  return rayfinClient.connectors.salesmodel.executeQuery(
    { query: "EVALUATE TOPN(10, 'Sales')" },
    { timeoutMs: 20_000 },
  );
}

A value above 5 minutes is capped at 5 minutes, and a value of zero or less uses the default.

Render the table shape

A successful semantic-model result has one normalized table:

type SemanticModelQueryResult =
  | {
      status: 'success';
      table: {
        columns: { name: string; dataType: string }[];
        rows: unknown[][];
      };
      requestId: string;
    }
  | {
      status: 'error';
      error: QueryError;
      requestId: string;
    };

Rows are row-major arrays aligned with columns, so a generic renderer can use the column index instead of reading object keys from the raw Power BI response.

src/features/sales/SemanticModelTable.tsx
import type { SemanticModelQueryResult } from '@microsoft/rayfin-connector-fabric-semanticmodel';

export function SemanticModelTable({ result }: { result: SemanticModelQueryResult }) {
  if (result.status === 'error') {
    return (
      <p>
        {result.error.category}: {result.error.message}
      </p>
    );
  }

  return (
    <table>
      <thead>
        <tr>
          {result.table.columns.map((column) => (
            <th key={column.name}>{column.name}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {result.table.rows.map((row, rowIndex) => (
          <tr key={rowIndex}>
            {result.table.columns.map((column, columnIndex) => (
              <td key={column.name}>{String(row[columnIndex] ?? '')}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

Cap rows when you need a guard

ExecuteQueryInput is:

type ExecuteQueryInput = {
  query: string;
  resultSetRowCountLimit?: number;
};

There is no default row limit. Omitting resultSetRowCountLimit returns every row the DAX query produces. Use the field when you want a guard on response size; prefer it over wrapping the DAX in TOPN unless you intentionally want a ranked subset. If the result exceeds the limit, the connector returns status: 'error' with category 'overflow', so the app does not mistake a truncated table for a complete answer.

Handle error categories

QueryError carries category, message, optional code, optional details, and an optional recoveryHint.

CategoryMeaningApp response
networkThe request did not reach Power BI.Retry or show a transient connectivity message.
apiPower BI rejected the request, often because of auth, permissions, or throttling.Ask the user to sign in again, wait, or check model access.
queryPower BI ran the DAX and returned a query error.Show the DAX error and let the user change the query.
overflowA row or byte cap was exceeded.Ask for a narrower query or a higher explicit limit.
unknownThe connector could not classify the failure.Show the message and include requestId in diagnostics.

Exercise the connector from the CLI

connector invoke runs a DAX payload against a registered connector. Put the payload in a JSON file, so shell quoting cannot change the DAX:

rayfin/queries/top-sales.json
{
  "query": "EVALUATE TOPN(10, Sales)",
  "resultSetRowCountLimit": 500
}
npx rayfin connector invoke salesmodel executeQuery --file rayfin/queries/top-sales.json

For fabric-semanticmodel, the default --transport auto path calls Fabric and Power BI directly under the developer's own identity. It works with or without npx rayfin up, but the connector entry must have both workspaceId and itemId under config:.

Changed in 2.0

The direct path queries the model-scoped /datasets/{itemId}/executeDaxQueries endpoint, so the developer needs Read and Build permissions on the semantic model, not write access to the workspace.

New in 1.36

--transport deployed forces the deployed BaaS route. It needs a Rayfin app-session token in RAYFIN_TOKEN; a normal rayfin login cannot mint that token.

The output is already normalized: status: 'success' carries table and requestId; status: 'error' carries error and requestId. A resolved invocation is not automatically a success, and the CLI exits non-zero for the normalized error arm. A CLI probe proves model access under your identity; the connector is proven once the deployed app runs the query as the signed-in user.

Use connector inspect for read-only exploration before writing app code:

npx rayfin connector inspect --name salesmodel
npx rayfin connector inspect --name salesmodel --query rayfin/queries/sales-by-region.dax

connector inspect supports semantic models, including direct selectors and portal URLs. See CLI connector reference for selector and payload rules.

Note

Rayfin 1.36.1 coerces Arrow Int64 values, including Int64 values inside Power BI Variant/Union columns, before CLI output is serialized. Safe Int64 values such as DISTINCTCOUNT results should no longer fail with Do not know how to serialize a BigInt. An Int64 or Decimal outside JavaScript's safe integer range returns an overflow error instead. Changed in 1.36.1

Troubleshoot semantic-model queries

SymptomLikely causeFix
rayfin up rejects auth.type: applicationCategory B semantic model connectors are delegated-only.Set auth.type: delegated.
executeQuery returns a raw transport payload or cannot decode the table.fabricSemanticModel() is missing from the runtime map.Pass runtime: { salesmodel: fabricSemanticModel() } to connectorsService.
client.connectors.salesmodel is not typed.The connector key differs across rayfin.yml, AppConnectorsSchema, configs, or runtime.Use the connector name from rayfin.yml in all four places.
A slow query fails after 5 minutes.The backend deadline for connector calls is 5 minutes.Narrow the DAX query; timeoutMs can only shorten the wait.
A large query fails with category overflow.resultSetRowCountLimit or a service byte cap stopped a truncated result.Narrow the DAX query or choose a higher explicit limit.
connector invoke reports missing workspaceId/itemId in rayfin.yml.The semantic model connector lacks a complete config: block.Re-add the connector with --workspace-id and --item-id.
connector invoke fails with a permissions error on the direct path.The developer lacks Read or Build permission on the semantic model.Ask the model owner for Read and Build permissions.
connector invoke exits non-zero but prints a JSON result.The operation resolved to status: 'error'.Read error.category, error.message, and requestId; a resolved call is not a successful query.
A semantic-model query returns category overflow.An Int64 or Decimal value cannot be represented as a JavaScript safe number.Narrow or cast the DAX result so the returned numeric values fit safely, and include requestId in diagnostics.
PromptQuery a Fabric semantic model from a Rayfin app
In my Rayfin 2.0 project, add a Fabric semantic model connector named salesmodel and call it from the frontend. Use `npx rayfin connector add --type fabric-semanticmodel --workspace-id <workspace-id> --item-id <semantic-model-item-id> --name salesmodel`, run the pinned npm install command the CLI prints, and do not edit rayfin/connectors/salesmodel/schema.ts by hand. Prove access first with `npx rayfin connector invoke salesmodel executeQuery --file <payload.json>`, where the file holds `{ "query": "EVALUATE TOPN(1, <table>)" }`. In the app's `RayfinClient.create` call, register `connectors: connectorsService<AppConnectorsSchema>({ configs: { salesmodel: connectorConfig }, runtime: { salesmodel: fabricSemanticModel() } })` from @microsoft/rayfin-connectors and @microsoft/rayfin-connector-fabric-semanticmodel, with `salesmodel: SalesmodelSchema` in AppConnectorsSchema (or use the maps in src/lib/connectors.ts when the CLI generated it). Then call `client.connectors.salesmodel.executeQuery({ query, resultSetRowCountLimit: 500 })`, branch on `result.status`, render `result.table.columns` with row-major `result.table.rows`, and show `result.error.category`, `result.error.message`, and `result.requestId` on failure. Deploy with `npx rayfin up` and confirm the deployed app renders rows.
Something wrong on this page?Report an issueEdit this page

On this page