SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
fix(querybuilder): keep DateTime64 columns native in aggregations (#12382)
Tushar Vatsd93713c1844d
diff --git a/pkg/querybuilder/exists_expr.go b/pkg/querybuilder/exists_expr.goindex 63dcd0644d..bc1ec70ca5 100644--- a/pkg/querybuilder/exists_expr.go+++ b/pkg/querybuilder/exists_expr.go@@ -49,12 +49,17 @@ func ExistsExpression(columns []*schema.Column, key *telemetrytypes.TelemetryFie}return rawPath + " IS NULL", nilcase schema.ColumnTypeEnumString,- schema.ColumnTypeEnumFixedString,- schema.ColumnTypeEnumDateTime64:+ schema.ColumnTypeEnumFixedString:if exists {return comparison("<>", "''"), nil}return comparison("=", "''"), nil+ case schema.ColumnTypeEnumDateTime64:+ zero := fmt.Sprintf("toDateTime64(0, %d)", column.Type.(schema.DateTime64ColumnType).Precision)+ if exists {+ return comparison("<>", zero), nil+ }+ return comparison("=", zero), nilcase schema.ColumnTypeEnumLowCardinality:switch elementType := column.Type.(schema.LowCardinalityColumnType).ElementType; elementType.GetType() {case schema.ColumnTypeEnumString:diff --git a/pkg/querybuilder/fallback_expr.go b/pkg/querybuilder/fallback_expr.goindex 35d4a72419..6516c2c61c 100644--- a/pkg/querybuilder/fallback_expr.go+++ b/pkg/querybuilder/fallback_expr.go@@ -8,6 +8,7 @@ import ("regexp""strconv"+ schema "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes")@@ -194,6 +195,16 @@ func DataTypeCollisionHandledFieldName(key *telemetrytypes.TelemetryFieldKey, vareturn tblFieldName, value}+// ColumnIsTemporal reports whether a column carries a time value.+func ColumnIsTemporal(col *schema.Column) bool {+ switch col.Type.GetType() {+ case schema.ColumnTypeEnumDateTime64, schema.ColumnTypeEnumDateTime,+ schema.ColumnTypeEnumDate, schema.ColumnTypeEnumDate32:+ return true+ }+ return false+}+func castFloat(col string) string { return fmt.Sprintf("toFloat64OrNull(%s)", col) }func castFloatHack(col string) string { return fmt.Sprintf("toFloat64(%s)", col) }func castString(col string) string { return fmt.Sprintf("toString(%s)", col) }diff --git a/pkg/telemetryschema/tracestelemetryschema/field_mapper.go b/pkg/telemetryschema/tracestelemetryschema/field_mapper.goindex 8aada77ea9..4ba6d79ef8 100644--- a/pkg/telemetryschema/tracestelemetryschema/field_mapper.go+++ b/pkg/telemetryschema/tracestelemetryschema/field_mapper.go@@ -382,7 +382,13 @@ func (m *fieldMapper) ColumnExpressionFor(if err != nil {return "", err}- coerced, _ := querybuilder.DataTypeCollisionHandledFieldName(key, dummyValue, value, qbtypes.FilterOperatorUnknown)+ coerced := value+ // a time column keeps its native type; coercing it would yield seconds+ if temporal, err := m.columnIsTemporal(ctx, startNs, endNs, key); err != nil {+ return "", err+ } else if !temporal {+ coerced, _ = querybuilder.DataTypeCollisionHandledFieldName(key, dummyValue, value, qbtypes.FilterOperatorUnknown)+ }stmts = append(stmts, guard, coerced)}return fmt.Sprintf("multiIf(%s, NULL)", strings.Join(stmts, ", ")), nil@@ -421,6 +427,20 @@ func (m *fieldMapper) ColumnExpressionFor(return fmt.Sprintf("multiIf(%s, NULL)", strings.Join(args, ", ")), nil}+// columnIsTemporal reports whether key resolves to a single time column, after evolution+// selection. Multiple columns mean an attribute-map union, which is never temporal.+func (m *fieldMapper) columnIsTemporal(ctx context.Context, startNs, endNs uint64, key *telemetrytypes.TelemetryFieldKey) (bool, error) {+ columns, err := m.getColumn(ctx, startNs, endNs, key)+ if err != nil {+ return false, err+ }+ newColumns, _, err := qbtypes.SelectEvolutionsForColumns(columns, key.Evolutions, startNs, endNs)+ if err != nil {+ return false, err+ }+ return len(newColumns) == 1 && querybuilder.ColumnIsTemporal(newColumns[0]), nil+}+// columnMatchesDataType reports whether a metadata field's data type is consistent with a// column's ClickHouse type. A bare key's column is only unioned with same-named metadata// keys that could be the same field; a string attribute named `timestamp` is corrupt@@ -432,9 +452,11 @@ func columnMatchesDataType(col *schema.Column, dt telemetrytypes.FieldDataType)switch col.Type.GetType() {case schema.ColumnTypeEnumBool:return dt == telemetrytypes.FieldDataTypeBool+ case schema.ColumnTypeEnumDateTime64:+ return falsecase schema.ColumnTypeEnumUInt64, schema.ColumnTypeEnumUInt32,schema.ColumnTypeEnumInt8, schema.ColumnTypeEnumInt16,- schema.ColumnTypeEnumFloat64, schema.ColumnTypeEnumDateTime64:+ schema.ColumnTypeEnumFloat64:return dt == telemetrytypes.FieldDataTypeInt64 ||dt == telemetrytypes.FieldDataTypeFloat64 ||dt == telemetrytypes.FieldDataTypeNumberdiff --git a/pkg/telemetryschema/tracestelemetryschema/field_mapper_test.go b/pkg/telemetryschema/tracestelemetryschema/field_mapper_test.goindex fbf6bf367c..e3c05c42cd 100644--- a/pkg/telemetryschema/tracestelemetryschema/field_mapper_test.go+++ b/pkg/telemetryschema/tracestelemetryschema/field_mapper_test.go@@ -202,3 +202,104 @@ func TestFieldForResourceWithEvolution(t *testing.T) {})}}++// TestColumnExpressionForTemporalColumn covers the time column: ClickHouse converts it to a+// number as seconds since epoch, so it must reach the aggregation in its native type. Every+// exists guard and every non-temporal coercion is left exactly as it was.+func TestColumnExpressionForTemporalColumn(t *testing.T) {+ ctx := context.Background()+ tsStart := uint64(time.Date(2024, 6, 1, 0, 0, 0, 0, time.UTC).UnixNano())+ tsEnd := uint64(time.Date(2024, 6, 5, 0, 0, 0, 0, time.UTC).UnixNano())++ testCases := []struct {+ name string+ key telemetrytypes.TelemetryFieldKey+ requiredDataType telemetrytypes.FieldDataType+ expectedResult string+ }{+ {+ name: "time column is not coerced under a numeric aggregation",+ key: telemetrytypes.TelemetryFieldKey{Name: "timestamp"},+ requiredDataType: telemetrytypes.FieldDataTypeFloat64,+ expectedResult: "multiIf(timestamp <> toDateTime64(0, 9), timestamp, NULL)",+ },+ {+ name: "time column is not coerced under a group by",+ key: telemetrytypes.TelemetryFieldKey{Name: "timestamp"},+ requiredDataType: telemetrytypes.FieldDataTypeString,+ expectedResult: "multiIf(timestamp <> toDateTime64(0, 9), timestamp, NULL)",+ },+ {+ name: "numeric intrinsic keeps its cast and guard",+ key: telemetrytypes.TelemetryFieldKey{Name: "duration_nano"},+ requiredDataType: telemetrytypes.FieldDataTypeFloat64,+ expectedResult: "multiIf(duration_nano <> 0, accurateCastOrNull(duration_nano, 'Float64'), NULL)",+ },+ {+ name: "string intrinsic keeps its cast and guard",+ key: telemetrytypes.TelemetryFieldKey{Name: "name"},+ requiredDataType: telemetrytypes.FieldDataTypeFloat64,+ expectedResult: "multiIf(name <> '', accurateCastOrNull(name, 'Float64'), NULL)",+ },+ {+ name: "map-backed attribute keeps its exists guard",+ key: telemetrytypes.TelemetryFieldKey{+ Name: "user.id",+ FieldContext: telemetrytypes.FieldContextAttribute,+ FieldDataType: telemetrytypes.FieldDataTypeString,+ },+ requiredDataType: telemetrytypes.FieldDataTypeString,+ expectedResult: "multiIf(mapContains(attributes_string, 'user.id'), attributes_string['user.id'], NULL)",+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ fm := NewFieldMapper()+ result, err := fm.ColumnExpressionFor(ctx, valuer.UUID{}, tsStart, tsEnd, &tc.key, tc.requiredDataType, nil)+ require.NoError(t, err)+ assert.Equal(t, tc.expectedResult, result)+ })+ }+}++// TestColumnExpressionForTimestampAttributeCollision covers a user attribute that shares its+// name with the intrinsic time column. It must not join the candidate union: a second branch+// would force a numeric supertype across the multiIf and put the DateTime64 back into+// seconds since epoch. The attribute stays reachable under its explicit context.+func TestColumnExpressionForTimestampAttributeCollision(t *testing.T) {+ ctx := context.Background()+ tsStart := uint64(time.Date(2024, 6, 1, 0, 0, 0, 0, time.UTC).UnixNano())+ tsEnd := uint64(time.Date(2024, 6, 5, 0, 0, 0, 0, time.UTC).UnixNano())++ keys := map[string][]*telemetrytypes.TelemetryFieldKey{+ "timestamp": {+ {+ Name: "timestamp",+ Signal: telemetrytypes.SignalTraces,+ FieldContext: telemetrytypes.FieldContextAttribute,+ FieldDataType: telemetrytypes.FieldDataTypeNumber,+ },+ },+ }++ fm := NewFieldMapper()++ t.Run("bare timestamp resolves to the intrinsic column alone", func(t *testing.T) {+ bare := telemetrytypes.TelemetryFieldKey{Name: "timestamp"}+ result, err := fm.ColumnExpressionFor(ctx, valuer.UUID{}, tsStart, tsEnd, &bare, telemetrytypes.FieldDataTypeFloat64, keys)+ require.NoError(t, err)+ assert.Equal(t, "multiIf(timestamp <> toDateTime64(0, 9), timestamp, NULL)", result)+ })++ t.Run("explicit attribute context still reaches the attribute", func(t *testing.T) {+ attr := telemetrytypes.TelemetryFieldKey{+ Name: "timestamp",+ FieldContext: telemetrytypes.FieldContextAttribute,+ FieldDataType: telemetrytypes.FieldDataTypeNumber,+ }+ result, err := fm.ColumnExpressionFor(ctx, valuer.UUID{}, tsStart, tsEnd, &attr, telemetrytypes.FieldDataTypeFloat64, keys)+ require.NoError(t, err)+ assert.Contains(t, result, "attributes_number['timestamp']")+ })+}diff --git a/tests/fixtures/thirdpartyapi.py b/tests/fixtures/thirdpartyapi.pynew file mode 100644index 0000000000..95912ae2ab--- /dev/null+++ b/tests/fixtures/thirdpartyapi.py@@ -0,0 +1,69 @@+"""Shared helpers for the third-party (external) API monitoring domain list.++A translator over v5 builder queries that answers with a UI-formatted scalar table, so the+response is read by column rather than by series.+"""++from typing import Any++import requests++from fixtures import types++DOMAIN_LIST_ENDPOINT = "/api/v1/third-party-apis/overview/list"++# The group-by key the translator always prepends; its column holds the domain name.+DOMAIN_COLUMN = "http_host"++REQUEST_TIMEOUT = 30+++def make_third_party_apis_request(+ signoz: types.SigNoz,+ token: str,+ start_ms: int,+ end_ms: int,+ *,+ show_ip: bool = True,+ filter_expression: str | None = None,+ group_by: list[dict] | None = None,+ timeout: int = REQUEST_TIMEOUT,+) -> requests.Response:+ """POST a domain-list request."""+ payload: dict[str, Any] = {+ "start": start_ms,+ "end": end_ms,+ "show_ip": show_ip,+ }+ if filter_expression is not None:+ payload["filter"] = {"expression": filter_expression}+ if group_by is not None:+ payload["groupBy"] = group_by++ return requests.post(+ signoz.self.host_configs["8080"].get(DOMAIN_LIST_ENDPOINT),+ timeout=timeout,+ headers={"authorization": f"Bearer {token}"},+ json=payload,+ )+++def scalar_result(response: requests.Response) -> dict:+ """The single scalar table from a third-party-apis response."""+ return response.json()["data"]["data"]["results"][0]+++def index_columns_by_query(result: dict) -> dict[str, int]:+ """queryName -> column index, aggregation columns only; group columns are addressed by+ name (DOMAIN_COLUMN) since they share their query's name."""+ return {col["queryName"]: i for i, col in enumerate(result["columns"]) if col["columnType"] == "aggregation"}+++def domain_column_index(result: dict) -> int:+ return next(i for i, col in enumerate(result["columns"]) if col["name"] == DOMAIN_COLUMN)+++def rows_by_domain(result: dict) -> dict[str, list[Any]]:+ """domain name -> its row. Suites share a stack, so look up the domains you seeded."""+ index = domain_column_index(result)+ return {row[index]: row for row in result["data"]}diff --git a/tests/fixtures/traces.py b/tests/fixtures/traces.pyindex 36f8425f09..f4314158ae 100644--- a/tests/fixtures/traces.py+++ b/tests/fixtures/traces.py@@ -65,6 +65,22 @@ class TracesKind(Enum):def from_value(cls, value: int) -> "TracesKind":return cls(value)+ def kind_string(self) -> str:+ """The `kind_string` column value, mirroring ptrace.SpanKind.String() — the exporter+ writes `otelSpan.Kind().String()`. Features filter on these, e.g. third-party-apis+ requires `kind_string = 'Client'`."""+ return _KIND_STRINGS[self]+++_KIND_STRINGS = {+ TracesKind.SPAN_KIND_UNSPECIFIED: "Unspecified",+ TracesKind.SPAN_KIND_INTERNAL: "Internal",+ TracesKind.SPAN_KIND_SERVER: "Server",+ TracesKind.SPAN_KIND_CLIENT: "Client",+ TracesKind.SPAN_KIND_PRODUCER: "Producer",+ TracesKind.SPAN_KIND_CONSUMER: "Consumer",+}+class TracesStatusCode(Enum):STATUS_CODE_UNSET = 0@@ -344,7 +360,7 @@ class Traces(ABC):self.flags = flagsself.name = nameself.kind = kind.value- self.kind_string = kind.name+ self.kind_string = kind.kind_string()self.status_code = status_code.valueself.status_message = status_messageself.status_code_string = status_code.namediff --git a/tests/integration/tests/queriertraces/12_timestamp_aggregations.py b/tests/integration/tests/queriertraces/12_timestamp_aggregations.pynew file mode 100644index 0000000000..fcbc8c7aa5--- /dev/null+++ b/tests/integration/tests/queriertraces/12_timestamp_aggregations.py@@ -0,0 +1,181 @@+"""Aggregations over the intrinsic `timestamp` column.++`timestamp` is DateTime64(9), so a numeric coercion rescales it to seconds — the #5824+regression. Order-based aggregations answer with an instant; sum/avg have no time meaning.+"""++from collections.abc import Callable+from datetime import UTC, datetime, timedelta+from http import HTTPStatus++import pytest++from fixtures import types+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD+from fixtures.querier import RequestType, make_query_request+from fixtures.traces import TraceIdGenerator, Traces, TracesKind, TracesStatusCode++# Suites share one stack, so every query scopes to this service to keep other tests'+# spans out of the aggregate.+SERVICE = "timestamp-agg-svc"+++def seed_two_spans(insert_traces: Callable[[list[Traces]], None], oldest: datetime, newest: datetime) -> None:+ insert_traces(+ [+ Traces(+ timestamp=ts,+ duration=timedelta(milliseconds=10),+ trace_id=TraceIdGenerator.trace_id(),+ span_id=TraceIdGenerator.span_id(),+ name="op",+ kind=TracesKind.SPAN_KIND_CLIENT,+ status_code=TracesStatusCode.STATUS_CODE_OK,+ resources={"service.name": SERVICE},+ attributes={},+ )+ for ts in (oldest, newest)+ ]+ )+++def query_timestamp_aggregation(signoz: types.SigNoz, token: str, expression: str, now: datetime):+ return make_query_request(+ signoz,+ token,+ start_ms=int((now - timedelta(minutes=10)).timestamp() * 1000),+ end_ms=int((now + timedelta(minutes=1)).timestamp() * 1000),+ request_type=RequestType.SCALAR,+ queries=[+ {+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "traces",+ "stepInterval": "60s",+ "filter": {"expression": f"service.name = '{SERVICE}'"},+ "aggregations": [{"expression": expression}],+ },+ }+ ],+ )++[email protected]("expression,bound", [("max(timestamp)", "newest"), ("min(timestamp)", "oldest")])+def test_timestamp_order_aggregations_return_the_instant(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+ expression: str,+ bound: str,+) -> None:+ """+ Setup:+ Two spans for one service, 3 and 1 minutes ago.++ Tests:+ max/min answer with the extreme span's instant. Coerced to Float64 the value would be+ ~1.7e9 seconds, which reads as January 1970 when a consumer treats it as milliseconds.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ oldest, newest = now - timedelta(minutes=3), now - timedelta(minutes=1)+ seed_two_spans(insert_traces, oldest, newest)++ response = query_timestamp_aggregation(signoz, get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD), expression, now)++ assert response.status_code == HTTPStatus.OK, response.text+ raw = response.json()["data"]["data"]["results"][0]["data"][0][0]+ # a native DateTime64 serializes as an RFC 3339 instant+ assert isinstance(raw, str), f"{expression} returned {raw!r}, expected an instant"+ actual = datetime.fromisoformat(raw.replace("Z", "+00:00"))++ expected = newest if bound == "newest" else oldest+ assert abs((actual - expected).total_seconds()) < 1, f"{expression} returned {raw!r} ({actual.isoformat()}), expected {expected.isoformat()}"+++def test_timestamp_quantile_returns_an_instant_within_range(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+) -> None:+ """+ Tests:+ ClickHouse computes quantiles over DateTime64 natively, so p99 lands inside the+ seeded range rather than erroring or collapsing to epoch.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ oldest, newest = now - timedelta(minutes=3), now - timedelta(minutes=1)+ seed_two_spans(insert_traces, oldest, newest)++ response = query_timestamp_aggregation(signoz, get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD), "p99(timestamp)", now)++ assert response.status_code == HTTPStatus.OK, response.text+ raw = response.json()["data"]["data"]["results"][0]["data"][0][0]+ assert isinstance(raw, str), f"p99(timestamp) returned {raw!r}, expected an instant"+ actual = datetime.fromisoformat(raw.replace("Z", "+00:00"))++ assert oldest - timedelta(seconds=1) <= actual <= newest + timedelta(seconds=1), f"p99(timestamp) returned {actual.isoformat()}, outside [{oldest.isoformat()}, {newest.isoformat()}]"++[email protected]("expression,expected", [("count(timestamp)", 2), ("rate(timestamp)", None)])+def test_timestamp_counting_aggregations_are_numeric(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+ expression: str,+ expected: int | None,+) -> None:+ """+ Tests:+ count and rate count rows rather than reading the column's value, so they stay+ numeric for a time column.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ seed_two_spans(insert_traces, now - timedelta(minutes=3), now - timedelta(minutes=1))++ response = query_timestamp_aggregation(signoz, get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD), expression, now)++ assert response.status_code == HTTPStatus.OK, response.text+ raw = response.json()["data"]["data"]["results"][0]["data"][0][0]+ assert isinstance(raw, (int, float)) and not isinstance(raw, bool), f"{expression} returned {raw!r}, expected a number"+ if expected is not None:+ assert raw == expected, f"{expression} returned {raw!r}, expected {expected}"+ else:+ assert raw > 0, f"{expression} returned {raw!r}, expected a positive rate"+++# KNOWN GAP, pinned deliberately: ClickHouse rejects sum/avg over DateTime64, and rate_*+# additionally divides a time by an interval; both surface as the generic 500. They returned+# a meaningless seconds number before #5824. Flip to BAD_REQUEST once validated up front.+ "expression",+ [+ "sum(timestamp)",+ "avg(timestamp)",+ "rate_sum(timestamp)",+ "rate_avg(timestamp)",+ "rate_min(timestamp)",+ "rate_max(timestamp)",+ ],+)+def test_timestamp_arithmetic_aggregations_are_unsupported(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+ expression: str,+) -> None:+ """+ Tests:+ Aggregations that cannot produce a time from a time column fail rather than+ answering with a rescaled number.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ seed_two_spans(insert_traces, now - timedelta(minutes=3), now - timedelta(minutes=1))++ response = query_timestamp_aggregation(signoz, get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD), expression, now)++ assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR, f"{expression} returned {response.status_code}: {response.text[:200]}"diff --git a/tests/integration/tests/thirdpartyapi/01_domain_list.py b/tests/integration/tests/thirdpartyapi/01_domain_list.pynew file mode 100644index 0000000000..38ee44baff--- /dev/null+++ b/tests/integration/tests/thirdpartyapi/01_domain_list.py@@ -0,0 +1,551 @@+"""Integration tests for the third-party (external) API monitoring domain list.++A translator over v5 builder queries, so these cover the contract it exposes (columns,+grouping, base filter, IP masking) plus the `max(timestamp)` Last Seen from #5824.+"""++from collections.abc import Callable+from datetime import UTC, datetime, timedelta+from http import HTTPStatus++import pytest++from fixtures import types+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD+from fixtures.thirdpartyapi import (+ domain_column_index,+ index_columns_by_query,+ make_third_party_apis_request,+ rows_by_domain,+ scalar_result,+)+from fixtures.traces import TraceIdGenerator, Traces, TracesKind, TracesStatusCode++# the placeholder the response layer writes where a query has no value for a row+NO_VALUE = "n/a"+++# timestamp_attr seeds a numeric attribute named `timestamp`: resolution must keep the+# intrinsic column, else the multiIf union fails with "no supertype for DateTime64, Float64".[email protected]("noise", ["clean", "timestamp_attr"])+def test_domain_list_last_seen_is_the_span_instant(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+ noise: str,+) -> None:+ """+ Setup:+ Two client spans to api.stripe.com, 3 and 1 minutes ago.++ Tests:+ Last Seen resolves to the newer span's instant. A numeric coercion of the+ DateTime64 column would yield seconds since epoch (~1.7e9), which lands in+ January 1970 once read as milliseconds.+ """+ extra_attrs = {"timestamp": 1.0} if noise == "timestamp_attr" else {}+ now = datetime.now(tz=UTC).replace(microsecond=0)+ newest = now - timedelta(minutes=1)+ domain = f"api.stripe-{noise}.com"++ insert_traces(+ [+ Traces(+ timestamp=ts,+ duration=timedelta(milliseconds=120),+ trace_id=TraceIdGenerator.trace_id(),+ span_id=TraceIdGenerator.span_id(),+ name="POST /v1/charges",+ kind=TracesKind.SPAN_KIND_CLIENT,+ status_code=TracesStatusCode.STATUS_CODE_OK,+ resources={"service.name": "checkout"},+ attributes={+ "http.url": f"https://{domain}/v1/charges",+ "http.host": domain,+ **extra_attrs,+ },+ )+ for ts in (now - timedelta(minutes=3), newest)+ ]+ )++ response = make_third_party_apis_request(+ signoz,+ get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD),+ start_ms=int((now - timedelta(minutes=10)).timestamp() * 1000),+ end_ms=int((now + timedelta(minutes=1)).timestamp() * 1000),+ )++ assert response.status_code == HTTPStatus.OK, response.text+ result = scalar_result(response)+ rows = rows_by_domain(result)+ assert domain in rows, result["data"]++ raw_last_seen = rows[domain][index_columns_by_query(result)["lastseen"]]+ # a native DateTime64 serializes as an RFC 3339 instant; the span is seeded on a whole+ # second, so the instant is exact+ assert isinstance(raw_last_seen, str), f"Last Seen returned {raw_last_seen!r}, expected an RFC 3339 instant"+ last_seen = datetime.fromisoformat(raw_last_seen)++ assert last_seen == newest, f"Last Seen {raw_last_seen!r} resolved to {last_seen.isoformat()}, expected the newer span at {newest.isoformat()}"+++def test_domain_list_groups_by_domain_and_counts_endpoints(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+) -> None:+ """+ Setup:+ api.github.com with 2 distinct URLs (one called twice); api.openai.com with 1.++ Tests:+ One row per domain, endpoint counts are distinct-URL counts, and the columns+ used only to feed the error-rate formula are stripped from the response.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ specs = [+ ("api.github.com", "https://api.github.com/repos"),+ ("api.github.com", "https://api.github.com/repos"),+ ("api.github.com", "https://api.github.com/issues"),+ ("api.openai.com", "https://api.openai.com/v1/chat"),+ ]+ insert_traces(+ [+ Traces(+ timestamp=now - timedelta(seconds=i + 1),+ duration=timedelta(milliseconds=200),+ trace_id=TraceIdGenerator.trace_id(),+ span_id=TraceIdGenerator.span_id(),+ name="client call",+ kind=TracesKind.SPAN_KIND_CLIENT,+ status_code=TracesStatusCode.STATUS_CODE_OK,+ resources={"service.name": "gateway"},+ attributes={"http.url": url, "http.host": host},+ )+ for i, (host, url) in enumerate(specs)+ ]+ )++ response = make_third_party_apis_request(+ signoz,+ get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD),+ start_ms=int((now - timedelta(minutes=10)).timestamp() * 1000),+ end_ms=int((now + timedelta(minutes=1)).timestamp() * 1000),+ )++ assert response.status_code == HTTPStatus.OK, response.text+ body = response.json()+ assert body["status"] == "success", body+ # the six queries are merged into exactly one table+ assert len(body["data"]["data"]["results"]) == 1, body["data"]["data"]["results"]++ result = scalar_result(response)++ by_query = index_columns_by_query(result)+ # exact set: the error/total_span intermediates only feed the error_rate formula and+ # must be stripped, and a new column should trip this rather than slip through+ assert by_query.keys() == {"endpoints", "lastseen", "rps", "p99", "error_rate"}, result["columns"]+ assert [col["name"] for col in result["columns"] if col["columnType"] == "group"] == ["http_host"], result["columns"]++ width = len(result["columns"])+ assert all(len(row) == width for row in result["data"]), result["data"]++ rows = rows_by_domain(result)+ endpoints = {domain: rows[domain][by_query["endpoints"]] for domain in ("api.github.com", "api.openai.com") if domain in rows}+ assert endpoints == {"api.github.com": 2, "api.openai.com": 1}, result["data"]++ # every query groups by http_host, so a seeded domain has a value in every column+ for domain in ("api.github.com", "api.openai.com"):+ assert NO_VALUE not in rows[domain], (domain, result["data"])+++def test_domain_list_excludes_non_client_and_urlless_spans(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+) -> None:+ """+ Setup:+ A client span with an http.url, a server span with one, and a client span without.++ Tests:+ The base filter (`http_url EXISTS AND kind_string = 'Client'`) keeps only the+ first domain; the other two never reach the response.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ specs = [+ ("included.example.com", TracesKind.SPAN_KIND_CLIENT, "https://included.example.com/a"),+ (+ "server-kind.example.com",+ TracesKind.SPAN_KIND_SERVER,+ "https://server-kind.example.com/a",+ ),+ ("no-url.example.com", TracesKind.SPAN_KIND_CLIENT, None),+ ]+ insert_traces(+ [+ Traces(+ timestamp=now - timedelta(seconds=i + 1),+ duration=timedelta(milliseconds=50),+ trace_id=TraceIdGenerator.trace_id(),+ span_id=TraceIdGenerator.span_id(),+ name="call",+ kind=kind,+ status_code=TracesStatusCode.STATUS_CODE_OK,+ resources={"service.name": "gateway"},+ attributes=({"http.host": host} if url is None else {"http.url": url, "http.host": host}),+ )+ for i, (host, kind, url) in enumerate(specs)+ ]+ )++ response = make_third_party_apis_request(+ signoz,+ get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD),+ start_ms=int((now - timedelta(minutes=10)).timestamp() * 1000),+ end_ms=int((now + timedelta(minutes=1)).timestamp() * 1000),+ )++ assert response.status_code == HTTPStatus.OK, response.text+ domains = rows_by_domain(scalar_result(response)).keys()++ assert "included.example.com" in domains, domains+ assert "server-kind.example.com" not in domains, domains+ assert "no-url.example.com" not in domains, domains++[email protected]("show_ip", [False, True])+def test_domain_list_show_ip_masks_ip_domains(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+ show_ip: bool,+) -> None:+ """+ Setup:+ One client span each to a hostname, a bare IPv4 and a bare IPv6 address.++ Tests:+ show_ip gates both IP forms (net.ParseIP accepts either); the hostname always shows.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ specs = [+ ("named.example.com", "https://named.example.com/a"),+ ("10.42.7.9", "http://10.42.7.9/metrics"),+ ("2001:db8::42", "http://[2001:db8::42]/metrics"),+ ]+ insert_traces(+ [+ Traces(+ timestamp=now - timedelta(seconds=i + 1),+ duration=timedelta(milliseconds=50),+ trace_id=TraceIdGenerator.trace_id(),+ span_id=TraceIdGenerator.span_id(),+ name="call",+ kind=TracesKind.SPAN_KIND_CLIENT,+ status_code=TracesStatusCode.STATUS_CODE_OK,+ resources={"service.name": "gateway"},+ attributes={"http.url": url, "http.host": host},+ )+ for i, (host, url) in enumerate(specs)+ ]+ )++ response = make_third_party_apis_request(+ signoz,+ get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD),+ start_ms=int((now - timedelta(minutes=10)).timestamp() * 1000),+ end_ms=int((now + timedelta(minutes=1)).timestamp() * 1000),+ show_ip=show_ip,+ )++ assert response.status_code == HTTPStatus.OK, response.text+ domains = rows_by_domain(scalar_result(response)).keys()++ assert "named.example.com" in domains, domains+ assert ("10.42.7.9" in domains) is show_ip, domains+ assert ("2001:db8::42" in domains) is show_ip, domains+++def test_domain_list_latency_and_rate_values(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+) -> None:+ """+ Setup:+ 3 client spans of 250ms on one domain, 1 on another.++ Tests:+ p99 is duration_nano in nanoseconds, and rps is rate() over the scalar window+ (count / (end - start) seconds), so the busier domain's rate is 3x the other's.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ busy, quiet = "busy.example.com", "quiet.example.com"+ duration = timedelta(milliseconds=250)+ specs = [(busy, 0), (busy, 1), (busy, 2), (quiet, 3)]+ insert_traces(+ [+ Traces(+ timestamp=now - timedelta(seconds=i + 1),+ duration=duration,+ trace_id=TraceIdGenerator.trace_id(),+ span_id=TraceIdGenerator.span_id(),+ name="call",+ kind=TracesKind.SPAN_KIND_CLIENT,+ status_code=TracesStatusCode.STATUS_CODE_OK,+ resources={"service.name": "gateway"},+ attributes={"http.url": f"https://{host}/a", "http.host": host},+ )+ for host, i in specs+ ]+ )++ start_ms = int((now - timedelta(minutes=10)).timestamp() * 1000)+ end_ms = int((now + timedelta(minutes=1)).timestamp() * 1000)+ response = make_third_party_apis_request(signoz, get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD), start_ms, end_ms)++ assert response.status_code == HTTPStatus.OK, response.text+ result = scalar_result(response)+ by_query = index_columns_by_query(result)+ rows = rows_by_domain(result)++ # every span has the same duration, so the percentile is that duration exactly+ expected_ns = duration / timedelta(microseconds=1) * 1000+ for domain in (busy, quiet):+ assert rows[domain][by_query["p99"]] == pytest.approx(expected_ns), (domain, result["data"])++ window_seconds = (end_ms - start_ms) / 1000+ assert rows[busy][by_query["rps"]] == pytest.approx(3 / window_seconds, rel=0.05), result["data"]+ assert rows[quiet][by_query["rps"]] == pytest.approx(1 / window_seconds, rel=0.05), result["data"]+++ "label,errors,total,expected",+ [("quarter", 1, 4, 25.0), ("all", 2, 2, 100.0), ("none", 0, 3, 0.0)],+)+def test_domain_list_error_rate_is_a_percentage_of_spans(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+ label: str,+ errors: int,+ total: int,+ expected: float,+) -> None:+ """+ Setup:+ `total` client spans on one domain, `errors` of them failed.++ Tests:+ error_rate is (error/total_span)*100 across the range, including the all-failed and+ none-failed edges.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ domain = f"errors-{label}.example.com"+ statuses = [TracesStatusCode.STATUS_CODE_ERROR] * errors + [TracesStatusCode.STATUS_CODE_OK] * (total - errors)+ insert_traces(+ [+ Traces(+ timestamp=now - timedelta(seconds=i + 1),+ duration=timedelta(milliseconds=100),+ trace_id=TraceIdGenerator.trace_id(),+ span_id=TraceIdGenerator.span_id(),+ name="call",+ kind=TracesKind.SPAN_KIND_CLIENT,+ status_code=status,+ resources={"service.name": "gateway"},+ attributes={"http.url": f"https://{domain}/a", "http.host": domain},+ )+ for i, status in enumerate(statuses)+ ]+ )++ response = make_third_party_apis_request(+ signoz,+ get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD),+ start_ms=int((now - timedelta(minutes=10)).timestamp() * 1000),+ end_ms=int((now + timedelta(minutes=1)).timestamp() * 1000),+ )++ assert response.status_code == HTTPStatus.OK, response.text+ result = scalar_result(response)+ rows = rows_by_domain(result)+ assert domain in rows, result["data"]++ error_rate = rows[domain][index_columns_by_query(result)["error_rate"]]+ assert error_rate == pytest.approx(expected), result["data"]+++def test_domain_list_user_filter_narrows_the_base_filter(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+) -> None:+ """+ Setup:+ Two client spans to the same domain from different services.++ Tests:+ A caller filter is ANDed onto the base filter, so only the named service's span+ contributes.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ domain = "filtered.example.com"+ insert_traces(+ [+ Traces(+ timestamp=now - timedelta(seconds=i + 1),+ duration=timedelta(milliseconds=100),+ trace_id=TraceIdGenerator.trace_id(),+ span_id=TraceIdGenerator.span_id(),+ name="call",+ kind=TracesKind.SPAN_KIND_CLIENT,+ status_code=TracesStatusCode.STATUS_CODE_OK,+ resources={"service.name": service},+ attributes={"http.url": f"https://{domain}/{service}", "http.host": domain},+ )+ for i, service in enumerate(("keeper-svc", "dropped-svc"))+ ]+ )++ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ start_ms = int((now - timedelta(minutes=10)).timestamp() * 1000)+ end_ms = int((now + timedelta(minutes=1)).timestamp() * 1000)++ unfiltered = make_third_party_apis_request(signoz, token, start_ms, end_ms)+ filtered = make_third_party_apis_request(signoz, token, start_ms, end_ms, filter_expression="service.name = 'keeper-svc'")++ assert unfiltered.status_code == HTTPStatus.OK, unfiltered.text+ assert filtered.status_code == HTTPStatus.OK, filtered.text++ unfiltered_result = scalar_result(unfiltered)+ filtered_result = scalar_result(filtered)+ endpoints_key = "endpoints"+ assert rows_by_domain(unfiltered_result)[domain][index_columns_by_query(unfiltered_result)[endpoints_key]] == 2+ assert rows_by_domain(filtered_result)[domain][index_columns_by_query(filtered_result)[endpoints_key]] == 1+++def test_domain_list_caller_group_by_adds_a_dimension(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_traces: Callable[[list[Traces]], None],+) -> None:+ """+ Setup:+ Two client spans to one domain, from two services.++ Tests:+ A caller groupBy is merged after the domain key, so the domain splits into one row+ per group value and the extra key gets its own column.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ domain = "grouped.example.com"+ insert_traces(+ [+ Traces(+ timestamp=now - timedelta(seconds=i + 1),+ duration=timedelta(milliseconds=100),+ trace_id=TraceIdGenerator.trace_id(),+ span_id=TraceIdGenerator.span_id(),+ name="call",+ kind=TracesKind.SPAN_KIND_CLIENT,+ status_code=TracesStatusCode.STATUS_CODE_OK,+ resources={"service.name": service},+ attributes={"http.url": f"https://{domain}/a", "http.host": domain},+ )+ for i, service in enumerate(("svc-a", "svc-b"))+ ]+ )++ response = make_third_party_apis_request(+ signoz,+ get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD),+ start_ms=int((now - timedelta(minutes=10)).timestamp() * 1000),+ end_ms=int((now + timedelta(minutes=1)).timestamp() * 1000),+ group_by=[+ {+ "name": "service.name",+ "fieldDataType": "string",+ "fieldContext": "resource",+ "signal": "traces",+ }+ ],+ )++ assert response.status_code == HTTPStatus.OK, response.text+ result = scalar_result(response)++ assert "service.name" in {col["name"] for col in result["columns"]}, result["columns"]+ domain_idx = domain_column_index(result)+ service_idx = next(i for i, col in enumerate(result["columns"]) if col["name"] == "service.name")+ services = {row[service_idx] for row in result["data"] if row[domain_idx] == domain}+ assert services == {"svc-a", "svc-b"}, result["data"]+++def test_domain_list_is_empty_outside_the_seeded_window(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+) -> None:+ """+ Tests:+ A window with no matching spans answers 200 with no rows, not an error.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ long_ago = now - timedelta(days=400)+ response = make_third_party_apis_request(+ signoz,+ get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD),+ start_ms=int(long_ago.timestamp() * 1000),+ end_ms=int((long_ago + timedelta(minutes=5)).timestamp() * 1000),+ )++ assert response.status_code == HTTPStatus.OK, response.text+ assert scalar_result(response)["data"] == []+++def test_domain_list_requires_authentication(signoz: types.SigNoz) -> None:+ """+ Tests:+ The route sits behind ViewAccess, so an unauthenticated call is rejected.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ response = make_third_party_apis_request(+ signoz,+ "",+ start_ms=int((now - timedelta(minutes=10)).timestamp() * 1000),+ end_ms=int(now.timestamp() * 1000),+ )++ assert response.status_code == HTTPStatus.UNAUTHORIZED, response.text+++def test_domain_list_rejects_inverted_time_range(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+) -> None:+ """+ Tests:+ The request is validated before any query is built, so start >= end is a client+ error rather than an empty result.+ """+ now = datetime.now(tz=UTC).replace(microsecond=0)+ response = make_third_party_apis_request(+ signoz,+ get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD),+ start_ms=int(now.timestamp() * 1000),+ end_ms=int((now - timedelta(minutes=5)).timestamp() * 1000),+ )++ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text