:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(logs): show curated resource facets whatever the tenant's key count (#106512)
Frank Hamandbd380dbce3cc
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex d370369f4584..7a99d8c3ebcc 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -31112,6 +31112,13 @@"LogAttributesQuery": {"additionalProperties": false,"properties": {+ "attributeKeys": {+ "description": "Return only attribute keys that exactly match an entry in this list.",+ "items": {+ "type": "string"+ },+ "type": "array"+ },"attributeType": {"type": "string"},diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 9adbf57553b3..b7bdec67d7ec 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -4710,6 +4710,8 @@ export interface LogAttributesQuery extends DataNode<LogAttributesQueryResponse>filterGroup?: PropertyGroupFilterserviceNames?: string[]attributeType: string+ /** Return only attribute keys that exactly match an entry in this list. */+ attributeKeys?: string[]}export interface LogAttributeResult {diff --git a/posthog/schema.py b/posthog/schema.pyindex addb75f57880..495fd76cdfe7 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -30255,6 +30255,10 @@ class LogAttributesQuery(BaseModel):model_config = ConfigDict(extra="forbid",)+ attributeKeys: list[str] | None = Field(+ default=None,+ description=("Return only attribute keys that exactly match an entry in this list."),+ )attributeType: strdateRange: DateRange | None = NonefilterGroup: PropertyGroupFilter | None = Nonediff --git a/products/logs/backend/log_attributes_query_runner.py b/products/logs/backend/log_attributes_query_runner.pyindex 06980ff808bf..e12e25c99778 100644--- a/products/logs/backend/log_attributes_query_runner.py+++ b/products/logs/backend/log_attributes_query_runner.py@@ -70,6 +70,7 @@ class LogAttributesQueryRunner(AnalyticsQueryRunner[LogAttributesQueryResponse],AND time_bucket <= {date_to_start_of_interval} + {one_interval_period}AND attribute_type = {attributeType}AND attribute_key ILIKE {search}+ AND {key_filter}AND {where}GROUP BY team_id, attribute_keyORDER BY lower(attribute_key) = lower({exact}) DESC, has(splitByNonAlpha(lower(attribute_key)), lower({exact})) DESC, sum(attribute_count) desc, attribute_key asc@@ -82,6 +83,7 @@ class LogAttributesQueryRunner(AnalyticsQueryRunner[LogAttributesQueryResponse],"attributeType": ast.Constant(value=self.query.attributeType),"limit": ast.Constant(value=self.query.limit),"offset": ast.Constant(value=self.query.offset),+ "key_filter": self._key_filter(),"where": self.where(),**self.query_date_range.to_placeholders(),},@@ -114,6 +116,7 @@ class LogAttributesQueryRunner(AnalyticsQueryRunner[LogAttributesQueryResponse],AND time_bucket <= {date_to_start_of_interval} + {one_interval_period}AND attribute_type = {attributeType}AND attribute_key ILIKE {search}+ AND {key_filter}AND {where}GROUP BY team_id, attribute_key@@ -130,6 +133,7 @@ class LogAttributesQueryRunner(AnalyticsQueryRunner[LogAttributesQueryResponse],AND attribute_type = {attributeType}AND attribute_value ILIKE {search}AND attribute_key NOT ILIKE {search}+ AND {key_filter}AND {where}GROUP BY team_id, attribute_key)@@ -148,6 +152,7 @@ class LogAttributesQueryRunner(AnalyticsQueryRunner[LogAttributesQueryResponse],"attributeType": ast.Constant(value=self.query.attributeType),"limit": ast.Constant(value=self.query.limit),"offset": ast.Constant(value=self.query.offset),+ "key_filter": self._key_filter(),"where": self.where(),**self.query_date_range.to_placeholders(),},@@ -156,6 +161,16 @@ class LogAttributesQueryRunner(AnalyticsQueryRunner[LogAttributesQueryResponse],assert isinstance(query, ast.SelectQuery)return query+ def _key_filter(self) -> ast.Expr:+ # Keep this filter out of where(). That method also filters the resource fingerprint subquery.+ # The subquery has no attribute_key.+ if not self.query.attributeKeys:+ return ast.Constant(value=True)+ return parse_expr(+ "attribute_key IN {keys}",+ placeholders={"keys": ast.Tuple(exprs=[ast.Constant(value=key) for key in self.query.attributeKeys])},+ )+def where(self) -> ast.Expr:exprs: list[ast.Expr] = []diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex c15b16e0a280..d72cd38585fd 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -85,6 +85,7 @@ __all__ = [tracer = trace.get_tracer(__name__)LOGS_MAX_EXPORT_ROWS = 10_000+MAX_ATTRIBUTE_KEYS = 100class DateRangeSerializer(serializers.Serializer):@@ -213,6 +214,18 @@ class _LogsAttributesQuerySerializer(serializers.Serializer):required=False,help_text="Date range to search within. Defaults to last hour.",)+ keys = serializers.CharField(+ required=False,+ help_text="Comma-separated list of attribute keys. The endpoint returns only keys that exactly match an entry in the list.",+ )+ date_from = serializers.CharField(+ required=False,+ help_text="Start of the range as a top-level parameter. The endpoint ignores it when you send dateRange.",+ )+ date_to = serializers.CharField(+ required=False,+ help_text="End of the range as a top-level parameter. The endpoint ignores it when you send dateRange.",+ )serviceNames = serializers.ListField(child=serializers.CharField(),required=False,@@ -1865,6 +1878,9 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):except (json.JSONDecodeError, ValidationError, ValueError):# Default to last hour if dateRange is malformeddateRange = DateRange(date_from="-1h")+ # Flat params let clients that cannot send a JSON query param (the generated frontend client) scope the window.+ if "dateRange" not in request.GET and (request.GET.get("date_from") or request.GET.get("date_to")):+ dateRange = DateRange(date_from=request.GET.get("date_from"), date_to=request.GET.get("date_to"))try:serviceNames = json.loads(request.GET.get("serviceNames", "[]"))@@ -1891,9 +1907,16 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):except ValueError:offset = 0+ attribute_keys = list(dict.fromkeys(k.strip() for k in request.GET.get("keys", "").split(",") if k.strip()))+ if len(attribute_keys) > MAX_ATTRIBUTE_KEYS:+ return Response(+ {"error": f"At most {MAX_ATTRIBUTE_KEYS} keys are allowed."}, status=status.HTTP_400_BAD_REQUEST+ )+query = LogAttributesQuery(dateRange=dateRange,attributeType=attributeType,+ attributeKeys=attribute_keys or None,search=search,searchValues=search_values,limit=limit,diff --git a/products/logs/backend/test/test_log_values_attributes.py b/products/logs/backend/test/test_log_values_attributes.pyindex 988fd262e3b1..1592ce9870c2 100644--- a/products/logs/backend/test/test_log_values_attributes.py+++ b/products/logs/backend/test/test_log_values_attributes.py@@ -426,3 +426,124 @@ class TestLogAttributesIlikeEscaping(ClickhouseTestMixin, APIBaseTest):names = {r["name"] for r in response.json()["results"]}self.assertIn("50%off", names)self.assertNotIn("50ABCoff", names)+++class TestLogAttributesKeysFilter(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ DATE_RANGE = '{"date_from": "2025-12-16T09:00:00Z", "date_to": "2025-12-16T11:00:00Z"}'+ FILLER_KEYS = [f"filler.key.{i:03d}" for i in range(100)]++ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ # The 100 filler keys occur in two logs. The environment key occurs in one log.+ # A list of the 100 most common keys omits the environment key. The facet probe must find it.+ filler = dict.fromkeys(cls.FILLER_KEYS, "x")+ resources = [+ {"service.name": "api", **filler},+ {"service.name": "api", **filler},+ {"service.name": "api", "deployment.environment": "production"},+ ]+ sql = ""+ for i, resource_attributes in enumerate(resources):+ sql += (+ json.dumps(+ {+ "uuid": f"019b2664-0000-7000-0000-0000000001{i:02d}",+ "team_id": cls.team.id,+ "timestamp": "2025-12-16 09:30:00.000000",+ "observed_timestamp": "2025-12-16 09:30:00.000000",+ "body": f"keys filter log {i}",+ "severity_text": "info",+ "severity_number": 9,+ "service_name": "api",+ "resource_attributes": resource_attributes,+ }+ )+ + "\n"+ )+ sync_execute(f"INSERT INTO logs FORMAT JSONEachRow\n{sql}")++ def _get(self, params: dict):+ query_params = {"dateRange": self.DATE_RANGE, "attribute_type": "resource", **params}+ return self.client.get(f"/api/projects/{self.team.pk}/logs/attributes", query_params)++ def _names(self, params: dict) -> list[str]:+ response = self._get(params)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ return [r["name"] for r in response.json()["results"]]++ def test_keys_returns_low_volume_key_beyond_top_100(self):+ self.assertNotIn("deployment.environment", self._names({}))+ self.assertEqual(+ self._names({"keys": "deployment.environment.name,deployment.environment,env"}),+ ["deployment.environment"],+ )++ def test_keys_survive_resource_attribute_filter(self):+ # Keep the key filter out of the resource fingerprint subquery. That subquery has no attribute_key.+ filter_group = json.dumps(+ {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [+ {+ "key": "service.name",+ "type": "log_resource_attribute",+ "operator": "exact",+ "value": ["api"],+ }+ ],+ }+ ],+ }+ )+ self.assertEqual(+ self._names({"keys": "deployment.environment", "filterGroup": filter_group}), ["deployment.environment"]+ )++ @parameterized.expand(+ [+ ("spaces_and_blanks", " deployment.environment , ,env,", ["deployment.environment"]),+ ("duplicates", "deployment.environment,deployment.environment", ["deployment.environment"]),+ ("absent_key", "k8s.pod.name", []),+ ]+ )+ def test_keys_parsing(self, _name, keys, expected):+ self.assertEqual(self._names({"keys": keys}), expected)++ def test_empty_keys_does_not_filter(self):+ self.assertEqual(len(self._names({"keys": ""})), 100)++ @parameterized.expand(+ [+ ("window_over_the_seed", "2025-12-16T09:00:00Z", "2025-12-16T11:00:00Z", ["deployment.environment"]),+ ("window_before_the_seed", "2025-12-15T09:00:00Z", "2025-12-15T11:00:00Z", []),+ ]+ )+ def test_flat_date_params_scope_window(self, _name, date_from, date_to, expected):+ # The generated frontend client cannot send the JSON dateRange, so it scopes the window with flat params.+ response = self.client.get(+ f"/api/projects/{self.team.pk}/logs/attributes",+ {+ "attribute_type": "resource",+ "keys": "deployment.environment",+ "date_from": date_from,+ "date_to": date_to,+ },+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([r["name"] for r in response.json()["results"]], expected)++ def test_date_range_json_wins_over_flat_params(self):+ names = self._names(+ {"keys": "deployment.environment", "date_from": "2025-12-15T09:00:00Z", "date_to": "2025-12-15T11:00:00Z"}+ )+ self.assertEqual(names, ["deployment.environment"])++ def test_too_many_keys_returns_400(self):+ response = self._get({"keys": ",".join(f"key.{i}" for i in range(101))})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.test.tsnew file mode 100644index 000000000000..64b1943118e2--- /dev/null+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.test.ts@@ -0,0 +1,70 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { logsViewerFiltersLogic } from '../Filters/logsViewerFiltersLogic'+import { facetPresenceLogic } from './facetPresenceLogic'+import { FACETS, presenceProbeKeys } from './facets'++const ID = 'test-viewer'++describe('facetPresenceLogic', () => {+ let logic: ReturnType<typeof facetPresenceLogic.build>+ let requestParams: URLSearchParams | null+ let emittedKeys: string[]++ beforeEach(() => {+ requestParams = null+ emittedKeys = []+ // Mock the HTTP response so the request uses the generated client's URL builder.+ useMocks({+ get: {+ '/api/projects/:team_id/logs/attributes/': ({ request }) => {+ requestParams = new URL(request.url).searchParams+ return [200, { results: emittedKeys.map((name) => ({ name })), count: emittedKeys.length }]+ },+ },+ })+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ })++ const mountAndLoad = async (): Promise<void> => {+ logic = facetPresenceLogic({ id: ID })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadPresentResourceKeysSuccess'])+ }++ it('probes the curated keys without a date range the backend cannot parse', async () => {+ await mountAndLoad()++ expect(requestParams?.get('attribute_type')).toEqual('resource')+ expect(requestParams?.get('keys')?.split(',')).toEqual(presenceProbeKeys(FACETS))+ // The generated client converts an object to "[object Object]". The backend reads it as "last hour".+ expect(Array.from(requestParams?.values() ?? [])).not.toContain('[object Object]')+ // The endpoint uses its default window for a recent selection.+ expect(requestParams?.has('date_from')).toBe(false)+ })++ it('probes an older selection so its keys keep their facets', async () => {+ await mountAndLoad()++ logsViewerFiltersLogic({ id: ID }).actions.setFilters({ dateRange: { date_from: '-30d', date_to: null } })+ await expectLogic(logic).toDispatchActions(['loadPresentResourceKeys', 'loadPresentResourceKeysSuccess'])++ expect(requestParams?.get('date_from')).toEqual('-30d')+ expect(requestParams?.has('dateRange')).toBe(false)+ })++ it('shows the environment facet when only the env alias is emitted', async () => {+ emittedKeys = ['env']+ await mountAndLoad()++ const environment = logic.values.visibleFacets.find((f) => f.key === 'environment')+ expect(environment?.source).toMatchObject({ type: 'resourceAttribute', key: 'env' })+ })+})diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.tsindex e7ad8ffb7f90..bbe1fc6e2d10 100644--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts@@ -1,5 +1,6 @@import { MakeLogicType, connect, events, kea, key, listeners, path, props, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'import { teamLogic } from 'scenes/teamLogic'@@ -7,11 +8,12 @@ import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViimport { logsAttributesRetrieve } from '../../../generated/api'import { customFacetsLogic } from './customFacetsLogic'-import { FACETS, FacetConfig, resolveFacets } from './facets'+import { FACETS, FacetConfig, presenceProbeKeys, presenceProbeWindow, resolveFacets } from './facets'-// Broad, filter-independent window for the "which resource attributes does this tenant emit" probe.-// Cheap: keys-only group-by on the log_attributes aggregation table (no value scan).-const PRESENCE_LOOKBACK = { date_from: '-90d' }+// Request the exact keys used by curated facets. Other resource keys cannot hide a facet.+// Send date_from and date_to as separate parameters. The generated client converts objects to strings.+// A dateRange object becomes "[object Object]". The endpoint then uses its one-hour fallback.+const PRESENCE_KEYS = presenceProbeKeys(FACETS)export interface FacetPresenceLogicProps {id: string@@ -20,7 +22,17 @@ export interface FacetPresenceLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface facetPresenceLogicValues {customFacets: FacetConfig[] // customFacetsLogic+ utcDateRange: {+ date_from: string | null | undefined+ date_to: string | null | undefined+ explicitDate: boolean | null | undefined+ } // logsViewerFiltersLogiccurrentTeamId: number | null // teamLogic+ presenceWindow: {+ date_from: string+ date_to?: string | undefined+ } | null+ presenceWindowSignature: stringpresentResourceKeys: string[]presentResourceKeysLoading: booleanresolvedFacets: FacetConfig[]@@ -31,7 +43,7 @@ export interface facetPresenceLogicValues {export interface facetPresenceLogicActions {bumpFacetRefresh: () => {value: true- }+ } // logsViewerFiltersLogicloadPresentResourceKeys: () => anyloadPresentResourceKeysFailure: (error: string,@@ -53,6 +65,20 @@ export interface facetPresenceLogicActions {export interface facetPresenceLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ presenceWindow: (utcDateRange: {+ date_from: string | null | undefined+ date_to: string | null | undefined+ explicitDate: boolean | null | undefined+ }) => {+ date_from: string+ date_to?: string | undefined+ } | null+ presenceWindowSignature: (+ presenceWindow: {+ date_from: string+ date_to?: string | undefined+ } | null+ ) => stringresolvedFacets: (presentResourceKeys: string[]) => FacetConfig[]visibleFacets: (resolvedFacets: FacetConfig[], customFacets: FacetConfig[]) => FacetConfig[]}@@ -77,7 +103,14 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([path((key) => ['products', 'logs', 'frontend', 'components', 'LogsViewer', 'FacetRail', 'facetPresenceLogic', key]),connect((props: FacetPresenceLogicProps) => ({- values: [teamLogic, ['currentTeamId'], customFacetsLogic, ['customFacets']],+ values: [+ teamLogic,+ ['currentTeamId'],+ customFacetsLogic,+ ['customFacets'],+ logsViewerFiltersLogic({ id: props.id }),+ ['utcDateRange'],+ ],actions: [logsViewerFiltersLogic({ id: props.id }), ['bumpFacetRefresh']],})),@@ -92,8 +125,9 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([}const response = await logsAttributesRetrieve(String(values.currentTeamId), {attribute_type: 'resource',- dateRange: PRESENCE_LOOKBACK,- limit: 100,+ keys: PRESENCE_KEYS.join(','),+ limit: PRESENCE_KEYS.length,+ ...values.presenceWindow,})return response.results.map((r) => r.name)},@@ -102,6 +136,24 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([})),selectors({+ presenceWindow: [+ (s) => [s.utcDateRange],+ (utcDateRange: {+ date_from: string | null | undefined+ date_to: string | null | undefined+ explicitDate: boolean | null | undefined+ }) => presenceProbeWindow(utcDateRange),+ ],+ // Use a string so an equal window object does not start another probe.+ presenceWindowSignature: [+ (s) => [s.presenceWindow],+ (+ presenceWindow: {+ date_from: string+ date_to?: string+ } | null+ ) => JSON.stringify(presenceWindow),+ ],// Column facets always render; resource-attribute facets only when the tenant emits the key (or one// of its aliases, which resolution rewrites the facet onto). Custom facets skip that presence gate// entirely — the user picked them from a live taxonomic list, so they're known to exist already —@@ -125,6 +177,15 @@ export const facetPresenceLogic = kea<facetPresenceLogicType>([bumpFacetRefresh: () => actions.loadPresentResourceKeys(),})),+ subscriptions(({ actions }) => ({+ // A change between recent selections does not change the signature or start a new probe.+ presenceWindowSignature: (signature: string, previous: string | undefined) => {+ if (previous !== undefined && signature !== previous) {+ actions.loadPresentResourceKeys()+ }+ },+ })),+events(({ actions }) => ({afterMount: () => actions.loadPresentResourceKeys(),})),diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.tsindex 10a452ef87f9..5c9635ff4727 100644--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts@@ -10,6 +10,8 @@ import {facetScopeSignature,filterFacetsByName,mergeSelectedIntoOptions,+ presenceProbeKeys,+ presenceProbeWindow,resolveFacets,} from './facets'@@ -314,6 +316,45 @@ describe('facets', () => {})})+ describe('presenceProbeKeys', () => {+ it('asks about every curated resource key and alias, once each', () => {+ expect(presenceProbeKeys(CONFIGURED_FACETS)).toEqual([+ 'deployment.environment.name',+ 'deployment.environment',+ 'env',+ 'k8s.namespace.name',+ 'k8s.deployment.name',+ 'k8s.pod.name',+ 'k8s.node.name',+ 'host.name',+ ])+ })++ // Each key in the probe must keep its facet when resolveFacets receives it.+ it.each(presenceProbeKeys(CONFIGURED_FACETS))('a reported %s keeps a resource facet on it', (key) => {+ const resolved = resolveFacets(CONFIGURED_FACETS, [key])+ expect(resolved.some((f) => f.source.type === 'resourceAttribute' && f.source.key === key)).toBe(true)+ })+ })++ describe('presenceProbeWindow', () => {+ it.each<+ [string, { date_from?: string | null; date_to?: string | null }, ReturnType<typeof presenceProbeWindow>]+ >([+ ['no selection uses the default window', {}, null],+ ['a recent relative selection uses the default window', { date_from: '-1h' }, null],+ ['a recent absolute selection uses the default window', { date_from: new Date().toISOString() }, null],+ ['an older relative selection is probed as-is', { date_from: '-30d' }, { date_from: '-30d' }],+ [+ 'an older absolute selection keeps its end',+ { date_from: '2020-01-01T00:00:00.000Z', date_to: '2020-01-02T00:00:00.000Z' },+ { date_from: '2020-01-01T00:00:00.000Z', date_to: '2020-01-02T00:00:00.000Z' },+ ],+ ])('%s', (_, range, expected) => {+ expect(presenceProbeWindow(range)).toEqual(expected)+ })+ })+describe('buildCustomFacet / customFacetIdentity', () => {it.each<['attribute' | 'resourceAttribute']>([['attribute'], ['resourceAttribute']])('round-trips the key and sourceType through a %s facet',diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.tsindex 10909bf473ea..abed2e1626a3 100644--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts@@ -1,3 +1,6 @@+import { dayjs } from 'lib/dayjs'+import { dateStringToDayJs } from 'lib/utils/dateFilters'+import { UniversalFiltersGroup } from '~/types'import { SEVERITY_BAR_COLORS } from 'products/logs/frontend/components/VirtualizedLogsList/columnDefinitions'@@ -222,6 +225,41 @@ export const FACETS: FacetConfig[] = [HOST_FACET,]+/**+ * Return each resource attribute key and alias for these facets once.+ * The presence probe uses these exact keys. Other resource keys cannot hide a facet.+ */+export function presenceProbeKeys(facets: FacetConfig[]): string[] {+ const keys = facets.flatMap((facet) =>+ facet.source.type === 'resourceAttribute' ? [facet.source.key, ...(facet.source.aliasKeys ?? [])] : []+ )+ return Array.from(new Set(keys))+}++/** The endpoint uses seven days when the request has no date range. */+export const PRESENCE_DEFAULT_LOOKBACK_DAYS = 7++/**+ * Return the probe window for a selected range.+ * Return null to use the endpoint's default seven-day window.+ * If the selection starts before that window, use its range to include older keys.+ * This limits the read to the selected range.+ */+export function presenceProbeWindow(range: {+ date_from?: string | null+ date_to?: string | null+}): { date_from: string; date_to?: string } | null {+ const from = range.date_from+ if (!from) {+ return null+ }+ const start = dayjs(from).isValid() ? dayjs(from) : dateStringToDayJs(from)+ if (!start || !start.isBefore(dayjs().subtract(PRESENCE_DEFAULT_LOOKBACK_DAYS, 'day'))) {+ return null+ }+ return range.date_to ? { date_from: from, date_to: range.date_to } : { date_from: from }+}+/*** Resolve the configured facets against the resource-attribute keys a tenant actually emits.* Column facets always pass through. A resource-attribute facet is kept only if the tenant emits itsdiff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 281cc524ad7e..ba9fa8ba02e1 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -2871,10 +2871,25 @@ export type LogsAttributesRetrieveParams = {* Date range to search within. Defaults to last hour.*/dateRange?: _DateRangeApi+ /**+ * Start of the range as a top-level parameter. The endpoint ignores it when you send dateRange.+ * @minLength 1+ */+ date_from?: string+ /**+ * End of the range as a top-level parameter. The endpoint ignores it when you send dateRange.+ * @minLength 1+ */+ date_to?: string/*** Property filters to narrow which logs are scanned for attributes.*/filterGroup?: _LogPropertyFilterApi[]+ /**+ * Comma-separated list of attribute keys. The endpoint returns only keys that exactly match an entry in the list.+ * @minLength 1+ */+ keys?: string/*** Max results (default: 100)* @minimum 1diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yamlindex 666026f9093a..cd7dfbbcc9d9 100644--- a/products/logs/mcp/tools.yaml+++ b/products/logs/mcp/tools.yaml@@ -355,6 +355,9 @@ tools:To search resource-level attributes (e.g. k8s.pod.name, k8s.namespace.name), you MUST explicitly passattribute_type: "resource" — it will NOT return resource attributes unless you do. Accepts optionalserviceNames, dateRange, and filterGroup to narrow which logs are scanned.+ exclude_params:+ - date_from+ - date_toresponse:include:- resultsdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2d0103d68273..354c8514b3b9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -51817,6 +51817,8 @@ export namespace Schemas {}export interface LogAttributesQuery {+ /** Return only attribute keys that exactly match an entry in this list. */+ attributeKeys?: string[] | null;attributeType: string;dateRange?: DateRange | null;filterGroup?: PropertyGroupFilter | null;@@ -113557,10 +113559,25 @@ export namespace Schemas {* Date range to search within. Defaults to last hour.*/dateRange?: _DateRange;+ /**+ * Start of the range as a top-level parameter. The endpoint ignores it when you send dateRange.+ * @minLength 1+ */+ date_from?: string;+ /**+ * End of the range as a top-level parameter. The endpoint ignores it when you send dateRange.+ * @minLength 1+ */+ date_to?: string;/*** Property filters to narrow which logs are scanned for attributes.*/filterGroup?: _LogPropertyFilter[];+ /**+ * Comma-separated list of attribute keys. The endpoint returns only keys that exactly match an entry in the list.+ * @minLength 1+ */+ keys?: string;/*** Max results (default: 100)* @minimum 1diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.tsindex 7d924bfeb184..81c0bf3f740b 100644--- a/services/mcp/src/generated/logs/api.ts+++ b/services/mcp/src/generated/logs/api.ts@@ -5512,6 +5512,16 @@ export const LogsAttributesRetrieveQueryParams = () => zod.object({}).optional().describe('Date range to search within. Defaults to last hour.'),+ date_from: zod+ .string()+ .min(1)+ .optional()+ .describe('Start of the range as a top-level parameter. The endpoint ignores it when you send dateRange.'),+ date_to: zod+ .string()+ .min(1)+ .optional()+ .describe('End of the range as a top-level parameter. The endpoint ignores it when you send dateRange.'),filterGroup: zod.array(zod.object({@@ -5564,6 +5574,13 @@ export const LogsAttributesRetrieveQueryParams = () => zod.object({).default(logsAttributesRetrieveQueryFilterGroupDefault).describe('Property filters to narrow which logs are scanned for attributes.'),+ keys: zod+ .string()+ .min(1)+ .optional()+ .describe(+ 'Comma-separated list of attribute keys. The endpoint returns only keys that exactly match an entry in the list.'+ ),limit: zod.number().min(1)diff --git a/services/mcp/src/tools/generated/logs.ts b/services/mcp/src/tools/generated/logs.tsindex cd69d487eb5c..9863281c0850 100644--- a/services/mcp/src/tools/generated/logs.ts+++ b/services/mcp/src/tools/generated/logs.ts@@ -548,7 +548,7 @@ const logsAttributeValuesList = (): ToolBase<const LogsAttributesListSchema = () => {const LogsAttributesRetrieveQueryParams = orvalSchemas.LogsAttributesRetrieveQueryParams()- return LogsAttributesRetrieveQueryParams+ return LogsAttributesRetrieveQueryParams.omit({ date_from: true, date_to: true })}const logsAttributesList = (): ToolBase<@@ -566,6 +566,7 @@ const logsAttributesList = (): ToolBase<attribute_type: params.attribute_type,dateRange: params.dateRange,filterGroup: params.filterGroup,+ keys: params.keys,limit: params.limit,offset: params.offset,search: params.search,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attributes-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attributes-list.jsonindex 4de54d1ff0ec..bf01500cc055 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attributes-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attributes-list.json@@ -80,6 +80,11 @@},"type": "array"},+ "keys": {+ "description": "Comma-separated list of attribute keys. The endpoint returns only keys that exactly match an entry in the list.",+ "minLength": 1,+ "type": "string"+ },"limit": {"description": "Max results (default: 100)","maximum": 100,