Skip to content

Script and Metadata Format — Specification

Format version: 1 (draft) Status: public authoring API for script packs. Changes after the first release must be backward compatible or bump the format version.

The format is the same for every database engine (ADR 0006). What differs per engine is the SQL inside the scripts and a few lexical rules the platform takes from the engine’s dialect: how binds are told apart from literals (§4.4), which statements are procedural blocks and which terminator line is dropped (§8). Examples in this document come from the Oracle pack (engines/oracle/pack), the reference pack; a PostgreSQL pack follows the same rules.


File Purpose
*.sql Query or action script, optionally with an embedded YAML header.
*.yaml Container (dashboard/layout) definition.
pack.yaml Pack descriptor in a pack root: name, engine (the engine id the pack is written for, e.g. oracle, postgresql; omitted for an engine-neutral pack, e.g. one holding only containers), version, formatVersion, optional connectionInit (script id), optional palettes, optional columnKeys (§5.1), optional ignore (directories not scanned for scripts, e.g. [fixtures]), optional requires: { version } (the default minimum database version of the pack’s scripts, §11.1), optional licenses (§11.2).

A catalog is loaded for one engine: the engine’s shipped pack, engine-neutral packs and the user’s scripts for that engine (scripts/<engine> in the configuration folder). A pack whose engine is another one is an error and is not loaded. Scripts in the user’s folder belong to the engine of the folder; they need no pack.yaml.

Packs are layered: user directory > shipped pack, matched by id. A higher layer replaces every variant of an id (§1.1). Within one layer, the same id is allowed only for variants that differ in minimum version or licences; other duplicates are errors, and all of them are rejected.

One script may need different SQL for different database versions or licences. Each variant is its own file with the same id; per connection the catalog uses the best variant the connection meets (§11.1), so navigation targets, links and dashboards name the id only.

File names follow name[@version][+licence…].sql:

File Meaning
top_sql_for_range.sql The pack’s default minimum version (§11.1), no licence in the name.
top_sql_for_range@11.2.sql Minimum version 11.2: used on 11.2 up to the version below the next variant.
session_top_sql_for_range+tuning.sql Needs the tuning licence; preferred over the variant without it when the connection has it.
top_sql@12.1+tuning.sql Both.
activity_by_wait_class+diagnostics.sql and activity_by_wait_class.sql (source: local) Oracle pack: the first reads ASH when the Diagnostics Pack is licensed; otherwise the second reads OPA’s own session samples (§17).

The suffix is not part of a derived id (sessions/active@11.2.sql → sessions.active). It supplies requires.version and requires.licenses when the header leaves them out. When the header states them, they must agree: a different version, or a +licence that requires.licenses does not list, is an error. A header requires.version without an @version suffix is a warning, so that variants can always be told apart by their file names.

A .sql file may begin (after optional whitespace) with a block comment delimited by /*--- and ---*/. Its content is YAML. The file remains valid SQL.

/*---
id: sessions.active
title: Active Sessions
---*/
select ...

Without a header, defaults apply (§13). Sidecar YAML files are reserved for a later format version.

SQL text never contains special syntax for the platform: inputs are ordinary :name binds, and everything else is declared in the header.

Field Type Default Notes
formatVersion int pack’s Rarely needed per file.
id string derived from relative path Lowercase, [a-z0-9_.-]. Derived ids: extension removed, path separators become ., letters lowercased, any other character becomes _. Collisions are duplicates (§1).
title string file name, humanised
category string parent directory path Catalog tree path, /-separated. The navigation context menu uses it too: the first segment is a header, every further segment a submenu (SQL/Plan Management → header SQL, submenu Plan Management).
description string — Shown as tooltip/help.
version int 1 Author’s revision; used for override-shadowing warnings.
kind query | action | container | connection-init | sampler query (.sql), container (.yaml) sampler: §17.
requires map, or a list of predicates — Minimum database version, licenses, and context predicates (§11). The bare list form is the context predicates.
unless map — unless: { licenses: [diagnostics] }: unavailable when all these licences are confirmed (§17).
source database | local database local: the SQL runs on OPA’s local sample store, not on the database (§17).
sampler object — kind: sampler only (§17).
inputs list inferred from binds §4.
ranges list — Pairs of time inputs shown as one period control (§4.3).
columns map — Column → semantic key / formatting (§5).
steps list single implicit step §8.
display object {renderer: table} §7.
navigation object — §9.
refresh object — Auto-refresh (§6).
confirm string — Human-readable confirmation summary for actions (§10).
layout object — Containers only (§12).
safety read | write | dangerous read for query, write for action §10.
transaction rollback | commit | none rollback Applied after the last step.
timeout duration app default Per statement.
maxRows int app default Row cap per result.

Durations are written as an integer with a unit: 500ms, 5s, 1m, 2h, 7d.

inputs:
- name: sql_id # bind name, without ':'
semantic: oracle.sql.id # optional; lets the value come from context (§4.1)
type: string # string|integer|number|date|timestamp|boolean|enum
required: true # default: true if no default is given
default: null # literal, or a time expression for date/timestamp (§4.2)
fromContext: true # false = never take the value from context (default true)
label: SQL ID
choices: [A, B] # enum only
precision: minute # date/timestamp only: day|minute|second (default minute)
showWhen: { capabilities: [cdb_root] } # in the inputs bar only where the connection has them (§11.3)

Every view with user-editable inputs shows them in an inputs bar above its result: the view opens and runs immediately with the resolved values; editing a value and pressing Enter (or Run) re-executes. When a required input has neither a value from context nor a default, the view waits and says which input is missing; the inputs bar is the prompt (no modal dialog). A value the user edited stays until a new context value arrives for that input (e.g. a new dashboard selection), which replaces the edit.

The role of an input follows from semantic and default; nothing is guessed from bind or column names.

semantic default / required Role Value comes from
set required, no default identity (e.g. sql_id, sid) context only. Missing → the view waits (waiting-for-input), a navigation target is not offered (or shown disabled).
set has a default, or required: false contextual parameter (e.g. a time range, an optional wait class) context if present, else the default. Editable in the inputs bar.
not set any local parameter (e.g. top_n) default or the inputs bar only; never from context.

fromContext: false turns a contextual parameter into a local one while keeping its semantic key for documentation and type checks (e.g. a 7-day history window that must not inherit a 5-minute dashboard selection).

Resolution order for a value taken from context: selection (clicked row / chart point / chart range) → inherited context (dashboard channel, container inputs, parent tab) → global context → default → prompt.

default of a date or timestamp input (and chart selection defaults, §7.1) may be a time expression. The syntax follows Grafana’s:

expr := 'now' offset* truncation? | absolute
offset := ('+' | '-') integer unit
truncation:= '/' unit
unit := s | m | h | d | w # w truncates to Monday 00:00
absolute := YYYY-MM-DD [ ' ' HH:MM [ ':' SS [ '.' fraction ] ] ]
Expression Meaning
now current database time
now-15m, now-2h, now-7d, now+1h offset from now
now/d, now/h, now/m truncated (like trunc(sysdate, 'DD'))
now-1d/d 00:00 yesterday
2026-10-29 10:00 absolute value

Rules:

  • now is the database clock, not the workstation clock: the engine keeps the offset measured by the connection-init script (§11). Date/time values are database wall-clock values without time-zone conversion, displayed and bound as such.
  • A relative value stays relative. It is re-evaluated on every execution (open, manual run, auto-refresh), so “last 15 minutes” moves with time. The inputs bar shows the resolved value together with the expression. When the user picks a concrete value, it becomes absolute and stays fixed until changed or replaced by a preset.
  • type: date binds a date and time without fractional seconds (Oracle DATE; on engines whose date has no time of day, compare with a timestamp input instead); type: timestamp binds a TIMESTAMP. precision: day shows a date-only picker; minute/second show date and time. timestamp with time zone is reserved for a later format version.
ranges:
- from: t_from
to: t_to
label: Period
presets: [15m, 1h, 6h, 1d, 7d] # each preset sets from = now-<preset>, to = now (relative)

A range shows two time inputs as one period control with presets. Before executing, from < to is checked; an invalid range keeps the view from running and marks the control.

  • Named placeholders :name are found by a lexer that ignores string literals, quoted identifiers, comments and whatever the engine’s dialect adds: Oracle q'[...]' quoting; PostgreSQL $$...$$ / $tag$...$tag$ dollar quoting, E'...' strings and :: casts (x::text is not a bind).
  • The same bind name may appear several times; all occurrences are one bind, so an expression with binds can be repeated in GROUP BY or ORDER BY. Engines whose driver binds only by position still bind each name once (PostgreSQL: the first occurrence is the driver’s parameter, later ones refer to it as $n); the script does not change.
  • Types (PostgreSQL): text values are sent untyped, so the server infers their type from the query (queryid = :queryid works with a text context value); integers go as int4 when they fit, else int8; numbers as numeric; dates and timestamps as timestamp. A bind whose type the query does not determine needs a cast: :name::text is null, select :t_from::timestamp.
  • Only :identifier (starting with a letter) is a bind. := is not a bind. Numeric placeholders (:1, $1) are not binds (:1 is a validation error). ? is a validation error, except on engines where it is an operator (PostgreSQL JSON operators).
  • Values are always bound, never substituted into text.
  • Undeclared binds in a script are local parameters: type: string, required: false, entered as text with a NULL option.

Short form maps a result column (case-insensitive) to a semantic key:

columns:
inst_id: oracle.instance.number
sid: oracle.session.sid
serial#: oracle.session.serial

Long form adds presentation:

columns:
elapsed_s:
semantic: perf.elapsed_seconds
label: Elapsed, s
format: "#,##0.00" # number pattern
unit: s # s|ms|us|bytes|percent|count — enables human-readable display
hidden: false
width: 90
key: false # true = part of the row identity, used to keep selection across refresh
role: clock # connection-init only: this column is the database's current time (§11)
cell: { palette: wait-classes } # styling of in-cell graphics drawn from the value (§5.2)
showWhen: { capabilities: [cdb_root] } # shown only where the connection has them, else as hidden (§11.3)

Semantic keys are opaque strings. Recommended style: dotted, lowercase, engine- or domain-first (oracle.session.sid, pg.backend.pid, perf.time.range.start). Keys of different engines never meet: a catalog holds one engine’s packs. A key used with conflicting types across scripts produces a warning.

pack.yaml
columnKeys:
sql_id: oracle.sql.id
inst_id: oracle.instance.number
sid: oracle.session.sid
serial#: oracle.session.serial

A result column whose name matches a columnKeys entry gets that semantic key in every script, including plain .sql files without a header. columnKeys of all loaded packs are merged; on conflict the user layer wins. A script’s own columns entry takes precedence; columns: { sid: null } removes the key for that script. This is pack data: the platform still never interprets column or key names.

A text value of the form bar(…), stacked-bar(…) or sparkline(…) is drawn as a small graphic in the table renderer. The SQL decides what is drawn: no header is needed, so this works in plain .sql files too. The value must parse completely (keyword case-insensitive, spaces allowed). Anything else, including a malformed graphic, is shown as text.

Value Drawn as
bar(42) · bar(42,100) A bar behind the number, filling 42/100 of the cell. Without a maximum, relative to the largest bar value in the column. Negative values draw no bar.
stacked-bar(CPU=12;User I/O=30) · stacked-bar({"CPU":12,"User I/O":30}) One bar split into segments in the given order. Plain form: name=value pairs separated by ; (the value follows the last =). JSON form: an object, with any characters in names; null values are skipped. Zero or negative segments are not drawn.
sparkline(3,5,,8) · sparkline([3,5,null,8]) A tiny chart of the numbers in order; an empty item or null is a gap. Zero is always on the scale.

Inside the parentheses either JSON or the plain form is accepted; a leading [ or { selects JSON. Numbers use . as the decimal separator. Build plain lists of decimals with to_char(v, 'TM9', 'NLS_NUMERIC_CHARACTERS=''.,'''), or use json_arrayagg / json_objectagg, which always use ..

Optional styling in the column’s metadata:

columns:
activity:
label: Activity
width: 160
cell:
palette: wait-classes # segment colours by segment name (pack.yaml palettes)
colors: { CPU: "#3CB043" } # overrides the palette
scale: column # stacked-bar: column (default) = length relative to the largest row total | row = every bar fills the cell
trend:
cell:
style: area # sparkline: line (default) | area | bars
color: "#1F6FEB" # sparkline colour, or the bar colour of bar(…)
  • A segment name without a colour gets a stable colour derived from the name, the same in every row.
  • A column of graphics sorts by the bar value, the stacked total or the last sparkline point.
  • The tooltip lists the segments with values and shares (stacked-bar), or the point count, minimum, maximum and last value (sparkline). Values are formatted with the column’s format/unit.
  • Copy and the record renderer show the original text.

Example: the ASH samples of each SQL split by wait class.

select sql_id,
'stacked-bar(' || listagg(wait_class || '=' || n, ';') within group (order by n desc) || ')' activity
from (select sql_id, nvl(decode(session_state, 'ON CPU', 'CPU', wait_class), 'Other') wait_class, count(*) n
from gv$active_session_history
where sample_time >= :t_from and sql_id is not null
group by sql_id, nvl(decode(session_state, 'ON CPU', 'CPU', wait_class), 'Other'))
group by sql_id
refresh:
interval: 15s # interval when the view opens; omit = manual refresh only
choices: [5s, 15s, 1m, 5m] # offered in the view's refresh selector ("Off" is always offered)
minInterval: 5s # lower bound for any interval the user picks
autoStart: true # default true when interval is set
  • The view toolbar has a refresh selector (Off / the choices) and pause/resume; the user’s choice is remembered per definition.
  • A tick is skipped while the previous execution is still running. Views in hidden tabs do not refresh.
  • Every execution re-evaluates relative time values (§4.2).
  • In containers, see §12 for which views refresh on the timer.
display:
renderer: table # table|record|chart|text|document
alternatives: [record] # renderers offered in the switcher (compatible ones are offered anyway)
display:
renderer: chart
chart:
type: stacked-area # line|area|stacked-area|bar|stacked-bar
x: sample_time # time or category column
# long format:
series: wait_class
value: aas
# or wide format:
# values: [reads, writes]
yLabel: Average active sessions
palette: wait-classes # named palette from pack.yaml, or inline `colors: {CPU: "#3CB043"}`
maxPoints: 10000 # per series (default 10000); above it the series is decimated, never truncated
xRange: { from: t_from, to: t_to } # optional: input names; the x-axis spans the query window
fill: # optional, time axis: the x values lie on a regular grid
step: 1m # grid step (required)
missing: zero # zero (default): a grid position without a row is 0 for every series | gap: lines break there
selection: # optional: what a selection on this chart publishes
range: # dragging along a time x-axis selects an interval
from: perf.time.range.start
to: perf.time.range.end
click: bucket # point (default) | bucket | none
bucket: 1m # width of a clicked bucket; default = spacing of the x values
snap: data # data (default): interval edges snap to x values | none
default: { from: now-5m, to: now } # initial interval (time expressions); omit = nothing selected
follow: true # initial state of the view's "follow" toggle (default false)

Click.

  • click: point publishes the semantic keys of x, series (if any) and of every other column in the source row.
  • click: bucket (requires range) additionally publishes the interval [x, x + bucket) under the range keys. A click on one minute of an ASH chart is then the same as dragging over that minute.
  • Hit-testing: the clicked x is the nearest x value; the series is the one whose line (or stacked band / bar segment) is under the cursor. If no source row exists for that (x, series), only the x key (and, for bucket, the interval) is published.

Range (brush). Dragging along the x-axis publishes only the two range keys. A new selection replaces everything the chart published before: dragging after a click removes the clicked series and row keys. Esc or a click on an empty area clears the selection.

Follow. The view toolbar has a “follow” toggle.

  • On: the interval is kept relative to now. For example, 10:20–10:25 selected at 10:30 is kept as now-10m … now-5m, aligned to bucket. Each time the chart executes (e.g. on refresh), the interval is re-evaluated; if it changed, the new interval is published and dependent views re-execute.
  • Off: the interval is absolute. The chart refreshes, the selection stays where it is, nothing new is published, and dependent views do not re-execute. An interval that has scrolled out of the chart’s window stays selected and is marked as outside.

Gaps and missing points. Without fill, the renderer infers the step of a time axis from the data (the lower quartile of the distances) and breaks lines across wider gaps. That guess fails for sparse data, e.g. a sampler such as ASH on a quiet database, so such charts declare the grid:

  • missing: zero puts every multiple of step on the axis, from the start of the xRange window (floored to the step) to its end (exclusive), or over the data when there is no xRange. A position without a row is 0 for every series, so areas and lines drop to zero instead of bridging idle periods. Data x values off the grid are kept. A grid longer than 100 000 positions is not built (the data’s own x values are used).
  • missing: gap keeps only the data’s x values but breaks lines wherever two neighbours are more than step apart.

Decimation. When a series has more than maxPoints points, the renderer keeps the minimum and maximum of each x bucket, so peaks remain visible. The result model itself is never reduced.

renderer: text renders a single-column result as monospace lines (e.g. DBMS_XPLAN output).

display:
renderer: text
text: { format: sql } # optional

format: sql: the text is a SQL statement or procedural block. It is shown in two tabs, Original (as returned) and Formatted (keywords in upper case, one clause per line). Formatting is cosmetic and best effort; the original is never changed. The last tab chosen is remembered.

display:
renderer: document
document:
column: report # CLOB/BLOB column; first row is used
mime: text/html
open: external # external browser via a private temp file; "Save as…" always available

Rows that form a hierarchy (blocking chains, plan lines, object dependencies) are shown as a tree in the table renderer: each row with children gets a toggle (▾ expanded, ▸ collapsed) and is indented by its depth. A script that declares a tree is always shown as a tree; everything else about the table (formats, copy, navigation, in-cell graphics) stays.

display:
tree:
key: [inst_id, sid] # the columns that identify a row
parent: [blocking_instance, blocking_session] # the same row's parent's key: as many columns, in the same order
column: chain # where the toggles are (default: the first visible column)
expanded: all # all (default) | none | a number of levels shown expanded (1: roots and their children)

The short form is one string, the parent’s columns, >, the key’s columns; parentheses are optional for one column:

display:
tree: "(blocking_instance, blocking_session) > (inst_id, sid)"
# or
display:
tree: "parent_id > id"
  • A row whose parent columns are all NULL, or name no row of the result, is a root. A cycle that no root reaches starts at its first row in result order.
  • Children keep the order of the result (write order siblings by, or order by a path); sorting by a column header sorts the roots and each row’s children, keeping the tree.
  • Keys are compared by value: 1, 1.0 and a NUMBER 1 are the same key, whatever the column types.
  • A key should identify one row. Where the same key appears on several rows, children go under the first of them. A node that appears more than once (a process waiting on two others) needs a key of its own, e.g. its path from the root ("parent_path > path").
  • The parent columns are usually hidden: true; they still give their semantic keys to navigation.
  • Collapsed rows stay collapsed across refreshes (by key). The context menu has Expand all and Collapse all; Alt+Right and Alt+Left expand or collapse the selected row.
  • When the result lacks one of the columns, the rows are shown as a flat table.

Without steps, the whole body is one statement (step name main): a procedural block when its first word (after comments) starts one in the engine’s dialect (Oracle: BEGIN or DECLARE; PostgreSQL: none, a DO block is run as SQL), else SQL. The platform strips one trailing terminator line if the dialect has one (Oracle: /), and for SQL statements one trailing ;.

For several statements, declare steps and delimit the body with marker lines --@step <name> (a full line, at line start). The platform never splits on ;.

When steps is declared, markers are mandatory (even for a single step), their names and order must match steps exactly, and any text before the first marker other than whitespace and comments is an error.

steps:
- name: setup
type: session # sql|block|session (plsql: alias of block)
output: none # none|result|messages
- name: main
type: sql
output: result
label: Plan
--@step setup
alter session set statistics_level = all
--@step main
select ...
  • All steps run in order on one database session.
  • A failing step stops execution (unless continueOnError: true); the transaction policy is then applied.
  • A step may set serverOutput: true to capture the engine’s server output into messages (Oracle: DBMS_OUTPUT; PostgreSQL: notices). dbmsOutput is accepted as an alias.
  • block runs the text as one procedural block of the engine; how its binds are passed is the engine’s business (Oracle binds each occurrence separately inside a block).
  • Each output: result step produces its own result, shown as tabs or stacked (display.layout: tabs|stacked). Per-step display overrides are allowed.
  • type: exec is not a step type: a script for an engine’s own command-line client is a client script (§8.1).

client: sqlplus (or a list, client: [sqlplus, sqlcl]: the first one configured is used) makes the whole body a script for the engine’s own client (ADR 0008): SQL*Plus or SQLcl for Oracle, psql for PostgreSQL. OPA never runs it itself; its view shows the inputs and the text, and “Run in…” opens the client in a terminal window, logged on to the current connection, and runs it. Without exit (\q in psql) the client stays open.

/*---
id: diag.short_stack
title: Short Stack of a Process
category: Diagnostics
client: sqlplus
safety: dangerous
inputs:
- { name: spid, semantic: oracle.process.spid, type: integer, label: OS PID }
---*/
oradebug setospid &spid
oradebug short_stack
  • The body is taken as written: no steps, no bind parsing, no undeclared inputs; client commands (SET, COLUMN, SPOOL, \d) are allowed.
  • Inputs are the client’s own variables, set before the script: in SQL*Plus/SQLcl :name (a VARIABLE) and &name (a DEFINE), in psql :name (a \set holding a quoted SQL literal). A value in &name substitution is inserted as text: write '&name' for text, or use the bind :name, which takes any value.
  • The default safety is write: the run is confirmed with the text, the values and the connection. read runs it at once; dangerous asks for explicit acknowledgement.
  • Every other script can also be run in a client (“Run in” on its view): its steps become the client’s statements, each with the client’s end (;, / after a PL/SQL block).

Targets are found automatically from the targets’ inputs (§4.1); nothing needs to be wired between scripts.

navigation:
priority: 100 # on the TARGET: ranking among automatically found candidates
links: # on the SOURCE: explicit, optionally remapped targets
- target: sql.details
label: SQL details
default: true # double-click target
- target: sql.plan
map: # explicit remap: target input name <- source semantic key
sql_id: oracle.sql.id
hidden: false # true = never offered automatically, only via explicit links

Candidates. For a selection (table row, chart point or chart range), a definition is offered when:

  1. every identity input is satisfied from context (selection, inherited or global) with a compatible type; and
  2. at least one input with a semantic key (and fromContext not false) gets its value from the selection itself. Global, container or inherited keys alone never make a script a candidate, and a script whose inputs all fall back to defaults is not offered.

Definitions that meet rule 2 but miss an identity input are shown disabled, with the missing keys listed. Scripts without semantic inputs are reachable only through explicit links.

Ranking. First the source’s explicit links, then the number of inputs matched from the selection, then priority. Targets matched by the clicked column (table) or the clicked series/x (chart) come first, so a click on a SQL_ID cell lists SQL targets before session targets.

Default (double-click). An explicit link with default: true, else the unique top-ranked target. Ties show a chooser; the user’s pick can be remembered per source script and clicked column (a user preference, not pack data) and is then the default while those targets still tie. A unique default or an explicit default: true link always wins over a remembered pick; “Ask again on double-click” in the context menu forgets it. Actions with safety other than read are never a default.

Values. The opened target resolves its inputs as in §4.1: identity inputs from context; contextual parameters from context when present (so a drill-down from a dashboard selection inherits the selected interval), else from their defaults.

Type compatibility. integer → number always; number → integer only for integral values; date ↔ timestamp (to date drops fractional seconds); anything → string only through an explicit map. An incompatible value makes the target unavailable, with the reason shown.

  • write and dangerous show a confirmation dialog with the statement text and bound values.
  • dangerous additionally requires explicit acknowledgement.
  • confirm: "Kill session {sid},{serial} on instance {inst_id}?" may supply a human-readable summary. Placeholders reference input names and are display-only, never SQL.
  • The platform never builds SQL text from values. A pack script may do so itself in a procedural block (the kill-session example in §15 does, from integer binds); that is the script author’s responsibility and should be limited to typed, validated values.

11. Global context, database clock and requirements

Section titled “11. Global context, database clock and requirements”

kind: connection-init (referenced from pack.yaml) runs once after connecting (without one, the engine’s probe statement checks the connection) (and again after a reconnect). Its single-row result is mapped via columns into the global context. It must run on every database version the pack supports, and its own requires is ignored.

Special columns, by role:

Role Value
clock The database’s current time. The platform stores the difference to the local clock and uses it as now in time expressions (§4.2). Without such a column, now is the local clock and a warning is shown. In mock mode now is the local clock unless the fixture provides one.
version The database version, e.g. 19.0.0.0.0, 11.2.0.4.0 or 16.4 (the leading dotted number counts). Used for requires.version and variants (§11.1).
licenses The licences to suggest, comma- or space-separated (§11.2). NULL or empty suggests none.
capabilities What the database has, comma- or space-separated (§11.3): the capabilities declared in pack.yaml that are present. Names not declared are ignored; NULL or empty means none.
identity A stable name of the database (Oracle pack: DBID and database or PDB name; PostgreSQL: system identifier and database name). Names the local sample store (§17); without it, all databases share one store named unknown.

requires states what a script needs:

requires:
version: "11.2" # minimum database version (§11.1); quote it
licenses: [diagnostics] # licences declared in pack.yaml (§11.2)
context: # predicates over the global context
- key: oracle.db.edition
op: in # = != < <= > >=, or `in` with a list
value: [EE]

The list form requires: [ {key, op, value}, … ] is the context part alone. A context predicate whose key is absent from the global context is unsatisfied (the reason names the missing key). In mock mode the global context comes from the connection-init fixture.

Unavailable scripts (any requirement not met):

  • are hidden in the catalog unless “Show unavailable” is on, which shows them greyed with the reasons;
  • are never offered by navigation;
  • appear as a placeholder with the reasons inside a container (the child is not created);
  • are refused by the executor, so they never reach the database.

Before a database is connected, version and licenses are not evaluated; context predicates are.

Versions are dotted numbers compared part by part (11.2 < 11.2.0.4 < 12.1 < 19; trailing zeros are ignored). A script without requires.version and without an @version file suffix takes the pack’s default from pack.yaml (requires: { version: "19" }). Without a pack default, it has no minimum. Containers, connection-init and source: local scripts never take the pack default.

For each id the connection uses the variant (§1.1) with the highest minimum version that the database meets; between variants with the same version, the one needing more licences wins if the connection has them. If no variant fits, the best variant is listed as unavailable with its reasons.

Oracle pack: Oracle 26ai reports itself as 23.26.x (v$instance.version is 23.0.0.0.0; version_full and the banner carry the release update), so a variant for 26ai is named @23.26. The demo pack’s connection-init returns the full version: v$instance.version_full from 18c on (e.g. 19.19.0.0.0, so variants can name a release update), else the release from the v$version banner.

Example: with active.sql (pack default 19) and active@11.2.sql, a 19c database uses active.sql, an 11.2.0.4 or 18c database uses active@11.2.sql, and a 10.2 database has no Active Sessions.

Database options or management packs that must be licensed before a script may even query their views are declared in pack.yaml (the Oracle pack’s, as an example; a pack without paid options declares none, and the connection dialog then shows no licences):

licenses:
diagnostics:
label: Diagnostics Pack
objects: [gv$active_session_history, dba_hist_*, dbms_workload_repository]
tuning:
label: Tuning Pack
requires: [diagnostics] # needing tuning means needing diagnostics too
objects: [gv$sql_monitor, dbms_sqltune, dbms_sql_monitor]
  • A script that names an undeclared licence is rejected.
  • A script whose SQL uses one of a licence’s objects without requiring it gets a load-time warning. Matching is by unquoted identifier outside comments and literals; * is a wildcard; a dotted name counts each part.
  • For each connection the user confirms which licences the database has. The connection-init licenses column only pre-selects the dialog, because configuration is not a licence. The confirmed set is stored with the connection profile. Confirming a licence confirms the licences it requires.

What a database has installed or switched on, which OPA detects instead of asking (ADR 0007): PostgreSQL extensions, an Oracle CDB root. Declared in pack.yaml beside licences, in one namespace with them:

capabilities:
pgstattuple:
label: the pgstattuple extension # used in reasons: "requires the pgstattuple extension, which this database does not have"
objects: [pgstattuple, pgstattuple_approx, pgstatindex] # optional: using one without requiring it warns at load time
  • The connection-init’s role: capabilities column lists the ones present (§11). The pack decides what present means (PostgreSQL pack: the extension created in the database connected to and, where it needs it, in shared_preload_libraries). Nothing is confirmed by the user or stored in the profile.
  • A script requires them with requires: { capabilities: [...] }, or excludes itself with unless: { capabilities: [...] } (unavailable when all the listed ones are present).
  • The file suffix names them as it names licences: table_bloat+pgstattuple.sql. A +name is a licence or a capability by what the pack declares; a name declared as both is an error.
  • Variant choice (§11.1): the highest minimum version first, then the most licences and capabilities together. A variant x+cap.sql is used where cap is present, x.sql elsewhere.
  • Mock mode takes them from the connection-init fixture; --capabilities=a,b overrides them (empty: none).
  • showWhen: { capabilities: [...] } on a column or an input shows it only where the connection has them: one script serves every kind of database, with a column or input that matters only for some (the Oracle pack’s container column and input appear in a CDB root only). Elsewhere the column is hidden but still gives its context key to navigation.
id: dash.top_activity
title: Top Activity
category: Dashboards
kind: container
inputs:
- { name: t_from, semantic: perf.time.window.start, type: timestamp, default: now-60m }
- { name: t_to, semantic: perf.time.window.end, type: timestamp, default: now }
ranges:
- { from: t_from, to: t_to, label: Window, presets: [15m, 1h, 6h, 1d] }
refresh:
interval: 15s
choices: [5s, 15s, 1m]
layout:
type: split # split|tabs|grid|view
orientation: vertical
ratios: [0.55, 0.45]
children:
- view: ash.activity_by_wait_class
publishSelectionAs: picked
- type: tabs
contextFrom: picked
children:
- view: ash.top_sql_for_range
- view: ash.top_sessions_for_range
  • grid takes columns: N and places children row by row.
  • A view node may override display, refresh, and constant inputs.
  • Container inputs have no binds. They are shown in the container’s inputs bar and passed to children by semantic key, as inherited context.
  • Channels. A node with publishSelectionAs: <channel> publishes its selection to the channel. Nodes under contextFrom: <channel> (consumers) receive it as inherited context. A consumer waits (waiting-for-input) until the channel has a value; a chart’s selection.default provides an initial one.
  • Which views refresh. A view re-executes when (a) its own refresh tick fires, (b) its resolved inputs or its channel value changed, or (c) the user refreshes it. The container’s refresh applies to source views (nodes without contextFrom). Consumers by default re-execute only when their channel changes; a node may give a consumer its own refresh. refresh.group: true aligns the ticks of all timer-driven views in the container.

id from the relative path, title from the file name, kind: query, renderer: table, binds entered as text in the inputs bar, columns typed from JDBC metadata, semantic keys only from pack-wide columnKeys (§5.1).

Errors (script rejected):

  • unknown kind
  • malformed YAML
  • duplicate ids in a layer
  • an inputs entry without a matching bind (query and action only; container inputs are passed to children)
  • a numeric (:1) or ? bind placeholder
  • step markers that don’t match steps
  • a chart referencing missing columns (checked at render time)
  • an unsupported step type
  • an invalid time expression, or a time expression on an input that is not date/timestamp
  • a ranges entry or xRange naming an unknown input or an input that is not date/timestamp
  • selection.click: bucket without selection.range
  • a tree without key or parent, or with a different number of columns in each
  • an invalid requires.version; a file name suffix that disagrees with requires (§1.1)
  • a licence not declared in any pack.yaml
  • variants of a container or connection-init script

Warnings:

  • unknown fields
  • semantic type conflicts
  • an override shadowing a newer built-in version
  • binds without declared inputs
  • fromContext: false on an identity input (the value can then only be prompted)
  • a connection-init script without a role: clock column
  • a script using an object of a licence it does not require (§11.2)
  • requires.version in the header without an @version file name suffix; a file name with a malformed variant suffix
  • requires on a connection-init script (ignored)

Every diagnostic carries file, line and column.

Examples from the Oracle pack.

Pack descriptor

pack.yaml
name: oracle
engine: oracle
version: 1
formatVersion: 1
connectionInit: system.connection_init
requires: { version: "19" } # default minimum version of this pack's scripts (§11.1)
licenses: # §11.2
diagnostics: { label: Diagnostics Pack, objects: [gv$active_session_history, dba_hist_*] }
tuning: { label: Tuning Pack, requires: [diagnostics], objects: [gv$sql_monitor, dbms_sqltune] }
columnKeys:
sql_id: oracle.sql.id
inst_id: oracle.instance.number
sid: oracle.session.sid
serial#: oracle.session.serial
palettes:
wait-classes:
CPU: "#3CB043"
User I/O: "#1F6FEB"
System I/O: "#58A6FF"
Concurrency: "#8B0000"
Application: "#D73A49"
Commit: "#E36209"
Configuration: "#6F42C1"
Network: "#A0522D"
Cluster: "#F0E68C"
Other: "#E83E8C"

Connection init

/*---
id: system.connection_init
kind: connection-init
columns:
own_inst_id: oracle.app.own_inst_id
db_version_major: oracle.db.version_major
db_now: { semantic: oracle.db.now, role: clock }
---*/
select to_number(sys_context('userenv','instance')) own_inst_id,
to_number(regexp_substr(version, '^\d+')) db_version_major,
cast(systimestamp as timestamp) db_now -- server wall clock, as in ASH sample_time
from v$instance

ASH activity chart (source of a time selection)

/*---
id: ash.activity_by_wait_class
title: Activity by Wait Class
category: ASH
inputs:
- { name: t_from, semantic: perf.time.window.start, type: timestamp, default: now-60m }
- { name: t_to, semantic: perf.time.window.end, type: timestamp, default: now }
ranges:
- { from: t_from, to: t_to, label: Window, presets: [15m, 1h, 6h] }
columns:
sample_time: perf.time.minute
wait_class: oracle.wait.class
display:
renderer: chart
alternatives: [table]
chart:
type: stacked-area
x: sample_time
series: wait_class
value: aas
yLabel: Average active sessions
palette: wait-classes
xRange: { from: t_from, to: t_to }
selection:
range: { from: perf.time.range.start, to: perf.time.range.end }
click: bucket
bucket: 1m
default: { from: now-5m, to: now }
follow: true
refresh:
interval: 15s
choices: [5s, 15s, 1m, 5m]
---*/
select trunc(sample_time, 'MI') sample_time,
decode(session_state, 'ON CPU', 'CPU', wait_class) wait_class,
round(count(*) / 60, 2) aas
from gv$active_session_history
where sample_time >= :t_from
and sample_time < :t_to
group by trunc(sample_time, 'MI'), decode(session_state, 'ON CPU', 'CPU', wait_class)
order by 1

Top SQL for a time range (dashboard child, navigation target and standalone report)

/*---
id: ash.top_sql_for_range
title: Top SQL for Period
category: ASH
inputs:
- { name: t_from, semantic: perf.time.range.start, type: timestamp, default: now-15m }
- { name: t_to, semantic: perf.time.range.end, type: timestamp, default: now }
- { name: wait_class, semantic: oracle.wait.class, type: string, required: false }
- { name: top_n, type: integer, default: 20, label: Top N }
ranges:
- { from: t_from, to: t_to, label: Period, presets: [5m, 15m, 1h] }
---*/
select sql_id, count(*) samples, round(count(*) / ((cast(:t_to as date) - cast(:t_from as date)) * 86400), 2) aas
from gv$active_session_history
where sample_time >= :t_from
and sample_time < :t_to
and (:wait_class is null or decode(session_state, 'ON CPU', 'CPU', wait_class) = :wait_class)
group by sql_id
order by samples desc
fetch first :top_n rows only

Here t_from/t_to and wait_class are contextual parameters, top_n is local. sql_id gets its semantic key from the pack’s columnKeys. Opened from the catalog, the report runs for the last 15 minutes. In the dashboard it follows the chart’s selection. It is offered in a context menu only where the selection itself carries a time range or a wait class.

RTSM Active report

/*---
id: sql.rtsm_active
title: SQL Monitor Report (Active)
category: SQL
inputs:
- { name: sql_id, semantic: oracle.sql.id, type: string }
display:
renderer: document
document: { column: report, mime: text/html, open: external }
---*/
select dbms_sql_monitor.report_sql_monitor(
sql_id => :sql_id, type => 'ACTIVE', report_level => 'ALL') report
from dual

Kill session (action)

/*---
id: sessions.kill
title: Kill Session
category: Sessions
kind: action
safety: dangerous
transaction: none
confirm: "Kill session {sid},{serial} on instance {inst_id}?"
inputs:
- { name: inst_id, semantic: oracle.instance.number, type: integer }
- { name: sid, semantic: oracle.session.sid, type: integer }
- { name: serial, semantic: oracle.session.serial, type: integer }
steps:
- { name: kill, type: block, output: messages }
---*/
--@step kill
begin
-- values are typed integer binds; to_char() keeps the dynamic text numeric-only
execute immediate 'alter system kill session '''
|| to_char(:sid) || ',' || to_char(:serial) || ',@' || to_char(:inst_id)
|| ''' immediate';
end;

OPA’s AI assistant and its MCP server (ADR 0003) offer the pack’s scripts to a language model as tools: the model lists, describes and runs them. Only kind: query scripts with safety: read that are available on the connection are offered; actions never are. Inputs the model leaves out are resolved like a navigation, from the context of the window the chat was opened from, then from defaults. Three pieces of metadata control this.

Script: ai. ai: false keeps a script away from the assistant and MCP clients, e.g. an interactive HTML report that is large and useless to a model. Default true.

ai: false

Column: sensitive. Values that may hold business data (captured bind values, application text) are withheld before results leave OPA, unless the user’s data policy is Full. The model sees ‹redacted› instead.

columns:
value_string: { sensitive: true }

Independently of this, under the default Redacted policy, quoted literals in every text cell become '?', numbers compared with an operator or listed in IN (…) become ?, and bind values printed in plans (1 - :B1 (NUMBER): 42) are replaced. Column names, identifiers and plan structure stay.

Pack: ai.instructions. A Markdown file in the pack with domain instructions for the model: what the scripts are for, which to use for which question, how to reason. The instructions of all loaded packs are added to the system text, built-in layer first. The file must be inside the pack directory.

pack.yaml
ai: { instructions: ai/instructions.md }

Write the instructions for the model, not for people: name script ids, the semantic keys they take, and the licences they need. Keep them short: they are sent with every request.

Where the database keeps no activity history (PostgreSQL), or keeps one that may not be used without a licence (Oracle: ASH, part of the Diagnostics Pack), OPA can sample sessions itself and keep the samples in a local SQLite file, one per database (ADR 0004). Two pieces of metadata do this.

kind: sampler. One SQL query without binds, run every interval on a dedicated session outside the pool after connecting. Each run is one sample: its rows are appended to the local table, stamped with a sample id and the database time.

kind: sampler
unless: { licenses: [diagnostics] } # no sampling when the real thing is licensed
sampler:
table: session_samples # lowercase name; the view scripts query
interval: 1s # default 1s, at least 500ms; the user can change it in the status bar
retention: 7d # default 7d: older samples are deleted
full: 24h # default 24h: older samples are thinned...
thin: 10 # ...to every 10th, which then stands for 10 (weight)
  • Result columns must be plain names ([a-z_][a-z0-9_]*, case is ignored): alias serial# as serial. sample_id, sample_time and weight are reserved. A column added to the query later is added to the table; columns removed stay, as NULL.
  • Text is stored once in a dictionary, numbers as integers or reals (exactly, as text, beyond 64 bits), dates and timestamps as yyyy-MM-dd HH:mm:ss.fff text.
  • A tick that comes while the previous sample is still running is skipped, never queued.
  • Each sample ends the transaction its query may have begun (a rollback, free where the engine opens none), so the sampler’s session never shows as idle in a transaction.
  • Right after connecting, local scripts wait (up to 20 s) for the sampler’s first sample when its table does not exist yet, instead of failing.
  • The status bar shows the state and size; sampling can be stopped, started, its interval changed, and automatic start after connecting turned off.

unless. unless: { licenses: [...] } makes any definition unavailable when all the listed licences are confirmed for the connection. The reason reads “not used when Diagnostics Pack is licensed”. unless: { capabilities: [...] } does the same for capabilities (§11.3).

source: local. The script’s SQL steps run on the local sample store (SQLite 3.53 dialect) instead of the database. Binds work as everywhere (:name, passed as parameters, never as text); date and time binds are passed as yyyy-MM-dd HH:mm:ss.fff text, which compares correctly with stored times. Result column types come from the values: integers, numbers, text, and text shaped like a date and time (yyyy-MM-dd HH:mm[:ss[.fff]]) as timestamps, so strftime('%Y-%m-%d %H:%M:00', sample_time) is a time axis for a chart. Name result columns in upper case to match database scripts. A local script has no database version requirement, and the pack default version does not apply.

Each sampler table gives two views:

View Columns
<table> sample_id, sample_time, weight and the sampler’s columns: one row per sampled row
<table>_samples sample_id, sample_time, weight, elapsed_ms, row_count: one row per sample taken, including samples with no rows

Averages over a period divide by the samples taken, not by the length of the period: sum(weight) of rows / sum(weight) of <table>_samples. This stays right when ticks were skipped, OPA was closed part of the time, or samples were thinned.

-- average active sessions per minute
with taken as (
select strftime('%Y-%m-%d %H:%M:00', sample_time) minute, sum(weight) samples
from session_samples_samples where sample_time >= :t_from and sample_time < :t_to group by 1
)
select a.minute SAMPLE_TIME, round(1.0 * sum(a.weight) / t.samples, 2) AAS
from (select strftime('%Y-%m-%d %H:%M:00', sample_time) minute, weight from session_samples
where sample_time >= :t_from and sample_time < :t_to) a
join taken t on t.minute = a.minute
group by a.minute

Variants. A local script is usually a variant (§1.1) of a script that reads the licensed views: top_sql_for_range+diagnostics.sql and top_sql_for_range.sql (source: local) share the id ash.top_sql_for_range. With the licence the connection uses the first, without it the second, and dashboards, links and navigation do not change.

Export and offline analysis. “Export samples…” in the status bar writes the samples of a period to a new file; “Open samples file…” opens such a file without a database. Then local scripts read it, now is its last sample, the global context is the one recorded by the connection that wrote it, and database scripts refuse to run.