Skip to content

: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.

fix(file-system): serve recents view-log-first to kill loader timeouts (#65246)

Rafael Audibertc01e0c856d9e
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
index 6fcb2563ad06..0a766d05b6c8 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
@@ -479,7 +479,7 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
// flips shortcutDataHasLoaded), and kea-loaders' global onFailure handler in
// initKea captures the exception so the previously-silent hang is surfaced.
const response = await withTimeout(
- api.fileSystemShortcuts.list(),
+ (signal) => api.fileSystemShortcuts.list({ signal }),
SHORTCUTS_LOADER_TIMEOUT_MS,
'loadShortcuts timed out'
)
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index a70476d95008..1cfab40945be 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2464,6 +2464,7 @@ const api = {
createdAtGt,
createdAtLt,
searchNameOnly,
+ signal,
}: {
parent?: string
path?: string
@@ -2479,6 +2480,7 @@ const api = {
createdAtGt?: string
createdAtLt?: string
searchNameOnly?: boolean
+ signal?: AbortSignal
}): Promise<CountedPaginatedResponseWithUsers<FileSystemEntry>> {
return await new ApiRequest()
.fileSystem()
@@ -2498,7 +2500,7 @@ const api = {
created_at__lt: createdAtLt,
search_name_only: searchNameOnly,
})
- .get()
+ .get({ signal })
},
async unfiled(type?: string): Promise<CountResponse | null> {
return await new ApiRequest().fileSystemUnfiled(type).get()
@@ -2541,12 +2543,17 @@ const api = {
},
fileSystemLogView: {
- async list(params?: { type?: string; limit?: number }): Promise<FileSystemViewLogEntry[]> {
+ async list(params?: {
+ type?: string
+ limit?: number
+ signal?: AbortSignal
+ }): Promise<FileSystemViewLogEntry[]> {
+ const { signal, ...query } = params ?? {}
const request = new ApiRequest().fileSystemLogView()
- if (params) {
- request.withQueryString(params)
+ if (Object.keys(query).length) {
+ request.withQueryString(query)
}
- return await request.get()
+ return await request.get({ signal })
},
async create(data: { ref?: string; type?: string }): Promise<FileSystemEntry> {
return await new ApiRequest().fileSystemLogView().create({ data })
@@ -2558,12 +2565,14 @@ const api = {
limit?: number
offset?: number
ordering?: string
+ signal?: AbortSignal
}): Promise<CountedPaginatedResponse<FileSystemEntry>> {
+ const { signal, ...query } = params ?? {}
const request = new ApiRequest().fileSystemShortcut()
- if (params) {
- request.withQueryString(params)
+ if (Object.keys(query).length) {
+ request.withQueryString(query)
}
- return await request.get()
+ return await request.get({ signal })
},
async create(data: { path: string; href?: string; ref?: string; type?: string }): Promise<FileSystemEntry> {
return await new ApiRequest().fileSystemShortcut().create({ data })
diff --git a/frontend/src/lib/utils/async.test.ts b/frontend/src/lib/utils/async.test.ts
index f306de0aa202..c7c786dfab33 100644
--- a/frontend/src/lib/utils/async.test.ts
+++ b/frontend/src/lib/utils/async.test.ts
@@ -35,6 +35,28 @@ describe('async utils', () => {
await jest.advanceTimersByTimeAsync(9000)
await expect(wrapped).resolves.toBe('slow')
})
+
+ it('passes a non-aborted signal to the factory while the promise is in flight', async () => {
+ let received: AbortSignal | undefined
+ const wrapped = withTimeout((signal) => {
+ received = signal
+ return Promise.resolve('done')
+ }, 10000)
+ await expect(wrapped).resolves.toBe('done')
+ expect(received?.aborted).toBe(false)
+ })
+
+ it('aborts the factory signal when it times out', async () => {
+ let received: AbortSignal | undefined
+ const wrapped = withTimeout((signal) => {
+ received = signal
+ return new Promise<string>(() => {}) // never settles
+ }, 10000)
+ const assertion = expect(wrapped).rejects.toThrow(PromiseTimeoutError)
+ await jest.advanceTimersByTimeAsync(10000)
+ await assertion
+ expect(received?.aborted).toBe(true)
+ })
})
describe('retryWithBackoff()', () => {
diff --git a/frontend/src/lib/utils/async.ts b/frontend/src/lib/utils/async.ts
index ea08b7313c7d..c30f19946bb2 100644
--- a/frontend/src/lib/utils/async.ts
+++ b/frontend/src/lib/utils/async.ts
@@ -96,20 +96,35 @@ export class PromiseTimeoutError extends Error {
}
/**
- * Races a promise against a timeout. If `promise` does not settle within `timeoutMs`, the
- * returned promise rejects with a {@link PromiseTimeoutError}.
+ * Races a promise against a timeout. If it does not settle within `timeoutMs`, the returned
+ * promise rejects with a {@link PromiseTimeoutError}.
+ *
+ * Pass a factory `(signal) => Promise<T>` rather than a bare promise to get cancellation: on
+ * timeout the {@link AbortSignal} is aborted so the underlying request stops instead of running to
+ * completion in the background (which otherwise keeps loading the server long after the client gave
+ * up). A bare promise still works but cannot be cancelled.
*
* Use this to guard against a fetch that can stall indefinitely without ever resolving or
- * rejecting (e.g. a hung connection that is never aborted). Such a fetch leaves any awaiting
- * loader permanently "loading", which is exactly what freezes the global search page on a
- * loading skeleton.
+ * rejecting (e.g. a hung connection). Such a fetch leaves any awaiting loader permanently
+ * "loading", which is exactly what freezes the global search page on a loading skeleton.
*
* @example
- * const response = await withTimeout(api.fileSystem.list(...), 10000, 'loadRecents timed out')
+ * const response = await withTimeout(
+ * (signal) => api.fileSystem.list({ ...params, signal }),
+ * 10000,
+ * 'loadRecents timed out'
+ * )
*/
-export function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message?: string): Promise<T> {
+export function withTimeout<T>(
+ promiseOrFactory: Promise<T> | ((signal: AbortSignal) => Promise<T>),
+ timeoutMs: number,
+ message?: string
+): Promise<T> {
+ const controller = typeof promiseOrFactory === 'function' ? new AbortController() : undefined
+ const promise = typeof promiseOrFactory === 'function' ? promiseOrFactory(controller!.signal) : promiseOrFactory
return new Promise<T>((resolve, reject) => {
const timeoutId = setTimeout(() => {
+ controller?.abort()
reject(new PromiseTimeoutError(message ?? `Promise timed out after ${timeoutMs}ms`))
}, timeoutMs)
promise.then(
diff --git a/frontend/src/models/recentItemsModel.ts b/frontend/src/models/recentItemsModel.ts
index 3b0f051e7303..79f2d966c2aa 100644
--- a/frontend/src/models/recentItemsModel.ts
+++ b/frontend/src/models/recentItemsModel.ts
@@ -42,11 +42,13 @@ export const recentItemsModel = kea<recentItemsModelType>([
try {
const response = await withTimeout(
- api.fileSystem.list({
- orderBy: '-last_viewed_at',
- notType: 'folder',
- limit: RECENTS_FETCH_LIMIT,
- }),
+ (signal) =>
+ api.fileSystem.list({
+ orderBy: '-last_viewed_at',
+ notType: 'folder',
+ limit: RECENTS_FETCH_LIMIT,
+ signal,
+ }),
LOADER_TIMEOUT_MS,
'loadRecents timed out'
)
@@ -75,7 +77,7 @@ export const recentItemsModel = kea<recentItemsModelType>([
try {
const results = await withTimeout(
- api.fileSystemLogView.list({ type: 'scene' }),
+ (signal) => api.fileSystemLogView.list({ type: 'scene', signal }),
LOADER_TIMEOUT_MS,
'loadSceneLogViews timed out'
)
diff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.py
index e0601d1223b4..d80a17bd6aeb 100644
--- a/posthog/api/file_system/file_system.py
+++ b/posthog/api/file_system/file_system.py
@@ -56,7 +56,7 @@ from posthog.models.file_system.file_system import (
surface_q,
)
from posthog.models.file_system.file_system_representation import FileSystemRepresentation
-from posthog.models.file_system.file_system_view_log import FileSystemViewLog, annotate_file_system_with_view_logs
+from posthog.models.file_system.file_system_view_log import get_recent_file_system_items, recent_view_logs
from posthog.models.file_system.unfiled_file_saver import save_unfiled_files
from posthog.models.team import Team
from posthog.models.user import User
@@ -64,6 +64,10 @@ from posthog.utils import str_to_bool
DELETE_PREVIEW_ENTRY_LIMIT = 200
+# Search-within-Recents scans this many of the user's most-recent views, then the text filter trims
+# them to a page. Bounds the hydration key set so the query stays cheap on heavy view-log histories.
+RECENTS_SEARCH_SCAN_LIMIT = 200
+
class FileSystemSerializer(serializers.ModelSerializer):
last_viewed_at = serializers.DateTimeField(read_only=True, allow_null=True)
@@ -414,21 +418,9 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
elif order_by_param:
if order_by_param in ["path", "-path", "created_at", "-created_at"]:
queryset = queryset.order_by(order_by_param)
- elif order_by_param == "-last_viewed_at" and self.request.user.is_authenticated:
- queryset = annotate_file_system_with_view_logs(
- team_id=self.team.id,
- user_id=self.request.user.id,
- queryset=queryset,
- )
- queryset = queryset.order_by(F("last_viewed_at").desc(nulls_last=True), "-created_at")
- elif order_by_param == "last_viewed_at" and self.request.user.is_authenticated:
- queryset = annotate_file_system_with_view_logs(
- team_id=self.team.id,
- user_id=self.request.user.id,
- queryset=queryset,
- )
- queryset = queryset.order_by(F("last_viewed_at").asc(nulls_first=True), "created_at")
else:
+ # `last_viewed_at` ordering (Recents, with or without a search term) is served
+ # view-log-first in `_list_recents`, so it never reaches this queryset path.
queryset = queryset.order_by("-created_at")
elif self.action == "list":
if depth_param is not None:
@@ -446,24 +438,85 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return queryset
def list(self, request, *args, **kwargs):
- response = super().list(request, *args, **kwargs)
- results = response.data.get("results", [])
- user_ids = set()
-
- # Collect user IDs from the "created_by" meta field
- for item in results:
- created_by = item.get("meta", {}).get("created_by")
- if created_by and isinstance(created_by, int):
- user_ids.add(created_by)
-
- if user_ids:
- users_qs = User.objects.filter(organization=self.organization, id__in=user_ids).distinct()
- response.data["users"] = UserBasicSerializer(users_qs, many=True).data
- else:
- response.data["users"] = []
+ order_by_param = request.query_params.get("order_by")
+ # Recents (the high-volume, timeout-prone path) is served view-log-first, with or without a
+ # search term — one query function, no join, no COUNT(*).
+ if order_by_param in ("-last_viewed_at", "last_viewed_at") and request.user.is_authenticated:
+ return self._list_recents(request, descending=order_by_param == "-last_viewed_at")
+ response = super().list(request, *args, **kwargs)
+ response.data["users"] = self._created_by_users(response.data.get("results", []))
return response
+ def _created_by_users(self, results: builtins.list[dict[str, Any]]) -> builtins.list[dict[str, Any]]:
+ # Collect user IDs from the "created_by" meta field so the client can render avatars
+ # without a second round-trip.
+ user_ids = {
+ created_by
+ for item in results
+ if isinstance((created_by := item.get("meta", {}).get("created_by")), int) and created_by
+ }
+ if not user_ids:
+ return []
+ users_qs = User.objects.filter(organization=self.organization, id__in=user_ids).distinct()
+ return cast(builtins.list[dict[str, Any]], UserBasicSerializer(users_qs, many=True).data)
+
+ def _list_recents(self, request: Request, *, descending: bool) -> Response:
+ """Serve the Recents widget view-log-first (see `get_recent_file_system_items`).
+
+ Avoids both the un-indexable sort on a joined column and the pagination `COUNT(*)` — the
+ widget only ever needs the first page, so we return the rows directly. A `search` term just
+ filters the hydration: we scan a wider window of recent views and let the text filter trim
+ it, so search-within-Recents shares the exact same query path.
+
+ Only the params the Recents callers actually send are honoured here: `limit`, `not_type`,
+ `search` (+ `search_name_only`). The other list filters (`parent`, `type`, `depth`, `ref`,
+ `type__startswith`, `created_at__*`) are intentionally not applied on this path — nothing
+ pairs them with `last_viewed_at` ordering. Add handling here if a caller ever needs to.
+ """
+ try:
+ limit = int(request.query_params.get("limit", FileSystemsLimitOffsetPagination.default_limit))
+ except (TypeError, ValueError):
+ limit = FileSystemsLimitOffsetPagination.default_limit
+ limit = max(1, min(limit, 1000))
+
+ not_type_param = request.query_params.get("not_type")
+ exclude_types = [not_type_param] if not_type_param else None
+ search_param = request.query_params.get("search")
+
+ base_queryset = FileSystem.objects.filter(surface_q(self.file_system_surface), team_id=self.team.id)
+ if self.user_access_control:
+ base_queryset = self.user_access_control.filter_and_annotate_file_system_queryset(base_queryset)
+ if search_param:
+ base_queryset = self._apply_search_to_queryset(
+ base_queryset, search_param, basename_only=str_to_bool(request.query_params.get("search_name_only"))
+ )
+
+ items = get_recent_file_system_items(
+ team_id=self.team.id,
+ user_id=cast(User, request.user).id,
+ surface=self.file_system_surface,
+ # When searching, the text filter does the narrowing, so scan a wider recency window.
+ limit=RECENTS_SEARCH_SCAN_LIMIT if search_param else limit,
+ exclude_types=exclude_types,
+ file_system_queryset=base_queryset,
+ descending=descending,
+ )
+ # Ordering is handled at the view-log query level, so a search scan that widened the window
+ # is the only reason to re-slice here — `descending` already picked the right end.
+ items = items[:limit]
+
+ results = self.get_serializer(items, many=True).data
+ return Response(
+ {
+ "count": len(results),
+ "next": None,
+ "previous": None,
+ "results": results,
+ "users": self._created_by_users(results),
+ }
+ )
+
def _ensure_can_delete(self, entry: FileSystem) -> None:
stack: list[FileSystem] = [entry]
seen: set[str] = set()
@@ -808,18 +861,13 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
validated = serializer.validated_data
- queryset = FileSystemViewLog.objects.filter(
- surface_q(self.file_system_surface), team=self.team, user=request.user
+ queryset = recent_view_logs(
+ team_id=self.team.id,
+ user_id=request.user.id,
+ surface=self.file_system_surface,
+ type=validated.get("type") or None,
+ limit=validated.get("limit"),
)
- log_type = validated.get("type")
- if log_type:
- queryset = queryset.filter(type=log_type)
-
- queryset = queryset.order_by("-viewed_at")
-
- limit = validated.get("limit")
- if limit is not None:
- queryset = queryset[:limit]
return Response(FileSystemViewLogSerializer(queryset, many=True).data)
diff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.py
index 143d9a5f0d0a..9e7a1b60ecca 100644
--- a/posthog/api/test/test_file_system.py
+++ b/posthog/api/test/test_file_system.py
@@ -338,18 +338,124 @@ class TestFileSystemOrdering(APIBaseTest):
response = self.client.get(
f"/api/environments/{self.team.id}/file_system/",
- {"order_by": "-last_viewed_at", "parent": "Testing", "not_type": "folder"},
+ {"order_by": "-last_viewed_at", "not_type": "folder"},
)
assert response.status_code == status.HTTP_200_OK
- results = response.json()["results"]
+ body = response.json()
+ results = body["results"]
+ # Recents is now view-log-first: it returns only items the user has actually viewed, newest
+ # first. Never-viewed files (Third, Fourth) are not padded in. `count` reflects the returned
+ # rows (no COUNT(*) over a join).
paths = [item["path"] for item in results]
- assert paths == ["Testing/Second", "Testing/First", "Testing/Fourth", "Testing/Third"]
+ assert paths == ["Testing/Second", "Testing/First"]
+ assert body["count"] == 2
assert parse_datetime(results[0]["last_viewed_at"]) == timestamp - timedelta(hours=1)
assert parse_datetime(results[1]["last_viewed_at"]) == timestamp - timedelta(hours=3)
+ def test_recents_excludes_shortcuts_and_stale_view_logs(self) -> None:
+ timestamp = now()
+
+ FileSystem.objects.create(
+ team=self.team,
+ path="Reports/Live",
+ depth=2,
+ type="insight",
+ ref="live",
+ shortcut=False,
+ created_by=self.user,
+ )
+ # A shortcut shares (type, ref) with its canonical file; it must not show up as a duplicate.
+ FileSystem.objects.create(
+ team=self.team,
+ path="Shortcuts/Live",
+ depth=2,
+ type="insight",
+ ref="live",
+ shortcut=True,
+ created_by=self.user,
+ )
+
+ FileSystem.objects.create(
+ team=self.team,
+ path="Folders/Folder",
+ depth=2,
+ type="folder",
+ ref="folder",
+ shortcut=False,
+ created_by=self.user,
+ )
+
+ FileSystemViewLog.objects.create(
+ team=self.team, user=self.user, type="insight", ref="live", viewed_at=timestamp - timedelta(minutes=1)
+ )
+ # A view log whose canonical file was deleted must be skipped, not returned as a dead row.
+ FileSystemViewLog.objects.create(
+ team=self.team, user=self.user, type="insight", ref="gone", viewed_at=timestamp
+ )
+ # Folders are excluded by `not_type=folder`.
+ FileSystemViewLog.objects.create(
+ team=self.team, user=self.user, type="folder", ref="folder", viewed_at=timestamp
+ )
+
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/file_system/",
+ {"order_by": "-last_viewed_at", "not_type": "folder"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ results = response.json()["results"]
+ assert [item["path"] for item in results] == ["Reports/Live"]
+
+ def test_recents_ascending_returns_globally_oldest_within_limit(self) -> None:
+ timestamp = now()
+
+ # a viewed longest ago, c most recently.
+ for ref, age_hours in (("a", 3), ("b", 2), ("c", 1)):
+ FileSystem.objects.create(
+ team=self.team, path=f"R/{ref}", depth=2, type="insight", ref=ref, shortcut=False, created_by=self.user
+ )
+ FileSystemViewLog.objects.create(
+ team=self.team,
+ user=self.user,
+ type="insight",
+ ref=ref,
+ viewed_at=timestamp - timedelta(hours=age_hours),
+ )
+
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/file_system/",
+ {"order_by": "last_viewed_at", "not_type": "folder", "limit": "2"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ # Ascending + limit must pick the globally oldest two (a, b), oldest first — not the two most
+ # recent reversed (b, c). Ordering and the slice both live in the view-log query.
+ assert [item["ref"] for item in response.json()["results"]] == ["a", "b"]
+
+ def test_recents_with_search_filters_viewed_items(self) -> None:
+ timestamp = now()
+
+ for path, ref in (("Revenue/Dashboard", "rev"), ("Growth/Dashboard", "growth")):
+ FileSystem.objects.create(
+ team=self.team, path=path, depth=2, type="insight", ref=ref, shortcut=False, created_by=self.user
+ )
+ FileSystemViewLog.objects.create(
+ team=self.team, user=self.user, type="insight", ref=ref, viewed_at=timestamp - timedelta(minutes=1)
+ )
+
+ # Search-within-Recents shares the view-log-first path: it returns only viewed items whose
+ # path matches the term.
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/file_system/",
+ {"order_by": "-last_viewed_at", "not_type": "folder", "search": "revenue"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert [item["path"] for item in response.json()["results"]] == ["Revenue/Dashboard"]
+
class TestFileSystemSearchNameOnly(APIBaseTest):
def setUp(self) -> None:
diff --git a/posthog/models/file_system/file_system_view_log.py b/posthog/models/file_system/file_system_view_log.py
index 327b30b852d9..af8c8a6687db 100644
--- a/posthog/models/file_system/file_system_view_log.py
+++ b/posthog/models/file_system/file_system_view_log.py
@@ -1,11 +1,12 @@
from __future__ import annotations
+from collections.abc import Sequence
from dataclasses import is_dataclass
from datetime import datetime
from typing import TYPE_CHECKING, Optional, cast
from django.db import IntegrityError, models
-from django.db.models import F, FilteredRelation, Q, QuerySet
+from django.db.models import Q, QuerySet
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.utils import timezone
@@ -102,37 +103,90 @@ def log_file_system_view(
FileSystemViewLog.objects.filter(**update_kwargs).update(viewed_at=now, surface=surface)
-def annotate_file_system_with_view_logs(
- *, team_id: int, user_id: int, queryset: Optional[QuerySet] = None
-) -> QuerySet[FileSystem]:
- queryset = queryset or FileSystem.objects.all()
- base_qs = queryset.filter(team_id=team_id).alias(
- matching_view_logs=FilteredRelation(
- "team__filesystemviewlog",
- condition=(
- Q(team__filesystemviewlog__user_id=user_id)
- & Q(team__filesystemviewlog__type=models.F("type"))
- & Q(team__filesystemviewlog__ref=models.F("ref"))
- ),
- )
- )
-
- return base_qs.annotate(last_viewed_at=F("matching_view_logs__viewed_at"))
+def recent_view_logs(
+ *,
+ team_id: int,
+ user_id: int,
+ surface: str = DEFAULT_SURFACE,
+ type: Optional[str] = None,
+ exclude_types: Optional[Sequence[str]] = None,
+ limit: Optional[int] = None,
+ descending: bool = True,
+) -> QuerySet[FileSystemViewLog]:
+ """A user's view-log rows for one surface, newest first by default.
+
+ Served end-to-end by the ``(team, user, -viewed_at)`` index: no join to FileSystem and no
+ sort on a computed column. This is the single query behind both Recents and the per-scene
+ "last viewed" markers. ``descending=False`` orders oldest-first; the slice then happens at the
+ query level so ``limit`` always returns the globally oldest/newest rows, never a re-sorted page.
+ """
+ queryset = FileSystemViewLog.objects.filter(surface_q(surface), team_id=team_id, user_id=user_id)
+ if type is not None:
+ queryset = queryset.filter(type=type)
+ if exclude_types:
+ queryset = queryset.exclude(type__in=list(exclude_types))
+ queryset = queryset.order_by("-viewed_at" if descending else "viewed_at")
+ if limit is not None:
+ queryset = queryset[:limit]
+ return queryset
-def get_recent_file_system_items(*, team_id: int, user_id: int, limit: Optional[int] = None) -> QuerySet[FileSystem]:
- queryset = annotate_file_system_with_view_logs(
- team_id=team_id,
- user_id=user_id,
- queryset=FileSystem.objects.filter(Q(shortcut=False) | Q(shortcut__isnull=True)),
+def get_recent_file_system_items(
+ *,
+ team_id: int,
+ user_id: int,
+ surface: str = DEFAULT_SURFACE,
+ limit: Optional[int] = None,
+ exclude_types: Optional[Sequence[str]] = ("folder",),
+ file_system_queryset: Optional[QuerySet[FileSystem]] = None,
+ descending: bool = True,
+) -> list[FileSystem]:
+ """Recently-viewed FileSystem rows for a user, newest first by default.
+
+ View-log-first: read the recent ``(type, ref)`` keys from the indexed view log, then hydrate
+ the canonical FileSystem rows for exactly those keys. This replaces a left join plus an
+ ``ORDER BY`` on a computed ``last_viewed_at`` column, which forced a full scan and sort of the
+ team's entire tree on every homepage/search load.
+
+ ``file_system_queryset`` lets callers pre-scope the hydration (e.g. apply access control)
+ before the ``(type, ref)`` keys are matched. ``descending`` is threaded down to the view-log
+ query so the ``limit`` slice picks the globally oldest/newest views, not a re-sorted page.
+ """
+ log_rows = list(
+ recent_view_logs(
+ team_id=team_id,
+ user_id=user_id,
+ surface=surface,
+ exclude_types=exclude_types,
+ limit=limit,
+ descending=descending,
+ ).values_list("type", "ref", "viewed_at")
)
+ if not log_rows:
+ return []
+
+ # The (team, user, type, ref) unique constraint guarantees one row per key, so no dedup needed.
+ key_filter = Q()
+ for row_type, row_ref, _ in log_rows:
+ key_filter |= Q(type=row_type, ref=row_ref)
+
+ base_queryset = (
+ file_system_queryset
+ if file_system_queryset is not None
+ else FileSystem.objects.filter(surface_q(surface), team_id=team_id)
+ )
+ rows_by_key: dict[tuple[str, Optional[str]], FileSystem] = {
+ (row.type, row.ref): row
+ for row in base_queryset.filter(key_filter).exclude(shortcut=True).select_related("created_by")
+ }
- queryset = queryset.order_by(models.F("last_viewed_at").desc(nulls_last=True))
-
- if limit is not None:
- queryset = queryset[:limit]
-
- return queryset
+ ordered: list[FileSystem] = []
+ for row_type, row_ref, viewed_at in log_rows:
+ row = rows_by_key.get((row_type, row_ref))
+ if row is not None:
+ row.last_viewed_at = viewed_at # type: ignore[attr-defined]
+ ordered.append(row)
+ return ordered
def resolve_representation(