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.

feat(canvas): add cursor paging to canvas state reads (#107398)

Paul D'Ambrae7bfc7319382
diff --git a/products/canvas/backend/logic/runtime.py b/products/canvas/backend/logic/runtime.py
index 73e10ac3d77f..7a1645dddb59 100644
--- a/products/canvas/backend/logic/runtime.py
+++ b/products/canvas/backend/logic/runtime.py
@@ -202,7 +202,12 @@ def read_state(
team_id: int, user_id: int, canvas_id: UUID, capabilities: dict[str, Any] | None, **query: Any
) -> dict[str, Any]:
"""The shared entries plus the viewer's own entries, filtered and paged by `query`."""
- return CanvasStateReader.entries(_readable_state(team_id, user_id, canvas_id, capabilities), **query)
+ try:
+ return CanvasStateReader.entries(_readable_state(team_id, user_id, canvas_id, capabilities), **query)
+ except ValueError as error:
+ raise CanvasRequestRejected(
+ status.HTTP_400_BAD_REQUEST, "Invalid cursor. Read again from the first page without a cursor."
+ ) from error
def read_state_value(
diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.py
index 4a28b7a966cb..87c0de21a51f 100644
--- a/products/canvas/backend/presentation/serializers.py
+++ b/products/canvas/backend/presentation/serializers.py
@@ -1268,7 +1268,19 @@ class CanvasStateQuerySerializer(serializers.Serializer):
required=False,
default=0,
min_value=0,
- help_text="Entry offset from next_offset. Keep filters unchanged between pages.",
+ help_text=(
+ "Entry offset from next_offset. Keep filters unchanged between pages. Prefer cursor: an offset can skip "
+ "or repeat entries when state changes between pages."
+ ),
+ )
+ cursor = serializers.CharField(
+ required=False,
+ max_length=2048,
+ help_text=(
+ "Cursor from next_cursor. Resumes after the last entry of the previous page, so an entry that exists "
+ "for the whole read comes back exactly once. A key written between pages can be missing. Keep filters "
+ "unchanged between pages. Takes precedence over offset."
+ ),
)
limit = serializers.IntegerField(
required=False,
@@ -1339,7 +1351,14 @@ class CanvasStateResponseSerializer(serializers.Serializer):
many=True,
help_text="The canvas's shared entries plus the caller's own user-scoped entries.",
)
- next_offset = serializers.IntegerField(allow_null=True, help_text="Next entry offset, or null when complete.")
+ next_offset = serializers.IntegerField(
+ allow_null=True,
+ help_text="Next entry offset, or null when complete. Null when the request used a cursor.",
+ )
+ next_cursor = serializers.CharField(
+ allow_null=True,
+ help_text="Cursor for the next page, or null when complete. Pass it as cursor.",
+ )
complete = serializers.BooleanField(help_text="True when no further entries remain for this selection.")
diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.py
index c164a2af6219..aaa5cdd84d52 100644
--- a/products/canvas/backend/presentation/views.py
+++ b/products/canvas/backend/presentation/views.py
@@ -1971,6 +1971,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
parameters=[CanvasStateQuerySerializer],
responses={
200: CanvasStateResponseSerializer,
+ 400: OpenApiResponse(description="Invalid query, or a malformed cursor."),
403: OpenApiResponse(description="Canvas state requires an authenticated user."),
},
)
@@ -1987,9 +1988,12 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
return _state_rejection()
query = CanvasStateQuerySerializer(data=request.query_params)
query.is_valid(raise_exception=True)
- result = canvas_api.read_state(
- self.team_id, user.id, canvas.id, canvas.head_capabilities, **query.validated_data
- )
+ try:
+ result = canvas_api.read_state(
+ self.team_id, user.id, canvas.id, canvas.head_capabilities, **query.validated_data
+ )
+ except CanvasRequestRejected as rejection:
+ return Response(rejection.body, status=rejection.status_code)
return Response(CanvasStateResponseSerializer(result).data)
@extend_schema(
diff --git a/products/canvas/backend/state_reads.py b/products/canvas/backend/state_reads.py
index 8a5578809a2b..dbb4bda7c39c 100644
--- a/products/canvas/backend/state_reads.py
+++ b/products/canvas/backend/state_reads.py
@@ -1,12 +1,39 @@
import json
+import base64
import hashlib
from typing import Any
-from django.db.models import QuerySet
+from django.db.models import Q, QuerySet
+
+from posthog.dataclasses import frozen
from products.canvas.backend.models import CanvasState
+@frozen
+class StateCursor:
+ """The scope and key of the last entry a page returned."""
+
+ scope: str
+ key: str
+
+ @classmethod
+ def decode(cls, cursor: str) -> "StateCursor":
+ """Raises ValueError for a malformed cursor."""
+ try:
+ decoded = json.loads(base64.b64decode(cursor.encode(), altchars=b"-_", validate=True))
+ except (ValueError, TypeError) as error:
+ raise ValueError("Invalid state cursor.") from error
+ if not isinstance(decoded, list) or len(decoded) != 2 or not all(isinstance(part, str) for part in decoded):
+ raise ValueError("Invalid state cursor.")
+ return cls(scope=decoded[0], key=decoded[1])
+
+ def encode(self) -> str:
+ # UTF-8 without ASCII escapes, so a cursor for any valid key stays within the query parameter limit.
+ payload = json.dumps([self.scope, self.key], separators=(",", ":"), ensure_ascii=False)
+ return base64.urlsafe_b64encode(payload.encode()).decode()
+
+
class CanvasStateReader:
@staticmethod
def entries(
@@ -18,7 +45,21 @@ class CanvasStateReader:
keys_only: bool = False,
offset: int = 0,
limit: int | None = None,
+ cursor: str | None = None,
) -> dict[str, Any]:
+ """One page of entries, ordered by scope and key.
+
+ A cursor resumes after the last entry of the previous page, so an entry
+ that exists for the whole read comes back exactly once, whatever other
+ keys change between pages. A key written between pages can be missing
+ when it sorts before the cursor. An offset counts rows, so a delete
+ between pages can make it skip an entry that existed all along. A
+ cursor takes precedence over `offset`.
+ """
+ if cursor is not None:
+ after = StateCursor.decode(cursor)
+ queryset = queryset.filter(Q(scope__gt=after.scope) | Q(scope=after.scope, key__gt=after.key))
+ offset = 0
if scope:
queryset = queryset.filter(scope=scope)
if key is not None:
@@ -32,9 +73,11 @@ class CanvasStateReader:
selected = queryset.order_by("scope", "key").values(*fields)
rows = list(selected[offset : offset + limit + 1] if limit is not None else selected[offset:])
has_more = limit is not None and len(rows) > limit
+ page = rows[:limit] if limit is not None else rows
return {
- "entries": rows[:limit] if limit is not None else rows,
- "next_offset": offset + limit if has_more and limit is not None else None,
+ "entries": page,
+ "next_offset": offset + limit if has_more and limit is not None and cursor is None else None,
+ "next_cursor": StateCursor(scope=page[-1]["scope"], key=page[-1]["key"]).encode() if has_more else None,
"complete": not has_more,
}
diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.py
index 4fb7ffbf2e4f..1451fbc7a664 100644
--- a/products/canvas/backend/tests/test_canvas_api.py
+++ b/products/canvas/backend/tests/test_canvas_api.py
@@ -1,5 +1,6 @@
import re
import json
+import base64
from datetime import timedelta
from types import SimpleNamespace
from typing import Any, cast
@@ -1836,6 +1837,40 @@ class TestCanvasState(CanvasAPIBaseTest):
selected = self.client.get(url, {"key": "policy"}).json()
assert [(entry["key"], entry["value"]) for entry in selected["entries"]] == [("policy", "a long policy")]
+ def test_state_cursor_pages_do_not_skip_entries_when_earlier_keys_change(self):
+ canvas_id = self._state_canvas()
+ for key in ("a", "b", "c"):
+ self._set_state(canvas_id, "shared", key, key)
+ url = f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/"
+
+ first = self.client.get(url, {"keys_only": "true", "limit": "2"}).json()
+ assert [entry["key"] for entry in first["entries"]] == ["a", "b"]
+ assert first["next_cursor"] is not None
+ # With offsets, deleting an already-read key shifts "c" to offset 1 and the next page skips it.
+ assert self._set_state(canvas_id, "shared", "a", None).status_code == status.HTTP_204_NO_CONTENT
+ second = self.client.get(url, {"keys_only": "true", "limit": "2", "cursor": first["next_cursor"]}).json()
+ assert [entry["key"] for entry in second["entries"]] == ["c"]
+ assert second["complete"] is True
+ assert second["next_cursor"] is None
+
+ # The decoded cursor must be the [scope, key] pair, not any two-item JSON value.
+ valid_cursor = first["next_cursor"]
+ for bad_cursor in ("not-a-cursor", base64.urlsafe_b64encode(b'"ab"').decode(), f"{valid_cursor}!!!!"):
+ assert self.client.get(url, {"cursor": bad_cursor}).status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_state_cursor_for_a_long_non_ascii_key_is_accepted(self):
+ canvas_id = self._state_canvas()
+ long_key = "\U0001f600" * 200
+ for key in (long_key, "~"):
+ assert self._set_state(canvas_id, "shared", key, 1).status_code == status.HTTP_200_OK
+ url = f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/"
+
+ first = self.client.get(url, {"keys_only": "true", "limit": "1"}).json()
+ second = self.client.get(url, {"keys_only": "true", "limit": "1", "cursor": first["next_cursor"]})
+
+ assert second.status_code == status.HTTP_200_OK, second.json()
+ assert [entry["key"] for entry in [*first["entries"], *second.json()["entries"]]] == ["~", long_key]
+
def test_state_value_chunks_detect_changes(self):
canvas_id = self._state_canvas()
value = {"text": "é\\n" * 30}
diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.ts
index ad55c3820b01..ebe1ad623b0b 100644
--- a/products/canvas/frontend/generated/api.schemas.ts
+++ b/products/canvas/frontend/generated/api.schemas.ts
@@ -1606,10 +1606,15 @@ export interface CanvasStateResponseApi {
/** The canvas's shared entries plus the caller's own user-scoped entries. */
entries: CanvasStateEntryApi[]
/**
- * Next entry offset, or null when complete.
+ * Next entry offset, or null when complete. Null when the request used a cursor.
* @nullable
*/
next_offset: number | null
+ /**
+ * Cursor for the next page, or null when complete. Pass it as cursor.
+ * @nullable
+ */
+ next_cursor: string | null
/** True when no further entries remain for this selection. */
complete: boolean
}
@@ -1947,6 +1952,12 @@ export type CanvasesSourceRetrieveParams = {
}
export type CanvasesStateRetrieveParams = {
+ /**
+ * Cursor from next_cursor. Resumes after the last entry of the previous page, so an entry that exists for the whole read comes back exactly once. A key written between pages can be missing. Keep filters unchanged between pages. Takes precedence over offset.
+ * @minLength 1
+ * @maxLength 2048
+ */
+ cursor?: string
/**
* Only read this exact key.
* @minLength 1
@@ -1969,7 +1980,7 @@ export type CanvasesStateRetrieveParams = {
*/
limit?: number
/**
- * Entry offset from next_offset. Keep filters unchanged between pages.
+ * Entry offset from next_offset. Keep filters unchanged between pages. Prefer cursor: an offset can skip or repeat entries when state changes between pages.
* @minimum 0
*/
offset?: number
diff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yaml
index 89abcfb6232c..225830ac3bba 100644
--- a/products/canvas/mcp/tools.yaml
+++ b/products/canvas/mcp/tools.yaml
@@ -411,9 +411,9 @@ tools:
own user-scoped entries, never another user's. Use this with canvas-source-retrieve when collaborative
progress, checklist selections, filters, or other runtime values live outside the source. Only scopes
declared by the live canvas version are readable. Optionally filter to `user` or `shared` with `scope`.
- Returns a key inventory by default. Keep filters unchanged and follow next_offset until complete is true.
- Set key or key_prefix and keys_only=false for small selected values. Use canvas-state-value-retrieve for
- long values. This reads persisted state directly; no composition storage tool is needed.
+ Returns a key inventory by default. Keep filters unchanged and pass next_cursor as cursor until complete is
+ true. Set key or key_prefix and keys_only=false for small selected values. Use canvas-state-value-retrieve
+ for long values. This reads persisted state directly; no composition storage tool is needed.
param_overrides:
limit:
input_schema: CanvasStateReadLimitSchema
diff --git a/products/tasks/backend/logic/services/loop_runs.py b/products/tasks/backend/logic/services/loop_runs.py
index 8238b04a3e66..ea6531304efd 100644
--- a/products/tasks/backend/logic/services/loop_runs.py
+++ b/products/tasks/backend/logic/services/loop_runs.py
@@ -168,7 +168,7 @@ def render_context_target_block(context_target: dict | None, *, loop_id: str) ->
f"`current_version_id` with `canvas-source-retrieve`, then publish the "
f"complete project with `canvas-publish-create`, passing the version you "
f"read as `expected_current_version_id`. Follow the `building-canvases` skill."
- " Read runtime state with `canvas-state-retrieve`: list keys without values, follow next_offset, "
+ " Read runtime state with `canvas-state-retrieve`: list keys without values, pass next_cursor as cursor, "
"and select only the keys needed. Read long values with `canvas-state-value-retrieve`, keeping "
"the revision fixed across chunks. Discover these tools through MCP search and info; do not assume "
"a composition storage tool is available. Missing tools, denied access, missing values, and incomplete "
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index fe84ace4dde9..cebad59992f4 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2114,7 +2114,7 @@
}
},
"canvas-state-retrieve": {
- "description": "Read persisted `ph.state` entries for a visible canvas. Returns shared entries and the authenticated user's own user-scoped entries, never another user's. Use this with canvas-source-retrieve when collaborative progress, checklist selections, filters, or other runtime values live outside the source. Only scopes declared by the live canvas version are readable. Optionally filter to `user` or `shared` with `scope`. Returns a key inventory by default. Keep filters unchanged and follow next_offset until complete is true. Set key or key_prefix and keys_only=false for small selected values. Use canvas-state-value-retrieve for long values. This reads persisted state directly; no composition storage tool is needed.",
+ "description": "Read persisted `ph.state` entries for a visible canvas. Returns shared entries and the authenticated user's own user-scoped entries, never another user's. Use this with canvas-source-retrieve when collaborative progress, checklist selections, filters, or other runtime values live outside the source. Only scopes declared by the live canvas version are readable. Optionally filter to `user` or `shared` with `scope`. Returns a key inventory by default. Keep filters unchanged and pass next_cursor as cursor until complete is true. Set key or key_prefix and keys_only=false for small selected values. Use canvas-state-value-retrieve for long values. This reads persisted state directly; no composition storage tool is needed.",
"category": "Canvas",
"feature": "canvas",
"summary": "Read canvas state",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 459a4b8f975f..9c691fa4deb7 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2129,7 +2129,7 @@
}
},
"canvas-state-retrieve": {
- "description": "Read persisted `ph.state` entries for a visible canvas. Returns shared entries and the authenticated user's own user-scoped entries, never another user's. Use this with canvas-source-retrieve when collaborative progress, checklist selections, filters, or other runtime values live outside the source. Only scopes declared by the live canvas version are readable. Optionally filter to `user` or `shared` with `scope`. Returns a key inventory by default. Keep filters unchanged and follow next_offset until complete is true. Set key or key_prefix and keys_only=false for small selected values. Use canvas-state-value-retrieve for long values. This reads persisted state directly; no composition storage tool is needed.",
+ "description": "Read persisted `ph.state` entries for a visible canvas. Returns shared entries and the authenticated user's own user-scoped entries, never another user's. Use this with canvas-source-retrieve when collaborative progress, checklist selections, filters, or other runtime values live outside the source. Only scopes declared by the live canvas version are readable. Optionally filter to `user` or `shared` with `scope`. Returns a key inventory by default. Keep filters unchanged and pass next_cursor as cursor until complete is true. Set key or key_prefix and keys_only=false for small selected values. Use canvas-state-value-retrieve for long values. This reads persisted state directly; no composition storage tool is needed.",
"category": "Canvas",
"feature": "canvas",
"summary": "Read canvas state",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 69d8476c138e..14af6f5c6c88 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21917,10 +21917,15 @@ export namespace Schemas {
/** The canvas's shared entries plus the caller's own user-scoped entries. */
entries: CanvasStateEntry[];
/**
- * Next entry offset, or null when complete.
+ * Next entry offset, or null when complete. Null when the request used a cursor.
* @nullable
*/
next_offset: number | null;
+ /**
+ * Cursor for the next page, or null when complete. Pass it as cursor.
+ * @nullable
+ */
+ next_cursor: string | null;
/** True when no further entries remain for this selection. */
complete: boolean;
}
@@ -118869,6 +118874,12 @@ export namespace Schemas {
};
export type CanvasesStateRetrieveParams = {
+ /**
+ * Cursor from next_cursor. Resumes after the last entry of the previous page, so an entry that exists for the whole read comes back exactly once. A key written between pages can be missing. Keep filters unchanged between pages. Takes precedence over offset.
+ * @minLength 1
+ * @maxLength 2048
+ */
+ cursor?: string;
/**
* Only read this exact key.
* @minLength 1
@@ -118891,7 +118902,7 @@ export namespace Schemas {
*/
limit?: number;
/**
- * Entry offset from next_offset. Keep filters unchanged between pages.
+ * Entry offset from next_offset. Keep filters unchanged between pages. Prefer cursor: an offset can skip or repeat entries when state changes between pages.
* @minimum 0
*/
offset?: number;
diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.ts
index c1b510a43893..edf3f7cba9ac 100644
--- a/services/mcp/src/generated/canvas/api.ts
+++ b/services/mcp/src/generated/canvas/api.ts
@@ -1435,6 +1435,8 @@ export const CanvasesStateRetrieveParams = () => zod.object({
),
})
+export const canvasesStateRetrieveQueryCursorMax = 2048
+
export const canvasesStateRetrieveQueryKeyMax = 200
export const canvasesStateRetrieveQueryKeyPrefixMax = 200
@@ -1446,6 +1448,14 @@ export const canvasesStateRetrieveQueryOffsetDefault = 0
export const canvasesStateRetrieveQueryOffsetMin = 0
export const CanvasesStateRetrieveQueryParams = () => zod.object({
+ cursor: zod
+ .string()
+ .min(1)
+ .max(canvasesStateRetrieveQueryCursorMax)
+ .optional()
+ .describe(
+ 'Cursor from next_cursor. Resumes after the last entry of the previous page, so an entry that exists for the whole read comes back exactly once. A key written between pages can be missing. Keep filters unchanged between pages. Takes precedence over offset.'
+ ),
key: zod.string().min(1).max(canvasesStateRetrieveQueryKeyMax).optional().describe('Only read this exact key.'),
key_prefix: zod
.string()
@@ -1468,7 +1478,9 @@ export const CanvasesStateRetrieveQueryParams = () => zod.object({
.number()
.min(canvasesStateRetrieveQueryOffsetMin)
.default(canvasesStateRetrieveQueryOffsetDefault)
- .describe('Entry offset from next_offset. Keep filters unchanged between pages.'),
+ .describe(
+ 'Entry offset from next_offset. Keep filters unchanged between pages. Prefer cursor: an offset can skip or repeat entries when state changes between pages.'
+ ),
scope: zod
.enum(['user', 'shared'])
.optional()
diff --git a/services/mcp/src/tools/generated/canvas.ts b/services/mcp/src/tools/generated/canvas.ts
index a19e5930f7b7..9b850352c4cc 100644
--- a/services/mcp/src/tools/generated/canvas.ts
+++ b/services/mcp/src/tools/generated/canvas.ts
@@ -587,6 +587,7 @@ const canvasStateRetrieve = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/canvases/${encodeURIComponent(String(params.id))}/state/`,
query: {
+ cursor: params.cursor,
key: params.key,
key_prefix: params.key_prefix,
keys_only: params.keys_only,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-state-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-state-retrieve.json
index 3998f8e33776..e187f529469b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-state-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-state-retrieve.json
@@ -1,6 +1,12 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "cursor": {
+ "description": "Cursor from next_cursor. Resumes after the last entry of the previous page, so an entry that exists for the whole read comes back exactly once. A key written between pages can be missing. Keep filters unchanged between pages. Takes precedence over offset.",
+ "maxLength": 2048,
+ "minLength": 1,
+ "type": "string"
+ },
"id": {
"description": "A UUID string identifying this canvas.",
"type": "string"
@@ -28,7 +34,7 @@
},
"offset": {
"default": 0,
- "description": "Entry offset from next_offset. Keep filters unchanged between pages.",
+ "description": "Entry offset from next_offset. Keep filters unchanged between pages. Prefer cursor: an offset can skip or repeat entries when state changes between pages.",
"minimum": 0,
"type": "number"
},