: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
feat(skills): add etag and conditional requests to the skills list (#99968)
posthog[bot]4b0ff84f3946
diff --git a/docs/internal/skills/skills-list-conditional-requests.md b/docs/internal/skills/skills-list-conditional-requests.mdnew file mode 100644index 000000000000..7c62c4101d88--- /dev/null+++ b/docs/internal/skills/skills-list-conditional-requests.md@@ -0,0 +1,48 @@+# Skills list conditional requests++The skills list returns `304 Not Modified` when a client already has the current response data.+Clients can reuse the body and reduce network traffic.+Each request still validates its parameters, applies access rules, queries the list, and serializes the response.++## Endpoint++```text+GET /api/projects/{team_id}/llm_skills/+```++| Response header | Value |+| ------------------ | -------------------------------------------------------------------------------------- |+| `ETag` | Weak validator, `W/"<sha256 hex>"`. Send it as `If-None-Match` to revalidate the list. |+| `X-Skills-Version` | Marketplace version, `1.0.<epoch microseconds>`. This is a content change hint. |+| `Cache-Control` | `private, no-cache`. Store the body, but revalidate before reuse. |+| `Vary` | `Authorization, Cookie`. Caches must separate credentials. |++A matching `If-None-Match` returns `304` with no body.+A stale or absent validator returns the usual `200` response with a current ETag.+Invalid parameters still return an error, including when `If-None-Match` is `*`.+An invalid page still returns `404`.++## ETag++The ETag hashes the serialized response data, the user ID, the query string, and the deployment revision.+Access changes, owner membership changes, profile edits, category changes, and hard deletions change the ETag when they change the response.+The response also reflects any owner redaction required by the caller's credential.+The validator is weak because it identifies equivalent data across formatting and content encoding changes.++This design saves response bytes.+It does not skip the list query or serialization.+A timestamp aggregate cannot identify all changes in a response that includes access rules and user profiles.+No separate owner aggregate or access fingerprint runs for conditional requests.++## Marketplace version++`team_skills_version` in `products/skills/backend/api/skill_services.py` reads `Max(updated_at)` across the team's skill rows, including archived rows.+The version preserves microseconds with integer arithmetic.+The list and marketplace read this version without a time-based cache.+The marketplace still caches the synthesized repository by team and version.++A publish, file edit, or archive updates a skill timestamp.+In-place category writers must update `updated_at` explicitly.+Owner and profile changes do not change this version.+A hard deletion can leave the maximum timestamp unchanged or move it backward.+Clients must use the ETag to validate the list; `X-Skills-Version` is not a complete list validator.diff --git a/products/review_hog/backend/reviewer/lazy_seed.py b/products/review_hog/backend/reviewer/lazy_seed.pyindex afbac4861cef..9e1728265924 100644--- a/products/review_hog/backend/reviewer/lazy_seed.py+++ b/products/review_hog/backend/reviewer/lazy_seed.py@@ -440,7 +440,8 @@ def _sync_canonicals(# The sync owns the category tag; re-stamp a seeded row whose category drifted (e.g. after# the canonical category was changed). In-place — it's our metadata, not user content, so# no version bump. Idempotent: only writes on actual drift.- LLMSkill.objects.filter(pk=live.pk).update(category=category)+ # QuerySet.update() skips auto_now, but the shared marketplace version uses updated_at.+ LLMSkill.objects.filter(pk=live.pk).update(category=category, updated_at=timezone.now())live_files = list(live.files.all())live_hash = _compute_row_hash(live, live_files)diff --git a/products/review_hog/backend/tests/test_perspectives.py b/products/review_hog/backend/tests/test_perspectives.pyindex afdb34bcda0f..69d79a912cb5 100644--- a/products/review_hog/backend/tests/test_perspectives.py+++ b/products/review_hog/backend/tests/test_perspectives.py@@ -92,10 +92,13 @@ class TestSyncCanonicalPerspectives(BaseTest):# category was renamed) must be re-stamped, or it strands under no Skills-UI tab.sync_canonical_perspectives(self.team)LLMSkill.objects.filter(team=self.team, name=_LOGIC).update(category="stale_category")+ stamped_before = LLMSkill.objects.get(team=self.team, name=_LOGIC, is_latest=True).updated_atsync_canonical_perspectives(self.team)- assert LLMSkill.objects.get(team=self.team, name=_LOGIC, is_latest=True).category == REVIEW_HOG_SKILL_CATEGORY+ restamped = LLMSkill.objects.get(team=self.team, name=_LOGIC, is_latest=True)+ assert restamped.category == REVIEW_HOG_SKILL_CATEGORY+ assert restamped.updated_at > stamped_beforedef test_leaves_team_edited_row_alone(self) -> None:sync_canonical_perspectives(self.team)diff --git a/products/signals/backend/scout_harness/config_registry.py b/products/signals/backend/scout_harness/config_registry.pyindex b11c3d93b67e..4294b4d240ce 100644--- a/products/signals/backend/scout_harness/config_registry.py+++ b/products/signals/backend/scout_harness/config_registry.py@@ -15,6 +15,8 @@ from __future__ import annotationsfrom datetime import UTC, datetime+from django.utils import timezone+import structlogfrom croniter import CroniterError, croniter@@ -90,7 +92,8 @@ def ensure_scout_category(team_id: int, skill_name: str | None = None) -> None:rows = rows.filter(name=skill_name)else:rows = rows.filter(name__in=SignalScoutConfig.objects.for_team(team_id).values_list("skill_name", flat=True))- rows.update(category=SCOUT_SKILL_CATEGORY)+ # QuerySet.update() skips auto_now, but the shared marketplace version uses updated_at.+ rows.update(category=SCOUT_SKILL_CATEGORY, updated_at=timezone.now())def enabled_scout_count(team_id: int, *, exclude_skill: str | None = None) -> int:diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pyindex ba617207bda3..db4cfe569a2c 100644--- a/products/signals/backend/test/test_scout_coordinator.py+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -559,12 +559,14 @@ def test_register_missing_configs_stamps_scout_category():scout = _create_skill(team, "signals-scout-custom")helper = _create_skill(team, "custom-helper")assert scout.category == ""+ stamped_before = scout.updated_atregister_missing_configs(team.id)scout.refresh_from_db()helper.refresh_from_db()assert scout.category == "scout"+ assert scout.updated_at > stamped_before# Non-scout skills are left untouched.assert helper.category == ""diff --git a/products/skills/backend/api/skill_services.py b/products/skills/backend/api/skill_services.pyindex f6db9afe7c5e..b3e1c1bd3542 100644--- a/products/skills/backend/api/skill_services.py+++ b/products/skills/backend/api/skill_services.py@@ -1,15 +1,16 @@import refrom dataclasses import dataclass+from datetime import UTC, datetimefrom typing import Any, TypeVarfrom django.db import IntegrityError, transaction-from django.db.models import QuerySet+from django.db.models import Max, QuerySetfrom django.utils import timezonefrom posthog.dataclasses import frozenfrom posthog.models import Team, User-from ..marketplace.packaging import CODEX_METADATA_PATH, SPEC_DESCRIPTION_MAX_LENGTH+from ..marketplace.packaging import CODEX_METADATA_PATH, SPEC_DESCRIPTION_MAX_LENGTH, compute_plugin_versionfrom ..models.skills import (CATEGORY_BY_NAME_PREFIX,LLMSkill,@@ -340,6 +341,20 @@ def get_latest_skills_queryset(team: Team) -> QuerySet[LLMSkill]:return get_active_skill_queryset(team).filter(is_latest=True)+def team_skills_version(team: Team) -> str:+ """Keep archived rows in the version so an archive does not expose an older timestamp.++ This is a marketplace version, not a validator for the access-filtered list.+ In-place writers must update updated_at because QuerySet.update() skips auto_now.+ """+ latest = LLMSkill.objects.filter(team=team).aggregate(latest=Max("updated_at"))["latest"]+ if latest is None:+ return "1.0.0"+ elapsed = latest - datetime(1970, 1, 1, tzinfo=UTC)+ epoch_microseconds = (elapsed.days * 86400 + elapsed.seconds) * 1_000_000 + elapsed.microseconds+ return compute_plugin_version(epoch_microseconds)++def get_skill_by_name_from_db(team: Team,skill_name: str,diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.pyindex 821f211c7344..a9d3c4ed4f7b 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -1,10 +1,13 @@+import hashlibfrom collections.abc import Sequencefrom typing import Any, cast+from urllib.parse import urlencodefrom uuid import UUIDfrom django.db import IntegrityError, OperationalError, transactionfrom django.db.models import Case, Exists, IntegerField, OuterRef, Q, QuerySet, Value, When-from django.http import HttpResponse+from django.http import HttpResponse, HttpResponseBase+from django.utils.cache import get_conditional_response, patch_cache_control, patch_vary_headersimport psycopgimport structlog@@ -30,7 +33,9 @@ from posthog.auth import (PersonalAPIKeyAuthentication,SessionAuthentication,)+from posthog.dataclasses import frozenfrom posthog.event_usage import report_user_action+from posthog.git import get_git_commit_shortfrom posthog.models import Userfrom posthog.models.utils import execute_with_timeoutfrom posthog.permissions import AccessControlPermission, get_authenticator_scopes, posthog_feature_flag_value@@ -139,8 +144,16 @@ from .skill_services import (set_skill_owners,skill_name_is_well_formed,skill_names_owned_by,+ team_skills_version,)++@frozen+class SkillsListValidators:+ version: str+ etag: str++logger = structlog.get_logger(__name__)# Generous ceiling for an uploaded skill zip — per-skill content (body, 200 files × 1 MB) is@@ -363,6 +376,16 @@ class SkillSearchSustainedThrottle(_SkillUserThrottle):rate = SustainedRateThrottle.rate+class SkillListBurstThrottle(_SkillUserThrottle):+ scope = "skills_list_burst"+ rate = BurstRateThrottle.rate+++class SkillListSustainedThrottle(_SkillUserThrottle):+ scope = "skills_list_sustained"+ rate = SustainedRateThrottle.rate++class ZipRenderer(BaseRenderer):"""Lets ``Accept: application/zip`` through content negotiation on the zip actions.@@ -435,6 +458,8 @@ class LLMSkillViewSet(return [SkillBundleBurstThrottle(), SkillBundleSustainedThrottle()]if self.action == "search":return [SkillSearchBurstThrottle(), SkillSearchSustainedThrottle()]+ if self.action == "list":+ return [SkillListBurstThrottle(), SkillListSustainedThrottle()]if self.action in ["update_by_name", "get_by_name", "resolve_by_name"]:return [BurstRateThrottle(), SustainedRateThrottle()]return super().get_throttles()@@ -1884,10 +1909,30 @@ class LLMSkillViewSet()return Response(self._serialize_skill(published_skill))- @extend_schema(parameters=[LLMSkillListQuerySerializer])+ @extend_schema(+ parameters=[LLMSkillListQuerySerializer],+ responses={+ 200: LLMSkillListSerializer,+ 304: OpenApiResponse(+ description="Not modified. The client sent an If-None-Match that matches the current list."+ ),+ },+ )@llma_track_latency("llma_skills_list")@monitor(feature=None, endpoint="llma_skills_list", method="GET")- def list(self, request: Request, *args, **kwargs) -> Response:+ def list(self, request: Request, *args, **kwargs) -> HttpResponseBase:+ version = team_skills_version(self.team)+ list_response = self._list_response(request)+ validators = self._list_validators(request, list_response, version)+ # Validate and apply access rules before a conditional response can reuse a cached body.+ response = get_conditional_response(request._request, etag=validators.etag) or list_response+ response["ETag"] = validators.etag+ response["X-Skills-Version"] = validators.version+ patch_cache_control(response, private=True, no_cache=True)+ patch_vary_headers(response, ["Authorization", "Cookie"])+ return response++ def _list_response(self, request: Request) -> Response:queryset = self.filter_queryset(self._get_list_queryset(request))page = self.paginate_queryset(queryset)if page is not None:@@ -1901,6 +1946,22 @@ class LLMSkillViewSet(data = serializer.datareturn Response({"count": len(data), "results": data})+ def _list_validators(self, request: Request, response: Response, version: str) -> SkillsListValidators:+ seed = urlencode(+ [+ ("rev", get_git_commit_short() or ""),+ ("user", request.user.pk),+ *sorted(request.query_params.lists()),+ ],+ doseq=True,+ )+ body = SafeJSONRenderer().render(response.data)+ # A weak ETag identifies the data across renderer formatting and content encodings.+ return SkillsListValidators(+ version=version,+ etag='W/"' + hashlib.sha256(seed.encode() + b"\0" + body).hexdigest() + '"',+ )+# `Sequence`, not `list[...]`: the viewset defines a `list` method that shadows the builtin in the# class body where this annotation is evaluated.def _list_context_with_owners(self, skills: Sequence[LLMSkill]) -> dict[str, Any]:diff --git a/products/skills/backend/api/test/test_marketplace_endpoints.py b/products/skills/backend/api/test/test_marketplace_endpoints.pyindex a67a2c1e6e08..c86f318b9eee 100644--- a/products/skills/backend/api/test/test_marketplace_endpoints.py+++ b/products/skills/backend/api/test/test_marketplace_endpoints.py@@ -27,6 +27,7 @@ from posthog.models.utils import hash_key_valuefrom products.access_control.backend.models.access_control import AccessControl+from ...api import skill_servicesfrom ...api.skill_serializers import validate_skill_file_pathfrom ...api.skill_services import archive_skill, set_skill_ownersfrom ...marketplace import adapters@@ -748,17 +749,24 @@ class TestMarketplaceVersion(APIBaseTest):version = json.loads(tree[".claude-plugin/marketplace.json"])["plugins"][0]["version"]return int(version.rsplit(".", 1)[1])- def test_plugin_version_query_is_cached_across_requests(self):- # The Max(updated_at) query should run once per window, not on every synthesis — a clone is- # two requests (info/refs + upload-pack) plus repeated auto-update polls.- LLMSkill.objects.create(+ def test_marketplace_observes_the_version_advertised_by_the_list(self):+ skill = LLMSkill.objects.create(team=self.team, name="s", description="d", body="x", version=1, is_latest=True, created_by=self.user)+ now = timezone.now().replace(microsecond=100)+ LLMSkill.objects.filter(pk=skill.pk).update(updated_at=now)cache.clear()- with patch.object(adapters, "_team_plugin_version", wraps=adapters._team_plugin_version) as spy:- adapters.synthesize_team_marketplace_repo(self.team)- adapters.synthesize_team_marketplace_repo(self.team)- assert spy.call_count == 1+ before = adapters.synthesize_team_marketplace_repo(self.team)+ version_before = skill_services.team_skills_version(self.team)++ LLMSkill.objects.filter(pk=skill.pk).update(body="new body", updated_at=now + timedelta(microseconds=1))+ response = self.client.get(f"/api/projects/{self.team.id}/llm_skills/")+ assert response.status_code == status.HTTP_200_OK+ version = response["X-Skills-Version"]+ assert version != version_before+ after = adapters.synthesize_team_marketplace_repo(self.team)+ assert after.head_sha != before.head_sha+ assert version.encode() in b"".join(obj.data for obj in after.objects)def test_archiving_newest_skill_does_not_regress_version(self):now = timezone.now().replace(microsecond=0)diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex 92e406b077d0..2043d5688f44 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -40,6 +40,7 @@ from ...api.skill_services import (backfill_skill_digests,compute_spec_problems,create_skill,+ create_skill_file,publish_skill_version,resolve_skill_owners,set_skill_owners,@@ -394,14 +395,15 @@ class TestLLMSkillAPI(APIBaseTest):@parameterized.expand([- ("non_numeric", "abc"),- ("float", "1.5"),+ ("non_numeric", "abc", ""),+ ("float", "1.5", ""),+ ("conditional", "abc", "*"),])- def test_list_skills_invalid_created_by_id_returns_400(self, _label, value):+ def test_list_skills_invalid_created_by_id_returns_400(self, _label, value, etag):self.create_skill(name="some-skill")- response = self.client.get(self._url() + f"?created_by_id={value}")+ response = self.client.get(self._url() + f"?created_by_id={value}", HTTP_IF_NONE_MATCH=etag)assert response.status_code == status.HTTP_400_BAD_REQUEST@@ -424,6 +426,129 @@ class TestLLMSkillAPI(APIBaseTest):assert response.json()["count"] == len(expected_names)assert sorted(r["name"] for r in response.json()["results"]) == sorted(expected_names)+ @parameterized.expand([("weak",), ("strong",), ("wildcard",)])+ def test_list_answers_304_when_nothing_changed(self, validator: str) -> None:+ self.create_skill(name="skill-a", description="Does A things.")+ first = self.client.get(self._url())+ assert first.status_code == status.HTTP_200_OK+ assert first["ETag"]+ assert first["Cache-Control"] == "private, no-cache"++ etag = first["ETag"]+ if validator == "strong":+ etag = etag.removeprefix("W/")+ elif validator == "wildcard":+ etag = "*"+ second = self.client.get(self._url(), HTTP_IF_NONE_MATCH=etag)++ assert second.status_code == status.HTTP_304_NOT_MODIFIED+ assert second["ETag"] == first["ETag"]+ assert second["X-Skills-Version"] == first["X-Skills-Version"]+ assert not second.content++ @parameterized.expand(+ [+ (+ "publish",+ lambda self: publish_skill_version(+ self.team, user=self.user, skill_name="skill-a", description="Does B things.", base_version=1+ ),+ ),+ (+ "file_edit",+ lambda self: create_skill_file(+ self.team, user=self.user, skill_name="skill-a", path="notes.md", content="x"+ ),+ ),+ ("archive", lambda self: archive_skill(self.team, "skill-a")),+ # Owners are keyed on the skill name, so an owner-only change touches no skill row. The+ # skills version alone cannot see it, and the list serializes owners.+ (+ "owner_change",+ lambda self: set_skill_owners(self.team, "skill-a", [self._create_user("[email protected]")]),+ ),+ ("category", lambda self: LLMSkill.objects.filter(team=self.team, name="skill-a").update(category="scout")),+ ("hard_delete", lambda self: LLMSkill.objects.filter(team=self.team, name="skill-a").delete()),+ ("creator_profile", lambda self: User.objects.filter(pk=self.user.pk).update(first_name="Updated")),+ (+ "owner_profile",+ lambda self: User.objects.filter(email="[email protected]").update(first_name="Updated"),+ ),+ (+ "owner_access",+ lambda self: OrganizationMembership.objects.filter(+ organization=self.organization, user__email="[email protected]"+ ).delete(),+ ),+ ]+ )+ def test_list_etag_changes_after_a_store_change(self, _label, change):+ self.create_skill(name="skill-a", description="Does A things.")+ set_skill_owners(self.team, "skill-a", [])+ self.create_skill(name="skill-b", description="Does B things.")+ set_skill_owners(self.team, "skill-b", [self._create_user("[email protected]")])+ first = self.client.get(self._url())++ change(self)+ response = self.client.get(self._url(), HTTP_IF_NONE_MATCH=first["ETag"])++ assert response.status_code == status.HTTP_200_OK+ assert response["ETag"] != first["ETag"]+ assert response.json() != first.json()++ def test_list_etag_does_not_carry_across_a_deploy(self):+ # Every other seed input is a store row, so without the revision a release that serializes+ # the list differently would answer 304 with the previous shape until the next store write.+ self.create_skill(name="skill-a", description="Does A things.")+ with patch("products.skills.backend.api.skills.get_git_commit_short", return_value="1111111111"):+ etag = self.client.get(self._url())["ETag"]++ with patch("products.skills.backend.api.skills.get_git_commit_short", return_value="2222222222"):+ response = self.client.get(self._url(), HTTP_IF_NONE_MATCH=etag)++ assert response.status_code == status.HTTP_200_OK+ assert response["ETag"] != etag++ def test_list_etag_does_not_carry_between_filtered_pages(self):+ self.create_skill(name="pdf-processing", description="Handles PDFs.")+ self.create_skill(name="code-review", description="Reviews code.")+ etag = self.client.get(self._url())["ETag"]++ response = self.client.get(self._url() + "?search=pdf", HTTP_IF_NONE_MATCH=etag)++ assert response.status_code == status.HTTP_200_OK+ assert [r["name"] for r in response.json()["results"]] == ["pdf-processing"]++ def test_list_etag_does_not_carry_between_users(self):+ # Access filtering is per user, so one member's validator must never match another's list.+ other = self._create_user("[email protected]")+ self.create_skill(name="skill-a", description="Does A things.")+ etag = self.client.get(self._url())["ETag"]++ self.client.force_login(other)+ response = self.client.get(self._url(), HTTP_IF_NONE_MATCH=etag)++ assert response.status_code == status.HTTP_200_OK+ assert [r["name"] for r in response.json()["results"]] == ["skill-a"]++ @parameterized.expand([("burst", "Burst"), ("sustained", "Sustained")])+ def test_list_skills_throttles_a_session_caller(self, _label: str, window: str) -> None:+ # The default burst/sustained classes count personal-API-key traffic only, so without its+ # own throttles the list action lets a session or OAuth client poll it with no ceiling.+ self.create_skill(name="throttle-list-skill")+ period = "minute" if window == "Burst" else "hour"+ with (+ patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True),+ patch("posthog.rate_limit.team_is_allowed_to_bypass_throttle", return_value=False),+ patch(f"products.skills.backend.api.skills.SkillList{window}Throttle.rate", new=f"1/{period}"),+ patch("rest_framework.throttling.SimpleRateThrottle.timer", return_value=1000),+ ):+ assert self.client.get(self._url()).status_code == status.HTTP_200_OK+ blocked = self.client.get(self._url())++ assert blocked.status_code == status.HTTP_429_TOO_MANY_REQUESTS, blocked.content+ assert int(blocked["Retry-After"]) > 0+# --- Search ---def test_search_skills_orders_fields_by_relevance_and_skips_non_markdown_file_contents(self):@@ -2273,6 +2398,18 @@ class TestSkillAccessControlRBAC(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json()["count"] == 1assert [skill["name"] for skill in response.json()["results"]] == [self.skill.name]+ for access, expected_count in [("viewer", 2), ("none", 1)]:+ AccessControl.objects.filter(+ team=self.team,+ resource="llm_skill",+ resource_id=str(restricted.id),+ organization_member=membership,+ ).update(access_level=access)+ response = self.client.get(+ self._url(), {"limit": "1", "order_by": "name"}, HTTP_IF_NONE_MATCH=response["ETag"]+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["count"] == expected_countreturnallowed_status = status.HTTP_302_FOUND if endpoint == "id" else status.HTTP_200_OK@@ -2479,9 +2616,11 @@ class TestLLMSkillOwners(APIBaseTest):create_skill(self.team, user=self.user, name="orphaned", description="d", body="# b")set_skill_owners(self.team, "orphaned", [member])+ url = self._url() + f"?owner_id={member.id}"+ etag = self.client.get(url)["ETag"]member.organization_memberships.filter(organization=self.organization).delete()- response = self.client.get(self._url() + f"?owner_id={member.id}")+ response = self.client.get(url, HTTP_IF_NONE_MATCH=etag)assert response.status_code == status.HTTP_200_OK, response.json()assert response.json()["results"] == []diff --git a/products/skills/backend/marketplace/README.md b/products/skills/backend/marketplace/README.mdindex e5f0779f91fd..0cc1cbc55631 100644--- a/products/skills/backend/marketplace/README.md+++ b/products/skills/backend/marketplace/README.md@@ -105,11 +105,13 @@ an update). The minted token lives in the user's OS keychain / git credential st## Versioning / auto-update-Claude Code re-pulls when the `version` in `marketplace.json` / `plugin.json` changes. We-derive it from team content (`compute_plugin_version` keyed on the latest skill change time, in-milliseconds) so any publish/archive bumps it forward monotonically with zero manual semver.-The synthesized repo is cached on `team_id` + that version, so repeated clones and auto-update-polls reuse one synthesis and the cache invalidates automatically on any change.+Claude Code re-pulls when the `version` in `marketplace.json` / `plugin.json` changes.+`compute_plugin_version` uses the latest skill change time in microseconds.+Publishes and archives update this timestamp.+The synthesized repository cache uses the team ID and version, so repeated clones reuse the same repository.+Each request reads the version without a time-based cache so a pull sees a change reported by the skills list.+The shared version function is `api/skill_services.py:team_skills_version`.+See [skills list conditional requests](../../../../docs/internal/skills/skills-list-conditional-requests.md) for the version's limits and the list ETag.> **Open question (the spike answers it):** whether Claude Code re-pulls on any version> _difference_ or only strictly-greater, and whether background auto-update reliably re-authsdiff --git a/products/skills/backend/marketplace/adapters.py b/products/skills/backend/marketplace/adapters.pyindex ac597df2797f..de249f193718 100644--- a/products/skills/backend/marketplace/adapters.py+++ b/products/skills/backend/marketplace/adapters.py@@ -8,7 +8,7 @@ from collections.abc import Iteratorfrom typing import Any, Literal, TypeVarfrom django.core.cache import cache-from django.db.models import F, Func, IntegerField, Max, Q, QuerySet, TextField+from django.db.models import F, Func, IntegerField, Q, QuerySet, TextFieldfrom django.db.models.functions import Castimport structlog@@ -16,7 +16,7 @@ import structlogfrom posthog.dataclasses import frozenfrom posthog.models import Team, User-from ..api.skill_services import compute_spec_problems, skill_names_owned_by+from ..api.skill_services import compute_spec_problems, skill_names_owned_by, team_skills_versionfrom ..models.skills import LLMSkill, LLMSkillFilefrom .git_smart_http import FileTree, SynthesizedRepo, synthesize_repofrom .packaging import (@@ -29,7 +29,6 @@ from .packaging import (build_skill_stub_tree,build_skill_tree,build_skills_bundle_zip,- compute_plugin_version,file_tree_bytes,)@@ -45,12 +44,6 @@ _MARKETPLACE_COMMIT_MESSAGE = "PostHog skills marketplace"# The cache key already embeds the content-derived plugin version, so a hit is only ever# the current content. The TTL just bounds memory for superseded versions._MARKETPLACE_REPO_CACHE_TTL_SECONDS = 300-# The plugin version is Max(updated_at) over a team's skill rows — cheap, but it runs on every-# info/refs, every upload-pack, and every auto-update poll. Briefly cache it so a clone + a burst of-# polls collapse to one query per window instead of one per request. Auto-update detection lags by-# at most this TTL (content is never stale — only the version label that triggers a re-pull).-_MARKETPLACE_VERSION_CACHE_TTL_SECONDS = 15-# Bound the in-memory/cached footprint of a team's marketplace so an outlier team with very many# (or very large) skills can't OOM the web worker on clone. Past this cumulative content size we# skip the remaining skills (logged) rather than synthesize an unbounded tree.@@ -93,10 +86,10 @@ def synthesize_team_marketplace_repo(team: Team) -> SynthesizedRepo:A normal ``git clone`` hits ``info/refs`` then ``git-upload-pack``, and auto-update pollsrepeatedly — synthesizing the whole repo (loading every skill + file, hashing every blob)- each time would be wasteful. The cache key embeds ``_team_plugin_version`` (which changes+ each time would be wasteful. The cache key embeds ``team_skills_version`` (which changesexactly when content changes), so a hit is always current and any change invalidates it."""- version = _team_plugin_version_cached(team)+ version = team_skills_version(team)cache_key = f"skills_marketplace_repo:{team.id}:{version}"cached = cache.get(cache_key)if cached is not None:@@ -112,7 +105,7 @@ def synthesize_team_marketplace_repo(team: Team) -> SynthesizedRepo:def build_team_marketplace_tree(team: Team, version: str | None = None) -> FileTree:"""Synthesize the full plugin-marketplace file tree for a team's latest skills."""if version is None:- version = _team_plugin_version(team)+ version = team_skills_version(team)# Lean query: the marketplace only needs the latest live skills, not the version-history# annotations / created_by join that get_latest_skills_queryset adds.@@ -179,27 +172,6 @@ def _files_by_skill_id(skills: list[LLMSkill]) -> dict[Any, list[LLMSkillFile]]:return grouped-def _team_plugin_version_cached(team: Team) -> str:- """``_team_plugin_version`` behind a short TTL so the Max() query runs ~once per window per team- instead of on every clone / upload-pack / auto-update poll."""- cache_key = f"skills_marketplace_version:{team.id}"- version = cache.get(cache_key)- if version is None:- version = _team_plugin_version(team)- cache.set(cache_key, version, timeout=_MARKETPLACE_VERSION_CACHE_TTL_SECONDS)- return version---def _team_plugin_version(team: Team) -> str:- # Max over ALL of the team's skill rows, including archived ones. Publishes add a row with a- # fresh updated_at and archive_skill bumps updated_at on the rows it soft-deletes, so this is- # monotonic and reflects archives. Deriving it from only live skills would regress the version- # when the most-recently-updated skill is archived. Milliseconds (not seconds) so two edits- # within the same second still produce distinct versions and clients don't miss an update.- latest = LLMSkill.objects.filter(team=team).aggregate(latest=Max("updated_at"))["latest"]- return compute_plugin_version(int(latest.timestamp() * 1000)) if latest is not None else "1.0.0"--@frozenclass SkillBundle:zip_bytes: bytesdiff --git a/products/skills/backend/marketplace/packaging.py b/products/skills/backend/marketplace/packaging.pyindex 8dbdd333ae9c..ee79fb9a2a6f 100644--- a/products/skills/backend/marketplace/packaging.py+++ b/products/skills/backend/marketplace/packaging.py@@ -369,17 +369,9 @@ def _read_zip_text(archive: zipfile.ZipFile, member: str, label: str) -> str:raise SkillImportError(f"'{label}' must be UTF-8 text; binary files are not supported.")-def compute_plugin_version(latest_change_epoch_millis: int) -> str:- """Content-derived, monotonic plugin version so auto-update fires on any change.-- Keyed off the most recent change time (in epoch milliseconds) across all of a team's skill- rows (see ``adapters._team_plugin_version``): publishes and file edits add/refresh a row's- ``updated_at``, and archive bumps it too, so this advances on every change and never- regresses. Millisecond resolution keeps two edits within the same second distinct. Whether- Claude Code re-pulls on any version *difference* vs. strictly-greater is the open question- the auto-update spike answers — this scheme is safe for either.- """- return f"1.0.{latest_change_epoch_millis}"+def compute_plugin_version(latest_change_epoch_microseconds: int) -> str:+ """Use full timestamp precision so updates within one millisecond have distinct versions."""+ return f"1.0.{latest_change_epoch_microseconds}"def build_marketplace_tree(