Space Mining · 17 / 26

Telemetry and KQL (Kusto Query Language) Examples

OpenTelemetry traces, metrics and events for the mining platform, with Kusto queries for latency, unsigned filings, ledger gaps, time to safe mode, advice use and assay agreement.

What the telemetry is for

OpenTelemetry is the vendor-neutral standard for traces, metrics and logs. The platform's software emits one trace per work item, such as a report draft or a site proposal, and links the steps of a campaign by a campaign identifier, so an operator can answer three questions: is it fast and available, is it correct and safe, and what does it cost. Vehicle and safe-mode events are recorded alongside, without buyer detail. Telemetry carries identifiers, outcomes and measurements. It never carries buyer names, prices or report text (ADR-010). Flight software keeps its own qualified logs.

Traces

Spans for each step of an item, parent and child, from intake to the record. One trace identifier follows the item across services and the gateway.

Metrics

Counters and histograms for item latency, advice use, safe-mode events, tokens, cost and guardrail blocks. Cheap to store and good for alerts.

Events

Business events with a name and properties: plan signed, advice shown, edited or dismissed, safe-mode event, ledger reconciled, report signed, assay compared.

Correlation

The W3C trace context header travels from intake through the AI (artificial intelligence) gateway and the ground gateway, so their logs join the same trace.

The shape of a trace

A trace for one shift report draft A root span for the report draft contains child spans for the input scan, a fast-model draft, procedure retrieval, a policy check, the draft tool call and the output scan, drawn as bars on a shared time axis. ONE SHIFT REPORT DRAFT · ILLUSTRATIVE 9.8 SECONDS report.item 9800 ms airs.scan.input 150 ms gateway.llm_call sm-fast 6200 ms retrieval.search 300 ms policy.check 60 ms airs.scan.tool_args 140 ms tool.call draft_shift_report 2500 ms airs.scan.output 200 ms service span gateway or tool retrieval security scan
Each component shows up as a span, so the slow or failing step is visible at a glance.
SpanKindKey attributes
report.itemServer (root)campaign.id (hashed), stage, outcome
airs.scan.input, airs.scan.output, airs.scan.tool_argsClientairs.profile, airs.action, airs.detections (names only)
gateway.llm_callClientgen_ai.request.model (alias), gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gateway.cost_usd, gateway.fallback_used
retrieval.searchClientknowledge.index, filter.class, results.count, top.score
policy.checkInternalpolicy.rule, policy.decision
tool.callClienttool.name, tool.outcome, tool.signed

What must never be in telemetry

DataRuleHow
Report text and supplier documentsNeverNot an attribute. Debugging uses the masked cases table in the lakehouse
Buyer names and pricesNever in clearDropped by the collector before export
Campaign identifiersHashedKeyed hash, so queries can group by campaign without exposing it
Blocked contentNeverRecord the detection names and the verdict only
Masses, timings, versions and outcomesAllowedNeeded for safety, accountability and performance analysis

Instrumenting the service

A sketch in Python with the OpenTelemetry SDK (Software Development Kit) and the Azure Monitor distribution, which sends to Application Insights. The root span is a server span so it appears as a request; child spans appear as dependencies; business events are logged with a custom event name. Check the current package and attribute names before you build.

telemetry.py · spans, metrics and business events
import logging, os
from opentelemetry import trace, metrics
from opentelemetry.trace import SpanKind
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor(connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"])
tracer = trace.get_tracer("mining.platform")
meter = metrics.get_meter("mining.platform")
item_ms = meter.create_histogram("sm.item.duration", unit="ms")
blocks = meter.create_counter("sm.guardrail.blocks")
log = logging.getLogger("sm.events")

def draft_report_item(facts, campaign):
    with tracer.start_as_current_span("report.item", kind=SpanKind.SERVER) as item:
        item.set_attributes({"campaign.id": hash_id(campaign), "stage": "documentation"})

        with tracer.start_as_current_span("airs.scan.input") as sp:
            verdict = scan(prompt=json.dumps(facts), campaign=campaign, model="sm-fast")
            sp.set_attributes({"airs.profile": "mission-docs-prod", "airs.action": verdict["action"]})
            if verdict["action"] != "allow":
                blocks.add(1, {"detection": detection_name(verdict), "stage": "input"})
                log.warning("guardrail block", extra={"microsoft.custom_event.name": "guardrail.block",
                            "campaign.id": hash_id(campaign), "airs.detection": detection_name(verdict)})
                return document_manually(facts, reason="blocked")

        with tracer.start_as_current_span("gateway.llm_call") as llm:
            draft, usage = draft_shift_report(facts)
            llm.set_attributes({"gen_ai.request.model": "sm-fast", "gen_ai.usage.input_tokens": usage.input,
                                "gen_ai.usage.output_tokens": usage.output, "gateway.cost_usd": usage.cost})
        ...
        log.info("report signed", extra={"microsoft.custom_event.name": "report.signed", "campaign.id": hash_id(campaign),
                 "edits": edit_count, "minutes_to_sign": minutes})
        item_ms.record(elapsed_ms(item), {"stage": "documentation"})

A collector in the middle

An OpenTelemetry Collector receives telemetry from the service and the gateway, removes or hashes sensitive attributes, keeps every error, block and safe-mode event, samples the rest, and sends it to Azure Monitor for operations and to the lakehouse for long-term analysis.

otel-collector.yaml · redact, keep what matters, fan out
receivers:
  otlp:
    protocols: { grpc: {}, http: {} }

processors:
  attributes/privacy:
    actions:
      - { key: report.text,   action: delete }
      - { key: buyer.name,    action: delete }
      - { key: price.usd,     action: delete }
      - { key: campaign.key,  action: hash }
  tail_sampling:
    decision_wait: 10s
    policies:
      - { name: keep-errors, type: status_code, status_code: { status_codes: [ERROR] } }
      - { name: keep-blocks, type: string_attribute, string_attribute: { key: airs.action, values: [block] } }
      - { name: keep-safety, type: string_attribute, string_attribute: { key: safemode.event, values: ["true"] } }
      - { name: sample-rest, type: probabilistic, probabilistic: { sampling_percentage: 10 } }
  batch: {}

exporters:
  azuremonitor:
    connection_string: ${env:APPLICATIONINSIGHTS_CONNECTION_STRING}
  otlphttp/lakehouse:
    endpoint: ${env:LAKEHOUSE_OTLP_ENDPOINT}

service:
  pipelines:
    traces:  { receivers: [otlp], processors: [attributes/privacy, tail_sampling, batch], exporters: [azuremonitor, otlphttp/lakehouse] }
    metrics: { receivers: [otlp], processors: [batch], exporters: [azuremonitor] }
    logs:    { receivers: [otlp], processors: [attributes/privacy, batch], exporters: [azuremonitor, otlphttp/lakehouse] }

KQL queries operators use

These queries use the workspace-based Application Insights tables in Log Analytics: AppRequests for the root span, AppDependencies for child spans, AppEvents for business events and AppMetrics for metrics. Custom attributes appear in the Properties column. Table and column names can differ with your setup, so adjust them to your workspace. The same Kusto Query Language also runs in Azure Data Explorer if you export telemetry there.

Documentation latency by stage

Median and 95th percentile processing time per stage, hourly, for the last day.

KQL
AppRequests
| where TimeGenerated > ago(1d) and Name == "report.item"
| extend stage = tostring(Properties["stage"])
| summarize items = count(), p50 = percentile(DurationMs, 50), p95 = percentile(DurationMs, 95)
    by stage, bin(TimeGenerated, 1h)
| order by TimeGenerated desc, stage asc

Reports filed without a signature (must be zero)

Finds any report filed with no signature or content hash. Any row is an incident.

KQL
AppEvents
| where Name == "report.filed"
| extend signer = tostring(Properties["signed_by"]), hash = tostring(Properties["content_hash"])
| where isempty(signer) or isempty(hash)
| project TimeGenerated, campaign = tostring(Properties["campaign.id"]), OperationId

Ledger gaps and release attempts (any release over tolerance must be zero)

Gaps per day, and shipments released while the gap was above tolerance.

KQL
AppEvents
| where TimeGenerated > ago(30d) and Name in ("ledger.reconciled", "shipment.released")
| extend gap = todouble(Properties["gap_pct"]), status = tostring(Properties["status"])
| summarize reconciled = countif(Name == "ledger.reconciled"), over_tolerance = countif(Name == "ledger.reconciled" and gap > 0.5),
            released_over_tolerance = countif(Name == "shipment.released" and gap > 0.5 and status != "escalated") by day = bin(TimeGenerated, 1d)
| order by day desc

Time to safe mode, by cause

How quickly vehicles reached safe mode after a fault, by cause, to watch the safety margin.

KQL
AppEvents
| where TimeGenerated > ago(90d) and Name == "safemode.event"
| extend cause = tostring(Properties["cause"]), ms = todouble(Properties["time_to_safe_ms"])
| summarize events = count(), p50 = percentile(ms, 50), p99 = percentile(ms, 99), over_target = countif(ms > 200) by cause
| order by over_target desc, events desc

How often engineers change the advice

Advice shown versus edited or dismissed, by uncertainty band, a measure of usefulness and trust.

KQL
AppEvents
| where TimeGenerated > ago(30d) and Name in ("advice.shown", "advice.edited", "advice.dismissed")
| extend band = tostring(Properties["uncertainty_band"])
| summarize shown = countif(Name == "advice.shown"), edited = countif(Name == "advice.edited"), dismissed = countif(Name == "advice.dismissed") by band
| extend edit_pct = round(100.0 * edited / shown, 1), dismiss_pct = round(100.0 * dismissed / shown, 1)
| order by band asc

Guardrail blocks by detection

How often each Prisma AIRS detection fired, by hour, to spot an attack or a noisy rule.

KQL
AppEvents
| where TimeGenerated > ago(7d) and Name == "guardrail.block"
| extend detection = tostring(Properties["airs.detection"])
| summarize blocks = count(), campaigns = dcount(tostring(Properties["campaign.id"]))
    by detection, bin(TimeGenerated, 1h)
| order by TimeGenerated desc, blocks desc

Tokens and cost by model alias

Spend and token use per alias and per day, from gateway metadata.

KQL
AppDependencies
| where TimeGenerated > ago(14d) and Name == "gateway.llm_call"
| extend model = tostring(Properties["gen_ai.request.model"]),
         tin = toint(Properties["gen_ai.usage.input_tokens"]),
         tout = toint(Properties["gen_ai.usage.output_tokens"]),
         cost = todouble(Properties["gateway.cost_usd"])
| summarize calls = count(), input_tokens = sum(tin), output_tokens = sum(tout), cost_usd = round(sum(cost), 2)
    by model, day = bin(TimeGenerated, 1d)
| order by day desc, cost_usd desc

Advised sites versus assays

Agreement between advised and measured composition, the input to the advisor review.

KQL
AppEvents
| where TimeGenerated > ago(180d) and Name == "assay.compared"
| extend resource = tostring(Properties["resource"]), diff = todouble(Properties["difference_pct"]), within = tobool(Properties["within_uncertainty"])
| summarize sites = count(), median_diff = percentile(diff, 50), p95_diff = percentile(diff, 95), within_pct = round(100.0 * countif(within) / count(), 1) by resource
| order by sites desc

Vehicles with a late heartbeat

Vehicles whose last heartbeat is older than the plan allows, an early sign of a lost link.

KQL
AppEvents
| where TimeGenerated > ago(2d) and Name == "vehicle.heartbeat"
| extend vehicle = tostring(Properties["vehicle_id"]), mode = tostring(Properties["mode"])
| summarize last_seen = max(TimeGenerated), last_mode = arg_max(TimeGenerated, mode) by vehicle
| where last_seen < ago(30m)
| project vehicle, last_seen, mode

Alert: block rate spike

Compares the hourly block rate with its normal pattern and returns hours that are anomalously high. Use it as an alert query.

KQL
let items = AppRequests | where Name == "report.item"
    | make-series items = count() default = 0 on TimeGenerated from ago(14d) to now() step 1h;
let blocked = AppEvents | where Name == "guardrail.block"
    | make-series blocked = count() default = 0 on TimeGenerated from ago(14d) to now() step 1h;
items
| join kind=inner (blocked) on $left.TimeGenerated == $right.TimeGenerated
| project TimeGenerated, rate = series_divide(blocked, items)
| extend (flag, score, baseline) = series_decompose_anomalies(rate, 2.5)
| mv-expand TimeGenerated to typeof(datetime), rate to typeof(double), flag to typeof(int), score to typeof(double)
| where flag == 1 and TimeGenerated > ago(3h)

Service-level objectives and alerts

ObjectiveSignalTargetAlert
Fast draftsreport.item p95Under 30 secondsp95 over target for 15 minutes
AvailableShare of items not ending in errorAt least 99.5%Below target for 10 minutes
Signed filingReports filed without a signatureZeroAny occurrence, page the on-call
AccountabilityShipments released over ledger toleranceZeroAny occurrence, page the on-call and logistics
Safety marginTime to safe mode, p99Under 200 msAny event over target, page vehicle engineering
Scans on all trafficModel calls with a scan span100%Any unscanned model call
Link healthVehicles with a late heartbeatZeroAny vehicle late for 30 minutes
Attacks visibleBlock rate versus baselineWithin normal rangeAnomaly flagged for 1 hour
Cost under controlCost per mission day, dailyWithin budgetOver 120% of the 7-day average

Dashboards

Operations

Item latency and errors by stage, step breakdown, tool health and gateway fallbacks.

Safety and assurance

Safe-mode events and time to safe mode, ledger gaps, advice use and assay agreement.

Security

Blocks by detection, anomalies, scan coverage and filings without a signature.

Cost

Tokens and cost by model and stage, cost per mission day and budget burn.

Build this for your business

This example is speculative and describes no real mission, but the same pattern, deterministic safety for every hard duty, a governed gateway, runtime security, advisory-only AI and measured quality, fits any remote, high-consequence operation. We can scope a pilot on your own systems.

Book a discovery call