-
Notifications
You must be signed in to change notification settings - Fork 307
Add attribute discovery and filtering to world.analytics #2903
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5a8d11e
Add attribute discovery and filtering to world.analytics
karthikscale3 6c43e52
Shorten changeset; document world.analytics in the World SDK reference
karthikscale3 369fe23
Drop analytics.attributes.listValues
karthikscale3 e19f7b3
Feature-detect world.analytics in the attributes guide example
karthikscale3 fe54d70
Fix stale 'querying attributes not available' bullet in the guide
karthikscale3 1f47722
Surface the analytics namespace on the API reference index pages
karthikscale3 716b6ee
Bump changeset to minor
karthikscale3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| '@workflow/world': minor | ||
| '@workflow/world-vercel': minor | ||
| --- | ||
|
|
||
| Add `analytics.attributes.list()` for attribute key discovery, and an `attributes` key=value filter to `analytics.runs.list()`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
139 changes: 139 additions & 0 deletions
139
docs/content/docs/v5/api-reference/workflow-runtime/world/analytics.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| --- | ||
| title: Analytics | ||
| description: Metadata-only read APIs for runs, steps, events, hooks, waits, and attributes, backed by the observability pipeline. | ||
| type: reference | ||
| summary: "Interfaces: world.analytics.runs, .attributes, .steps, .events, .hooks, .waits. Metadata-only listings with plan-based lookback windows; filter runs by attribute key=value." | ||
| prerequisites: | ||
| - /docs/api-reference/workflow-runtime/get-world | ||
| related: | ||
| - /docs/api-reference/workflow-runtime/world/storage | ||
| - /docs/observability/attributes | ||
| keywords: | ||
| - world.analytics | ||
| - analytics.runs | ||
| - analytics.attributes | ||
| - attribute filter | ||
| - listValues | ||
| - lookback window | ||
| - observability-upgrade-required | ||
| - pageInfo | ||
| - metadata-only | ||
| --- | ||
|
|
||
| `world.analytics` is an optional, read-only namespace for observability surfaces — dashboards, CLIs, and admin tools that list large numbers of runs without touching payload data. | ||
|
|
||
| It differs from [Storage](/docs/api-reference/workflow-runtime/world/storage) in three ways: | ||
|
|
||
| - **Metadata only.** Results never include run input/output, step data, or hook tokens. There is no `resolveData` option. | ||
| - **Served from the observability pipeline.** On Vercel, queries hit a ClickHouse-backed analytics store instead of the runtime database, so large listings do not compete with workflow execution. Data is ingested asynchronously and may trail the live state by a few seconds. | ||
| - **Plan-bounded lookback.** Listings only cover the observability retention window for your plan (up to 30 days). Every page includes a `pageInfo` block describing the current window, and requesting an older window fails with an `observability-upgrade-required` error. | ||
|
|
||
| The namespace is optional — worlds that don't implement it (such as the local development world) leave it `undefined`, so feature-detect before use: | ||
|
|
||
| ```typescript lineNumbers | ||
| import { getWorld } from "workflow/runtime"; | ||
|
|
||
| const world = await getWorld(); | ||
| if (world.analytics) { // [!code highlight] | ||
| const page = await world.analytics.runs.list(); | ||
| } | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## analytics.runs | ||
|
|
||
| ### runs.list() | ||
|
|
||
| List runs with metadata, current status, and attributes. Without an explicit time window, the listing defaults to the trailing 24 hours; pass `startTime`/`endTime` to reach older runs within your plan window. | ||
|
|
||
| ```typescript lineNumbers | ||
| const page = await world.analytics.runs.list({ | ||
| workflowName: "orderWorkflow", | ||
| status: "failed", | ||
| attributes: { source: "checkout" }, // [!code highlight] | ||
| pagination: { limit: 50, sortOrder: "desc" }, | ||
| }); | ||
| ``` | ||
|
|
||
| | Parameter | Type | Description | | ||
| |-----------|------|-------------| | ||
| | `params.workflowName` | `string` | Filter to one workflow | | ||
| | `params.status` | `string` | `pending`, `running`, `completed`, `failed`, or `cancelled` | | ||
| | `params.startTime` / `params.endTime` | `string` | ISO 8601 window; must be provided together | | ||
| | `params.attributes` | `Record<string, string>` | Only return runs whose latest attributes match every pair (up to 8) | | ||
| | `params.pagination` | `PaginationOptions` | Cursor pagination | | ||
|
|
||
| **Returns:** `PaginatedResponse<AnalyticsRun>` — each run includes `runId`, `status`, `workflowName`, `deploymentId`, `attributes`, and lifecycle timestamps. | ||
|
|
||
| Attribute matching is latest-write-wins: a run whose attribute moved from `"v1"` to `"v2"` no longer matches `{ key: "v1" }`. Reserved `$`-prefixed keys may be used in filters even though user code cannot write them. | ||
|
|
||
| ### runs.get() | ||
|
|
||
| Fetch one run by ID. Point lookups search the full plan window, not just the trailing 24 hours. | ||
|
|
||
| ```typescript lineNumbers | ||
| const run = await world.analytics.runs.get(runId); | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## analytics.attributes | ||
|
|
||
| Discover which [attributes](/docs/observability/attributes) exist on your runs — for example to build filter dropdowns over arbitrary user-defined keys. | ||
|
|
||
| ### attributes.list() | ||
|
|
||
| List the distinct attribute keys observed on runs in the window, ordered alphabetically. | ||
|
|
||
| ```typescript lineNumbers | ||
| const page = await world.analytics.attributes.list({ // [!code highlight] | ||
| workflowName: "orderWorkflow", | ||
| }); | ||
| for (const { key, runCount, lastSeenAt } of page.data) { | ||
| console.log(key, runCount, lastSeenAt); | ||
| } | ||
| ``` | ||
|
|
||
| | Parameter | Type | Description | | ||
| |-----------|------|-------------| | ||
| | `params.workflowName` | `string` | Only count runs of one workflow | | ||
| | `params.startTime` / `params.endTime` | `string` | ISO 8601 window; must be provided together | | ||
| | `params.pagination` | `PaginationOptions` | Cursor pagination | | ||
|
|
||
| **Returns:** `PaginatedResponse<AnalyticsAttributeKey>` — `{ key, runCount, firstSeenAt, lastSeenAt }` | ||
|
|
||
| --- | ||
|
|
||
| ## analytics.steps, analytics.events, analytics.hooks, analytics.waits | ||
|
|
||
| Run-scoped listings mirroring their [Storage](/docs/api-reference/workflow-runtime/world/storage) counterparts, minus payload data: | ||
|
|
||
| ```typescript lineNumbers | ||
| const steps = await world.analytics.steps.list({ runId }); | ||
| const events = await world.analytics.events.list({ runId, eventType: "step_failed" }); | ||
| const related = await world.analytics.events.listByCorrelationId({ correlationId }); | ||
| const hooks = await world.analytics.hooks.list({ runId }); | ||
| const waits = await world.analytics.waits.list({ runId, status: "waiting" }); | ||
| ``` | ||
|
|
||
| Each namespace also has a `get()` for point lookups (`steps.get(runId, stepId)`, `events.get(runId, eventId)`, `hooks.get(hookId)`, `waits.get(runId, waitId)`). Hook listings never include the hook token — resolve it separately through the runtime APIs if you need to deliver a payload. | ||
|
|
||
| --- | ||
|
|
||
| ## Lookback windows and pageInfo | ||
|
|
||
| Every paginated response carries `pageInfo` describing the window the query was allowed to scan: | ||
|
|
||
| {/* @skip-typecheck: shape illustration, not runnable code */} | ||
| ```typescript | ||
| { | ||
| currentLookbackDays: 2, // what your plan allows today | ||
| maxLookbackDays: 30, // ceiling with Observability Plus | ||
| currentWindowStart: Date, | ||
| maxWindowStart: Date, | ||
| upgradeAvailable: true, // more history exists behind the plan gate | ||
| } | ||
| ``` | ||
|
|
||
| Requests for a window older than `currentWindowStart` fail with an `observability-upgrade-required` error; windows older than `maxWindowStart` return not-found. Use `pageInfo` to size date pickers and to decide whether to surface an upgrade prompt. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
docs/content/docs/v5/api-reference/workflow-runtime/world/meta.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| { | ||
| "title": "World SDK", | ||
| "pages": ["storage", "streams", "queue"] | ||
| "pages": ["storage", "analytics", "streams", "queue"] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| const state = vi.hoisted(() => ({ | ||
| makeRequest: vi.fn(), | ||
| })); | ||
|
|
||
| vi.mock('./utils.js', () => ({ | ||
| makeRequest: state.makeRequest, | ||
| })); | ||
|
|
||
| const { createAnalytics } = await import('./analytics.js'); | ||
|
|
||
| describe('createAnalytics attributes', () => { | ||
| beforeEach(() => { | ||
| state.makeRequest.mockReset(); | ||
| state.makeRequest.mockResolvedValue({ | ||
| data: [], | ||
| cursor: null, | ||
| hasMore: false, | ||
| }); | ||
| }); | ||
|
|
||
| it('serializes attribute filters on runs.list as a JSON query param', async () => { | ||
| const analytics = createAnalytics(); | ||
| await analytics.runs.list({ | ||
| attributes: { team: 'growth', '$eve.type': 'session' }, | ||
| }); | ||
|
|
||
| const { endpoint } = state.makeRequest.mock.calls[0][0]; | ||
| expect(endpoint).toBe( | ||
| `/v2/analytics/runs?attributes=${encodeURIComponent( | ||
| JSON.stringify({ team: 'growth', '$eve.type': 'session' }) | ||
| )}` | ||
| ); | ||
| }); | ||
|
|
||
| it('omits the attributes param when the filter object is empty', async () => { | ||
| const analytics = createAnalytics(); | ||
| await analytics.runs.list({ attributes: {} }); | ||
|
|
||
| const { endpoint } = state.makeRequest.mock.calls[0][0]; | ||
| expect(endpoint).toBe('/v2/analytics/runs'); | ||
| }); | ||
|
|
||
| it('lists attribute keys with filters and pagination', async () => { | ||
| const analytics = createAnalytics(); | ||
| await analytics.attributes.list({ | ||
| workflowName: 'daily-report', | ||
| startTime: '2026-06-20T00:00:00.000Z', | ||
| endTime: '2026-06-21T00:00:00.000Z', | ||
| pagination: { limit: 25, cursor: 'abc', sortOrder: 'asc' }, | ||
| }); | ||
|
|
||
| const { endpoint } = state.makeRequest.mock.calls[0][0]; | ||
| const url = new URL(endpoint, 'https://example.test'); | ||
| expect(url.pathname).toBe('/v2/analytics/attributes'); | ||
| expect(Object.fromEntries(url.searchParams)).toEqual({ | ||
| workflowName: 'daily-report', | ||
| startTime: '2026-06-20T00:00:00.000Z', | ||
| endTime: '2026-06-21T00:00:00.000Z', | ||
| limit: '25', | ||
| cursor: 'abc', | ||
| sortOrder: 'asc', | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
World.analyticsis optional, but this snippet dereferences it without the runtime check claimed by the@skip-typecheckannotation. It will throw in local/Postgres/custom Worlds whereanalyticsis absent. Please feature-detect here (as the new Analytics reference page does) before callingattributes.list()orruns.list().There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in e19f7b3. The snippet now feature-detects:
if (!world.analytics) { throw new Error(...) }before any analytics call, and the prose above it states the namespace is optional and absent on local/Postgres/custom Worlds. Since the guard makes the block genuinely type-safe, I also removed the@skip-typecheckannotation — the block is now typechecked bytest:docs(skipped count dropped by one, all green).