Skip to content

NQE

The Network Query Engine is how most integrations read the Forward model. Rather than fetching typed resources, you run a query and consume rows.

Two ways to run a query

run() sends the query and waits for the result in one request. Simple, and right for small or interactive queries.

result = client.nqe.run(
    "foreach d in network.devices select {name: d.name}",
    network_id="101",
    limit=1000,
)
result.items  # list[dict[str, Any]]
result.total_num_items  # how many rows the query produced in total

execute() starts the query in the background and returns a handle. This is what long-running or large queries need, and the only path that can stream.

execution = client.nqe.execute("foreach d in network.devices select {n: d.name}")
execution.wait()
for row in execution.rows():
    ...

query() wraps the second for the common case of "run this and give me every row":

rows = client.nqe.query(query_ref, network_id="101")

Naming a query

QueryRef covers the three mutually exclusive ways to identify a query:

from forward_sdk import QueryRef

QueryRef.inline("foreach d in network.devices select {n: d.name}")
QueryRef.by_id("FQ_ac651cb2901b067fe7dbfb511613ab44776d8029")
QueryRef.by_path("/NetBox/Devices")

A path is resolved to an ID before the query runs, through an index cached for the client's lifetime, so resolving many paths does not refetch the library each time. Pin a version with commit_id, and pass query parameters as keywords:

QueryRef.by_path("/NetBox/Devices", commit_id=commit, site="nyc")

Paging or streaming

rows() fetches a page at a time. Each page is its own request, so a transient failure is retried.

for row in execution.rows(page_size=10_000):
    ...

stream() reads the whole result as newline-delimited JSON. Rows arrive as they are produced, which is faster and uses less memory, but a dropped connection cannot be resumed.

for row in execution.stream():
    ...

Choose rows() when the run must survive a blip, and stream() when the result set is large and the run is short-lived.

Guard rails

Paging stops itself rather than hanging or exhausting memory:

from forward_sdk import PageGuards

rows = client.nqe.query(
    ref,
    guards=PageGuards(max_rows=500_000, max_pages=1000, repeat_limit=25),
)

Each limit raises ForwardPaginationError with what was collected so far. The guards also catch two server-side faults that would otherwise be invisible: a result set that ends before the total Forward promised, and a server that keeps returning the same full page without advancing.

The stalled-pager check compares each page's first and last row. A page whose first and last rows are identical is skipped, because it proves nothing: a query selecting a constant, select {n: 1}, gives every page the same first and last row whether the offset advanced or not. Counting those reported a stall at repeat_limit * page_size rows on a query that was paging correctly, which is easily mistaken for a server-side row cap. There is no such cap: a 545,464-row result pages to completion, and offset is honoured to the final row.

The trade is that a genuinely stalled server returning uniform rows is not diagnosed here. It still terminates, bounded by max_rows, max_pages and the total Forward reports.

Snapshots

Every query takes an optional snapshot_id. Omitting it, or passing None, runs against the network's latest processed snapshot without an extra lookup.

Telemetry

Each execution leaves a record on the client, so a job that runs many queries across threads can report what happened without holding on to the handles:

for report in client.nqe.execution_reports():
    print(
        report.query,
        report.rows_produced,
        report.millis_executing,
        report.poll_count,
        report.terminal_reason,
    )

terminal_reason is Forward's outcome when it finished, or the client-side reason waiting stopped. Retention is bounded and thread-safe, and reading it never raises, since the place it is usually read is a failure path.

Diffing across snapshots

changes = client.nqe.diff(QueryRef.by_id("FQ_..."), before="100", after="101")
for entry in changes:
    print(entry.type, entry.before, entry.after)

The snapshots are keyword-only because nothing in a pair of ids says which is which. before and after are independent and either may be absent: a row added between the snapshots has no before, a removed one has no after.

Only a committed query can be diffed, since Forward cannot diff source it has never seen. Passing inline source raises ForwardConfigurationError.

For inline source, or a query with parameters, diff on the client instead, keyed on columns you name:

changes = client.nqe.diff_source(
    "foreach d in network.devices select {name: d.name, os: d.platform.os}",
    before="100",
    after="101",
    key_columns=["name"],
)

It runs the query on both snapshots, reading every row, and returns entries in the shape Forward's diff does (ADDED, DELETED, MODIFIED, in key order). A key column missing from a row, or a key that repeats within one snapshot, raises ValueError. forward_sdk.nqe.diff_rows(before_rows, after_rows, ["name"]) does the same on rows you already have.

Typed rows

forward_sdk.nqe.decode_rows(rows, Model) validates each row into a pydantic model, dataclass or TypedDict. With normalize_enums=True, enum values such as Vendor.CISCO become CISCO first, so the model can use plain literals. It goes by shape, so ordinary text like a device named NYC.CORE1 is rewritten too.

State reads for change checks

Typed reads of the state a change check compares before and after, each run on one snapshot and read whole:

before = {s.key: s for s in client.nqe.bgp_sessions(snapshot_id=base_id)}
after = {s.key: s for s in client.nqe.bgp_sessions(snapshot_id=predicted_id)}
dropped = [
    k for k, s in before.items() if s.established and not (k in after and after[k].established)
]

lldp_adjacencies(devices=[...], skip_interfaces=["ma0"]), interface_admin() (use .up: Forward writes AdminStatus.UP, not UP), acl_entries() and acl_counts() work the same way. The queries are in forward_sdk.nqe.state.

The default ACL query identifies no entry: an ACL's entries share its device and name. To compare entries one by one, give a query that selects an identifying column and name it:

entries = client.nqe.acl_entries_with(
    query=my_acl_query,  # selects Device, AclName, Action and UUID
    key_columns=["Device", "UUID"],
    snapshot_id=base_id,
)
by_key = {e.identity: e for e in entries}  # e.row holds every column selected

A repeated key raises ValueError, since it would hide one entry behind another.

An NQE check's rows

Each NQE check result in the checks list carries nqe_result_key. client.nqe.check_result(snapshot_id, key, limit=100) reads the rows behind it. Forward answers in its internal run-result form, not the result page run() returns: use result.rows() for the rows with their typed cells unwrapped. result.truncated says only that this page is not all the rows, so page on the total:

rows, offset = [], 0
while True:
    page = client.nqe.check_result(snapshot_id, key, offset=offset, limit=1000)
    values = page.result.values or []
    rows += page.rows()
    offset += len(values)
    if not values or offset >= (page.result.total_num_values or 0):
        break

Pinning a query version

commit_id pins a query to one committed version. Two values are treated specially:

  • "head" is dropped, because Forward does not understand the symbolic name and omitting the field means the same thing.
  • An abbreviated hash raises ForwardConfigurationError. Forward needs the full 40 characters, and silently dropping the pin would run against whatever is at head and report success, which is exactly what pinning exists to prevent.

Query files

Queries shipped alongside your code usually need small transformations, which forward_sdk.nqe.files provides:

from forward_sdk.nqe.files import load_query, select_field_sets, missing_fields

source = load_query("queries/devices.nqe")  # ready to run
published = load_query("queries/devices.nqe", for_execution=False)

load_query strips the @primaryKey annotation, which the run endpoints reject, and inlines local import "..." lines, which the query library does not support. select_field_sets and missing_fields read the columns a query produces, which makes contract drift between a query and its consumer a test failure rather than a production surprise.

Reading a union value

Some NQE fields hold one of several cases, such as VlanIdOrRange in a trunk's trunkVlans (ID or RANGE). Field access on the union itself fails ("Can't access field 'ID' from 'entry'"); match it with when ... is, cases separated by semicolons, and otherwise as the default:

foreach device in network.devices
foreach iface in device.interfaces
where isPresent(iface.ethernet.switchedVlan)
foreach entry in iface.ethernet.switchedVlan.trunkVlans
let low = when entry is ID(i) -> i; RANGE(r) -> r.from
let high = when entry is ID(i) -> i; RANGE(r) -> r.to
select { device: device.name, intf: iface.name, low: low, high: high }

A case binds its payload: ID(i) gives the VLAN number, and RANGE(r) a record with from and to. A case with no payload is written NAME -> e. A when expression works anywhere an expression does, in let, select or where (where when entry is RANGE(r) -> true; otherwise -> false). A when has no then, else or match; for a plain condition use if c then a else b. The grammar is Forward's NqeParser.g4; the query above ran live on 26.10. client.nqe.schema() shows a union field as a OneOf type listing its cases.

Building predicates

Scoping a query at runtime means assembling query text from values, so escape them:

from forward_sdk.nqe.where import tag_scope, literal

scope = tag_scope(include=["core", "edge"], exclude=["lab"])
query = f"foreach d in network.devices\n{scope}\nselect {{n: d.name}}"

literal() renders a Python value as an NQE literal with correct escaping. Never interpolate a raw value into query text.

Two shapes, and picking the wrong one fails quietly:

Field holds Helper Emits
A collection, e.g. device.tagNames membership() "core" in device.tagNames
A string, e.g. device.platform.model one_of() device.platform.model in ["C9300"]
An enum, e.g. device.platform.vendor enum_one_of() device.platform.vendor == Vendor.CISCO

All three verified against a live instance. The distinctions are not stylistic:

  • membership() on a scalar matches nothing, so a probe built that way reports an empty scope on a healthy network and reads like a data problem.
  • one_of() on an enum fails at run time with the type of lookup value Vendor is not equal to list element type String, because NQE compares by type and an enum member is not a string.
from forward_sdk.models import Vendor
from forward_sdk.nqe.where import enum_one_of, membership, one_of

enum_one_of("device.platform.vendor", "Vendor", [Vendor.cisco, Vendor.arista])
one_of("device.platform.osVersion", ["17.9.4"])
membership("device.tagNames", ["production"])

Names are validated as identifiers rather than quoted, since quoting one turns it into a string and reintroduces the type error.

NQE's namespace is not the SDK's

The generated models describe Forward's REST schema. NQE's data model is a separate namespace, and the two disagree about type names and member names both. Do not build a predicate from forward_sdk.models; take the names from the NQE reference.

Type names, verified against a live instance:

Field NQE type SDK model class
device.platform.vendor Vendor Vendor
device.platform.deviceType DeviceType DeviceType
device.platform.os OS VendorOs

| cloudAccounts.cloudType | CloudType | — |

Passing `VendorOs` fails with *Variable VendorOs not in scope*.

Forward documents the NQE data model, and it is the authoritative source
for these names: each record's page under
`application/nqe/language/data-model` on docs.fwd.app links every field to
its type. There is no `VendorOs` page there, which is the tell. A
`toString()` rendering confirms it, since it prefixes the member with the
type name: `toString(device.platform.os)` gives `"OS.PAN_OS"`.

The same prefix matters when reading values back. A query selecting
`toString(device.platform.os)` yields `OS.PAN_OS`, not `PAN_OS`, so strip
the prefix if you want the bare member.

Enum members are validated as identifiers rather than quoted, since quoting one would make it a string and reintroduce the type error.

Retrying a transient failure

query() can resubmit a query whose execution ended with a transient outcome:

rows = client.nqe.query(ref, outcome_retries=2)  # SYSTEM_ERROR only, by default
rows = client.nqe.query(ref, outcome_retries=2, retry_outcomes={"SYSTEM_ERROR", "TIMED_OUT"})

Off by default. Forward's outcomes are OK, SYSTEM_ERROR, TIMED_OUT and USER_ERROR. A compile error (400) and a client-side ForwardTimeoutError are never retried. When the last attempt fails, ForwardExecutionError carries outcome, detail (Forward's error object) and attempts.