# Faster read and reaction progress

The worker page still polls stored progress every two seconds. Gmail checks run under the existing task lease after the response is sent; workers do not wait for a long scan before receiving the page response. Small checkpoints publish real read/reaction observations while the rest of a pass is still running. Completion requires a successful, caught-up pass and fresh verification of qualifying message copies. No optimistic reading/reaction credit is generated in the browser.

The deployed server uses Apache mod_php, which lacks FPM's `fastcgi_finish_request()`. The check response now declares its exact byte length, disables Apache compression for this response and uses `Cache-Control: no-store, no-transform`. Apache HTTP/1 responses close their connection so the next poll can use another worker while the previous request finishes background work. Background checking can survive the client closing that completed response. A localhost-only, header-guarded temporary diagnostic measured a simulated three-second background job: the ordinary response took 3.08 seconds; the fixed response arrived in 0.06 seconds. The diagnostic was removed immediately. This measures response delivery, not Google propagation latency.

## Gmail synchronization

`GmailTaskSync` maintains private `inbox_tasks.gmail_sync_state` JSON. It stores a Gmail history cursor, durable queues, already-observed message history IDs, pagination state and successful-check timestamps. It does not store tokens or original message bodies. The model hides this state; worker JSON contains only aggregate progress and safe checking timestamps/flags.

During the countdown, exact RFC Message-ID searches continue for sending slots that have not been found. Already identified messages use Gmail history instead of repeated searches and metadata reads. The earliest observed message history cursor is retained, so changes occurring between discovery and synchronization can be replayed. New message events can also discover delayed arrivals or duplicate copies, after validating the exact manifest RFC ID and configured subject. New deliveries/copies cannot join the work list after the countdown cutoff.

When work begins, the received list remains frozen. Existing verified metadata and history positions are reused. Pending conversations are inspected with `threads.get(format=metadata)` to find already-existing outgoing reactions. Only matching reaction messages receive full MIME-body retrieval. This removes the old four-conversations-per-round delay. Subsequent `history.list` requests identify changed task messages and newly sent reactions; only relevant message states and candidate reaction data are fetched. Unrelated email does not count, and unrelated message bodies are never retrieved.

A full baseline is used when no safe cursor/verified metadata exists. The cursor is captured before baseline reads, so changes during that baseline are replayed. An expired history cursor (404) causes a new baseline while preserving all earlier observations and confirmed reactions. A bounded reconciliation runs every 120 seconds as a safety check.

Requests run in parallel groups of at most six. Each pass targets at most 12 seconds of work, checked between request groups; an in-flight group can take up to its eight-second timeout. Unfinished work resumes from saved queues. Initial discovery also has a bounded scan time and rotates through unreceived sending slots. Task ownership/deadline/revocation are checked at checkpoints. A separate mailbox lock prevents overlapping optimized checks for the same Gmail mailbox across tasks. Frozen-message identity rules, logical-message deduplication, private margins, manual approval/payment and legacy Gmail mode are preserved.

## Quotas and retries

`GmailBudget` charges quota units, including every member of a parallel group. Original-message discovery/countdown reads, reaction checks and work-stage synchronization share the same rolling 60-second budget when fast sync is enabled. Defaults reserve at most **3,600 units per mailbox/project** and **600,000 units per Google project** per rolling minute. These deliberately leave room below Google's currently documented standard limits for other application activity. Actual project quotas and unrelated tools still apply; this is not a guarantee that Google will never throttle a request.

Buckets and reservations use the shared Laravel cache with a project lock, so separate web and cron processes cannot independently spend the same allowance. Numeric OAuth client-ID prefixes group clients in the same Google project; mailbox keys canonicalize Gmail aliases. Cache keys use hashes. Cache/counter failures stop requests rather than allowing an uncontrolled burst.

Quota costs use the current conservative Gmail method table: profile 1, history 2, message search 5, message metadata 20, thread metadata 40, reaction full message 60 and attachment 20. Reducing response fields reduces payload size but does not reduce the method's quota charge.

Local budget pauses retain progress and schedule a retry without reporting lost access or worker misconduct. Google's 429 and quota-related 403 responses honor Retry-After, share the appropriate cooldown, and use increasing retry delays with jitter. Other API/access errors remain checking-unavailable events. Backoff does not postpone closing an unfinished task at its deadline. Pending queues and confirmed evidence survive failures, including failed reaction attachment retrieval.

These counters cover this integration's instrumented Gmail calls, not all traffic from independent applications using the same Google project. Keep configured budgets below any lower custom quota. Do not raise limits just to make the UI look faster.

## Worker feedback

Read-in-Inbox and thumbs-up counters now appear before the longer instructions, each with a small progress bar. Newly confirmed steps produce a short feedback message and highlight. A status dot and relative check time explain automatic updates, catch-up, scheduled pauses and final verification. Stored counters remain visible during network failures. Repeated identical updates do not rebuild the message grid or repeat the reaction prompt in live regions. The browser slows retries if the application's own endpoint returns 429.

## Deployment and verification

Apply only `2026_10_19_000005_add_gmail_sync_state_to_inbox_tasks.php`; it adds one nullable JSON column, with no data backfill or task-policy changes. `INBOX_GMAIL_FAST_SYNC` controls the optimization; disabling it restores the original task-check path, keeping stored evidence and completion rules. The default is enabled after verification. No queue service or new dependencies are required.

Synthetic HTTP tests confirm:

- An unchanged 24-message work-phase pass uses **1 Gmail history request**, versus **28** requests in the previous checker (24 message reads + 4 conversation reads).
- A nonterminal read-plus-reaction change for one of those messages uses **4** reads: history, original state, reaction headers and reaction JSON.
- The optimized countdown uses one Gmail history read when all messages have been found; the Cortex manifest request is separate.
- All 24 pre-existing reactions can be detected in one bounded pass under normal simulated responses, with fresh checks before completion.
- Partial API failures, expired history, pagination, attachment failures, mailbox locks and rolling quota pauses preserve progress and never auto-approve payment.

These are request-count/behavior tests, not a measurement of real Google propagation latency. Real timing also depends on Google's availability, network latency, worker activity and current quota usage. No live campaign sends are needed to verify this change.

References:
- https://developers.google.com/workspace/gmail/api/guides/sync
- https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.history/list
- https://developers.google.com/workspace/gmail/api/reference/quota
