Skip to content

feat(prompts): hold a refetch cooldown after a failed prompt fetch - #968

Merged
jurajmajerik merged 3 commits into
mainfrom
prompts-refetch-cooldown
Sep 18, 2026
Merged

jurajmajerik merged 3 commits into
mainfrom
prompts-refetch-cooldown

Conversation

@jurajmajerik

Copy link
Copy Markdown
Contributor

Problem

After a failed prompt refetch the SDK serves the stale cached prompt but sets no cooldown, so once the TTL expires every prompts.get() call retries the network until one succeeds. A rate-limited client holds itself against the limit. The JavaScript SDK already has a cooldown for this; this ports it.

Changes

  • After a failed refetch, the stale entry is served for a 60 second cooldown before the next network attempt (source="stale_cache").
  • A 429's Retry-After header overrides the default, capped at one hour, carried by a new PromptFetchError raised on HTTP failures in both fetch paths.
  • Updated the public API snapshot and added a sampo changeset (minor, since PromptFetchError is new public API).

How did you test this code?

Two tests added: the cooldown lifecycle (fail, serve stale with no network call, retry after expiry; without the cooldown the middle call would hit the network) and the 429 Retry-After override. All 80 prompt tests pass locally.

@jurajmajerik
jurajmajerik requested a review from a team as a code owner September 17, 2026 15:13
@greptile-apps

greptile-apps Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Retrigger

The PR is not safe to merge until cooldown handling preserves zero-TTL refetch semantics and honors HTTP-date Retry-After values, and the explicit test requirements are satisfied.

Reviews (1) · Last reviewed commit: "feat(prompts): hold a refetch cooldown a..."

Comment thread posthog/ai/prompts.py Outdated
Comment on lines +558 to +566
if cached.retry_not_before is not None and now < cached.retry_not_before:
return PromptResult(
source="stale_cache",
prompt=cached.prompt,
name=cached.name,
version=cached.version,
label=cached.label,
config=copy.deepcopy(cached.config),
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Cooldown overrides zero TTL

A caller using cache_ttl_seconds=0 explicitly requests a refetch on every read, but this cooldown branch returns stale data without making a network request after a failure, potentially for up to an hour. Skip the cooldown when caching is disabled so the established zero-TTL behavior remains intact.

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/ai/prompts.py
Line: 558-566

Comment:
**Cooldown overrides zero TTL**

A caller using `cache_ttl_seconds=0` explicitly requests a refetch on every read, but this cooldown branch returns stale data without making a network request after a failure, potentially for up to an hour. Skip the cooldown when caching is disabled so the established zero-TTL behavior remains intact.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in e8dfbae

Comment thread posthog/ai/prompts.py Outdated
Comment on lines +166 to +169
try:
seconds = float(value.strip())
except ValueError:
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 HTTP-date cooldowns are ignored

Retry-After permits an HTTP-date, but this parser rejects that form and silently applies the 60-second default. The client can therefore retry before the server's stated deadline. Parse both delta-seconds and HTTP-date, as the repository's existing retry parser already does.

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/ai/prompts.py
Line: 166-169

Comment:
**HTTP-date cooldowns are ignored**

`Retry-After` permits an HTTP-date, but this parser rejects that form and silently applies the 60-second default. The client can therefore retry before the server's stated deadline. Parse both delta-seconds and HTTP-date, as the repository's existing retry parser already does.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in e8dfbae

Comment thread posthog/test/ai/test_prompts.py Outdated
Comment on lines +330 to +366
def test_hold_a_cooldown_after_a_failed_refetch_then_retry(
self, mock_time, mock_get_session
):
# Without the cooldown, one throttled client turns every later get()
# into another network request until one succeeds.
mock_get = mock_get_session.return_value.get
mock_get.side_effect = [
MockResponse(json_data=self.mock_prompt_response),
MockResponse(status_code=500, ok=False),
MockResponse(json_data=self.mock_prompt_response),
]
mock_time.return_value = 1000.0

prompts = Prompts(self.create_mock_posthog())
prompts.get("test-prompt", cache_ttl_seconds=300, with_metadata=False)

# Past TTL: the refetch fails, stale cache is served, cooldown starts.
mock_time.return_value = 1400.0
result = prompts.get("test-prompt", cache_ttl_seconds=300, with_metadata=True)
self.assertEqual(result.source, "stale_cache")
self.assertEqual(mock_get.call_count, 2)

# Within the 60s cooldown: stale cache again, no network attempt.
mock_time.return_value = 1430.0
result = prompts.get("test-prompt", cache_ttl_seconds=300, with_metadata=True)
self.assertEqual(result.source, "stale_cache")
self.assertEqual(mock_get.call_count, 2)

# Past the cooldown: the network is retried and the cache refreshed.
mock_time.return_value = 1470.0
result = prompts.get("test-prompt", cache_ttl_seconds=300, with_metadata=True)
self.assertEqual(result.source, "api")
self.assertEqual(mock_get.call_count, 3)

@patch("posthog.ai.prompts._get_session")
@patch("posthog.ai.prompts.time.time")
def test_hold_the_cooldown_for_the_retry_after_a_429_sends(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Cooldown tests duplicate scenarios

These adjacent tests repeat the same setup and cooldown lifecycle, varying only the response and duration. The repository directive says to prefer parameterized tests over near-duplicate test functions, so these cases must be parameterized before merging.

Context Used: Be direct and concise: state the issue, its impact, and the fix, with no preamble or praise. Do not comment on alphabetical sorting, trailing commas, or formatting. Linters catch these. Judge code by four simplicity rules: it passes all the tests, ex... (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/test/ai/test_prompts.py
Line: 330-366

Comment:
**Cooldown tests duplicate scenarios**

These adjacent tests repeat the same setup and cooldown lifecycle, varying only the response and duration. The repository directive says to prefer parameterized tests over near-duplicate test functions, so these cases must be parameterized before merging.

**Context Used:** Be direct and concise: state the issue, its impact, and the fix, with no preamble or praise. Do not comment on alphabetical sorting, trailing commas, or formatting. Linters catch these. Judge code by four simplicity rules: it passes all the tests, ex... ([source](https://app.greptile.com/review/custom-context?memory=instruction-0))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in e8dfbae

Comment thread posthog/test/ai/test_prompts.py Outdated
Comment on lines +336 to +362
mock_get.side_effect = [
MockResponse(json_data=self.mock_prompt_response),
MockResponse(status_code=500, ok=False),
MockResponse(json_data=self.mock_prompt_response),
]
mock_time.return_value = 1000.0

prompts = Prompts(self.create_mock_posthog())
prompts.get("test-prompt", cache_ttl_seconds=300, with_metadata=False)

# Past TTL: the refetch fails, stale cache is served, cooldown starts.
mock_time.return_value = 1400.0
result = prompts.get("test-prompt", cache_ttl_seconds=300, with_metadata=True)
self.assertEqual(result.source, "stale_cache")
self.assertEqual(mock_get.call_count, 2)

# Within the 60s cooldown: stale cache again, no network attempt.
mock_time.return_value = 1430.0
result = prompts.get("test-prompt", cache_ttl_seconds=300, with_metadata=True)
self.assertEqual(result.source, "stale_cache")
self.assertEqual(mock_get.call_count, 2)

# Past the cooldown: the network is retried and the cache refreshed.
mock_time.return_value = 1470.0
result = prompts.get("test-prompt", cache_ttl_seconds=300, with_metadata=True)
self.assertEqual(result.source, "api")
self.assertEqual(mock_get.call_count, 3)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Retry flow coverage is incomplete

The tests cover only one failed fetch followed by success, so they do not verify that another failure starts a new cooldown and later permits another retry. The repository requires retry logic to test the complete flow with multiple retry attempts; add a second failed retry and a subsequent cooldown and success cycle before merging.

Rule Used: When implementing retry logic, include comprehensive tests that verify the complete retry flow with multiple retry attempts, similar to existing patterns in the codebase. (source)

Learned From
PostHog/posthog#32651

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/test/ai/test_prompts.py
Line: 336-362

Comment:
**Retry flow coverage is incomplete**

The tests cover only one failed fetch followed by success, so they do not verify that another failure starts a new cooldown and later permits another retry. The repository requires retry logic to test the complete flow with multiple retry attempts; add a second failed retry and a subsequent cooldown and success cycle before merging.

**Rule Used:** When implementing retry logic, include comprehensive tests that verify the complete retry flow with multiple retry attempts, similar to existing patterns in the codebase. ([source](https://app.greptile.com/posthog-org-19734/-/custom-context?memory=24d1be3f-07fb-465d-b1a7-60dff301aed8))

**Learned From**
[PostHog/posthog#32651](https://github.com/PostHog/posthog/pull/32651)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in e8dfbae

@github-actions

github-actions Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-17 16:04:18 UTC
Duration: 256313ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 516ms
Endpoint And Method.Does Not Use Legacy Endpoints 509ms
Required Headers.Has Authorization Bearer Header 509ms
Required Headers.Has Content Type Json 509ms
Required Headers.Has Posthog Sdk Info Format 508ms
Required Headers.Has Posthog Attempt Header 509ms
Required Headers.Has Posthog Request Id 509ms
Required Headers.Has Posthog Request Timestamp 509ms
Required Headers.Has User Agent 509ms
Body Format.Body Has Created At And Batch 509ms
Body Format.No Api Key In Body 509ms
Body Format.No Sent At In Body 510ms
Event Format.Event Has Required Root Fields 509ms
Event Format.Event Uuid Is Valid 509ms
Event Format.Event Timestamp Is Rfc3339 509ms
Event Format.Distinct Id Is String 509ms
Event Format.Distinct Id At Root Not Properties 509ms
Event Format.Custom Properties Preserved 510ms
Event Format.Set Properties Preserved 508ms
Event Format.Set Once Properties Preserved 509ms
Event Format.Groups Properties Preserved 510ms
Event Format.Sdk Generates Uuid If Not Provided 509ms
Event Format.Event Has Required Root Fields Batch 512ms
Event Format.Event Uuid Is Valid Batch 511ms
Event Format.Event Timestamp Is Rfc3339 Batch 513ms
Event Format.Distinct Id Is String Batch 513ms
Event Format.Distinct Id At Root Not Properties Batch 512ms
Event Format.Custom Properties Preserved Batch 512ms
Event Format.Set Properties Preserved Batch 513ms
Event Format.Set Once Properties Preserved Batch 513ms
Event Format.Groups Properties Preserved Batch 513ms
Event Format.Sdk Generates Uuid If Not Provided Batch 512ms
Batch Behavior.Multiple Events In Single Batch 516ms
Batch Behavior.Batch Envelope Smoke 513ms
Batch Behavior.Flush With No Events Sends Nothing 506ms
Batch Behavior.Flush At Triggers Batch 1010ms
Batch Behavior.Created At Reflects Batch Creation Time 510ms
Deduplication.Generates Unique Uuids 516ms
Deduplication.Different Events Same Content Different Uuids 512ms
Deduplication.Preserves Uuid On Retry 6513ms
Deduplication.Preserves Timestamp On Retry 6520ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6522ms
Deduplication.No Duplicate Events In Batch 517ms
Header Behavior On Retry.Attempt Header Starts At One 509ms
Header Behavior On Retry.Attempt Header Increments On Retry 13526ms
Header Behavior On Retry.Request Id Preserved On Retry 6514ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3019ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6518ms
Response Format Validation.Success Response Has Uuid Keyed Results 510ms
Response Format Validation.Success Response Has Ok For Each Event 513ms
Response Format Validation.Success No Retry After When All Ok 511ms
Response Format Validation.Success Retry After Present When Retry Events 1515ms
Response Format Validation.Success No Retry After When Drop Only 511ms
Response Format Validation.Response Echoes Request Id 509ms
Retry Behavior.Retries On 408 6518ms
Retry Behavior.Retries On 500 6516ms
Retry Behavior.Retries On 503 8521ms
Retry Behavior.Retries On 504 6519ms
Retry Behavior.Retryable Errors Have Retry After 3515ms
Retry Behavior.Respects Retry After On Retryable Error 11522ms
Retry Behavior.Does Not Retry On 400 2513ms
Retry Behavior.Does Not Retry On 401 2512ms
Retry Behavior.Does Not Retry On 402 2513ms
Retry Behavior.Does Not Retry On 413 2513ms
Retry Behavior.Does Not Retry On 415 2512ms
Retry Behavior.Non Retryable Errors Have No Retry After 2511ms
Retry Behavior.Implements Backoff 22535ms
Retry Behavior.Max Retries Respected 22533ms
Partial Batch Handling.Handles 200 Full Success 2511ms
Partial Batch Handling.Handles 200 With All Ok 3517ms
Partial Batch Handling.Does Not Retry Dropped Events 3515ms
Partial Batch Handling.Does Not Retry Limited Events 3515ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6522ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6520ms
Partial Batch Handling.Retries Only Retry Events From Partial 6522ms
Partial Batch Handling.Partial Retry Preserves Uuids 6521ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6519ms
Partial Batch Handling.Partial Retry Request Id Preserved 6519ms
Partial Batch Handling.Respects Retry After On Partial 8519ms
Partial Batch Handling.Unknown Result Treated As Terminal 3516ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3519ms
Compression.Sends Gzip Content Encoding 510ms
Compression.No Content Encoding When Disabled 509ms
Compression.Compressed Body Is Decompressible 509ms
Error Handling.Does Not Retry On Unknown 4Xx 2512ms
Event Options.Cookieless Mode Override 510ms
Event Options.Disable Skew Correction Override 510ms
Event Options.Process Person Profile Override 509ms
Event Options.Product Tour Id Override 509ms
Event Options.Unset Options Omitted 509ms
Event Options.Options Override In Batch 512ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 509ms
Geoip And Historical Migration.Historical Migration Set In Body 509ms
Geoip And Historical Migration.Historical Migration Absent By Default 509ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 10ms
Request Payload.Flags Request Uses V2 Query Param 9ms
Request Payload.Flags Request Hits Flags Path Not Decide 10ms
Request Payload.Flags Request Omits Authorization Header 10ms
Request Payload.Token In Flags Body Matches Init 9ms
Request Payload.Groups Round Trip 9ms
Request Payload.Groups Default To Empty Object 9ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 8ms
Request Payload.Disable Geoip Omitted Defaults To False 9ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 9ms
Request Lifecycle.No Flags Request On Init Alone 4ms
Request Lifecycle.No Flags Request On Normal Capture 510ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 13ms
Request Lifecycle.Mock Response Value Is Returned To Caller 9ms
Retry Behavior.Retries Flags On 502 311ms
Retry Behavior.Retries Flags On 504 313ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 511ms

@marandaneto marandaneto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code looks good; no qualifying findings. Verdict: correct.

@jurajmajerik
jurajmajerik merged commit f69e670 into main Sep 18, 2026
42 checks passed
@jurajmajerik
jurajmajerik deleted the prompts-refetch-cooldown branch September 18, 2026 08:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants