Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

docs(scheduling): document the claim lease, retries and real timing

spacesdrive62298fcd48a5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7d658a3..35241aa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,17 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Fixed
- The docs home at `/docs` shows the Introduction page again; before, it showed the docs frame with an empty page
+- A scheduled post no longer stays in Publishing for ever when a publishing run stops halfway; the next run takes it over 20 minutes later (#63)
+- A scheduled post that reached Instagram is no longer marked failed when Instagram's reply is lost; the scheduler saves the Instagram container and checks it before deciding or publishing again, so the post is not published twice (#64)
+- A passing problem, such as a timeout or a temporary Instagram error, no longer fails a scheduled post at once; it goes back to Pending and is tried on the next two runs, and the row shows "Trying again on the next run" (#64)
+- The app and docs no longer promise that the GitHub backup publishes within 15 minutes; GitHub often starts these runs hours late, and the server's own scheduler is the one that publishes within 15 minutes (#65)
+- Deleting or editing a scheduled post at the moment a scheduler claims it can no longer remove or change a post that is being published (#66)
+- The overdue alert in Publish also counts posts stuck in Publishing for more than 50 minutes, and counts a retried post from its last attempt (#63)
+
+### Changed
+
+- `scheduled_posts` has two new columns, `claimed_at` and `attempts`, and the two indexes the schema always listed; existing instances run the upgrade SQL in the Supabase SQL editor before deploying (ADR-037)
+- The GitHub Actions scheduler runs at minutes 7, 22, 37 and 52, one run at a time, with a 14 minute limit; a private copy uses `7,37 * * * *` (#65)
---
diff --git a/DECISIONS.md b/DECISIONS.md
index b5d68a3..f2b3dbc 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -768,3 +768,28 @@ Records every significant architectural decision, the alternatives considered, a
- Google's button is drawn by the app with Google's real button over it at near-zero opacity. Clicks, keyboard focus and the sign-in stay Google's, but the visible label must follow Google's text options (`googleButtonLabel()`), and the button still only works on origins listed in the OAuth client.
- Self-hosters without the Send Email hook get Supabase's own Magic Link email, which holds a link rather than a code unless they add `{{ .Token }}` to its template, and is limited to a few emails an hour.
- With signups turned off in Supabase, the code is refused for unknown addresses, which keeps private instances private without a separate setting.
+
+---
+
+## ADR-037: Leases, bounded retries and a container check for scheduled publishing
+
+**Date:** 2026-10-15
+**Status:** Accepted
+
+**Decision:** A scheduler's claim on a post is a lease. One conditional UPDATE sets `status = 'publishing'`, `claimed_at = now()` and `attempts = attempts + 1`, and only matches the post as the run listed it (still `pending`, or `publishing` with the same expired `claimed_at`) with the same `attempts`. Each run lists due `pending` posts and `publishing` posts whose claim is older than 20 minutes, and takes the stale ones over. 20 minutes is above the Worker cron's 14 minute deadline and the GitHub job's new 14 minute `timeout-minutes` (the script also stops Instagram calls at 12 minutes), so a live run is never taken over; this follows pg-boss `expireInSeconds` and Graphile Worker's `locked_at`. The Instagram container id is saved in `data.containerId` right after the container is created. A run that holds a post with a saved container, and every failure after the container exists, first reads the container's `status_code` from the Graph API: `PUBLISHED` marks the post published, `FINISHED` publishes the same container, `IN_PROGRESS` waits, `EXPIRED` creates a new one and `ERROR` fails the post. An unreadable status leaves the post `publishing` for a run after the lease. This follows Postiz, which resolves in-flight posts before publishing them again, and Meta's documented container status `PUBLISHED`. Temporary failures (timeouts, unreachable Instagram, database errors, Graph codes -1, 1, 2, 4, 17, 341 and 9007, a container still processing or expired) go back to `pending` with the reason in `error`, up to 3 attempts, as pg-boss `retryLimit` and BullMQ `maxStalledCount` bound retries and stalls; definite failures fail at once. A post taken over after its third attempt is only checked on Instagram, never started again. Delete only removes a post that is not `publishing`, and edits only apply while it is `pending`, each checked in the same statement as the write. The rules live in `backend/lib/scheduledPublishing.ts`, which imports nothing at runtime, so `scripts/publish-scheduled.ts` imports it by relative path and stays free of npm packages. The GitHub workflow runs at minutes 7, 22, 37 and 52, one run at a time.
+
+**Context:** The atomic claim from `pending` to `publishing` (ADR-007, ADR-025) stopped two schedulers publishing the same post, but left four gaps (#62). A run that died after claiming left the post in `publishing` for ever, with nothing to take it over (#63). A publish whose reply was lost (a timeout after Instagram had published) marked a post `failed` although it was on Instagram, and nothing could tell, because the container id was not kept (#64). The GitHub fallback asked for a run every 15 minutes, but GitHub's documentation says scheduled runs are delayed under load, most of all at the start of every hour, and can be dropped; this repository's runs came every 3 to 5 hours over two days, and the app promised 15 minutes (#65). Delete and edit checked the status, then wrote in a second statement, so a claim in between could delete or change a post that was being published (#66).
+
+**Alternatives considered:**
+- A job queue (pg-boss, Graphile Worker, BullMQ) instead of the table. Each brings these patterns, but needs a long-running worker process or a dependency the Worker and the dependency-free script cannot carry.
+- Retrying a stuck post without checking Instagram first. Simpler, but a post whose publish succeeded and whose reply was lost would be published twice.
+- Marking every stuck post `failed` after the lease. It never double-publishes, but it reports published posts as failed and leaves passing problems to the user.
+- A second copy of the rules inside the script. It keeps the script self-contained, but the two schedulers would drift.
+
+**Trade-offs:**
+- The database gains `claimed_at` and `attempts` and the two `scheduled_posts` indexes, created with SQL the owner runs in the Supabase SQL editor before the code is deployed. Posts stuck in `publishing` before the change have no saved container, so the upgrade marks them `failed` with a message to check Instagram first.
+- A post found published through its container keeps `publishedMediaId` as `null`, because the container status does not carry the media id.
+- A post whose run died waits out the 20 minute lease before the next run takes it over, so it can go out up to about 35 minutes late.
+- Retries add up to two more scheduler runs, about half an hour, before a temporary failure is reported.
+- The GitHub fallback's timing stays best effort. Moving it off the top of the hour follows GitHub's advice, but GitHub still decides when the runs start; the docs and the app now say the Worker publishes within 15 minutes and the fallback catches missed posts later.
+- A file in `backend/lib/` is now part of the script's runtime, so it must stay import-free; `docs/guidelines/TYPESCRIPT.md` records the rule.
diff --git a/README.md b/README.md
index d78b35e..fa3090e 100644
--- a/README.md
+++ b/README.md
@@ -213,8 +213,12 @@ create table scheduled_posts (
account_id text not null references accounts(id) on delete cascade,
status text not null default 'pending',
scheduled_at timestamptz not null,
+ claimed_at timestamptz,
+ attempts integer not null default 0,
data jsonb
);
+create index scheduled_posts_user_id_idx on scheduled_posts (user_id);
+create index scheduled_posts_due_idx on scheduled_posts (status, scheduled_at);
-- Tracked content table
create table tracked_posts (
@@ -238,7 +242,7 @@ alter table scheduled_posts enable row level security;
alter table tracked_posts enable row level security;
```
-If you created the tables from an earlier version of this README, run the `tracked_posts` and `alter table` statements above as well. Then, in Supabase Authentication, turn off **Confirm email** unless you have set up email verification codes ([docs](https://twiligent.ujjwal.fyi/docs/self-host/email-codes)), and turn off new signups once your team has accounts if the instance is private. The sign-in page's email field sends a sign-in code; without the email codes setup, Supabase sends its own rate-limited Magic Link email, which holds a link (add `{{ .Token }}` to its template in Authentication, Emails to show the code too).
+If you created the tables from an earlier version of this README, run the `tracked_posts` and `alter table` statements above as well. If your `scheduled_posts` table has no `claimed_at` column, run the upgrade SQL in [the Supabase setup docs](https://twiligent.ujjwal.fyi/docs/self-host/supabase) before deploying this version: the schedulers need the `claimed_at` and `attempts` columns. Then, in Supabase Authentication, turn off **Confirm email** unless you have set up email verification codes ([docs](https://twiligent.ujjwal.fyi/docs/self-host/email-codes)), and turn off new signups once your team has accounts if the instance is private. The sign-in page's email field sends a sign-in code; without the email codes setup, Supabase sends its own rate-limited Magic Link email, which holds a link (add `{{ .Token }}` to its template in Authentication, Emails to show the code too).
**4. Configure credentials**
@@ -377,17 +381,18 @@ Instagram requires a Business or Creator account linked to a Facebook Page.
Twiligent uses a dual-scheduler approach to publish Instagram posts reliably:
1. **Primary:** The Cloudflare Worker has a built-in cron trigger that fires every 15 minutes. No setup required - it runs automatically once the Worker is deployed.
-2. **Fallback:** A GitHub Actions workflow (`publish-scheduled.yml`) also runs every 15 minutes. It serves as a backup in case the Worker cron misses a cycle.
+2. **Fallback:** A GitHub Actions workflow (`publish-scheduled.yml`) asks for a run every 15 minutes, at minutes 7, 22, 37 and 52. GitHub starts scheduled runs when it has capacity, often hours late and sometimes not at all, so this catches posts the Worker missed later, not within 15 minutes.
-Both schedulers write to the same `scheduled_posts` table in Supabase. A `publishing` status flag acts as a mutex to prevent the same post from being published twice.
+Both schedulers write to the same `scheduled_posts` table in Supabase. A run claims a post before publishing it, so the same post is never published twice, and a claim older than 20 minutes is taken over by the next run, so a run that stopped halfway does not leave the post stuck.
### How scheduling works
1. You schedule a post through the **Publish** page (photo, reel, or story with caption and optional metadata)
2. The post is saved to Supabase with `status: 'pending'` and a `scheduled_at` timestamp
3. The Worker cron fires every 15 minutes, queries for due posts, and publishes them via the Instagram Graph API
-4. Each post is marked `publishing` before the API call and `published` or `failed` after
-5. The GitHub Actions workflow runs the same logic as a redundant fallback
+4. Each post is marked `publishing` before the API call and `published` or `failed` after. The Instagram container id is saved before publishing, so a later run can check whether the post already went out before trying again
+5. A passing problem, such as a timeout or a temporary Instagram error, sends the post back to `pending` for the next run, up to 3 attempts
+6. The GitHub Actions workflow runs the same logic as a redundant fallback
### Setup (GitHub Actions fallback only)
@@ -416,7 +421,7 @@ flowchart TD
B -->|Upload preset config| H[Cloudinary CDN]
B -->|Worker cron every 15 min| B
B -->|Publish scheduled posts| G
- I[GitHub Actions - every 15 min] -->|Read pending posts| D
+ I[GitHub Actions - best effort] -->|Read pending posts| D
I -->|Publish fallback| G
```
@@ -431,8 +436,8 @@ flowchart TD
**Cron lifecycle:**
1. The Cloudflare scheduler fires the Worker on a `*/15 * * * *` cron
-2. The Worker queries `scheduled_posts` for rows with `status = 'pending'` and `scheduled_at <= now()`
-3. Each due post is set to `publishing` (mutex), published to Instagram, then set to `published` or `failed`
+2. The Worker queries `scheduled_posts` for rows with `status = 'pending'` and `scheduled_at <= now()`, and for `publishing` rows whose claim is older than 20 minutes
+3. Each post is claimed (`publishing`, with `claimed_at` and `attempts`), published to Instagram, then set to `published`, back to `pending` for a retry, or `failed`
4. A separate `0 0 * * *` cron refreshes expiring Instagram access tokens across all users
---
@@ -447,7 +452,7 @@ twiligent/
│ ├── deploy-backend.yml # Type check, test, then Wrangler deploy on backend, shared or root config changes
│ ├── deploy-frontend.yml # Type check, test, then Cloudflare Pages deploy on frontend, shared or root config changes
│ ├── deploy-site.yml # Type check, test, then deploy the public site to the twiligent-site Pages project
-│ └── publish-scheduled.yml # Scheduled post fallback (every 15 minutes, Node 24)
+│ └── publish-scheduled.yml # Scheduled post fallback (asks for every 15 minutes, Node 24)
│
├── backend/
│ ├── app.ts # createApp(): the ordered middleware pipeline and route groups
@@ -474,6 +479,7 @@ twiligent/
│ │ ├── safeAccount.ts # Strips tokens and cookies from accounts in responses
│ │ ├── oauthState.ts # HMAC-signed Instagram OAuth state
│ │ ├── analyticsMath.ts # Shared analytics formulas
+│ │ ├── scheduledPublishing.ts # Lease, retry and container rules shared with the GitHub Actions script
│ │ └── rateLimit/ # Rate limit rules, algorithms and Lua scripts
│ ├── types/
│ │ ├── env.ts # Env: Worker secrets and bindings
diff --git a/claude.md b/claude.md
index 78fa480..4890186 100644
--- a/claude.md
+++ b/claude.md
@@ -202,6 +202,7 @@ Read `docs/guidelines/CODE_STYLE.md` before writing code and run its checklist b
- Backend failures are typed errors from `lib/errors.ts` with a message a person can act on; frontend failures are toasts that start with what failed (`Couldn't save the password.`) and add the reason; success toasts confirm in past tense (`Password saved`)
- Formatting follows the file: 4 spaces in `backend/`, 2 elsewhere, single quotes, semicolons, trailing commas
- Pure logic goes in a plain `.ts` helper (`lib/`) so Node can test it; markup used twice becomes a component; copy that changes by mode lives in a typed table
+- `scripts/` stays free of npm packages but may import a `backend/lib/` helper that imports nothing at runtime, so both schedulers share one set of rules (`scheduledPublishing.ts`)
- Tests use `node:test` with sentence names that describe behaviour, live in `tests/` mirroring the source path, and use the smallest typed fake
- When the code and `CODE_STYLE.md` disagree, update the guide in the same change
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
index 6dc35e6..9f5eb6b 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/architecture/OVERVIEW.md
@@ -106,9 +106,14 @@ Cloudflare scheduler fires cron trigger
-> createServices(service-role Supabase, Redis, config, cron context)
-> if cron === '*/15 * * * *':
scheduledPublisher.publishDue()
- -> posts.listDue() [no userId filter - scans all users]
- -> for each post: posts.claim(id), then create, wait for and publish the container
+ -> posts.listDue(), posts.listStale(cutoff) [no userId filter - scans all users;
+ stale = publishing, claim older than 20 minutes]
+ -> for each post: posts.claim(post) [publishing, claimed_at = now, attempts + 1;
+ null when another run won]
+ -> check a saved container first, else create it and save data.containerId,
+ then wait for and publish the container
-> posts.updateById(id, { status: 'published' })
+ or back to 'pending' for a temporary failure (up to 3 attempts), or 'failed'
-> if cron === '0 0 * * *':
tokenRefresh.refreshExpiringInstagramTokens()
-> accounts.listAll() [all users, Instagram accounts with a token]
diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.md
index b1478f3..04e1a44 100644
--- a/docs/architecture/backend/CRON.md
+++ b/docs/architecture/backend/CRON.md
@@ -38,20 +38,24 @@ export async function runScheduledJob(cron: string, env: Env): Promise<void> {
**Function:** `scheduledPublisher.publishDue()` in `backend/services/scheduledPublisher.ts`
**What it does:**
-1. Lists due posts with `scheduledPostRepository.listDue()` (`status = 'pending'` and `scheduled_at <= now()`)
-2. For each due post:
- - Claims it with `scheduledPostRepository.claim()` (pending to `'publishing'`); a post another scheduler already claimed is skipped
+1. Lists due posts with `scheduledPostRepository.listDue()` (`status = 'pending'` and `scheduled_at <= now()`) and stale posts with `listStale(staleClaimCutoff(now))` (`status = 'publishing'` with a claim older than the 20 minute lease)
+2. For each candidate, until the run's 14 minute deadline has passed (after that it claims nothing more):
+ - Claims it with `scheduledPostRepository.claim(post)`: `'publishing'`, `claimed_at = now` and `attempts + 1`, only if the post is still as it was listed. A post another run claimed first is skipped; a stale post that is claimed is taken over and logged
+ - A post taken over after its third attempt is only checked on Instagram, never started again
- Loads the account with `accountRepository.findById()`, checks it with `publishableAccount()` and builds the container parameters with `buildMediaParams()`
- - Creates the Graph API container, waits for it (Reels and Stories poll the status every 3 seconds, up to 60 times; other media wait 2 seconds), then publishes it
+ - If the post has a saved `containerId`, reads its status first: `PUBLISHED` marks it published, `FINISHED` publishes that container, `EXPIRED` creates a new one, `ERROR` fails it
+ - Otherwise creates the Graph API container and saves its id in `data.containerId`, waits for it (Reels and Stories poll the status every 3 seconds, up to 60 times; other media wait 2 seconds), then publishes it
- On success: sets status to `'published'`, stores `publishedMediaId` and `publishedAt` in `data`
- - On failure: sets status to `'failed'`, stores `error` message in `data`, and logs the failure with the post id
+ - On failure: reads the container status if there is one; `PUBLISHED` means published, an unreadable status leaves the post `'publishing'` for a run after the lease. A temporary failure goes back to `'pending'` with the reason in `error`, up to 3 attempts; a definite failure or the third attempt sets `'failed'`. If saving the outcome fails, the claim stays for the lease
3. Returns `{ processed, errors }`; the job logs the totals
-`backend/tests/services/scheduledPublisher.test.ts` pins this sequence, the log lines and the stored results against a fake Supabase client and Graph API (fixtures and golden snapshots in `backend/tests/fixtures/`).
+The lease, attempt limit and failure rules live in `backend/lib/scheduledPublishing.ts`, shared with the GitHub Actions script. The full failure table is in `docs/architecture/data-flows/SCHEDULING.md`.
-**No userId filter** - the publisher operates across all users through the cron-only repository methods (`listDue`, `claim`, `findById`, `updateById`). It uses the service-role Supabase client. The manual trigger (`GET` or `POST /api/process-scheduled`) runs the same `publishDue()`.
+`backend/tests/services/scheduledPublisher.test.ts` pins this sequence, the log lines and the stored results against a fake Supabase client and Graph API (fixtures and golden snapshots in `backend/tests/fixtures/`), and its recovery tests cover lost replies, takeovers and retries.
-**Concurrency safety:** The `'publishing'` status acts as a mutex. If the Worker cron and GitHub Actions cron overlap, the second one to claim a post will find it already in `'publishing'` state and skip it (it won't appear in the `status=pending` query).
+**No userId filter** - the publisher operates across all users through the cron-only repository methods (`listDue`, `listStale`, `claim`, `findById`, `updateById`). It uses the service-role Supabase client. The manual trigger (`GET` or `POST /api/process-scheduled`) runs the same `publishDue()`.
+
+**Concurrency safety:** The claim is one conditional UPDATE, so when the Worker cron and GitHub Actions overlap, the second run to claim a post gets no row back and skips it. The 20 minute lease is longer than the 14 minute deadline of both schedulers, so a run that is still working is never taken over.
### `0 0 * * *` - Instagram Token Auto-Refresh
@@ -87,7 +91,7 @@ async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {
## Dual-Scheduler (GitHub Actions Fallback)
-The same `*/15` publishing logic also runs via `scripts/publish-scheduled.ts` in GitHub Actions. See `docs/architecture/data-flows/SCHEDULING.md` for details on how both systems coexist safely.
+The same publishing logic also runs via `scripts/publish-scheduled.ts` in GitHub Actions, at minutes 7, 22, 37 and 52 when GitHub starts the runs, which is often hours late. See `docs/architecture/data-flows/SCHEDULING.md` for details on how both systems coexist safely.
## Adding a New Cron Trigger
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index fe5680c..e90d185 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -43,7 +43,7 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from
| `instagramConnect` | `instagramConnectService.ts` | accounts | `authorizationUrl`, `userIdFromState`, `connect`, plus `configured` and `accountsPageUrl` |
| `authEmail` | `authEmailService.ts` | email quota (Redis, the fail-fast client) | `send(hook, webhookId)` (Supabase Auth's Send Email hook; no user) |
-Every user-scoped method takes the verified `userId` as its first argument. Methods that need one of the user's records load it with a `...ForUser` repository method and throw `NotFoundError` when it is missing or on the wrong platform, so another user's record is never found. `scheduledPublisher` and `tokenRefresh` are the only services that use the cross-user repository methods (`listAll`, `findById`, `updateById`, `listDue`, `claim`).
+Every user-scoped method takes the verified `userId` as its first argument. Methods that need one of the user's records load it with a `...ForUser` repository method and throw `NotFoundError` when it is missing or on the wrong platform, so another user's record is never found. `scheduledPublisher` and `tokenRefresh` are the only services that use the cross-user repository methods (`listAll`, `findById`, `updateById`, `listDue`, `listStale`, `claim`).
### Accounts (`accountService.ts`, `accountFactory.ts`)
@@ -93,7 +93,9 @@ A notice that hits a cap is skipped with a warning instead of failing, because t
`publishableAccount(account)` in `publishingService.ts` is the one check both publishers use: the account must be Instagram (`NotFoundError` otherwise) and have an `igUserId` and token (`ValidationError` otherwise). `cloudinaryConfig()` throws `NotConfiguredError` (503) when the Worker has no Cloudinary settings.
-`scheduledPublisher.publishDue()` lists due posts, claims each one atomically (`pending` to `publishing`, so the GitHub Actions scheduler and the cron never publish the same post), creates the container, waits for Reels and Stories to finish processing, publishes, and marks the post `published` or `failed`. See `docs/architecture/data-flows/SCHEDULING.md`.
+`scheduledPublisher.publishDue()` lists due posts and posts whose claim is older than the 20 minute lease, and claims each one in a single conditional update (`publishing`, `claimed_at = now`, `attempts + 1`), so the GitHub Actions scheduler and the cron never hold the same post and a run that died is taken over. It saves the container id before publishing, and a post with a saved container is checked on Instagram first, so a post that already went out is never published again. It then waits for Reels and Stories to finish processing, publishes, and marks the post `published`. A temporary failure goes back to `pending` for up to 3 attempts, a definite one or the third attempt marks it `failed`, and an outcome it cannot confirm leaves the post `publishing` for a run after the lease. The rules it shares with `scripts/publish-scheduled.ts` live in `backend/lib/scheduledPublishing.ts`. See `docs/architecture/data-flows/SCHEDULING.md`.
+
+`scheduledPostService.update` and `remove` re-check the status inside the write: `updatePendingForUser` only changes a `pending` post and `deleteForUser` never deletes a `publishing` one, so a scheduler claiming the post in between cannot be overridden. The errors stay `Can only edit pending posts` and `Cannot delete a post that is currently publishing`.
---
diff --git a/docs/architecture/cloudflare/CI_CD.md b/docs/architecture/cloudflare/CI_CD.md
index 1813474..5377f44 100644
--- a/docs/architecture/cloudflare/CI_CD.md
+++ b/docs/architecture/cloudflare/CI_CD.md
@@ -8,7 +8,7 @@
| `deploy-backend.yml` | Pushes to `main` that touch the backend, manual | Type check and test the backend, then deploy the Worker |
| `deploy-frontend.yml` | Pushes to `main` that touch the frontend, manual | Type check and test the frontend, then build and deploy the app to Pages |
| `deploy-site.yml` | Pushes to `main` that touch the site, manual | Type check and test the public site, then build and deploy it to Pages |
-| `publish-scheduled.yml` | Every 15 minutes, manual | Publish due Instagram posts (fallback for the Worker cron) |
+| `publish-scheduled.yml` | Minutes 7, 22, 37 and 52 of every hour (when GitHub starts them), manual | Publish due Instagram posts (fallback for the Worker cron) |
Nothing compiles TypeScript ahead of time: Wrangler and Vite strip the types while bundling, and Node strips them when it runs tests and `scripts/publish-scheduled.ts`. None of those steps checks types, so each workflow that ships code runs `tsc` first.
@@ -106,9 +106,15 @@ The site needs no other secret: every value it shows is public and lives in the
### `publish-scheduled.yml`
**Trigger:**
-- `schedule: cron('*/15 * * * *')` - every 15 minutes
+- `schedule: cron('7,22,37,52 * * * *')` - every 15 minutes, away from the top of the hour
- `workflow_dispatch` - manual trigger from GitHub Actions UI
+**Run limits:**
+- `concurrency: { group: publish-scheduled, cancel-in-progress: false }` - one run at a time; a run that starts while another is busy waits instead of cancelling it
+- `timeout-minutes: 14` - under the 20 minute claim lease, so a later run never takes over a post this run is still publishing. The script stops its Instagram calls at 12 minutes so every claimed post still gets its outcome saved
+
+**Timing is best effort.** GitHub's documentation says scheduled runs can be delayed under high load, most of all at the start of every hour, and that queued runs can be dropped. Over two days this repository's runs came every 3 to 5 hours. The minutes 7, 22, 37 and 52 follow GitHub's advice to avoid the top of the hour, but the workflow still only catches what the Worker missed when GitHub gets to it.
+
**What it does:**
1. Checkout repo
2. `actions/setup-node@v4` with Node 24 (no npm cache and no install: the script has no dependencies)
@@ -118,7 +124,9 @@ The site needs no other secret: every value it shows is public and lives in the
- `SUPABASE_URL` - the Supabase project URL
- `SUPABASE_SERVICE_KEY` - service-role key (needed to query all users' posts)
-**This is the GitHub Actions fallback for the Worker cron.** Both this workflow and the Worker cron (`*/15`) run the same publishing logic against the same Supabase table. The `publishing` status mutex prevents double-publishing.
+**This is the GitHub Actions fallback for the Worker cron.** Both this workflow and the Worker cron (`*/15`) run the same publishing logic against the same Supabase table. A conditional claim with a 20 minute lease prevents double-publishing and lets a later run take over a post whose run died; see `docs/architecture/data-flows/SCHEDULING.md`.
+
+The script imports the shared rules from `backend/lib/scheduledPublishing.ts` by relative path, and the workflow runs whatever is on the default branch, so a change to that file reaches this workflow on its next run without a deploy.
The script is type-checked by `npm run typecheck` (`scripts/tsconfig.json`) in `ci.yml`, not by this workflow.
diff --git a/docs/architecture/data-flows/PUBLISHING.md b/docs/architecture/data-flows/PUBLISHING.md
index dce695c..d40209b 100644
--- a/docs/architecture/data-flows/PUBLISHING.md
+++ b/docs/architecture/data-flows/PUBLISHING.md
@@ -61,32 +61,43 @@ User creates a scheduled post
INSERT INTO scheduled_posts (id, user_id, account_id, status='pending', scheduled_at, data)
│
▼
-2. Every 15 minutes, one of two schedulers fires:
- A. Cloudflare Worker cron -> runScheduledJob() -> scheduledPublisher.publishDue()
- B. GitHub Actions -> node scripts/publish-scheduled.ts -> direct Supabase REST calls
+2. A scheduler run starts:
+ A. Cloudflare Worker cron, every 15 minutes -> runScheduledJob() -> scheduledPublisher.publishDue()
+ B. GitHub Actions, asked for at minutes 7, 22, 37 and 52 but often started hours late
+ -> node scripts/publish-scheduled.ts -> direct Supabase REST calls
│
▼
-3. Scheduler queries due posts:
+3. Scheduler queries due posts and stale claims:
SELECT * FROM scheduled_posts WHERE status='pending' AND scheduled_at <= now()
+ SELECT * FROM scheduled_posts WHERE status='publishing' AND claimed_at < now() - 20 minutes
│
▼
-4. For each due post:
- a. UPDATE scheduled_posts SET status='publishing' WHERE id=:id AND status='pending'
- (This is the mutex - prevents double-publish if both schedulers fire simultaneously)
-
+4. For each candidate:
+ a. UPDATE scheduled_posts SET status='publishing', claimed_at=now(), attempts=attempts+1
+ WHERE id=:id AND attempts=:attempts AND (status='pending' OR claimed_at=:expiredClaim)
+ (Only one run gets the row; a stale claim is taken over by the next run)
+
b. SELECT account WHERE id=:accountId
(Gets the accessToken from accounts.data; a missing account, an account on another
platform or a missing token fails the post with a message that says which)
-
- c. Execute the publish pipeline (same as immediate publishing, steps 2-4 above); the
- schedulers poll a Reel or Story up to 60 times (3 minutes) and fail the post if it
- is still processing
-
- d. On success: UPDATE SET status='published', data.publishedMediaId=:id, data.publishedAt=:ts
-
- e. On failure: UPDATE SET status='failed', data.error=:message
+
+ c. If data.containerId is saved, read its status_code first: PUBLISHED marks the post
+ published, FINISHED publishes that container, EXPIRED creates a new one, ERROR fails it
+
+ d. Execute the publish pipeline (same as immediate publishing, steps 2-4 above), saving
+ data.containerId right after the container is created; the schedulers poll a Reel or
+ Story up to 60 times (3 minutes)
+
+ e. On success: UPDATE SET status='published', data.publishedMediaId=:id, data.publishedAt=:ts
+
+ f. On failure: read the container status if there is one. PUBLISHED marks the post
+ published; an unreadable status leaves it publishing for a run after the lease.
+ A temporary failure sets status='pending' with data.error, up to 3 attempts;
+ a definite failure or the third attempt sets status='failed', data.error=:message
```
+The full failure table is in `docs/architecture/data-flows/SCHEDULING.md`.
+
## Media Type Differences
| Type | Container params | Status polling | Notes |
@@ -102,5 +113,5 @@ User creates a scheduled post
| Container `ERROR` | Instagram processing failed (bad codec, too long, etc.) | User must re-upload |
| Container `EXPIRED` | >24 hours since container was created | User must re-create container |
| `media_publish` rejected | Usually quota exceeded or invalid containerId; the Worker answers 502 (`UPSTREAM_ERROR`) with Instagram's message | Check publishing limit |
-| Processing timeout | The container was still processing after the last poll | Try again later, or use a shorter or smaller video |
-| `status=failed` in scheduled post | Any of the above, plus `accessToken` expired | Re-connect the account |
+| Processing timeout | The container was still processing after the last poll | A scheduled post is retried on the next run, up to 3 attempts; otherwise try again later, or use a shorter or smaller video |
+| `status=failed` in scheduled post | Any of the above, plus `accessToken` expired, or a temporary failure on the third attempt | Re-connect the account if needed, then schedule the post again |
diff --git a/docs/architecture/data-flows/SCHEDULING.md b/docs/architecture/data-flows/SCHEDULING.md
index a4c986d..fc72c10 100644
--- a/docs/architecture/data-flows/SCHEDULING.md
+++ b/docs/architecture/data-flows/SCHEDULING.md
@@ -2,59 +2,121 @@
## Overview
-Two independent systems check for due posts every 15 minutes. Both target the same Supabase table. The `publishing` status field acts as a mutex to prevent double-publishing.
+Two independent systems publish due posts from the same Supabase table. The Worker cron is the main publisher and runs every 15 minutes. The GitHub Actions workflow is a fallback that runs when GitHub gets to it. A claim with a lease (`status`, `claimed_at`, `attempts`) makes sure only one run publishes a post, and lets a later run take over a post whose run died.
+
+Both schedulers follow the same rules from `backend/lib/scheduledPublishing.ts`: the lease length, the attempt limit, which failures are temporary, and what to do with a container an earlier attempt left.
## System A: Cloudflare Worker Cron
**Trigger:** `*/15 * * * *` cron in `wrangler.toml`
**Handler:** `backend/jobs/scheduled.ts` -> `runScheduledJob()` -> `scheduledPublisher.publishDue()` in `backend/services/scheduledPublisher.ts`
+**Deadline:** 14 minutes (the cron context's signal, under the Worker's 15 minute limit for scheduled events)
**Supabase client:** service-role (created from Worker env)
**Manual trigger:** `GET` or `POST /api/process-scheduled` runs the same `publishDue()`
## System B: GitHub Actions
-**Trigger:** `publish-scheduled.yml` workflow -> `schedule: cron('*/15 * * * *')`
-**Handler:** `scripts/publish-scheduled.ts` (standalone TypeScript run directly by Node 24 with type stripping, zero npm deps)
+**Trigger:** `publish-scheduled.yml` workflow -> `schedule: cron('7,22,37,52 * * * *')`, one run at a time (`concurrency: publish-scheduled`, not cancelled), `timeout-minutes: 14`
+**Handler:** `scripts/publish-scheduled.ts` (standalone TypeScript run directly by Node 24 with type stripping, zero npm deps). It imports `backend/lib/scheduledPublishing.ts` by relative path; that file imports nothing at runtime. Instagram calls stop at 12 minutes so every claimed post still gets its outcome saved before the job limit.
**Supabase client:** direct REST API calls using `SUPABASE_URL` + `SUPABASE_SERVICE_KEY` GitHub secrets
+### GitHub timing
+
+GitHub's documentation says scheduled runs can be delayed when Actions is under high load, most of all at the start of every hour, and that queued runs can be dropped. Over two days this repository's runs came every 3 to 5 hours, although the workflow asks for one every 15 minutes. The workflow therefore runs at minutes 7, 22, 37 and 52, away from the top of the hour. Treat it as best effort: it catches what the Worker missed when GitHub gets to it, often hours late.
+
## Why Both?
-- Redundancy: if the Worker cron fails or is paused, GitHub Actions continues
+- Redundancy: if the Worker cron fails or is paused, GitHub Actions still publishes, later
- GitHub Actions is free on public repos
-- The Worker cron covers private repo deployments or when GitHub Actions minutes are exhausted
+- The Worker cron is the dependable one: it covers private repo deployments, exhausted Actions minutes and GitHub's delays
+
+## The Claim Lease
+
+Each run lists two kinds of candidates:
-## The Mutex Pattern
+- Due posts: `status = 'pending'` and `scheduled_at <= now()` (`listDue()`)
+- Stale posts: `status = 'publishing'` and `claimed_at` older than 20 minutes (`listStale(cutoff)`, cutoff from `staleClaimCutoff()`)
-When a scheduler picks up a post to publish, it immediately sets `status = 'publishing'`. This is done via a targeted UPDATE before the Instagram API call:
+It then claims each candidate with one UPDATE that only matches the post as it was listed:
```sql
UPDATE scheduled_posts
-SET status = 'publishing'
-WHERE id = :id AND status = 'pending'
+SET status = 'publishing', claimed_at = now(), attempts = :attempts + 1
+WHERE id = :id
+ AND attempts = :attempts
+ AND (status = 'pending' -- a due post
+ OR (status = 'publishing' AND claimed_at = :claimed_at)) -- the same expired claim
```
-The `AND status = 'pending'` condition means only one scheduler can successfully claim a post. The second scheduler to run will find no matching rows for that post ID and skip it.
+A run that gets no row back skips the post: another run claimed it first. PostgreSQL serializes the updates, so exactly one run holds each post even when both schedulers run at the same moment. Both schedulers implement this claim: `claim(post)` in `backend/repositories/scheduledPostRepository.ts` for the Worker, and `claimPost()` in `scripts/publish-scheduled.ts` (a `PATCH` with the same filters and `Prefer: return=representation`).
+
+The lease is 20 minutes (`PUBLISH_LEASE_MS`). The Worker's cron deadline and the GitHub job's time limit are both 14 minutes, so a claim older than 20 minutes always belongs to a run that died. A live run is never taken over.
+
+Once a run's deadline has passed (the Worker's 14 minute signal, the script's 12 minute `RUN_DEADLINE`), it claims nothing more: every Instagram call would fail, and the post would only sit out the lease. A claim that fails with a database error is logged and the run moves on to the next post.
+
+## The Container Check
+
+The Instagram container id is saved in `data.containerId` right after the container is created, before the run waits for processing or publishes. A run that holds a post with a saved container reads the container's `status_code` first (`containerStep()`):
+
+| `status_code` | What the run does |
+|---|---|
+| `PUBLISHED` | Marks the post `published`. `publishedMediaId` stays `null`, because the container status does not carry the media id |
+| `FINISHED` | Publishes that same container |
+| `IN_PROGRESS` | Waits for it to finish, then publishes it |
+| `EXPIRED` | Creates a new container |
+| `ERROR` | Fails the post |
-Both schedulers implement this claim: `claim()` in `backend/repositories/scheduledPostRepository.ts` for the Worker, and `claimPost()` in `scripts/publish-scheduled.ts` (a `PATCH` filtered on `status=eq.pending` with `Prefer: return=representation`). A scheduler that gets no row back skips the post. PostgreSQL serializes the two updates, so exactly one scheduler publishes each post even when both run at the same moment.
+This is what keeps a post from going out twice when a run died or lost Instagram's reply after publishing.
+
+## How Failures Are Handled
+
+After any failure, if a container exists, the run reads its status before deciding. `PUBLISHED` means the post went out and it is marked `published`. If the status cannot be read, the outcome on Instagram is unknown: the post stays `publishing` and a run after the lease decides. Otherwise the failure decides (`failureOutcome()`, `failureMessage()`):
+
+| Failure | Outcome |
+|---|---|
+| Container status reads `PUBLISHED` | `published` |
+| Container status cannot be read | Stays `publishing`; a run after the 20 minute lease checks again |
+| Timeout, Instagram unreachable, database error | `pending` with the reason in `error`, up to 3 attempts |
+| Graph API codes -1, 1, 2, 4, 17, 341, 9007 (temporary errors and rate limits) | `pending` with the reason in `error`, up to 3 attempts |
+| Container still processing (`IN_PROGRESS`) or expired (`EXPIRED`) | `pending`, up to 3 attempts; an expired container is cleared so the retry creates a new one |
+| Any temporary failure on the third attempt | `failed`: `<reason>. Publishing stopped after 3 attempts; schedule the post again.` |
+| Instagram rejected the media, account missing or not Instagram, no access token, processing `ERROR` | `failed` at once |
+| Saving the outcome fails | Stays `publishing`; a run after the lease finds out from the saved container |
+| Post taken over after its third attempt | Only checked on Instagram, never started again; if not published, `failed`: `The publishing run stopped before it finished. Publishing stopped after 3 attempts; schedule the post again.` |
+
+Three runs of a 15 minute scheduler give a passing Instagram or network problem about half an hour to clear.
## Post Status Lifecycle
```
pending The post is waiting to be published
│
- ▼ scheduler picks it up
-publishing Claimed by a scheduler - in-flight
+ ▼ a run claims it: claimed_at = now, attempts + 1
+publishing Held by one run for up to 20 minutes
+ │
+ ├─ Instagram publishes, or the container reads PUBLISHED ──-> published
+ │ + data.publishedMediaId (null when found through the container)
+ │ + data.publishedAt
│
- ├─ Instagram API succeeds ──-> published
- │ + data.publishedMediaId
- │ + data.publishedAt
+ ├─ temporary failure, attempts < 3 ──-> pending
+ │ + data.error (the reason, shown while it waits)
│
- └─ Instagram API fails ─────-> failed
- + data.error (error message)
+ ├─ definite failure, or the third attempt ──-> failed
+ │ + data.error
+ │
+ └─ the run died, or the outcome is unknown ──-> stays publishing
+ a run after the lease takes it over
```
`published` and `failed` posts are visible in the UI. Users can delete failed posts and reschedule.
+## Edits and Deletes
+
+Both are checked in the same statement as the write, so a claim between the check and the write cannot slip past:
+
+- `deleteForUser()` deletes only a post whose status is not `publishing`. When nothing is deleted, the service reports `Cannot delete a post that is currently publishing` (or 404 when the post is gone).
+- `updatePendingForUser()` updates only a post that is still `pending`. Otherwise the service reports `Can only edit pending posts`.
+
## Scheduler Code Comparison
Both schedulers implement the same logic:
@@ -62,15 +124,21 @@ Both schedulers implement the same logic:
| Step | Worker (`scheduledPublisher.ts`) | GitHub Actions (`publish-scheduled.ts`) |
|---|---|---|
| Fetch due posts | `posts.listDue()` | `GET /scheduled_posts?status=eq.pending&scheduled_at=lte.now` |
-| Mark publishing | `posts.claim(id)` | `PATCH /scheduled_posts?id=eq.{id}&status=eq.pending` |
+| Fetch stale posts | `posts.listStale(staleClaimCutoff(now))` | `GET /scheduled_posts?status=eq.publishing&claimed_at=lt.{cutoff}` |
+| Claim | `posts.claim(post)` | `PATCH /scheduled_posts?id=eq.{id}&attempts=eq.{n}&status=eq.pending` (or `status=eq.publishing&claimed_at=eq.{claimedAt}`) |
| Fetch account | `accounts.findById(accountId)`, checked by `publishableAccount()` | `GET /accounts?id=eq.{accountId}` |
| Publish to IG | `createMediaContainer`, `fetchContainerStatus`, `publishMediaContainer` from `services/instagram/instagramPublishing.ts` | Its own Graph API calls |
+| Save the container | `posts.updateById(id, { containerId })` | `PATCH /scheduled_posts?id=eq.{id}` |
+| Decide after a failure | `containerStep`, `isTransientGraphCode`, `failureOutcome`, `failureMessage` from `lib/scheduledPublishing.ts` | The same functions, imported by relative path |
| Update status | `posts.updateById(id, ...)` | `PATCH /scheduled_posts?id=eq.{id}` |
-The Worker's repository methods `listDue`, `claim`, `findById` and `updateById` have no `userId` filter; only the schedulers use them.
+The Worker's repository methods `listDue`, `listStale`, `claim`, `findById` and `updateById` have no `userId` filter; only the schedulers use them.
## Configuration Requirements
+### Database
+- `scheduled_posts` needs the `claimed_at` and `attempts` columns and the two indexes. An instance created before the lease runs the upgrade SQL in `docs/architecture/database/SCHEMA.md` before deploying the code.
+
### For Worker Cron (System A)
- Worker secrets: `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `INSTAGRAM_APP_ID` (not used by scheduler directly - the account's stored `accessToken` is used)
- No additional setup beyond deploying the Worker
@@ -79,7 +147,8 @@ The Worker's repository methods `listDue`, `claim`, `findById` and `updateById`
- GitHub repo secrets: `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`
- The `publish-scheduled.yml` workflow must be enabled. Forks start with Actions disabled, and GitHub pauses scheduled workflows in public repositories after 60 days without commits.
- No personal access token is needed. The workflow only reads and updates Supabase.
-- Private repositories: a 15-minute schedule exceeds the 2,000 free Actions minutes a month; use `*/30 * * * *`.
+- Private repositories: a 15-minute schedule exceeds the 2,000 free Actions minutes a month; use `7,37 * * * *` (every 30 minutes, off the hour).
+- Keep `timeout-minutes` under the 20 minute lease, or a later run could take over a post this run is still publishing.
Step-by-step instructions for a person setting this up: `docs/workflows/SCHEDULING_SETUP.md`, also shown in the app under Settings, Scheduled publishing with direct links once a GitHub username is saved.
- `SUPABASE_SERVICE_KEY` can be a new secret key (`sb_secret_...`, sent on the `apikey` header only) or the legacy `service_role` JWT (sent on `apikey` and `Authorization`).
@@ -87,5 +156,7 @@ Step-by-step instructions for a person setting this up: `docs/workflows/SCHEDULI
## What users see
- Publish explains, next to the schedule fields, that the server publishes within 15 minutes after the chosen time.
-- Posts still `pending` more than 30 minutes after their time trigger an alert in Publish that names the administrator contact (`VITE_ADMIN_EMAIL`).
+- A `pending` post that is being retried shows `Trying again on the next run` under its status, and the reason of the last attempt in its error tooltip (`isRetrying()` in `frontend/src/features/publishing/scheduleHelpers.ts`).
+- The overdue alert in Publish counts `pending` posts more than 30 minutes late (a retried post counts from its last claim) and `publishing` posts whose claim is older than the lease plus 30 minutes, 50 minutes in all (`overduePostsOf()`). It reads `... more than 30 minutes late and not yet published, so the scheduler on this server is not running.` and names the administrator contact (`VITE_ADMIN_EMAIL`).
+- Settings, Scheduled publishing says the GitHub fallback often starts hours late and is a backup, not a 15 minute guarantee.
- Note: These GitHub secrets are only required for System B - the main deploy workflows (`deploy-backend.yml`, `deploy-frontend.yml`) do not need them
diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.md
index 9b59474..a8fe67f 100644
--- a/docs/architecture/database/SCHEMA.md
+++ b/docs/architecture/database/SCHEMA.md
@@ -104,16 +104,22 @@ Stores Instagram posts queued for future publishing.
| `account_id` | text | NOT NULL | FK -> `accounts.id` |
| `status` | text | NOT NULL | `'pending'`, `'publishing'`, `'published'`, `'failed'` |
| `scheduled_at` | timestamptz | NOT NULL | UTC timestamp when the post should be published |
+| `claimed_at` | timestamptz | NULL | When a scheduler last claimed the post. A `publishing` post whose claim is older than 20 minutes is taken over by the next run |
+| `attempts` | integer | NOT NULL DEFAULT 0 | How many times a scheduler has claimed the post. The third failed attempt is final |
| `data` | jsonb | - | Post content and result data (see below) |
+`claimed_at` and `attempts` change only in the claim, never through `updateById` or `updatePendingForUser`. The API returns them as `claimedAt` and `attempts` on `ScheduledPost`.
+
### Status lifecycle
```
pending -> publishing -> published
- ↘ failed
+ │ ↘ failed
+ ├─> pending a passing failure, while attempts < 3
+ └─> publishing a takeover after the 20 minute lease
```
-The `publishing` status is a mutex - it prevents double-publishing when both the Worker cron and GitHub Actions scheduler fire at the same time.
+A claim is one UPDATE that sets `status = 'publishing'`, `claimed_at = now()` and `attempts = attempts + 1`, and only matches the post as the scheduler listed it. Two schedulers never hold the same post, and a run that died leaves a claim the next run can take over. See `docs/architecture/data-flows/SCHEDULING.md`.
### `data` jsonb shape
@@ -130,16 +136,49 @@ The `publishing` status is a mutex - it prevents double-publishing when both the
"userTags": [{ "username": "...", "x": 0.5, "y": 0.5 }],
"altText": "...",
"collaborators": ["username1", "username2"],
+ "containerId": "17900000000000001",
"publishedMediaId": "17841400000000001",
"publishedAt": "2025-07-01T10:00:00Z",
"error": "Error message if failed"
}
```
-### Indexes recommended
+- `containerId` is the Instagram media container, saved right after it is created and before the scheduler waits or publishes. A later run reads its `status_code` to find out whether the post already went out. It is cleared when the container expired and a retry needs a new one.
+- `publishedMediaId` is `null` when a run found the post already published through the container status, because that status does not carry the media id.
+- `error` is set on a `failed` post, and also on a `pending` post that is being retried, where it holds the reason the last attempt failed.
+
+### Indexes
+
+```sql
+create index if not exists scheduled_posts_user_id_idx on public.scheduled_posts (user_id);
+create index if not exists scheduled_posts_due_idx on public.scheduled_posts (status, scheduled_at);
+```
+
+- `scheduled_posts_user_id_idx` - user-scoped queries
+- `scheduled_posts_due_idx` - the scheduler queries: due posts (`status = 'pending' AND scheduled_at <= now()`) and stale claims (`status = 'publishing'`)
-- `scheduled_posts(user_id)` - user-scoped queries
-- `scheduled_posts(status, scheduled_at)` - the cron scheduler query: `status=pending AND scheduled_at <= now()`
+These were listed as recommended before but did not exist in the production database; the upgrade SQL below creates them.
+
+### Upgrade SQL (claim lease and attempts)
+
+Run once in the Supabase SQL editor on an instance created before the claim lease. Run it before deploying the code that reads `claimed_at` and `attempts`.
+
+```sql
+alter table public.scheduled_posts
+ add column if not exists claimed_at timestamptz,
+ add column if not exists attempts integer not null default 0;
+
+-- posts stuck before this change have no saved container, so nothing can tell whether they went out
+update public.scheduled_posts
+set status = 'failed',
+ data = data || jsonb_build_object('error', 'Publishing was interrupted before Twiligent tracked it. Check Instagram before scheduling this post again.')
+where status = 'publishing' and claimed_at is null;
+
+create index if not exists scheduled_posts_user_id_idx on public.scheduled_posts (user_id);
+create index if not exists scheduled_posts_due_idx on public.scheduled_posts (status, scheduled_at);
+```
+
+A new instance gets the columns and indexes from the setup SQL in `README.md` and `site/content/docs/self-host/supabase.mdx`.
---
@@ -255,7 +294,7 @@ All SQL operations live in `backend/repositories/`, one repository per table. Se
### Available methods
-Each repository is built with `createXRepository(supabase)` and returns types from `shared/types/domain.ts`. Methods named `...ForUser` take the verified `userId` and always filter by it. The methods without a `userId` (`listAll`, `findById`, `updateById`, `listDue`, `claim`) reach every user and are only for the cron jobs.
+Each repository is built with `createXRepository(supabase)` and returns types from `shared/types/domain.ts`. Methods named `...ForUser` take the verified `userId` and always filter by it. The methods without a `userId` (`listAll`, `findById`, `updateById`, `listDue`, `listStale`, `claim`) reach every user and are only for the cron jobs.
```ts
// Accounts (accountRepository.ts)
@@ -276,11 +315,12 @@ saveForUser(settings: Settings, userId): Promise<void>
listForUser(userId): Promise<ScheduledPost[]>
findForUser(id, userId): Promise<ScheduledPost | null>
listDue(): Promise<ScheduledPost[]> // cron only - pending and overdue, every user
-claim(id): Promise<boolean> // cron only - pending to publishing; false when another scheduler won
+listStale(claimedBefore): Promise<ScheduledPost[]> // cron only - publishing with a claim older than the cutoff
+claim(post): Promise<ScheduledPost | null> // cron only - the claimed post; null when another run won
create(post: ScheduledPost, userId): Promise<void>
-updateForUser(id, updates: Partial<ScheduledPost>, userId): Promise<void>
+updatePendingForUser(id, updates: Partial<ScheduledPost>, userId): Promise<boolean> // false when the post is no longer pending
updateById(id, updates: Partial<ScheduledPost>): Promise<void> // cron only
-deleteForUser(id, userId): Promise<void>
+deleteForUser(id, userId): Promise<boolean> // never deletes a 'publishing' post; false when nothing was deleted
deleteAllForUser(userId): Promise<{ deleted: number; kept: number }> // skips 'publishing' status posts
// Tracked Content (trackedPostRepository.ts)
diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.md
index 7188c4b..cd55fe2 100644
--- a/docs/architecture/database/SECURITY.md
+++ b/docs/architecture/database/SECURITY.md
@@ -8,7 +8,7 @@ The backend uses the **service-role key** for all database operations. This key
2. Controllers pass that `userId` to services, and every user-scoped repository method (named `...ForUser`) appends `.eq('user_id', userId)` using this verified value
3. `userId` is never accepted from request body, query params, or any other user-controlled input
-**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `backend/repositories/` makes this auditable: a method that takes a `userId` ends in `ForUser`, and the few that reach every user (`listAll`, `findById`, `updateById`, `listDue`, `claim`) are used only by the cron services. Because ownership is a query filter, another user's record is simply not found (404).
+**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `backend/repositories/` makes this auditable: a method that takes a `userId` ends in `ForUser`, and the few that reach every user (`listAll`, `findById`, `updateById`, `listDue`, `listStale`, `claim`) are used only by the cron services. Because ownership is a query filter, another user's record is simply not found (404).
## Why Not Use RLS?
diff --git a/docs/guidelines/CODE_STYLE.md b/docs/guidelines/CODE_STYLE.md
index 9543416..923daac 100644
--- a/docs/guidelines/CODE_STYLE.md
+++ b/docs/guidelines/CODE_STYLE.md
@@ -42,6 +42,7 @@ import type { EmailQuotaRepository } from '../repositories/emailQuotaRepository.
- Backend and test imports are relative and end in `.ts`. Frontend imports use `@/` for `src/` (no extension) and `./` for siblings; files that Node tests import use relative `.ts` paths only.
- Pure logic that can be tested goes in a plain `.ts` file with no JSX (`frontend/src/lib/passwords.ts`, `backend/services/email/authEmails.ts`), so Node can run its test directly.
+- `scripts/` has no dependencies. A rule a script shares with the Worker lives in an import-free `backend/lib/` helper that the script imports by relative path (`scripts/publish-scheduled.ts` imports `../backend/lib/scheduledPublishing.ts`); that helper imports nothing at runtime. See `docs/guidelines/TYPESCRIPT.md`.
## Comments
diff --git a/docs/guidelines/NAMING.md b/docs/guidelines/NAMING.md
index 2d404e1..c36c06e 100644
--- a/docs/guidelines/NAMING.md
+++ b/docs/guidelines/NAMING.md
@@ -35,7 +35,7 @@ Use `.tsx` only for files that contain JSX; everything else is `.ts`.
- Backend validators: `parse` + noun - `parseScheduledPost`, `parseVideoLibraryQuery`
- Backend service factories: `create` + service name - `createAccountService`, `createScheduledPublisher`; their methods are short verbs, because the service names the noun - `accounts.list`, `accounts.refresh`, `scheduledPosts.removeAll`
- Backend platform functions: `camelCase` verb + noun - `fetchChannelData()`, `computeVideoAnalytics()`, `createMediaContainer()`
-- Backend repository methods: verb + `ForUser` when scoped to the verified user - `listForUser()`, `findForUser()`, `updateForUser()`, `deleteForUser()`; the cross-user methods for cron jobs have no suffix - `listAll()`, `findById()`, `updateById()`, `listDue()`, `claim()`
+- Backend repository methods: verb + `ForUser` when scoped to the verified user - `listForUser()`, `findForUser()`, `updateForUser()`, `deleteForUser()`; the cross-user methods for cron jobs have no suffix - `listAll()`, `findById()`, `updateById()`, `listDue()`, `listStale()`, `claim()`
- Frontend API methods: `camelCase` verb + noun - `getAnalytics()`, `createScheduledPost()`, `deleteAccount()`
- React event handlers: `handle` + PascalCase noun/event - `handleSubmit()`, `handleDeleteClick()`, `handleInputChange()`
- React custom hooks: `use` + PascalCase noun - `useAppContext()`, `useIsMobile()`
diff --git a/docs/guidelines/SUPABASE.md b/docs/guidelines/SUPABASE.md
index 9130316..01a7f12 100644
--- a/docs/guidelines/SUPABASE.md
+++ b/docs/guidelines/SUPABASE.md
@@ -88,7 +88,7 @@ await execute('accounts.update', () => {
Every user-scoped repository method takes the verified `userId`, ends in `ForUser`, and includes `.eq('user_id', userId)`. Methods that intentionally omit the filter serve the cron jobs only; they have no `ForUser` suffix and the repository's interface says so in its one comment:
```ts
-// methods named ...ForUser filter by the verified user id; listDue, claim and updateById serve the schedulers across all users
+// methods named ...ForUser filter by the verified user id; listDue, listStale, claim and updateById serve the schedulers across all users
export interface ScheduledPostRepository {
listForUser(userId: string): Promise<ScheduledPost[]>;
listDue(): Promise<ScheduledPost[]>;
@@ -96,7 +96,7 @@ export interface ScheduledPostRepository {
}
```
-Only `scheduledPublisher.ts` and `tokenRefreshService.ts` call the cross-user methods (`listAll`, `findById`, `updateById`, `listDue`, `claim`). See `docs/architecture/database/SECURITY.md`.
+Only `scheduledPublisher.ts` and `tokenRefreshService.ts` call the cross-user methods (`listAll`, `findById`, `updateById`, `listDue`, `listStale`, `claim`). See `docs/architecture/database/SECURITY.md`.
## Client Lifecycle
diff --git a/docs/guidelines/TYPESCRIPT.md b/docs/guidelines/TYPESCRIPT.md
index 0e3e48a..52aa732 100644
--- a/docs/guidelines/TYPESCRIPT.md
+++ b/docs/guidelines/TYPESCRIPT.md
@@ -46,6 +46,8 @@ Because Node runs `.ts` files by removing the types, only syntax that can be era
`shared/types` holds types only. It never imports runtime code, so either app can import it with `import type` and nothing from it reaches a bundle. The backend imports it by relative path (`../../shared/types/domain.ts`), the frontend by alias (`@shared/types/domain.ts`), except files that Node tests import, which use the relative path.
+`scripts/` installs no packages, so a script may import only `shared/types` (with `import type`) and import-free helpers from `backend/lib/` by relative path. `scripts/publish-scheduled.ts` imports `../backend/lib/scheduledPublishing.ts` this way, so both schedulers follow one copy of the lease, retry and container rules. Such a helper imports nothing at runtime (only `import type`), uses no Worker or Node API, and says in its first comment that a script imports it. `scripts/tsconfig.json` checks it through the import.
+
When a route's response changes, change its type in `shared/types` first. The type checker then lists every frontend file that reads the old shape.
## Typing Rules
diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.md
index c7aff03..731721f 100644
--- a/docs/workflows/DEPLOYMENT.md
+++ b/docs/workflows/DEPLOYMENT.md
@@ -13,7 +13,7 @@ A pull request merged into `main` -> GitHub Actions deploys automatically. `main
| `shared/**` | Backend and frontend workflows | Worker and app (in parallel) |
| `tsconfig.base.json` | All three workflows | Worker, app and site (in parallel) |
| Root `package.json` or `package-lock.json` | All three workflows | Worker, app and site (in parallel) |
-| `docs/`, `scripts/`, root `*.md` | None | Nothing deployed |
+| `docs/`, `scripts/`, root `*.md` | None | Nothing deployed (`publish-scheduled.yml` runs `scripts/publish-scheduled.ts` and `backend/lib/scheduledPublishing.ts` from `main` on its next run) |
Monitor deployment status at:
`https://github.com/spacesdrive/twiligent/actions`
@@ -66,6 +66,31 @@ npx wrangler pages deploy dist --project-name=twiligent-site
The site needs no environment variables or secrets. Self-hosters can skip this step: the site is the project's own marketing site and docs, not part of a running instance. See `docs/architecture/cloudflare/PAGES.md`.
+## Database Changes
+
+Supabase is not migrated by any workflow. A change to the database is SQL the owner runs in the Supabase SQL editor, and it goes in before the code that needs it is merged, because merging deploys the Worker at once.
+
+### Claim lease and attempts (`scheduled_posts`)
+
+The scheduler fix that adds the claim lease, retries and the container check reads two new columns. Run this in the Supabase SQL editor before merging it:
+
+```sql
+alter table public.scheduled_posts
+ add column if not exists claimed_at timestamptz,
+ add column if not exists attempts integer not null default 0;
+
+-- posts stuck before this change have no saved container, so nothing can tell whether they went out
+update public.scheduled_posts
+set status = 'failed',
+ data = data || jsonb_build_object('error', 'Publishing was interrupted before Twiligent tracked it. Check Instagram before scheduling this post again.')
+where status = 'publishing' and claimed_at is null;
+
+create index if not exists scheduled_posts_user_id_idx on public.scheduled_posts (user_id);
+create index if not exists scheduled_posts_due_idx on public.scheduled_posts (status, scheduled_at);
+```
+
+The columns are additive and the old code ignores them, so running the SQL first is safe. The two indexes were listed in `SCHEMA.md` before but did not exist in production. Check afterwards with `select status, count(*) from public.scheduled_posts group by status;`: no post should be `publishing` without a recent `claimed_at`. See `docs/architecture/database/SCHEMA.md`.
+
## Setting Worker Secrets
Secrets must be set before the first deploy or when adding new ones. Run these from `backend/` so Wrangler picks up `wrangler.toml`:
@@ -146,7 +171,7 @@ Open `https://app.twiligent.ujjwal.fyi` (custom domain on the `twiligent` Pages
Open `https://twiligent.ujjwal.fyi` (custom domain on the `twiligent-site` Pages project; `twiligent.spacesdrive.cc` 301-redirects here) -> verify the home page renders in light and dark (the theme toggle in the navbar) -> open `/docs`, press Ctrl K and search for `redis` -> open a result. Check that `/sitemap.xml` and `/llms.txt` load and that `https://twiligent.ujjwal.fyi/settings` redirects to `https://app.twiligent.ujjwal.fyi/settings`.
**Scheduled publisher:**
-GitHub Actions -> "Instagram Scheduled Publisher" -> "Run workflow" -> check run output.
+GitHub Actions -> "Instagram Scheduled Publisher" -> "Run workflow" -> check run output. A post taken over from an expired claim logs `Taken over: the claim from ... expired`. The workflow asks for runs at minutes 7, 22, 37 and 52, one at a time with a 14 minute limit, but GitHub often starts scheduled runs hours late; the Worker cron (`npx wrangler tail`, `scheduled post published`) is the one that publishes within 15 minutes.
## Addresses: Site and App
@@ -193,8 +218,9 @@ For a fresh deployment from this repo:
6. Install Node 22.18 or newer, run `npm ci` at the repository root, then `npx wrangler login`
7. Set all Worker secrets (see above)
8. Set all GitHub Actions secrets (see above)
-9. `npm run typecheck`, then `cd backend && npx wrangler deploy` (first manual deploy)
-10. Verify health endpoint
-11. `npm run build` at the root, then `cd frontend && npx wrangler pages deploy dist --project-name=twiligent`
-12. Verify frontend loads
-13. Add a YouTube channel via AccountManager to verify the full flow
+9. Run the setup SQL from `README.md` in the Supabase SQL editor (tables, the `scheduled_posts` columns and indexes, RLS)
+10. `npm run typecheck`, then `cd backend && npx wrangler deploy` (first manual deploy)
+11. Verify health endpoint
+12. `npm run build` at the root, then `cd frontend && npx wrangler pages deploy dist --project-name=twiligent`
+13. Verify frontend loads
+14. Add a YouTube channel via AccountManager to verify the full flow
diff --git a/docs/workflows/SCHEDULING_SETUP.md b/docs/workflows/SCHEDULING_SETUP.md
index eaf9e79..01613a3 100644
--- a/docs/workflows/SCHEDULING_SETUP.md
+++ b/docs/workflows/SCHEDULING_SETUP.md
@@ -2,7 +2,7 @@
> **Who this is for:** the administrator of a Twiligent instance. Step 2 needs the secret key of the instance's Supabase project. If you only sign in to someone else's Twiligent, you need none of this: the server already publishes your scheduled posts. This backup is optional even for administrators; the Worker cron publishes on its own once the backend is deployed. The public docs cover the same steps at `https://twiligent.ujjwal.fyi/docs/self-host/github`.
-GitHub can check your scheduled Instagram posts every 15 minutes and publish the ones that are due, for free. It runs alongside the server's own scheduler as a backup, so posts still go out if the server is paused. You set it up once. It takes about 5 minutes.
+GitHub can check your scheduled Instagram posts and publish the ones that are due, for free. It runs alongside the server's own scheduler as a backup, so posts still go out if the server is paused, though later: GitHub often starts these runs hours after their time. You set it up once. It takes about 5 minutes.
The same steps are in the app under **Settings, Scheduled publishing**, where typing your GitHub username turns every step into a direct link.
@@ -65,8 +65,10 @@ GitHub switches workflows off in new copies.
## After setup
-- GitHub checks every 15 minutes. You do not need to keep anything open.
+- The workflow asks GitHub for a run every 15 minutes, at minutes 7, 22, 37 and 52 of each hour. You do not need to keep anything open.
+- GitHub starts scheduled runs when it has capacity. Its own documentation says they can be delayed, most of all at the start of every hour, and that some are dropped. Over two days this project's own runs came every 3 to 5 hours. The server's scheduler is the one that publishes within 15 minutes; this backup catches what it missed, when GitHub gets to it.
+- Only one run works at a time, and each run stops after 14 minutes. A run that starts while another is busy waits for it.
- The workflow runs `node scripts/publish-scheduled.ts` on Node 24, which runs the TypeScript file directly. It installs nothing, so there is no build step to maintain in your copy.
-- The server scheduler and this workflow can run at the same time. Each post is claimed by whichever runs first, so it is published once.
+- The server scheduler and this workflow can run at the same time. Each post is claimed by whichever runs first, so it is published once. If a run stops halfway, the next run after 20 minutes takes the post over and checks Instagram before publishing, so the post is not published twice.
- If nothing changes in your copy for 60 days, GitHub pauses the schedule and emails you. Repeat step 4.
-- A private copy uses GitHub's free minutes (2,000 a month), and a run every 15 minutes uses more than that. Keep your copy public, or change `*/15 * * * *` to `*/30 * * * *` in `.github/workflows/publish-scheduled.yml`.
+- A private copy uses GitHub's free minutes (2,000 a month), and a run every 15 minutes uses more than that. Keep your copy public, or change `'7,22,37,52 * * * *'` to `'7,37 * * * *'` (every 30 minutes) in `.github/workflows/publish-scheduled.yml`.
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 756986f..004207d 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -27,6 +27,8 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that
| `backend/routes/publishingRoutes.ts` | `backend/tests/routes/publishingRoutes.test.ts` |
| `backend/routes/settingsRoutes.ts` | `backend/tests/routes/settingsRoutes.test.ts` |
| `backend/services/scheduledPublisher.ts` | `backend/tests/services/scheduledPublisher.test.ts` |
+| `backend/lib/scheduledPublishing.ts` | `backend/tests/lib/scheduledPublishing.test.ts` |
+| `backend/repositories/scheduledPostRepository.ts` | `backend/tests/repositories/scheduledPostRepository.test.ts` |
| `backend/services/tokenRefreshService.ts` | `backend/tests/services/tokenRefreshService.test.ts` |
| `backend/repositories/accountRepository.ts` | `backend/tests/repositories/accountRepository.test.ts` |
| `backend/middleware/errorHandler.ts` | `backend/tests/middleware/errorHandler.test.ts` |
@@ -40,6 +42,7 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that
| `frontend/src/lib/emailAddress.ts` | `frontend/tests/lib/emailAddress.test.ts` |
| `frontend/src/lib/googleIdentity.ts` | `frontend/tests/lib/googleIdentity.test.ts` |
| `frontend/src/features/analytics/overview/overviewStats.ts` | `frontend/tests/features/analytics/overview/overviewStats.test.ts` |
+| `frontend/src/features/publishing/scheduleHelpers.ts` | `frontend/tests/features/publishing/scheduleHelpers.test.ts` |
| `site/src/docs/searchShared.ts` | `site/tests/docs/searchShared.test.ts` |
| `site/content/docs/**/*.mdx` and `site/src/docs/nav.ts` | `site/tests/docs/content.test.ts` |
| `site/src/lib/chart.ts` | `site/tests/lib/chart.test.ts` |
@@ -59,6 +62,8 @@ Rate limiting has its own tests: `tests/lib/rateLimit/algorithms.test.ts` (each
Backend route and cron service tests (`tests/routes/*Routes.test.ts`, `tests/services/scheduledPublisher.test.ts`, `tests/services/tokenRefreshService.test.ts`) run the real code against `tests/fixtures/fakeSupabase.ts` and a scripted `fetch`, then compare responses, queries and outgoing requests with the `tests/fixtures/*.golden.json` snapshots. Route tests mount a route table with `mountWithContext()` from `tests/fixtures/routeHarness.ts`, which installs the real error handler and not-found handler and sets the request id (`req-test`), the signal and the context values the pipeline would set, so error responses are checked with their real `{ success: false, code, message, requestId }` body and status. Rows tagged with `tableRow(name, row)` are only visible to that table; untagged rows are visible to every table. A refactor must leave the snapshots unchanged. Prettier ignores the snapshots (`.prettierignore`), because the tests compare them byte for byte.
+Scheduled publishing recovery has its own tests. `tests/lib/scheduledPublishing.test.ts` covers the shared rules: the 20 minute lease outlasts the 14 minute limit of both schedulers, what a run does for each container status, which Graph API codes count as temporary, when a failure retries or fails, and when the final message says publishing stopped. `tests/repositories/scheduledPostRepository.test.ts` runs the claim against the fake Supabase client: two schedulers claiming the same listed post (only the first gets it, and the claim counts an attempt), which claims are stale and that a takeover must match the expired claim it saw, that a post being published is not deleted, and that an edit only lands while the post is pending. The `scheduled publisher recovery` block in `tests/services/scheduledPublisher.test.ts` runs the whole publisher: a publish reply lost on the way back is checked on Instagram and marked published, an unreadable container status leaves the post claimed, an expired claim is taken over and found published or publishes its ready container, a claim inside its lease is left alone, a passing failure goes back to `pending` and the third fails the post, a run past its deadline claims nothing, and a post taken over after its last attempt is only checked. On the frontend, `tests/features/publishing/scheduleHelpers.test.ts` covers when the overdue alert counts a retried post (from its last claim) and a stuck claim (after the lease and 30 minutes).
+
The Send Email hook has its own tests: `tests/lib/webhookSignature.test.ts` (valid, tampered, wrong-key, multi-signature and replayed requests), `tests/validators/authHookValidators.test.ts`, `tests/services/email/authEmails.test.ts` (the email for each action, the verify links, HTML escaping and the two Secure Email Change emails), `tests/repositories/emailQuotaRepository.test.ts` (daily and per-address caps, hashed keys, Redis failures), `tests/services/authEmailService.test.ts` (Resend requests, idempotency keys, the caps and Resend's own quota errors, skipped notices) and `tests/routes/authHookRoutes.test.ts` (the hook error shape, and the route answering unsigned calls with 401 in the full app). `tests/fixtures/authHook.ts` signs requests the way Supabase Auth does. The Lua claim script cannot run in Node; the repository test runs the same rules in memory. On the frontend, `tests/lib/authErrors.test.ts` covers when the sign-in page shows the daily cap warning and whether it offers Google, `tests/lib/emailAddress.test.ts` when an address looks complete enough to enable the Continue arrow, and `tests/lib/googleIdentity.test.ts` the label drawn on the Google button for each text option.
The testing workflow documented here describes what should run before shipping any change.
@@ -192,6 +197,10 @@ Open the app in a browser. For each changed area, test:
- [ ] Create a scheduled post -> appears in queue
- [ ] Manual trigger processes due posts correctly
- [ ] Failed posts show error in UI
+- [ ] A post interrupted mid-publish (status `publishing`, `claimed_at` set more than 20 minutes ago in the SQL editor) is taken over by the next run: it ends `published` if its saved container already went out, without a second post on Instagram
+- [ ] A lost reply cannot leave a published post marked `failed`: when the run cannot confirm the outcome, the post stays `publishing` until a run after the lease checks the container
+- [ ] A pending post with `attempts` above 0 shows "Trying again on the next run" under its status
+- [ ] Deleting or editing a post while it is `publishing` is refused with "Cannot delete a post that is currently publishing" or "Can only edit pending posts"
**Public site and docs (if `site/` or the app's docs links changed):**
@@ -246,7 +255,7 @@ Verify:
### 9. Scheduled Publisher Verification
-After any change to `scripts/publish-scheduled.ts` or `publish-scheduled.yml`:
+After any change to `scripts/publish-scheduled.ts`, `backend/lib/scheduledPublishing.ts` or `publish-scheduled.yml`:
1. GitHub Actions -> "Instagram Scheduled Publisher" -> "Run workflow"
2. Watch the run output
diff --git a/site/content/docs/reference/scheduling.mdx b/site/content/docs/reference/scheduling.mdx
index af9fa6a..9ccc38d 100644
--- a/site/content/docs/reference/scheduling.mdx
+++ b/site/content/docs/reference/scheduling.mdx
@@ -2,29 +2,53 @@ export const meta = { title: 'How scheduling works', description: 'What happens
## For members
-Nothing to set up. Pick a time, choose **Schedule post**, and close the browser if you like. The server publishes the post within 15 minutes after the time you picked.
+Nothing to set up. Pick a time, choose **Schedule post**, and close the browser if you like. The server publishes the post within 15 minutes after the time you picked. If Instagram or the network has a passing problem, it tries again on its next two runs.
## For administrators
-Deploying the backend is all that is required. The Worker's cron trigger runs every 15 minutes and publishes every post that is due. The GitHub workflow is an optional second runner for extra reliability.
+Deploying the backend is all that is required. The Worker's cron trigger runs every 15 minutes and publishes every post that is due. The GitHub workflow is an optional second runner that catches posts the Worker missed, but GitHub decides when its runs start, often hours late.
### The lifecycle of a post
| Step | Status | What happens |
| --- | --- | --- |
| 1 | <Badge>pending</Badge> | The file is on Cloudinary and the post is saved with its time. |
-| 2 | <Badge>publishing</Badge> | A scheduler claims the post. Only one scheduler can claim it, so it is published once. |
-| 3 | <Badge>published</Badge> | Instagram accepted it. The Instagram media ID is saved. |
-| 3 | <Badge>failed</Badge> | Instagram rejected it. The reason is saved and shown in the Error column. |
+| 2 | <Badge>publishing</Badge> | A scheduler claims the post for up to 20 minutes. Only one scheduler can hold it, so it is published once. |
+| 3 | <Badge>published</Badge> | Instagram accepted it. The Instagram media ID is saved, unless the post was found already published through its container. |
+| 3 | <Badge>pending</Badge> | A passing problem, such as a timeout or a temporary Instagram error. The reason is saved and the next run tries again, up to 3 attempts in all. |
+| 3 | <Badge>failed</Badge> | Instagram rejected it, the account cannot publish, or the third attempt failed too. The reason is saved and shown in the Error column. |
### Two schedulers, one post
-Both schedulers claim a post by changing it from `pending` to `publishing` in a single database update that only succeeds while it is still pending. Whichever arrives second finds nothing to claim and skips it.
+A scheduler claims a post in a single database update that sets it to `publishing`, records the time of the claim and counts the attempt. The update only succeeds while the post is exactly as the scheduler found it, so whichever arrives second finds nothing to claim and skips it.
+
+Each claim lasts 20 minutes. Both schedulers stop within 14 minutes, so a post still `publishing` after 20 minutes belongs to a run that stopped halfway, and the next run takes it over.
+
+### How a post is never published twice
+
+Before publishing, the scheduler saves the ID of the Instagram media container it created. A run that takes a post over, or that hits an error after the container exists, first asks Instagram for the container's status:
+
+| Container status | What the scheduler does |
+| --- | --- |
+| `PUBLISHED` | Marks the post published. It is already on Instagram. |
+| `FINISHED` | Publishes that same container. |
+| `IN_PROGRESS` | Waits for Instagram to finish processing. |
+| `EXPIRED` | Creates a new container. |
+| `ERROR` | Marks the post failed. |
+
+If Instagram cannot be asked, the post stays `publishing` and a run after the 20 minute claim decides. A post is never marked failed while it might already be live.
+
+### Retries
+
+Timeouts, an unreachable Instagram, database errors and Instagram's temporary error codes send the post back to `pending`, with the reason in the Error column, and the next run tries again. After the third attempt the post fails with the reason and `Publishing stopped after 3 attempts; schedule the post again.` Errors that will not pass on their own, such as Instagram rejecting the media or an account without access, fail the post at once.
### When posts stay pending
- The Worker was never deployed, or its cron triggers were removed. Check **Triggers** on the Worker in the Cloudflare dashboard.
- `SUPABASE_SERVICE_KEY` or `SUPABASE_URL` is wrong on the Worker.
+- The database is missing the `claimed_at` and `attempts` columns. Run the upgrade SQL in [Supabase](/docs/self-host/supabase#upgrading-an-existing-instance).
- The connected Instagram account's access was removed. Reconnect it.
-Twiligent warns members when a post is more than 30 minutes overdue and tells them to contact the administrator.
+Twiligent warns members when a post is more than 30 minutes late and not yet published, and tells them to contact the administrator. A retried post counts from its last attempt, and a post counts as stuck in `publishing` 50 minutes after its claim: the 20 minute claim plus 30 minutes in which a run should have taken it over.
+
+Edits and deletes are refused while a post is `publishing`, checked in the same database write, so a post is never changed or removed in the middle of being published.
diff --git a/site/content/docs/self-host/github.mdx b/site/content/docs/self-host/github.mdx
index f632a49..e4c0a47 100644
--- a/site/content/docs/self-host/github.mdx
+++ b/site/content/docs/self-host/github.mdx
@@ -20,7 +20,13 @@ Worker secrets stay in Cloudflare; the backend workflow does not need them.
## Backup scheduler
-The Worker already publishes scheduled posts. `publish-scheduled.yml` runs the same job from GitHub every 15 minutes as a safety net, with `node scripts/publish-scheduled.ts` on Node 24. The script needs no packages, so the workflow installs nothing. Each post is claimed before publishing, so it is never posted twice even when both run at once.
+The Worker already publishes scheduled posts. `publish-scheduled.yml` runs the same job from GitHub as a safety net, with `node scripts/publish-scheduled.ts` on Node 24. The script needs no packages, so the workflow installs nothing. Each post is claimed before publishing, so it is never posted twice even when both run at once, and a post whose run stopped halfway is taken over by the next run 20 minutes later.
+
+<Callout type="note" title="GitHub decides when the runs start">
+
+The workflow asks for a run every 15 minutes, at minutes 7, 22, 37 and 52 of each hour, one run at a time with a 14 minute limit. GitHub starts scheduled runs when it has capacity: its documentation says they can be delayed, most of all at the start of every hour, and that some are dropped. Twiligent's own runs have come every 3 to 5 hours. Rely on the Worker to publish within 15 minutes; this backup catches what the Worker missed, later.
+
+</Callout>
<Steps>
<Step title="Add two secrets">
@@ -42,7 +48,7 @@ Choose **Run workflow**. It worked if the run finishes with a green check and th
<Callout type="tip" title="Private forks">
-Public repositories get unlimited Actions minutes. A private fork gets 2,000 free minutes a month; change the schedule in the workflow to every 30 minutes to stay inside it.
+Public repositories get unlimited Actions minutes. A private fork gets 2,000 free minutes a month; change the schedule in `.github/workflows/publish-scheduled.yml` from `'7,22,37,52 * * * *'` to `'7,37 * * * *'`, every 30 minutes, to stay inside it.
</Callout>
diff --git a/site/content/docs/self-host/index.mdx b/site/content/docs/self-host/index.mdx
index c538e38..02b86d2 100644
--- a/site/content/docs/self-host/index.mdx
+++ b/site/content/docs/self-host/index.mdx
@@ -8,7 +8,7 @@ If you signed in to a Twiligent link someone gave you, you do not need any of th
## How the pieces fit
-Twiligent has two parts. The **frontend** is the website people sign in to, hosted on Cloudflare Pages. The **backend** is a Cloudflare Worker that talks to YouTube, Instagram and Reddit, stores data in Supabase, and publishes scheduled posts every 15 minutes. All secrets live in the backend; the frontend only holds values that are safe to be public.
+Twiligent has two parts. The **frontend** is the website people sign in to, hosted on Cloudflare Pages. The **backend** is a Cloudflare Worker that talks to YouTube, Instagram and Reddit, stores data in Supabase, and publishes scheduled posts every 15 minutes, trying again when Instagram has a passing problem. All secrets live in the backend; the frontend only holds values that are safe to be public.
The repository has a third folder, `site`, which is the project's own public website and these docs. You do not need it to run Twiligent.
diff --git a/site/content/docs/self-host/supabase.mdx b/site/content/docs/self-host/supabase.mdx
index ac1ffa5..50a50c7 100644
--- a/site/content/docs/self-host/supabase.mdx
+++ b/site/content/docs/self-host/supabase.mdx
@@ -32,8 +32,11 @@ create table scheduled_posts (
account_id text not null references accounts(id) on delete cascade,
status text not null default 'pending',
scheduled_at timestamptz not null,
+ claimed_at timestamptz,
+ attempts integer not null default 0,
data jsonb
);
+create index scheduled_posts_user_id_idx on scheduled_posts(user_id);
create index scheduled_posts_due_idx on scheduled_posts(status, scheduled_at);
create table tracked_posts (
@@ -102,6 +105,27 @@ alter table scheduled_posts enable row level security;
alter table tracked_posts enable row level security;
```
+## Upgrading an existing instance
+
+Twiligent's schedulers record when a run claimed a post (`claimed_at`) and how many times it tried (`attempts`), so a run that stops halfway is taken over and a passing problem is retried. If your `scheduled_posts` table has no `claimed_at` column, run this in the **SQL Editor** before you deploy the new version of the Worker. It is safe to run more than once:
+
+```sql
+alter table public.scheduled_posts
+ add column if not exists claimed_at timestamptz,
+ add column if not exists attempts integer not null default 0;
+
+-- posts stuck before this change have no saved container, so nothing can tell whether they went out
+update public.scheduled_posts
+set status = 'failed',
+ data = data || jsonb_build_object('error', 'Publishing was interrupted before Twiligent tracked it. Check Instagram before scheduling this post again.')
+where status = 'publishing' and claimed_at is null;
+
+create index if not exists scheduled_posts_user_id_idx on public.scheduled_posts (user_id);
+create index if not exists scheduled_posts_due_idx on public.scheduled_posts (status, scheduled_at);
+```
+
+Posts that were stuck in Publishing are marked failed with a note to check Instagram first, because nothing recorded whether they went out.
+
### Why row level security with no policies
The backend uses the secret key, which bypasses row level security, and limits every query to the signed-in user itself. Turning security on with no policies means the public publishable key, which ships in the frontend, cannot read or change any table directly. Without it, anyone holding that public key could read other members' data.
diff --git a/site/content/docs/use/publishing.mdx b/site/content/docs/use/publishing.mdx
index 373ee7a..45a2582 100644
--- a/site/content/docs/use/publishing.mdx
+++ b/site/content/docs/use/publishing.mdx
@@ -22,18 +22,18 @@ Under **When**, keep **Publish now**, or pick **Schedule** and set a date and ti
## What happens after you schedule
-The file uploads straight away. The server publishes the post within 15 minutes after the time you picked, even when your browser is closed. There is nothing for a member to set up.
+The file uploads straight away. The server publishes the post within 15 minutes after the time you picked, even when your browser is closed. If Instagram or the network has a passing problem, the server tries again on its next two runs. There is nothing for a member to set up.
| Status | Meaning |
| --- | --- |
-| **Pending** | Waiting for its time. You can edit the caption and time, or delete it. |
-| **Publishing** | The server is publishing it right now. |
+| **Pending** | Waiting for its time. You can edit the caption and time, or delete it. When it shows **Trying again on the next run**, the last attempt hit a passing problem and the Error column says which. |
+| **Publishing** | The server is publishing it right now. It cannot be edited or deleted until it finishes. |
| **Published** | Live on Instagram. |
-| **Failed** | Instagram rejected it. The Error column says why. |
+| **Failed** | Instagram rejected it, or three attempts in a row hit a problem. The Error column says why. Schedule the post again once the cause is fixed. |
-<Callout type="warning" title="Pending for more than 30 minutes past its time?">
+<Callout type="warning" title="More than 30 minutes late and not yet published?">
-The scheduler on the server is not running. Email the administrator with the time of the post. Publish shows the same warning automatically.
+A post still Pending 30 minutes after its time (or after its last attempt), or still Publishing 50 minutes after it started, means the scheduler on the server is not running. Email the administrator with the time of the post. Publish shows the same warning automatically.
</Callout>
diff --git a/site/content/docs/use/troubleshooting.mdx b/site/content/docs/use/troubleshooting.mdx
index dcd778a..e2f6c35 100644
--- a/site/content/docs/use/troubleshooting.mdx
+++ b/site/content/docs/use/troubleshooting.mdx
@@ -6,8 +6,9 @@ export const meta = { title: 'Troubleshooting', description: 'Common problems fo
| "This Instagram account is already connected" | It is already in your Accounts list. Refresh it there instead. |
| Instagram connection says the account type is wrong | Switch the Instagram account to Business or Creator, then connect again. |
| Reddit says the session cookie is invalid or expired | Remove the Reddit account and add it again with a fresh reddit_session cookie. |
-| A scheduled post stays Pending | Email the administrator. |
-| A scheduled post Failed | Read the Error column. Common causes are a file Instagram does not accept or an account whose access was removed. |
+| A scheduled post shows Trying again on the next run | Nothing to do. The last attempt hit a passing problem, and the server tries again on its next run. |
+| A scheduled post stays Pending more than 30 minutes past its time, or Publishing more than 50 minutes | Email the administrator. |
+| A scheduled post Failed | Read the Error column. Common causes are a file Instagram does not accept, an account whose access was removed, or a problem that lasted three attempts. Schedule it again once the cause is fixed. |
| Publish says Cloudinary is not set up | Only the administrator can fix this. Let them know. |
| Analytics will not load | Use Refresh on the account. If it keeps failing, contact the administrator; the platform key may be missing. |