Skip to content

feat(cloud): native push gateway and dedicated infrastructure (1/3) - #19912

Merged
Jinwoo-H merged 5 commits into
mainfrom
feat/mobile-push-cloud
Sep 10, 2026
Merged

Jinwoo-H merged 5 commits into
mainfrom
feat/mobile-push-cloud

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 38 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4531 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4529
Prod 76 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4989 $\color{#cf222e}{\Huge{\mathbf{−}}}$​140 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4849

ELI5

Adds the server that accepts a notification from a paired desktop and delivers it through Apple or Google, with a durable queue so accepted work survives restarts. This is the cloud layer of the mobile-push split; desktop and mobile integration follow separately.

What Changed

Three commits provide the review order:

  1. Extract PostgreSQL schema startup into a cloud package and update Relay's dependency/Docker packaging.
  2. Add the native push gateway: host proof, device registration, separate 300-alert/300-dismissal quotas per 15 minutes, per-recipient idempotency, five-minute delivery expiry, APNs/FCM adapters and tests.
  3. Define dedicated push SQL/Cloud Run/IAM resources and add deployment/recovery checks and operational docs.

No desktop/mobile source or cross-client design document is included. The push deployment workflow is already on main. Existing mainline identity/census changes are preserved.

Why

The existing mobile socket path cannot provide notifications when the app is closed. The gateway supplies the backend independently of the client changes. Shared schema startup preserves the existing Relay implementation rather than introducing a second copy.

Linked Issue

Split from #19204, which remains the complete reference PR. This is PR 1 of the planned cloud → desktop → mobile sequence.

Visual Proof

N/A — backend and infrastructure only; no user interface changes in this PR.

Testing

  • Automated tests added/updated.
  • Local macOS: frozen cloud install, full cloud build/typecheck and full pnpm test passed: 1,677 tests, including 140 push tests and 632 Relay tests with isolated PostgreSQL 16 on port 55440. Shared-PostgreSQL Relay tests use the existing serialized project; push tests retain normal parallelism.
  • Linux/amd64: both push and Relay Docker images built successfully.
  • Terraform formatting and validation passed; validation reported zero warnings/errors.
  • Read-only production plan reviewed. Do not apply it wholesale: it includes six legacy shared-store push resource deletions plus unrelated root drift. Existing-resource ownership cleanup is documented in cloud/docs/push-database-cutover.md; it must be resolved separately before an infrastructure apply. No Terraform apply or production deployment occurred for this split.
  • Final census deduplication passed the focused workflow/rollout-lock tests. Test database removed and local container restored stopped. Client/device acceptance belongs to later PRs.

Review

Code/protocol matches the reviewed cloud portion of 8eea3ee9d5, apart from preserving newer mainline changes, removing omitted-document references and correcting stale comments. Start with the three commits above. Runtime queue/claim/retry behavior was not redesigned during extraction.

Agent skill upstream boundary

  • Not applicable; no upstream skill-installer implementation copied.

Checklist

  • Small diff — this remains a substantial service addition (about half the added lines are tests); scope is cloud only.
  • Explained behavior and review order.
  • N/A visual proof with reason.
  • Self-reviewed scope, dependencies and source equivalence.
  • Cross-platform and independently updated client boundaries considered.
  • Cloud build, typecheck and tests passed locally; hosted CI passed before this follow-up; new HEAD checks pending.

Review follow-up

Adds a 6,000-request/minute per-instance IP budget across authenticated routes so rotating host keys cannot reset all admission limits. Existing 600/minute host and 300-alert/300-dismissal per-15-minute event limits remain. This budget is shared behind NAT and is not a global spending cap.

Replaces full-map rate-limiter scans/sorts with Map-order eviction, removes the unused cross-project FCM override and gateway/project defaults, reuses the enforced device cap for list queries, and corrects dead-token guidance. Standalone startup now requires an explicit FCM project; Terraform already supplies the deployment project. No database migration or deployment in this follow-up.

Diff size

Added/deleted diff lines, including comments and blank lines:

Category Added Deleted
Tests, test fixtures and test configuration 4,951 2
Runtime and tooling code 2,847 121
Infrastructure, configuration and lockfile 1,081 11
Operational documentation 574 7
Total 9,453 141

@Jinwoo-H
Jinwoo-H marked this pull request as ready for review September 10, 2026 18:55
@greptile-apps

greptile-apps Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Too many files changed for review (114 files, 100 file limit).

Bypass the limit by tagging @greptile-apps to review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — one minor observation inline.

Reviewed changes

  • Shared PostgreSQL schema startup — extracted the applyPostgresSchema retry/collision helper into @orca-cloud/postgres-schema and rewired Relay's package.json/Dockerfile to consume it; behavior-preserving apart from the new eventPrefix option.
  • Durable push gateway (cloud/apps/push + packages/push-contract) — X25519 host-proof authentication, device registry with per-host caps, 300/15-min alert-and-dismissal quotas, per-recipient idempotency, a lease/claim/retry delivery queue, and APNs/FCM adapters with dead-token retirement.
  • Dedicated infrastructure — Terraform for the Cloud SQL instance, Cloud Run service, IAM/deploy identity and secrets backing the gateway, plus a Cloud Run deploy/recovery model, workflow/recovery/validation checks, and operational docs.

The host-proof protocol, the challenge-consume compare-and-swap, and the session-token hashing are sound against a database-only read attacker and replay; the claim/lease/finish fencing gives correct at-least-once delivery with on-device collapse dedupe. Test coverage is extensive (137 push tests) and the assertions pin real behavior rather than pass-through snapshots.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

return { ok: true, registrationId }
}
const [countRow] = await transaction.query(
'SELECT COUNT(*) AS devices FROM push_devices WHERE host_fingerprint = ?',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This COUNT(*) includes rows already marked dead (dead_at IS NOT NULL) alongside live ones, and nothing in the gateway ever reaps a retired row — markDead only sets the flag. A device that re-registers with a new deviceId (rather than reusing the old one, which upsert would revive) creates a new row that permanently consumes maxDevicesPerHost, so a long-lived host's churn can eventually make a fresh registration return too_many_devices until the Part-2 desktop issues deleteOwned. Worth either excluding dead from the count or documenting/automating dead-row retirement.

@coderabbitai

coderabbitai Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: fecc8b5c-49fc-485a-bfd8-85020430b14a

📥 Commits

Reviewing files that changed from the base of the PR and between 5d83cae and 63b8eee.

📒 Files selected for processing (7)
  • .github/workflows/cloud-push-deploy.yml
  • cloud/apps/push/src/apns-client.test.ts
  • cloud/apps/push/src/apns-client.ts
  • cloud/apps/push/src/apns-topic-recovery.test.ts
  • cloud/apps/push/src/push-deploy-preflight.test.ts
  • cloud/docs/push-gateway.md
  • cloud/packages/push-contract/src/contract.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • cloud/docs/push-gateway.md

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

Adds a mobile push gateway with host authentication, device registration, APNs and FCM delivery, durable queues, retries, quotas, dismissal handling, readiness checks, and graceful shutdown. Adds push contracts, PostgreSQL schema support, Cloud Run and Cloud SQL infrastructure, deployment identities, rollout and recovery tests, production configuration, and operational documentation.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 63b8e

This update to the mobile push gateway adds deployment validation for the FCM project id and hardens APNs topic-error handling so device registrations are preserved and notifications are retried instead of lost, which is a safe and well-tested improvement. However, several previously identified issues in the broader push gateway still remain unresolved, including FCM's collapse-key behavior potentially replacing unrelated pending alerts and an inconsistency in how the delivery worker labels expired-before-first-send notifications. Because no Terraform apply or production deployment has occurred yet, these do not block continued development, but they should be resolved before the gateway is deployed to production.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.49% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 69 functions across 57 files. (2 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description follows the required template and covers the change, rationale, linked issue (#19204), testing, visual proof, review notes, scope, and checklist. It also clearly documents deployment l…
Title check ✅ Passed The title clearly identifies the main changes: the native cloud push gateway and dedicated infrastructure. The “1/3” suffix accurately indicates the planned split sequence without obscuring the primar…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 14.49% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 69 functions across 57 files. (2 skipped: 2 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🧹 Nitpick comments (4)
cloud/dev/scripts/push-gateway-workflow.test.mjs (1)

109-109: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Bound the variable-block match so the default assertion cannot match a different variable.

Both patterns use [\s\S]*?, which crosses block boundaries. If push_min_instances loses its default = 1, the lazy match can still succeed against a default = 1 in any later variable block in variables.tf. The same applies to push_database_pool_max. The assertion then passes while the guarantee is gone.

Restrict the span to the variable block body.

♻️ Proposed fix
-  assert.match(terraform('variables.tf'), /variable "push_min_instances"[\s\S]*?default {5}= 1/)
+  assert.match(terraform('variables.tf'), /variable "push_min_instances" \{[^}]*?default {5}= 1/)
-  assert.match(terraform('variables.tf'), /variable "push_database_pool_max"[\s\S]*?default {5}= 2/)
+  assert.match(terraform('variables.tf'), /variable "push_database_pool_max" \{[^}]*?default {5}= 2/)

Also applies to: 136-136

cloud/apps/push/src/durable-push-store.test.ts (1)

169-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

This concurrent-connection assertion queries a different schema than the renamed table.

The fixture scopes db to a per-test schema by adding options=-c search_path=<schema> to the URL (lines 45-47). Line 170 opens concurrent with the raw databaseUrl and no options parameter, so it resolves push_delivery_batches in the default search_path, not in the test schema. The rename at line 165 applies only to the test schema.

The assertion therefore passes because it reads an unrelated copy of the table, not because the rename is isolated from other connections. It also depends on openPushDatabase having created those tables in the default schema as a side effect.

Either scope the concurrent connection to the same schema so the assertion tests what it describes, or remove the block. The surrounding rollback assertions at lines 179-181 already carry the value of this test.

cloud/apps/push/src/push-delivery-payload.ts (1)

3-8: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Validate the decoded payload with PushNotificationSchema instead of casting.

The parser accepts any non-array object and casts it to PushNotification. PushNotificationSchema validates required fields, rejects unknown fields, and enforces the contract refinements. Reuse it when reading payload_json so malformed persisted data cannot reach delivery code.

♻️ Proposed refactor
-import type { PushNotification } from '`@orca-cloud/push-contract`'
+import { PushNotificationSchema, type PushNotification } from '`@orca-cloud/push-contract`'
 
 export function parsePushDeliveryPayload(payload: string): PushNotification {
-  const value: unknown = JSON.parse(payload)
-  if (!value || typeof value !== 'object' || Array.isArray(value))
-    throw new Error('invalid_push_delivery_payload')
-  return value as PushNotification
+  const parsed = PushNotificationSchema.safeParse(JSON.parse(payload))
+  if (!parsed.success) throw new Error('invalid_push_delivery_payload')
+  return parsed.data
 }
cloud/apps/push/src/push-queued-dismissal.ts (1)

18-19: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Avoid the unused dismissal lookup.

When notification.kind === 'dismiss', reconcileQueuedDismissal performs the SELECT but never uses dismissed before the upsert. Move the lookup into the alert branch and share it with isDismissedAlert.

♻️ Proposed refactor to share the watermark lookup
+async function dismissedSeq(
+  tx: PushDatabase,
+  host: string,
+  notification: PushNotification
+): Promise<number> {
+  const [dismissed] = await tx.query(
+    'SELECT notification_seq FROM push_dismissed_events WHERE host_fingerprint = ? AND notification_epoch = ? AND notification_id = ?',
+    [host, notification.notificationEpoch, notification.notificationId]
+  )
+  return Number(dismissed?.notification_seq ?? -1)
+}
+
 export async function reconcileQueuedDismissal(
   tx: PushDatabase,
   host: string,
   registrationId: string,
   notification: PushNotification,
   now: number
 ): Promise<boolean> {
   if (!notification.notificationId) return false
   const key = [host, notification.notificationEpoch, notification.notificationId]
-  const [dismissed] = await tx.query(
-    'SELECT notification_seq FROM push_dismissed_events WHERE host_fingerprint = ? AND notification_epoch = ? AND notification_id = ?',
-    key
-  )
   if (notification.kind !== 'dismiss')
-    return Number(dismissed?.notification_seq ?? -1) >= notification.notificationSeq
+    return (await dismissedSeq(tx, host, notification)) >= notification.notificationSeq
 export async function isDismissedAlert(
   tx: PushDatabase,
   host: string,
   notification: PushNotification
 ): Promise<boolean> {
   if (notification.kind === 'dismiss' || !notification.notificationId) return false
-  const rows = await tx.query(
-    'SELECT notification_seq FROM push_dismissed_events WHERE host_fingerprint = ? AND notification_epoch = ? AND notification_id = ?',
-    [host, notification.notificationEpoch, notification.notificationId]
-  )
-  return Number(rows[0]?.notification_seq ?? -1) >= notification.notificationSeq
+  return (await dismissedSeq(tx, host, notification)) >= notification.notificationSeq
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 189ed032-8d9b-44bb-9aef-5ac57eb2825b

📥 Commits

Reviewing files that changed from the base of the PR and between 26f9fd8 and 1c4ca23.

⛔ Files ignored due to path filters (1)
  • cloud/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (109)
  • .github/workflows/cloud-verify.yml
  • cloud/README.md
  • cloud/apps/push/Dockerfile
  • cloud/apps/push/package.json
  • cloud/apps/push/src/apns-authentication-token.ts
  • cloud/apps/push/src/apns-client.test.ts
  • cloud/apps/push/src/apns-client.ts
  • cloud/apps/push/src/apns-http2-transport.ts
  • cloud/apps/push/src/apns-session-replacement.test.ts
  • cloud/apps/push/src/apns-stream-response.test.ts
  • cloud/apps/push/src/apns-stream-response.ts
  • cloud/apps/push/src/canonical-base64.ts
  • cloud/apps/push/src/client-ip-rate-limit.test.ts
  • cloud/apps/push/src/client-ip-rate-limit.ts
  • cloud/apps/push/src/config.test.ts
  • cloud/apps/push/src/config.ts
  • cloud/apps/push/src/desktop-host-proof-interop.test.ts
  • cloud/apps/push/src/device-registration-delete-race.test.ts
  • cloud/apps/push/src/device-registry-store.test.ts
  • cloud/apps/push/src/device-registry-store.ts
  • cloud/apps/push/src/durable-push-schema.ts
  • cloud/apps/push/src/durable-push-store.test.ts
  • cloud/apps/push/src/durable-push-store.ts
  • cloud/apps/push/src/durable-push-worker.test.ts
  • cloud/apps/push/src/durable-push-worker.ts
  • cloud/apps/push/src/fcm-access-token.ts
  • cloud/apps/push/src/fcm-client.test.ts
  • cloud/apps/push/src/fcm-client.ts
  • cloud/apps/push/src/host-challenge-answering.test-fixture.ts
  • cloud/apps/push/src/host-challenge-store.test.ts
  • cloud/apps/push/src/host-challenge-store.ts
  • cloud/apps/push/src/host-fingerprint.ts
  • cloud/apps/push/src/host-proof-concurrency.test.ts
  • cloud/apps/push/src/host-session-store.test.ts
  • cloud/apps/push/src/host-session-store.ts
  • cloud/apps/push/src/index.ts
  • cloud/apps/push/src/provider-retry-delay.ts
  • cloud/apps/push/src/push-auth-admission.ts
  • cloud/apps/push/src/push-background.ts
  • cloud/apps/push/src/push-database-postgres-startup.test.ts
  • cloud/apps/push/src/push-database.ts
  • cloud/apps/push/src/push-delivery-lifecycle.test.ts
  • cloud/apps/push/src/push-delivery-message.ts
  • cloud/apps/push/src/push-delivery-payload.ts
  • cloud/apps/push/src/push-dismissal-provider.test.ts
  • cloud/apps/push/src/push-dispatcher.ts
  • cloud/apps/push/src/push-notification-sound.test.ts
  • cloud/apps/push/src/push-observability.ts
  • cloud/apps/push/src/push-provider-outcome.ts
  • cloud/apps/push/src/push-queued-dismissal.ts
  • cloud/apps/push/src/push-readiness.test.ts
  • cloud/apps/push/src/push-readiness.ts
  • cloud/apps/push/src/push-request-drain.ts
  • cloud/apps/push/src/push-schema.ts
  • cloud/apps/push/src/push-send-idempotency.test.ts
  • cloud/apps/push/src/push-server-auth.test.ts
  • cloud/apps/push/src/push-server-harness.test-fixture.ts
  • cloud/apps/push/src/push-server-limits.test.ts
  • cloud/apps/push/src/push-server-send.test.ts
  • cloud/apps/push/src/push-server.ts
  • cloud/apps/push/src/push-session-concurrency.test.ts
  • cloud/apps/push/src/push-validation.test.ts
  • cloud/apps/push/tsconfig.build.json
  • cloud/apps/push/tsconfig.json
  • cloud/apps/push/vitest.config.ts
  • cloud/apps/relay/Dockerfile
  • cloud/apps/relay/package.json
  • cloud/apps/relay/src/postgres-schema-startup.ts
  • cloud/dev/fixtures/terraform-root-partition/families.json
  • cloud/dev/scripts/push-cloud-run-model.mjs
  • cloud/dev/scripts/push-gateway-recovery.test.mjs
  • cloud/dev/scripts/push-gateway-workflow.test.mjs
  • cloud/dev/scripts/push-validation-workflow.test.mjs
  • cloud/dev/scripts/relay-cloud-sql-connection-budget.test.mjs
  • cloud/dev/scripts/render-workload-identity-conditions.mjs
  • cloud/dev/scripts/workload-identity-attribute-conditions.test.mjs
  • cloud/docs/push-database-cutover.md
  • cloud/docs/push-gateway.md
  • cloud/docs/relay-workflows.md
  • cloud/infra/terraform/environments/production.tfvars
  • cloud/infra/terraform/environments/staging.tfvars
  • cloud/infra/terraform/outputs.tf
  • cloud/infra/terraform/push-dedicated-database.tf
  • cloud/infra/terraform/push-deploy-identity.tf
  • cloud/infra/terraform/push-gateway.tf
  • cloud/infra/terraform/relay-github-actions.tf
  • cloud/infra/terraform/relay-github-workflow-trust.tf
  • cloud/infra/terraform/variables.tf
  • cloud/package.json
  • cloud/packages/postgres-schema/package.json
  • cloud/packages/postgres-schema/src/index.ts
  • cloud/packages/postgres-schema/tsconfig.build.json
  • cloud/packages/postgres-schema/tsconfig.json
  • cloud/packages/push-contract/package.json
  • cloud/packages/push-contract/src/apns-token-length.test.ts
  • cloud/packages/push-contract/src/contract.test.ts
  • cloud/packages/push-contract/src/device-registration-messages.ts
  • cloud/packages/push-contract/src/host-auth-messages.ts
  • cloud/packages/push-contract/src/index.ts
  • cloud/packages/push-contract/src/notification-identity-limits.test.ts
  • cloud/packages/push-contract/src/push-host-proof-transcript.test.ts
  • cloud/packages/push-contract/src/push-host-proof-transcript.ts
  • cloud/packages/push-contract/src/push-host-proof-vector.json
  • cloud/packages/push-contract/src/push-limits.ts
  • cloud/packages/push-contract/src/send-messages.test.ts
  • cloud/packages/push-contract/src/send-messages.ts
  • cloud/packages/push-contract/src/wire-scalars.ts
  • cloud/packages/push-contract/tsconfig.build.json
  • cloud/packages/push-contract/tsconfig.json

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Comment on lines +56 to +59
if ((this.options.now ?? Date.now)() >= queued.expiresAt) {
await this.store.finish(queued)
continue
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Preserve expired for deliveries that expire before dispatch.

When a claimed delivery expires before drain dispatches it, finish(queued) writes the default done outcome. The expiry pruner writes expired for the same terminal condition, and push_delivery_batches retains delivery outcomes. This loses the expiry reason from the durable row, even though recovery and observability do not currently branch on it.

🐛 Proposed fix
       if ((this.options.now ?? Date.now)() >= queued.expiresAt) {
-        await this.store.finish(queued)
+        await this.store.finish(queued, undefined, 'expired')
         continue
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if ((this.options.now ?? Date.now)() >= queued.expiresAt) {
await this.store.finish(queued)
continue
}
if ((this.options.now ?? Date.now)() >= queued.expiresAt) {
await this.store.finish(queued, undefined, 'expired')
continue
}

Comment on lines +42 to +44
...(delivery.orca.kind === 'dismiss'
? {}
: { notification: { title: delivery.title, body: delivery.body } }),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- target file ---'
sed -n '1,130p' cloud/apps/push/src/fcm-client.ts
printf '%s\n' '--- related FCM symbols and tests ---'
rg -n -C 3 --glob '!node_modules' --glob '!dist' 'collapse_key|notification:|orca.kind|fcm-client|send' cloud/apps/push

Repository: stablyai/orca

Length of output: 50369


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 7707


🌐 Web query:

site:firebase.google.com/docs/cloud-messaging collapse_key notification messages HTTP v1 AndroidConfig collapse_key

💡 Result:

In Firebase Cloud Messaging (FCM) HTTP v1, the collapse_key is a parameter used to group messages so that only the latest message is delivered when the device is offline or restricted [1][2]. Key details regarding the use of collapse_key within AndroidConfig: 1. Functionality: When you set a collapse_key for a message, FCM identifies messages with the same key and the same registration token. If the device is offline or in a restricted state (e.g., Doze mode), FCM will store only the most recent message for that specific collapse_key, discarding any older pending messages [2][3]. 2. Default Behavior: If no collapse_key is provided, all messages are treated as non-collapsible (unless they are notification messages) and will be queued individually for delivery [1]. 3. Notification Messages: Notification messages are always considered collapsible by default [1][4]. Consequently, they ignore the collapse_key parameter entirely; FCM handles them according to its internal notification collapsing logic [1]. 4. Capacity: FCM can store up to four different collapsible messages per device simultaneously, each with a unique collapse_key [1]. If more than four unique keys are sent, FCM does not guarantee which keys will be retained [1]. To implement this in the HTTP v1 API, you include the collapseKey field within the android block of your message payload [1]. Example structure: { "message": { "token": "YOUR_DEVICE_TOKEN", "android": { "collapseKey": "your_collapse_key_string" } } }

Citations:


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- burst behavior test ---'
sed -n '118,188p' cloud/apps/push/src/push-server-send.test.ts
printf '%s\n' '--- delivery construction and collapse identity ---'
sed -n '1,240p' cloud/apps/push/src/push-delivery-message.ts
printf '%s\n' '--- FCM transport remainder ---'
sed -n '120,220p' cloud/apps/push/src/fcm-client.ts

Repository: stablyai/orca

Length of output: 6246


Do not rely on android.collapse_key for notification messages.

For non-dismiss deliveries, fcmMessageBody sends a top-level notification and sets android.collapse_key from delivery.collapseId. FCM treats these as collapsible notification messages and ignores the supplied collapse key. A newer alert may therefore replace a pending alert with a different notification identity.

If each identity requires its own collapse group, use a data-only message with client-side display handling. Otherwise, document and test the intended global collapse behavior.

Comment on lines +34 to +40
expect(results.filter((result) => result.ok)).toEqual([
{ ok: true, hostFingerprint: challenges[0]!.hostFingerprint },
{ ok: true, hostFingerprint: challenges[0]!.hostFingerprint }
])
expect(results.filter((result) => !result.ok)).toEqual(
Array.from({ length: 8 }, () => ({ ok: false, reason: 'already_consumed' }))
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert one successful proof for each challenge.

These assertions check only the aggregate result counts. Both challenges have the same hostFingerprint. A regression can accept one challenge twice and reject the other challenge, while this test still passes.

Assert the results for each five-call challenge group separately.

Proposed test change
-    expect(results.filter((result) => result.ok)).toEqual([
-      { ok: true, hostFingerprint: challenges[0]!.hostFingerprint },
-      { ok: true, hostFingerprint: challenges[0]!.hostFingerprint }
-    ])
-    expect(results.filter((result) => !result.ok)).toEqual(
-      Array.from({ length: 8 }, () => ({ ok: false, reason: 'already_consumed' }))
-    )
+    for (const [index, challenge] of challenges.entries()) {
+      const challengeResults = results.slice(index * 5, index * 5 + 5)
+      expect(challengeResults.filter((result) => result.ok)).toEqual([
+        { ok: true, hostFingerprint: challenge!.hostFingerprint }
+      ])
+      expect(challengeResults.filter((result) => !result.ok)).toEqual(
+        Array.from({ length: 4 }, () => ({ ok: false, reason: 'already_consumed' }))
+      )
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
expect(results.filter((result) => result.ok)).toEqual([
{ ok: true, hostFingerprint: challenges[0]!.hostFingerprint },
{ ok: true, hostFingerprint: challenges[0]!.hostFingerprint }
])
expect(results.filter((result) => !result.ok)).toEqual(
Array.from({ length: 8 }, () => ({ ok: false, reason: 'already_consumed' }))
)
for (const [index, challenge] of challenges.entries()) {
const challengeResults = results.slice(index * 5, index * 5 + 5)
expect(challengeResults.filter((result) => result.ok)).toEqual([
{ ok: true, hostFingerprint: challenge!.hostFingerprint }
])
expect(challengeResults.filter((result) => !result.ok)).toEqual(
Array.from({ length: 4 }, () => ({ ok: false, reason: 'already_consumed' }))
)
}


async function check(): Promise<boolean> {
try {
await database.query('SELECT 1 AS ready')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="$(fd -a '^push-database\.ts$' . | head -n1)"
test -n "$file"

ast-grep outline "$file" --items all --type function,class
rg -n -C5 'query_timeout|statement_timeout|connectionTimeoutMillis|query\s*\(' "$file"

Repository: stablyai/orca

Length of output: 7675


🏁 Script executed:

#!/bin/bash
set -euo pipefail

readiness="$(fd -a '^push-readiness\.ts$' . | head -n1)"
database="$(fd -a '^push-database\.ts$' . | head -n1)"
test -n "$readiness"
test -n "$database"

cat -n "$readiness"
sed -n '1,180p' "$database"

Repository: stablyai/orca

Length of output: 7866


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C3 '"pg"|"node-postgres"|query_timeout|statement_timeout|connectionTimeoutMillis' \
  --glob 'package.json' --glob 'pnpm-lock.yaml' --glob 'package-lock.json' --glob 'yarn.lock' .

Repository: stablyai/orca

Length of output: 1039


🌐 Web query:

node-postgres pg 8.22.0 query_timeout statement_timeout connectionTimeoutMillis official documentation

💡 Result:

In node-postgres version 8.22.0, these settings are part of the client configuration object used when initializing a Client or a Pool [1][2]. They are defined in milliseconds and default to no timeout if not specified [1][2]. 1. statement_timeout: This is passed to the PostgreSQL server. It specifies the maximum duration a statement is allowed to run before the database aborts it and returns an error [1][2][3]. 2. query_timeout: This is handled by the node-postgres driver itself. It specifies how long the client will wait for a response from the server after sending a query. If this timeout is reached, the driver stops listening for a response, but the database may continue executing the query [1][2][3]. 3. connectionTimeoutMillis: This specifies the maximum number of milliseconds to wait for a new connection to be established with the database before failing [1][2]. For robust error handling, it is often recommended to configure both statement_timeout and query_timeout, with the query_timeout set slightly longer than the statement_timeout to allow the database sufficient time to process and return its own timeout error [4][3].

Citations:


Add a client-side query timeout. statement_timeout is enforced by PostgreSQL, and connectionTimeoutMillis only bounds new connections. Neither bounds an established client.query() during a network failure. A stalled query leaves pending set, so later /ready requests wait on the same promise. Configure query_timeout on the serving pool.

Comment on lines +142 to +144
if (!invalidBearerIps.available(ip)) return null
const result = await sessions.resolve(bearer)
if (!result.ok) invalidBearerIps.allow(ip)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🛡️ Analyzed with Security Review | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="$(fd -a '^push-auth-admission\.ts$' . | head -n1)"
test -n "$file"

ast-grep outline "$file" --items all --type class,function
sed -n '1,240p' "$file"

rg -n -C8 \
  'invalidBearerIps|PushAuthAdmission|sessions\.resolve|parallel|concurr|invalid_token' \
  cloud/apps/push/src

Repository: stablyai/orca

Length of output: 27955


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="$(fd -a '^client-ip-rate-limit\.ts$' cloud/apps/push/src | head -n1)"
test -n "$file"
cat -n "$file"

rg -n -C5 'invalidBearerIps|invalidBearer|authAdmission|PushAuthAdmission' \
  cloud/apps/push/src --glob '*.test.ts' --glob '*.ts'

Repository: stablyai/orca

Length of output: 8775


Denial of Service

Reachability: External
Exploitability: Moderate
CWE: CWE-770 — Allocation of Resources Without Limits or Throttling

Make invalid-bearer admission atomic per IP.

PushAuthAdmission permits four concurrent callbacks, while available() does not reserve a token. Parallel invalid bearer requests can start multiple sessions.resolve() calls before invalidBearerIps.allow(ip) consumes tokens. Reserve the token before the lookup and release it only for valid sessions, or serialize these callbacks.

const end = workflow.indexOf('\n - ', start + 1)
const block = workflow.slice(start, end === -1 ? undefined : end)
return block
.slice(block.indexOf(' run: |\n') + ' run: |\n'.length)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that the step declares run: | before slicing.

If a step loses run: |, step() still extracts the indented body lines. run() can therefore execute the script, and the recovery test can pass without enforcing the workflow contract.

♻️ Proposed fix
+  const marker = '        run: |\n'
+  const offset = block.indexOf(marker)
+  assert.notEqual(offset, -1, `the "${name}" step no longer declares a run block`)
   return block
-    .slice(block.indexOf('        run: |\n') + '        run: |\n'.length)
+    .slice(offset + marker.length)

assert.match(workflow.slice(deploy, activation), /\.mode == "validation"/)
assert.ok(position('Prove the runtime identity can reach FCM') < activation)
const active = workflow.slice(activation, shift)
assert.ok(active.indexOf('gcloud run deploy') < active.indexOf('gcloud run revisions delete'))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert presence before comparing positions, or the ordering checks can pass vacuously.

String.prototype.indexOf returns -1 when the needle is absent. On Line 39, if ACTIVATION_ATTEMPTED=true is deleted from the workflow, the comparison becomes -1 < <index of deploy>, which is true, and the test still passes. The marker that gates rollback then loses its only assertion here. Line 33 has the same shape for gcloud run deploy.

Use the existing position-style guard, or assert the substring exists first.

♻️ Proposed fix
+  const at = (haystack, needle) => {
+    const index = haystack.indexOf(needle)
+    assert.notEqual(index, -1, `the activation step no longer contains "${needle}"`)
+    return index
+  }
-  assert.ok(active.indexOf('gcloud run deploy') < active.indexOf('gcloud run revisions delete'))
+  assert.ok(at(active, 'gcloud run deploy') < at(active, 'gcloud run revisions delete'))
@@
-  assert.ok(active.indexOf('ACTIVATION_ATTEMPTED=true') < active.indexOf('gcloud run deploy'))
+  assert.ok(at(active, 'ACTIVATION_ATTEMPTED=true') < at(active, 'gcloud run deploy'))

Also applies to: 39-39

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this follow-up commit — one prior minor observation remains open.

Reviewed changes

  • Cross-host admission budget — added a shared 6,000 req/min per-instance client-IP rate limit to the authenticated /v1/devices* and /v1/send routes so generating fresh host keys can't reset admission, and rewrote the limiter's eviction from a full-map scan/sort to Map-insertion-order LRU eviction with a test pinning that no full-map iteration occurs.
  • Fail-closed FCM project — ORCA_PUSH_FCM_PROJECT_ID is now required instead of silently defaulting to a hardcoded project; Terraform supplies var.project_id and the unused push_fcm_project_id override plus the gateway/FCM defaults were removed.
  • Device list bounded by host cap — the list query now reuses maxDevicesPerHost and drops the redundant maxDevicesPerListResponse.

The new push-authenticated-ip-limit.test.ts asserts real behavior (exact 6,000/600 exhaustion, key-rotation can't reset the budget, per-IP isolation, window refill) rather than pass-through snapshots, and the LRU rewrite keeps the map bounded on every call including denials.

ℹ️ Prior observation still open

The earlier dead-device-cap note (device-registry-store.upsert counts dead_at IS NOT NULL rows toward maxDevicesPerHost, with no automatic reap until Part 2's deleteOwned) is unchanged by these commits and stays an open thread. Left unresolved intentionally — it's a defer-able, non-blocking note aligned with the Part 2 sequence, not a regression introduced here.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 799ef3dc-e4ec-4c18-8d52-be28fbc3694a

📥 Commits

Reviewing files that changed from the base of the PR and between 1c4ca23 and 5d83cae.

📒 Files selected for processing (15)
  • cloud/README.md
  • cloud/apps/push/src/client-ip-rate-limit.test.ts
  • cloud/apps/push/src/client-ip-rate-limit.ts
  • cloud/apps/push/src/config.test.ts
  • cloud/apps/push/src/config.ts
  • cloud/apps/push/src/device-registry-store.test.ts
  • cloud/apps/push/src/device-registry-store.ts
  • cloud/apps/push/src/push-authenticated-ip-limit.test.ts
  • cloud/apps/push/src/push-server.ts
  • cloud/apps/push/src/push-validation.test.ts
  • cloud/docs/push-gateway.md
  • cloud/infra/terraform/push-gateway.tf
  • cloud/infra/terraform/variables.tf
  • cloud/packages/push-contract/src/contract.test.ts
  • cloud/packages/push-contract/src/push-limits.ts
💤 Files with no reviewable changes (2)
  • cloud/infra/terraform/variables.tf
  • cloud/packages/push-contract/src/contract.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • cloud/apps/push/src/device-registry-store.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.

const limiter = new ClientIpRateLimiter({ capacity: 1, maxTrackedIps: 2, now: () => 1_000 })
limiter.allow('old')
limiter.allow('recent')
expect(limiter.allow('old')).toBe(false)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that a denied allow() refreshes LRU recency.

ClientIpRateLimiter.allow reinserts the bucket even when it denies the request. Keep allow('old'); it makes old most recent, so new must evict recent.

Proposed fix
-    expect(limiter.available('old')).toBe(false)
-    expect(limiter.available('recent')).toBe(true)
+    expect(limiter.available('old')).toBe(true)
+    expect(limiter.available('recent')).toBe(false)

Comment thread cloud/README.md Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this follow-up commit — the prior dead-device-cap observation remains open and unchanged.

Reviewed changes

  • APNs topic-error handling — DeviceTokenNotForTopic no longer retires a device registration; it is now classified as a non-retryable provider error, so correcting the topic or environment resumes delivery without re-registering the phone, pinned by the new apns-topic-recovery.test.ts.
  • Deploy preflight pin — the inert-validation preflight in .github/workflows/cloud-push-deploy.yml now supplies the required ORCA_PUSH_FCM_PROJECT_ID, and a new push-deploy-preflight.test.ts executes that exact workflow script against the real loadPushConfig loader.
  • Contract default lock — contract.test.ts now asserts authenticatedRequestsPerMinutePerIp: 6_000 alongside the other normative limits.

The DeviceTokenNotForTopic reclassification matches Apple's semantics (a topic/environment mismatch, not a dead token) and is a strict improvement: retiring the device on a config error was destructive, while the new behavior drops only the affected notification (five-minute TTL) and keeps the registration live. The deploy-preflight test can genuinely fail — it fails closed if the required FCM project or the validation-mode rejection regresses — and the topic-recovery test asserts the real apnsRequests count and delivery_sent counter rather than a pass-through shape.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit eb2f2d5 into main Sep 10, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant