Skip to content

NQE

forward_sdk._sync.services.nqe.NqeService

Bases: Service

Run queries and read the query library.

run

run(
    query: QueryRef | str,
    *,
    network_id: str | None = None,
    snapshot_id: str | None = None,
    offset: int = 0,
    limit: int | None = DEFAULT_PAGE_SIZE,
    column_filters: Sequence[Mapping[str, Any]]
    | None = None,
    sort_by: Mapping[str, Any] | None = None,
) -> NqeRunResult

Run a query and return one page of results.

Parameters:

Name Type Description Default
query QueryRef | str

A :class:QueryRef, or query source as a string.

required
network_id str | None

Defaults to the client's network.

None
snapshot_id str | None

Defaults to the network's latest processed snapshot.

None
limit int | None

Rows per page, at most 10,000.

DEFAULT_PAGE_SIZE

execute

execute(
    query: QueryRef | str,
    *,
    network_id: str | None = None,
    snapshot_id: str | None = None,
    column_filters: Sequence[Mapping[str, Any]]
    | None = None,
    parameters: Mapping[str, Any] | None = None,
    sort_keys: Sequence[SortKey | str] | None = None,
    use_latest_data_files: bool | None = None,
) -> NqeExecution

Start a query in the background and return a handle to it.

parameters and sort_keys are conveniences for the common case; :class:QueryRef carries the same things when a reference is built once and reused.

Parameters:

Name Type Description Default
use_latest_data_files bool | None

Evaluate against the most recently uploaded data files instead of the versions the snapshot captured. Forward defaults this to false, which keeps a query reproducible against a snapshot; setting it means two runs of the same query against the same snapshot can differ.

None

execute_and_wait

execute_and_wait(
    query: QueryRef | str,
    *,
    network_id: str | None = None,
    snapshot_id: str | None = None,
    timeout: float | None = 1800.0,
    outcome_retries: int = 0,
    retry_outcomes: Collection[str] = TRANSIENT_OUTCOMES,
    retry_delay: float = 2.0,
) -> NqeExecution

Start a query, wait for it, and return the finished execution.

For callers that read results themselves, for example one bounded page through result_page(). outcome_retries, retry_outcomes and retry_delay behave as in :meth:query, which is built on this.

execution

execution(
    key: str, *, network_id: str | None = None
) -> NqeExecution

A handle on an execution that already exists, by its key.

Makes no request. Call status(), wait() or result_page() on it.

query

query(
    query: QueryRef | str,
    *,
    network_id: str | None = None,
    snapshot_id: str | None = None,
    page_size: int = MAX_PAGE_SIZE,
    guards: PageGuards | None = None,
    timeout: float | None = 1800.0,
    stream: bool = False,
    outcome_retries: int = 0,
    retry_outcomes: Collection[str] = TRANSIENT_OUTCOMES,
    retry_delay: float = 2.0,
) -> list[Row]

Run a query in the background and return every row.

The common case: start the query, wait for it, and collect the results.

Parameters:

Name Type Description Default
stream bool

Read results as a single stream rather than paging. Faster for large result sets, but a dropped connection cannot be resumed.

False
outcome_retries int

Extra submissions allowed when the execution finishes with an outcome in retry_outcomes. Off by default. The transport already retries failed HTTP requests; this covers a query that ran and ended badly. timeout applies to each attempt. A ForwardTimeoutError and a compile error (HTTP 400) are never retried, and USER_ERROR only if you add it.

0
retry_outcomes Collection[str]

Which outcomes count as transient. Forward's are SYSTEM_ERROR, TIMED_OUT and USER_ERROR; the default is SYSTEM_ERROR alone.

TRANSIENT_OUTCOMES
retry_delay float

Seconds before the first resubmission; doubles each time.

2.0

Raises:

Type Description
ForwardExecutionError

The final attempt failed; attempts says how many were made.

diff

diff(
    query: QueryRef | str,
    *,
    before: str,
    after: str,
    page_size: int = DEFAULT_PAGE_SIZE,
    guards: PageGuards | None = None,
) -> list[NqeDiffEntry]

Compare a query's results between two snapshots.

The query comes first, matching :meth:run and :meth:execute, and the snapshots are keyword-only because nothing in a pair of ids says which is which.

Only a committed query can be diffed; Forward has no way to diff query source it has never seen.

Parameters:

Name Type Description Default
query QueryRef | str

A committed query, by id or library path.

required
before str

The snapshot to compare from.

required
after str

The snapshot to compare to.

required

Returns:

Type Description
list[NqeDiffEntry]

One entry per changed row. before and after are independent

list[NqeDiffEntry]

and either may be absent: a row added between the snapshots has no

list[NqeDiffEntry]

before, a removed one has no after.

diff_source

diff_source(
    query: QueryRef | str,
    *,
    before: str,
    after: str,
    key_columns: Sequence[str],
    network_id: str | None = None,
    page_size: int = MAX_PAGE_SIZE,
    guards: PageGuards | None = None,
) -> list[NqeDiffEntry]

Diff a query's results between two snapshots on the client, keyed on key_columns.

For what :meth:diff cannot do: Forward's diff takes only a committed query, so inline source, or a query with parameters, is diffed here. Runs the query on both snapshots with :meth:query (every row, with its page checks) and compares in memory with :func:forward_sdk.nqe.rows.diff_rows, so size guards to what you can hold. Entries come back in Forward's diff shape (ADDED, DELETED, MODIFIED; unchanged rows left out), in key order.

Raises:

Type Description
ValueError

A key column is missing from a row, or repeats within one snapshot's rows.

bgp_sessions

bgp_sessions(
    *,
    snapshot_id: str | None = None,
    network_id: str | None = None,
    guards: PageGuards | None = None,
) -> builtins.list[BgpSession]

Every BGP neighbor with its session state, as typed rows.

Read whole, like :meth:query. A network with no BGP is an empty list. Compare snapshots on :attr:BgpSession.key.

lldp_adjacencies

lldp_adjacencies(
    *,
    snapshot_id: str | None = None,
    network_id: str | None = None,
    devices: Sequence[str] = (),
    skip_interfaces: Sequence[str] = (),
    guards: PageGuards | None = None,
) -> builtins.list[LldpAdjacency]

Every LLDP neighbor, optionally only on devices and without skip_interfaces.

Names are matched exactly; one with a quote, backslash or newline is refused before sending.

interface_admin

interface_admin(
    *,
    snapshot_id: str | None = None,
    network_id: str | None = None,
    guards: PageGuards | None = None,
) -> builtins.list[InterfaceAdmin]

Every interface's administrative state. Use :attr:InterfaceAdmin.up, not the text.

acl_entries

acl_entries(
    *,
    snapshot_id: str | None = None,
    network_id: str | None = None,
    guards: PageGuards | None = None,
) -> builtins.list[AclEntry]

Every ACL entry, one row each. :meth:acl_counts is the usual consumer.

acl_entries_with

acl_entries_with(
    *,
    query: str | None = None,
    key_columns: Sequence[str] = (),
    snapshot_id: str | None = None,
    network_id: str | None = None,
    guards: PageGuards | None = None,
) -> builtins.list[AclEntry]

:meth:acl_entries with a query and key of your own.

query must select the Device, AclName and Action columns and every column in key_columns; select one that makes each entry unique (aclEntry.uuid where the vendor has one) and name it there. Each entry keeps the whole row (row) and its key values (identity). With key_columns a repeated key raises ValueError, since it would hide one entry behind another. Without a query the default one is used, which identifies no entry, so key_columns must then be empty; an empty query counts as none, as in Go. Mirrors the Go SDK's ACLEntriesWith.

acl_counts

acl_counts(
    *,
    snapshot_id: str | None = None,
    network_id: str | None = None,
    guards: PageGuards | None = None,
) -> dict[tuple[str, str], int]

The number of entries in each ACL, keyed by (device, ACL name).

check_result

check_result(
    snapshot_id: str,
    result_key: str,
    *,
    offset: int | None = None,
    limit: int | None = None,
    options: NqeCheckResultOptions
    | Mapping[str, Any]
    | None = None,
) -> NqeCheckResult

One page of the rows behind an NQE check, by the check's nqeResultKey.

The key is on each NQE check's result in the checks list, and must belong to snapshot_id (Forward answers 400 otherwise). Forward answers with its internal run result, not the published result page: result.rows() gives the rows with the typed cells unwrapped. result.truncated compares this page with the total only; to read every row, page while offset + len(values) < totalNumValues. options takes sortBy and columnFilters too; itemFormat is refused by Forward, so it is dropped if present. Unpublished (NqeController.getNqeQueryResults); the shape was seen live on 26.11.

diff_page

diff_page(
    query: QueryRef | str,
    *,
    before: str,
    after: str,
    offset: int = 0,
    limit: int | None = DEFAULT_PAGE_SIZE,
) -> NqeDiffResult

Compare two snapshots and return one page of changes.

The counterpart to :meth:run for diffs. :meth:diff pages to completion, which is the wrong shape for showing an operator the first rows that changed: that would fetch the whole diff to display fifty rows. Page guards cannot stand in for this, because a page ceiling raises rather than stopping, which is right for a ceiling and wrong for a limit.

totalNumRows reports the size of the whole diff, so a caller can show how much was not fetched.

execution_reports

execution_reports() -> list[ExecutionReport]

What happened to each execution this client has run.

Retained on the client rather than only on the handle, because the convenience wrapper :meth:query does not hand the handle back, and a sync fanning many queries across threads asks once at the end rather than holding each one.

Bounded and thread-safe; reading it never raises.

schema

schema(
    snapshot_id: str | None = None,
) -> AnalysisNqeInlinedType

The NQE data model as one tree, member types written out inline.

Unpublished. Large, and recursive. A type's deprecated is a flag; a field's is the advice to follow instead.

run_metrics

run_metrics(
    *,
    from_: str | None = None,
    to: str | None = None,
    min_execution_seconds: int | None = None,
    limit: int | None = None,
) -> list[AnalysisNqeRunMetric]

Recent slow NQE runs. Unpublished, and it needs the DEBUG_NQE permission.

queries

queries(directory: str | None = None) -> list[NqeQuery]

List queries in the library.

resolve

resolve(query: QueryRef | str) -> QueryRef

Look up a library path and return a reference that can be run.

forward_sdk._sync.services.nqe.NqeExecution

A query running in the background on Forward.

Obtained from :meth:NqeService.execute. Call :meth:wait to block until it finishes, then :meth:rows or :meth:stream to read the results.

last_status property

last_status: str | None

The most recent status seen, without making a request.

millis_executing property

millis_executing: int | None

How long Forward reports it has spent on this query.

is_finished property

is_finished: bool

Whether the last status seen was terminal, without making a request.

timeout_minutes property

timeout_minutes: int | None

The budget Forward allows this execution, in minutes.

server_deadline property

server_deadline: float | None

When Forward's own budget for this execution runs out.

A time.monotonic() value, or None if Forward has not said.

report property

report: ExecutionReport

What happened to this execution, so far.

status

status() -> NqeExecutionStatus

Fetch the execution's current status.

result_key

result_key() -> str | None

The key naming this execution's result, once it has one.

Forward's published status omits it; the variant its UI reads carries it as resultKey, R_ and twenty hex characters. It is what NQE panel metrics (client.nqe_panels) and cached result reads take. None until the execution completes with an OK or USER_ERROR outcome, so call :meth:wait first.

wait

wait(
    *,
    poll_interval: float = POLL_INTERVAL,
    timeout: float | None = 1800.0,
) -> NqeExecutionStatus

Poll until the execution finishes.

Returns:

Type Description
NqeExecutionStatus

The final status.

Raises:

Type Description
ForwardExecutionError

The query finished without producing results, because it failed, timed out on the server, or was canceled.

ForwardTimeoutError

timeout elapsed first. The query keeps running on Forward; the handle stays usable.

result_page

result_page(
    *, offset: int = 0, limit: int | None = None
) -> NqeRunResult

Fetch one page of results as the API returns it.

rows

rows(
    *,
    page_size: int = MAX_PAGE_SIZE,
    guards: PageGuards | None = None,
) -> Iterator[Row]

Iterate every result row, a page at a time.

Prefer this to :meth:stream when a transient failure should be retried: each page is a separate request, so one can be re-sent, whereas an interrupted stream cannot be resumed.

stream

stream() -> Iterator[Row]

Stream every result row as newline-delimited JSON.

Lower latency and lower memory than :meth:rows because rows are yielded as they arrive, but the request cannot be resumed if the connection drops partway.

forward_sdk._sync.services.nqe_repo.NqeRepository

Bases: Service

The NQE query library.

Every method here uses unpublished endpoints; see the module docstring.

queries

queries(
    *,
    repository: str = "org",
    commit_id: str = "head",
    path: str | None = None,
    with_source: bool = False,
) -> list[RepositoryQuery]

List queries in a repository.

Forward honours path and with_source only against a specific commit. Asked at head it ignores both and returns the whole library without source, so a caller filtering by path would think the filter had applied, and one auditing published source against what it ships would find every query source-unavailable and conclude nothing was wrong. So head is resolved to its commit first whenever either is requested.

Source is per query: Forward rejects with_source without a path, because it will not stream the whole library's text at once. That is raised here as a configuration error rather than sent, since the server's own message names the parameter combination and not the reason.

Raises:

Type Description
ForwardConfigurationError

If with_source is set without a path. Use :meth:source for one query's text.

index

index(
    *, repository: str = "org", refresh: bool = False
) -> dict[str, RepositoryQuery]

Map every query path to its entry.

Cached for the client's lifetime, because resolving a batch of query paths otherwise re-fetches the whole library for each one. Any write through this object clears the cache.

find

find(
    path: str, *, repository: str = "org"
) -> RepositoryQuery

Look up one query by its library path.

Raises:

Type Description
ForwardNotFoundError

If no query exists at that path.

source

source(path: str, *, repository: str = 'org') -> str

The committed source of one query.

Forward honours path and with=sourceCode only against a specific commit. Asking at head silently ignores both: it returns the whole library, without source, and a caller filtering by path would think the filter had applied. So this resolves the query's commit first and then fetches that version.

A failure to ask is never reported as an absent query. A timeout or a server error propagates as itself, because it is not evidence about what is published: a consumer auditing a library against what it ships would otherwise read one gateway timeout as every query having disappeared.

Raises:

Type Description
ForwardNotFoundError

If no query exists at that path, or the committed version carries no source.

ForwardAPIError

If the lookup itself failed. Distinct from the above on purpose; see above.

bundle

bundle(
    entry: str,
    *,
    commit_id: str,
    overrides: Mapping[str, str] | None = None,
    repository: str = "org",
) -> NqeBundle

One self-contained query: entry and its imports, some replaced.

Every module is read at commit_id unless overrides supplies its source, so an edit to a deeply imported helper can be run -- and compared with the commit it came from -- before anything is committed. Pass the result's source to QueryRef.inline. Forward resolves an inline query's imports against the library's head, or not at all, so a bundle imports nothing. See :mod:forward_sdk.nqe.bundle.

"head" is accepted and resolved once, and the resolved commit is recorded on the bundle, so two bundles built minutes apart cannot silently read different versions of the same module.

Parameters:

Name Type Description Default
entry str

Library path of the query to run.

required
commit_id str

The library commit to read every other module at.

required
overrides Mapping[str, str] | None

Replacement source keyed by library path. A path that is not already imported may be added this way only if a replaced module imports it.

None

Raises:

Type Description
NqeBundleError

If the modules cannot be merged safely, an override names a module the query never imports, or a module imports Forward's own library, whose commit this does not pin.

ForwardNotFoundError

If a module is missing at that commit.

source_by_id

source_by_id(
    query_id: str, commit_id: str
) -> AnalysisNqeQuerySource

A query's source at one commit, by its id. Both are required.

head_commit_id

head_commit_id() -> str | None

The organization repository's current commit.

history

history(query_id: str) -> list[dict[str, Any]]

List the commits that touched a query.

export_org_sources

export_org_sources(paths: Sequence[str]) -> dict[str, str]

The source of org library queries under paths, by query path, in one request.

A path ending in / is a directory (everything under it, so ["/"] is the whole library); any other is one query. It is the CALLING USER'S view of the library, the committed head with that user's drafts applied, not a fixed commit, and it also includes the non-Forward queries the requested ones import. A path that matches nothing is simply absent. Read from Forward's source; not run live.

export_forward_sources

export_forward_sources(
    paths: Sequence[str],
) -> dict[str, str]

:meth:export_org_sources for the Forward Library at its head.

Queries the organization's license tier does not permit are left out.

drafts

drafts() -> list[DraftChange]

List the current user's staged, uncommitted changes.

stage_add

stage_add(path: str, source: str) -> None

Stage a new query.

stage_edit

stage_edit(
    path: str,
    source: str,
    *,
    query_id: str,
    commit_id: str | None = None,
) -> None

Stage a change to an existing query.

The basis identifies the version being edited, so Forward can reject an edit built on a version that has since moved on.

stage_directory

stage_directory(path: str) -> None

Create a directory in the library.

Forward expects a trailing slash here and rejects the path without one, so it is added if missing.

discard

discard(path: str) -> None

Discard one staged change, whether a query or a directory.

A trailing slash is removed. Forward is asymmetric here: creating a directory requires the slash and discarding it requires its absence, and passing the path back exactly as the draft listing reports it fails with an unhelpful message about access settings. Left alone, that asymmetry strands every directory a failed publish created.

dry_run

dry_run(
    paths: Sequence[str], *, snapshot_id: str | None = None
) -> dict[str, Any]

Validate staged changes without committing them.

Returns Forward's report, including any errors the changes would introduce and which existing queries depend on them.

Paths with nothing staged are dropped and the dry run retried, exactly as :meth:commit does, because a dry run is the same request with a flag and Forward refuses it for the same reason. Without this, the documented recommendation to dry-run before publishing and the no-op case of publishing an unchanged corpus could not be used together: the dry run raised where the commit would have reported. When every path is unchanged there is nothing to validate, and an empty report is returned rather than an error.

commit

commit(
    paths: Sequence[str], *, title: str, body: str = ""
) -> CommitReport

Commit staged changes.

Paths with nothing staged are dropped and the commit retried, because publishing a set of files where some are unchanged is the normal case, not an error.

publish

publish(
    files: Mapping[str, str],
    *,
    title: str,
    body: str = "",
    repository: str = "org",
    dry_run_snapshot_id: str | None = None,
    discard_on_failure: bool = True,
    overwrite_drafts: bool = False,
    ensure_directories: bool = True,
) -> CommitReport

Publish a set of queries to the library in one commit.

Each path is staged as an addition or an edit depending on whether it already exists, optionally validated, then committed together.

Parameters:

Name Type Description Default
files Mapping[str, str]

Library path to query source. Paths gain a leading slash.

required
dry_run_snapshot_id str | None

Validate against this snapshot before committing. Recommended: it catches a query that no longer compiles before it reaches anyone else.

None
discard_on_failure bool

Remove staged drafts if publishing fails, so a failed run does not leave half-staged changes behind.

True
overwrite_drafts bool

Publish even when one of these paths already has an uncommitted draft. Off by default: a commit names paths, not changes, so someone's half-finished edit sitting on a path you are publishing would be committed along with yours, and neither of you would be told.

False
ensure_directories bool

Create any enclosing directories that do not exist yet. Forward refuses to stage a query whose directory is missing, so a first publish into a new directory fails without this.

True

Raises:

Type Description
ForwardConflictError

If a path already has a draft and overwrite_drafts is not set.

forward_sdk.nqe.query_ref.QueryRef dataclass

Identifies a query to run, in exactly one of three ways.

Build one with :meth:inline, :meth:by_id or :meth:by_path rather than calling the constructor directly.

Attributes:

Name Type Description
text str | None

Query source, to run without saving it.

query_id str | None

A committed query's ID.

path str | None

A path in the query library, resolved to an ID before running.

repository Repository

Which library a path refers to. org is your organization's; fwd is the one Forward ships.

commit_id str | None

Pins a specific version. Omit for the latest.

parameters Mapping[str, Any]

Values for the query's declared parameters.

sort_keys Sequence[SortKey]

Server-side ordering of results.

resolved_query_id str | None

Filled in once a path has been looked up.

resolved_commit_id str | None

The commit the resolution came from.

effective_query_id property

effective_query_id: str | None

The ID to send, preferring one obtained by resolving a path.

is_runnable property

is_runnable: bool

Whether this can be sent as-is, without resolving a path first.

inline classmethod

inline(text: str, **parameters: Any) -> QueryRef

Run query source directly, without saving it to the library.

by_id classmethod

by_id(
    query_id: str,
    *,
    commit_id: str | None = None,
    **parameters: Any,
) -> QueryRef

Run a committed query by its ID (FQ_...).

by_path classmethod

by_path(
    path: str,
    *,
    repository: Repository = "org",
    commit_id: str | None = None,
    **parameters: Any,
) -> QueryRef

Run a query by its path in the query library.

resolved

resolved(
    query_id: str, commit_id: str | None = None
) -> QueryRef

Return a copy carrying the ID a path lookup produced.

to_payload

to_payload(*, include_sort: bool = True) -> dict[str, Any]

Build the request body identifying this query.

Raises:

Type Description
ForwardConfigurationError

If a library path has not been resolved to an ID yet. Call client.nqe.resolve() first.

forward_sdk.nqe.pagination.PageGuards dataclass

Limits applied while paging.

Attributes:

Name Type Description
max_pages int

Stop after this many requests.

max_rows int

Stop after this many rows. Guards memory: the page ceiling alone would permit tens of millions of rows.

repeat_limit int

How many identical full pages to tolerate before concluding that paging is not advancing.

deadline float | None

A time.monotonic() value after which to stop.

forward_sdk.nqe.files

Working with .nqe query files.

Integrations that ship queries alongside their code hit the same three problems, which the Forward NetBox and Nautobot plugins each solved separately:

  • A query saved in the library carries an @primaryKey annotation that the run endpoints reject, so it must be stripped before running inline.
  • Query files import shared helpers from neighbouring files, but the library has no notion of a local import, so imports must be inlined before publishing.
  • The columns a query produces are a contract with the code consuming them, and drift between the two is worth catching in a test rather than in production.

strip_primary_key

strip_primary_key(source: str) -> str

Remove @primaryKey annotations so a query can be run inline.

The annotation is meaningful only to the query library. The run endpoints reject it, so a file that is both published and run inline needs both forms.

contract_version

contract_version(source: str) -> str | None

Return the @contract-version recorded in the file, if any.

select_field_sets

select_field_sets(
    source: str,
) -> tuple[tuple[str, ...], ...]

Return the field names of each select { ... } block.

Used to check that a query still produces the columns its consumer expects. This is a structural scan, not a parser: it reads field names at the start of a line and tracks brace depth, which is enough for the conventional layout and does not require an NQE grammar.

local_import_closure

local_import_closure(
    path: Path, *, root: Path | None = None
) -> tuple[Path, ...]

Return path's local imports, dependencies first, without duplicates.

Raises:

Type Description
ValueError

On an import cycle, a missing file, or a path that escapes root.

inline_local_imports

inline_local_imports(
    path: Path, *, root: Path | None = None
) -> str

Return path's source with its local imports expanded in place.

The query library has no local imports, so a query split across files has to be flattened before it can be published. Imported files are concatenated dependencies-first, with their own import lines removed.

load_query

load_query(
    path: str | Path,
    *,
    for_execution: bool = True,
    inline_imports: bool = True,
    root: Path | None = None,
) -> str

Read a .nqe file, ready to run or ready to publish.

Parameters:

Name Type Description Default
path str | Path

The query file.

required
for_execution bool

Strip @primaryKey, which the run endpoints reject. Set False when publishing to the library, which needs it.

True
inline_imports bool

Expand local import "..." lines.

True
root Path | None

Directory imports may not escape. Defaults to the file's own.

None

iter_query_files

iter_query_files(directory: str | Path) -> Iterable[Path]

Yield the .nqe files in directory, in a stable order.

missing_fields

missing_fields(
    source: str, expected: Sequence[str]
) -> tuple[str, ...]

Return expected column names that no select block produces.

forward_sdk.nqe.bundle

Combine a library query and its imports into one self-contained source.

Forward runs only committed queries by ID. Inline source can import library modules, but those imports resolve against the library's current head: the synchronous endpoint resolves them there, the asynchronous one does not resolve them at all, and neither accepts a commit to pin them to. So a change to a module three imports deep cannot be tried without committing it first, and a baseline cannot be rerun once head has moved past it.

A bundle solves both. Every module is supplied as source -- fetched at a pinned commit, or replaced by a local edit -- and merged into a single program that imports nothing. Merging needs more than concatenation, because modules keep private helpers with the same names (two flatten definitions is ordinary), and a module sees only what it declares and what its direct imports export. So each module's top-level declarations are renamed with a per-module prefix, and every reference is rewritten to the declaration it resolved to before merging.

This is a token-level rewrite driven by the NQE lexer's rules, not a parser. It understands what it must in order to rename safely -- string, text-block, regex and pattern literals, comments, field selectors, record field names and shorthand, sort keys, when tags, parameters and local bindings -- and raises :class:NqeBundleError rather than guess at anything else. Forward typechecks the result, so a rewrite mistake surfaces as a compile error rather than a wrong answer in almost every case; comparing a bundle of an unchanged commit with that commit run by ID catches the rest.

NqeBundleError

Bases: ForwardConfigurationError

A set of modules could not be combined safely into one query.

NqeBundle dataclass

One self-contained query built from a library query and its imports.

Attributes:

Name Type Description
entry str

Library path of the query the bundle runs.

source str

The combined source, ready for QueryRef.inline.

modules tuple[str, ...]

Every module included, dependencies first, entry last.

overridden tuple[str, ...]

The modules whose source came from the caller rather than the library.

commit_id str | None

The library commit the other modules were read from, when the bundle was fetched from a repository.

module_path

module_path(import_target: str) -> str

The library path an import names, in the SDK's leading-slash form.

Imports are absolute library paths written without the leading slash. Forward's own library is addressed as @fwd/... and is kept that way.

import_paths

import_paths(source: str) -> tuple[str, ...]

The library paths a module imports, in the order it imports them.

bundle_sources

bundle_sources(
    entry: str, sources: Mapping[str, str]
) -> NqeBundle

Merge entry and everything it imports into one query.

Parameters:

Name Type Description Default
entry str

Library path of the query to run, as in sources.

required
sources Mapping[str, str]

Source for every module in the import closure, keyed by library path (/Dir/Query, or @fwd/...).

required

Raises:

Type Description
NqeBundleError

If a module is missing, imports form a cycle, or a module uses something this rewrite cannot rename safely.

tokenize

tokenize(source: str) -> list[Token]

Split NQE source into the tokens the rewrite needs.

Whitespace and comments are dropped; their text survives because rewriting splices the original source by position. Literals are single opaque tokens: identifiers inside a pattern or regex are capture names, not references.

forward_sdk.nqe.where

Building NQE predicate clauses.

Integrations scope queries at runtime -- to a set of device tags, to a subset of a network -- which means assembling query text from user-supplied values. Doing that with string formatting invites both broken queries and injected clauses, so every value goes through :func:literal.

literal

literal(value: object) -> str

Render a Python value as an NQE literal.

JSON encoding is used deliberately: NQE's string, number and boolean literals match JSON's, so this escapes quotes, backslashes and control characters correctly rather than approximately.

membership

membership(
    expression: str,
    values: Sequence[str],
    *,
    match: MatchMode = "any",
    negate: bool = False,
) -> str | None

Test whether a collection contains any of values.

Emits "value" in expression, so expression must be a collection -- device.tagNames, device.groupNames. For a scalar field such as device.platform.vendor use :func:one_of instead: asking whether a string is a member of a scalar matches nothing, and a probe built that way reports an empty scope on a perfectly healthy network, which reads like a data problem rather than a predicate one.

Parameters:

Name Type Description Default
expression str

The collection to test against, e.g. device.tagNames.

required
values Sequence[str]

Values to test for. Empty means no constraint.

required
match MatchMode

Whether one value must be present (any) or all of them (all). Ignored when negate is set.

'any'
negate bool

Exclude anything carrying any of the values. Exclusion is all-or-nothing by nature: "exclude these tags" means none of them may be present, so match does not apply.

False

Returns:

Type Description
str | None

The clause, or None when values is empty, so callers can drop

str | None

an unconstrained filter rather than emit where true.

one_of

one_of(field: str, values: Sequence[Any]) -> str | None

Test whether a string-valued field equals any of values.

Emits field in ["a", "b"], the other direction from :func:membership: here the field is on the left and the collection is the literal.

The field must hold a string. NQE compares by type, so applying this to an enum field such as device.platform.vendor fails at run time with the type of lookup value Vendor is not equal to list element type String. Use :func:enum_one_of for those; model and osVersion are strings and belong here.

Returns:

Type Description
str | None

The clause, or None when values is empty.

enum_one_of

enum_one_of(
    field: str, enum_type: str, values: Sequence[Any]
) -> str | None

Test whether an enum field equals any of values.

Emits (f == Vendor.ARISTA || f == Vendor.CISCO). NQE enum values are named constants rather than strings, so they are compared directly and are deliberately not quoted:

>>> enum_one_of("device.platform.vendor", "Vendor", ["ARISTA", "CISCO"])
'(device.platform.vendor == Vendor.ARISTA || device.platform.vendor == Vendor.CISCO)'

enum_type is the name of the type in NQE, which is not always the name of the corresponding SDK model class. NQE's data model is its own namespace, and the two disagree: device.platform.os has NQE type OS while the SDK model class is VendorOs, and passing VendorOs fails with Variable VendorOs not in scope.

Forward documents the NQE data model, and that is the authoritative source for these names:

https://docs.fwd.app/latest/application/nqe/language/data-model/

A toString() rendering confirms a name rather than discovering it, since it prefixes the member with the type name::

toString(device.platform.os)      -> "OS.PAN_OS"          so "OS"
toString(device.platform.vendor)  -> "Vendor.CISCO"       so "Vendor"

Member names are checked against NQE's own data model, so a name NQE would reject fails here instead of at query time. Do not take them from :mod:forward_sdk.models: those describe Forward's REST schema, and the two namespaces disagree. Measured against a live instance, Vendor alone diverges three ways::

Vendor.MICROSOFT  rejected by NQE; the REST model has it
Vendor.AZURE      accepted by NQE; the REST model does not have it
Vendor.GD         rejected; NQE spells it GENERAL_DYNAMICS

:mod:forward_sdk.nqe.enums carries the NQE names and is what this checks against.

Parameters:

Name Type Description Default
field str

The enum-valued field.

required
enum_type str

The NQE type name. See above: not necessarily the SDK class name.

required
values Sequence[Any]

Members, either as :class:~enum.Enum values or as names. A name is validated as an identifier rather than quoted, since a quoted value would be a string and fail the comparison.

required

Returns:

Type Description
str | None

The clause, or None when values is empty.

Raises:

Type Description
ValueError

If a member name could not be an NQE identifier, or if NQE has no such member for a type it knows. Enum members cannot be escaped the way a string can, so anything unexpected is refused rather than interpolated.

where

where(*clauses: str | None) -> str

Join clauses into where lines, skipping empty ones.

tag_scope

tag_scope(
    expression: str = "device.tagNames",
    *,
    include: Iterable[str] = (),
    exclude: Iterable[str] = (),
    include_match: MatchMode = "any",
) -> str

Build the where lines that scope a query to a set of tags.

Include and exclude are independent: with neither, nothing is emitted and the query is unscoped.