Validation & diagnostics
Inspect shared graph structure and bounded rendered source spans.
Diagnostics are read-only and do not send a query to a server. Structural analysis describes the expression graph, not an execution plan or a promise of backend cost.
from metricraft import QueryBuilder as Q
query = Q.from_metric("up").sum().by("job")
assert query.validate("promql") == ""
print(query.analyze())
print(query.debug_positions(mode="promql"))
Graph diagnostics count shared nodes once. Rendered source positions describe each occurrence and use UTF-8 byte offsets. Output and work budgets bound both kinds of diagnostics.
debug() and to_debug_json() return schema-1 graph JSON with IDs for children
and persistent matcher links. analyze() returns a detached summary of unique
nodes, names, structural complexity and heuristic findings. Graph and analysis
defaults are 1 MiB output and 10,000 work items (the root, child edges and unique
matcher links). Positive max_output_bytes and max_items override these per call.
debug_positions() uses the same native renderer and dialect checks as build().
Its spans describe expression occurrences; matcher details belong to graph
diagnostics. visualize_positions(source_code) verifies that the supplied text
matches the exact rendered query before returning source/span JSON. Applications
can display those spans themselves. Position diagnostics expand occurrences and
enforce both work and serialized-output limits. Snapshots are detached values;
they do not add cached strings or diagnostic fields to persistent nodes.
Methods and parameters
QueryBuilder
analyze()Inspect the shared native graph and return counts and structural heuristics as a Python dictionary.
QueryBuilder.analyze(*, max_output_bytes: Optional[int]=None, max_items: Optional[int]=None) -> Dict[str, Any]
| Parameter / type | Meaning and accepted values |
|---|---|
max_output_bytesint | NoneDefault: None | Positive integer byte budget; None uses the native 1 MiB default. bool and zero are rejected. Applies to UTF-8 output, not character count. |
max_itemsint | NoneDefault: None | Positive diagnostic work budget; None uses the native default. Graph inspection counts nodes/edges/matcher links; position output counts rendered occurrences. |
Returns dict — graph counts and heuristic advice, not a server execution plan.
Example
from metricraft import QueryBuilder as Q
Q.from_metric("up").sum().analyze()debug()Serialize a bounded diagnostic graph, emitting shared nodes and matcher links once.
QueryBuilder.debug(*, max_output_bytes: Optional[int]=None, max_items: Optional[int]=None) -> str
| Parameter / type | Meaning and accepted values |
|---|---|
max_output_bytesint | NoneDefault: None | Positive integer byte budget; None uses the native 1 MiB default. bool and zero are rejected. Applies to UTF-8 output, not character count. |
max_itemsint | NoneDefault: None | Positive diagnostic work budget; None uses the native default. Graph inspection counts nodes/edges/matcher links; position output counts rendered occurrences. |
Returns str — JSON describing unique native nodes and their relationships.
debug_positions()Render query text and UTF-8 byte spans of expression occurrences as a JSON string.
QueryBuilder.debug_positions(*, mode: BuildMode=QueryMode.METRICSQL, max_output_bytes: Optional[int]=None, max_items: Optional[int]=None, experimental_functions: bool=False, features: Iterable[str]=()) -> str
| Parameter / type | Meaning and accepted values |
|---|---|
modeQueryMode | strDefault: QueryMode.METRICSQL | 'promql' or 'metricsql' (default). Checks the entire expression, including dialect-specific argument forms. |
max_output_bytesint | NoneDefault: None | Positive integer byte budget; None uses the native 1 MiB default. bool and zero are rejected. Applies to UTF-8 output, not character count. |
max_itemsint | NoneDefault: None | Positive diagnostic work budget; None uses the native default. Graph inspection counts nodes/edges/matcher links; position output counts rendered occurrences. |
experimental_functionsboolDefault: False | Opt into Prometheus experimental functions. The backend must also enable the corresponding feature; this flag does not configure the server. |
featuresIterable[str]Default: () | Explicit feature names: 'promql-experimental-functions', 'promql-duration-expr', 'promql-extended-range-selectors', 'promql-binop-fill-modifiers'. Each requires matching server support. Pass a collection, not one string. |
Returns str — JSON with query text and UTF-8 byte spans, not Python character offsets.
to_debug_json()Serialize a bounded diagnostic graph, emitting shared nodes and matcher links once.
QueryBuilder.to_debug_json(*, max_output_bytes: Optional[int]=None, max_items: Optional[int]=None) -> str
| Parameter / type | Meaning and accepted values |
|---|---|
max_output_bytesint | NoneDefault: None | Positive integer byte budget; None uses the native 1 MiB default. bool and zero are rejected. Applies to UTF-8 output, not character count. |
max_itemsint | NoneDefault: None | Positive diagnostic work budget; None uses the native default. Graph inspection counts nodes/edges/matcher links; position output counts rendered occurrences. |
Returns str — JSON describing unique native nodes and their relationships.
validate()Return an empty string for a valid build or the native validation error text. Validation is never bypassed.
QueryBuilder.validate(standard: Optional[str]=None, strict: bool=True, **build_options: Any) -> str
| Parameter / type | Meaning and accepted values |
|---|---|
standardstr | NoneDefault: None | 'promql' or 'metricsql', case-insensitive. None selects MetricsQL. |
strictboolDefault: True | Must be True. strict=False is intentionally unsupported. |
**build_optionskeyword argumentsVariadic | Keyword options accepted by build(), excluding mode (use standard here). Limits and feature checks still apply. |
Returns str — empty on success, otherwise a native validation message. Invalid Python arguments can still raise exceptions.
visualize_positions()Return position JSON only after checking that the supplied source exactly matches this expression's build output.
QueryBuilder.visualize_positions(source_code: str, **options: Any) -> str
| Parameter / type | Meaning and accepted values |
|---|---|
source_codestrRequired | Exact output of this expression's build() with matching options; a different string raises ValueError. |
**optionskeyword argumentsVariadic | Keyword options accepted by debug_positions(), including mode, budgets and feature flags. |
Returns str — validated source/span JSON; no image or browser window is created.