Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343) - #353

Merged
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285
Jul 17, 2026
Merged

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343)#353
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285

Conversation

@AndresL230

@AndresL230AndresL230 commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator

Three independent fixes from the issue batch. Each is a self-contained commit; reviewable commit-by-commit.

Closes#342
Closes#285
Closes#343


#342 — scope /api/social/students to the viewer's school (security, P2)

get_students returned a profile for every user in the DB — name, streak, courses, and per-concept mastery — to any authenticated caller. The session user_id was bound and never used, so the endpoint authenticated without authorizing.

Decision (product call, confirmed): scope to school + honor profile_visibility; trim mastery from the payload.

  • School scope via a new bulk helper academics.school_peer_user_ids(user_id) — walks enrollments → course_offerings.course_id → courses.school_id and back to every user enrolled at those schools. Multi-step reads per the module's house style; not cached (mutable visibility boundary); fails closed on empty scope, mirroring the enrollment-scoping pattern in calendar.py.
  • Visibility:profile_visibility == 'private' users are dropped from the listing. Migration 0031 widens the user_settings CHECK to allow the 'school' tier the Settings UI has always offered but the DB rejected (a latent 500 on selecting it); update_settings now validates the value → 400 instead of a raw CHECK violation.
  • Payload trimmed to name/streak/courses. The mastery histogram + top concepts are academic-performance data that belong on the profile page (already gated on profile_visibility), not a browsable directory. Frontend directory, StudentRow type, and local-mode fixture updated to match.

⚠️Deploy note — migration 0031 is applied per-environment, not by merge:

  • Staging DB: already applied + verified (2026-07-17). The staging project has a clean schema_migrations ledger; only 0031 was pending. Constraint is now CHECK (profile_visibility = ANY (ARRAY['public','school','private'])). Safe to have applied ahead of the code — it only removes the pre-existing 'school' 500 in Settings.
  • Prod DB: NOT applied — do NOT run a plain db.migrate against prod. Prod has no schema_migrations ledger (Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317), so the runner would treat all 34 migrations as pending and try to re-run them from scratch. --baseline alone is also wrong (it would mark 0031 applied without running it). Correct sequence as part of the main→production promotion: (1) baseline 00010030 on prod so the already-present schema is recorded, (2) then apply only 0031 for real. This fixes the Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317 gap for prod as a side effect and needs a human watching.

#285 — promote stub users on sign-in instead of 409'ing (auth)

Sign-in 500'd whenever a stubusers row existed (id set, google_id NULL — created by graph_service.ensure_user_exists, reachable after a row delete because the HMAC sapling_session cookie outlives it). The new-user branch looked up by google_id only (NULL never matches), fell through to a blind INSERT on the deterministic id user_{google_id}, and collided on users_pkey → unhandled 409 → permanent sign-in 500 loop.

  • Both blind inserts (usersanduser_profiles — its user_id is also a PK and 409s for a stub that reached onboarding) become upserts.
  • on_conflict is the primary key, not google_id: the stub's google_id is NULL and NULLs never conflict, so only an id-conflict resolves it; merge-duplicates fills the NULL auth columns in.
  • The existing-user branch is untouched, so a legacy row whose id ≠ user_{google_id} keeps its id.
  • Tests drive the real/google/callback with the mocked tables raising the exact production 409 on insert — a regression to a blind insert fails loudly.

#343 — enable CodeRabbit on long-lived integration branches (CI, P2)

CodeRabbit reviews only the default branch unless base branches are listed, and the repo had no .coderabbit.yaml at all — so PRs targeting an integration branch got "Review skipped" while CI stayed green.


Verification

  • Backend: 966 passed, only the 3 pre-existing failures on clean main (test_storage_service ×2, test_ocr_pipeline event-loop error). ruff check clean on all touched files.
  • Frontend: tsc --noEmit clean, eslint clean on touched files, 88 vitest tests pass.
  • New tests: test_auth_stub_promotion.py (7), rewritten test_social_students.py (scope/visibility/payload + school_peer_user_ids traversal), test_profile_routes.py visibility-validation.

Not included

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a school-scoped student directory that shows peers based on shared school enrollment.
    • Added profile visibility options: Public, School, and Private.
    • Directory entries now display student names, courses, and learning streaks.
  • Bug Fixes

    • Improved Google sign-in for accounts with pre-existing records.
    • Invalid profile visibility values now return a clear validation error instead of a server error.
    • Private profiles are excluded from the school directory.

AndresL230and others added 3 commits July 17, 2026 11:11
CodeRabbit reviews only the default branch (main) unless base branches are
listed explicitly, and this repo had no .coderabbit.yaml at all — so every PR
targeting a long-lived integration branch got "Review skipped" while CI still
went green, making the absence of a review read as "nothing to flag."
The gap that still matters is `production`: main -> production promotion PRs
(#305, #314) are the last gate before prod and were never machine-reviewed.
`staging` is listed defensively — that branch was deleted 2026-07-15 (after #334
merged / #337 closed) and no open PR currently targets a non-main base, but it
was a real integration branch and should be covered if recreated.
Patterns are anchored regex so `staging` can't also match feature branches like
`docs/staging-environment-plan`. Validated against coderabbit schema.v2.json.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Google sign-in 500'd whenever a stub `users` row existed (id set, google_id
NULL) — created by `graph_service.ensure_user_exists` for any authenticated
graph request, and reachable after a row delete because the HMAC-signed
`sapling_session` cookie outlives it. The new-user branch looked users up by
google_id only (NULL never matches), fell through to a blind INSERT on the
deterministic id `user_{google_id}`, and collided on users_pkey -> unhandled
409 -> permanent sign-in 500 loop.
Swap both blind inserts (users and user_profiles — the latter's user_id is also
a PK and 409s for a stub that reached onboarding) for upserts. on_conflict is
the primary key, not google_id: the stub's google_id is NULL and NULLs never
conflict, so only an id-conflict resolves it; merge-duplicates fills the stub's
NULL auth columns in, promoting it to a real user. The existing-user branch is
left untouched so a legacy row whose id != user_{google_id} keeps its id.
Tests drive the real /google/callback with the mocked users/user_profiles
tables raising the exact production 409 on insert, so any regression to a blind
insert fails loudly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
get_students returned a profile for every user in the DB — name, streak,
courses, and per-concept mastery — to any authenticated caller; the session
user_id was bound and never used, so it authenticated without authorizing.
Two boundaries now apply, matching what the UI already claims ("Students at
your school") and the existing profile_visibility precedent:
- School scope via a new bulk helper `academics.school_peer_user_ids`, which
walks enrollments -> course_offerings.course_id -> courses.school_id and back
to every user enrolled at those schools. Multi-step reads per the module's
house style; not cached (it's a mutable visibility boundary); fails closed on
an empty scope, mirroring the enrollment-scoping pattern in calendar.py.
- profile_visibility: 'private' users are dropped from the listing. 0031 widens
the user_settings CHECK to allow the 'school' tier the Settings UI has always
offered but the DB rejected (a latent 500), and update_settings now validates
the value so a bad one returns 400 instead of a raw CHECK violation.
The payload is trimmed to name/streak/courses — the mastery histogram and top
concepts are academic-performance data that belong on the profile page (already
gated on profile_visibility), not in a browsable directory. Frontend directory,
StudentRow type, and local-mode fixture updated to match.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitaiBot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: b3532c9e-8a23-43de-ac11-61c4e3854bbb

📥 Commits

Reviewing files that changed from the base of the PR and between 9adf8d8 and 6a99676.

📒 Files selected for processing (12)
  • .coderabbit.yaml
  • backend/db/migrations/0031_profile_visibility_school.sql
  • backend/routes/auth.py
  • backend/routes/profile.py
  • backend/routes/social.py
  • backend/services/academics.py
  • backend/tests/test_auth_stub_promotion.py
  • backend/tests/test_profile_routes.py
  • backend/tests/test_social_students.py
  • frontend/src/components/screens/Social.tsx
  • frontend/src/lib/api.ts
  • frontend/src/lib/localData.ts

📝 Walkthrough

Walkthrough

The PR adds school-scoped, visibility-aware student directories with reduced mastery-free payloads, updates frontend rendering and local data, makes Google OAuth provisioning conflict-safe for stub users, validates profile visibility values, and configures automated review branches.

Changes

School Directory Visibility

Layer / File(s)Summary
Profile visibility contract
backend/db/migrations/0031_profile_visibility_school.sql, backend/routes/profile.py, backend/tests/test_profile_routes.py
The profile_visibility constraint accepts public, school, and private, while the settings route rejects other values with HTTP 400.
School-scoped directory flow
backend/services/academics.py, backend/routes/social.py, backend/tests/test_social_students.py
The students endpoint resolves school peers, excludes private profiles, fails closed without scope, and returns only user_id, name, streak, and deduplicated courses.
Directory payload and presentation
frontend/src/lib/api.ts, frontend/src/lib/localData.ts, frontend/src/components/screens/Social.tsx
Frontend types, local records, search filtering, and roster rows no longer use mastery fields and display streaks instead.

OAuth Stub Promotion

Layer / File(s)Summary
Google user provisioning
backend/routes/auth.py, backend/tests/test_auth_stub_promotion.py
Google sign-in uses ID-keyed upserts for new users and profiles, while existing approved users continue through the update path and related redirect behavior is tested.

Review Configuration

Layer / File(s)Summary
Automated review branch rules
.coderabbit.yaml
Repository language is set to en-US, and automatic reviews target only production and staging base branches.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
participant Viewer
participant StudentsRoute
participant Academics
participant Database
Viewer->>StudentsRoute: Request student directory
StudentsRoute->>Academics: Resolve school peers
Academics->>Database: Traverse enrollment and school relationships
Database-->>Academics: Peer user IDs
StudentsRoute->>Database: Read visibility and directory fields
Database-->>StudentsRoute: Visible users and courses
StudentsRoute-->>Viewer: Reduced student directory
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging6a99676Commit Preview URL

Branch Preview URL
Jul 17 2026, 03:15 PM

@AndresL230
AndresL230 marked this pull request as ready for review July 17, 2026 16:20
@AndresL230
AndresL230 merged commit 4227689 into mainJul 17, 2026
6 checks passed
@AndresL230
AndresL230 deleted the worktree-issue-batch-342-343-285 branch July 17, 2026 16:26
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343) - #353

Merged
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285
Jul 17, 2026
Merged

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343)#353
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285

Conversation

@AndresL230

@AndresL230AndresL230 commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator

Three independent fixes from the issue batch. Each is a self-contained commit; reviewable commit-by-commit.

Closes#342
Closes#285
Closes#343


#342 — scope /api/social/students to the viewer's school (security, P2)

get_students returned a profile for every user in the DB — name, streak, courses, and per-concept mastery — to any authenticated caller. The session user_id was bound and never used, so the endpoint authenticated without authorizing.

Decision (product call, confirmed): scope to school + honor profile_visibility; trim mastery from the payload.

  • School scope via a new bulk helper academics.school_peer_user_ids(user_id) — walks enrollments → course_offerings.course_id → courses.school_id and back to every user enrolled at those schools. Multi-step reads per the module's house style; not cached (mutable visibility boundary); fails closed on empty scope, mirroring the enrollment-scoping pattern in calendar.py.
  • Visibility:profile_visibility == 'private' users are dropped from the listing. Migration 0031 widens the user_settings CHECK to allow the 'school' tier the Settings UI has always offered but the DB rejected (a latent 500 on selecting it); update_settings now validates the value → 400 instead of a raw CHECK violation.
  • Payload trimmed to name/streak/courses. The mastery histogram + top concepts are academic-performance data that belong on the profile page (already gated on profile_visibility), not a browsable directory. Frontend directory, StudentRow type, and local-mode fixture updated to match.

⚠️Deploy note — migration 0031 is applied per-environment, not by merge:

  • Staging DB: already applied + verified (2026-07-17). The staging project has a clean schema_migrations ledger; only 0031 was pending. Constraint is now CHECK (profile_visibility = ANY (ARRAY['public','school','private'])). Safe to have applied ahead of the code — it only removes the pre-existing 'school' 500 in Settings.
  • Prod DB: NOT applied — do NOT run a plain db.migrate against prod. Prod has no schema_migrations ledger (Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317), so the runner would treat all 34 migrations as pending and try to re-run them from scratch. --baseline alone is also wrong (it would mark 0031 applied without running it). Correct sequence as part of the main→production promotion: (1) baseline 00010030 on prod so the already-present schema is recorded, (2) then apply only 0031 for real. This fixes the Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317 gap for prod as a side effect and needs a human watching.

#285 — promote stub users on sign-in instead of 409'ing (auth)

Sign-in 500'd whenever a stubusers row existed (id set, google_id NULL — created by graph_service.ensure_user_exists, reachable after a row delete because the HMAC sapling_session cookie outlives it). The new-user branch looked up by google_id only (NULL never matches), fell through to a blind INSERT on the deterministic id user_{google_id}, and collided on users_pkey → unhandled 409 → permanent sign-in 500 loop.

  • Both blind inserts (usersanduser_profiles — its user_id is also a PK and 409s for a stub that reached onboarding) become upserts.
  • on_conflict is the primary key, not google_id: the stub's google_id is NULL and NULLs never conflict, so only an id-conflict resolves it; merge-duplicates fills the NULL auth columns in.
  • The existing-user branch is untouched, so a legacy row whose id ≠ user_{google_id} keeps its id.
  • Tests drive the real/google/callback with the mocked tables raising the exact production 409 on insert — a regression to a blind insert fails loudly.

#343 — enable CodeRabbit on long-lived integration branches (CI, P2)

CodeRabbit reviews only the default branch unless base branches are listed, and the repo had no .coderabbit.yaml at all — so PRs targeting an integration branch got "Review skipped" while CI stayed green.


Verification

  • Backend: 966 passed, only the 3 pre-existing failures on clean main (test_storage_service ×2, test_ocr_pipeline event-loop error). ruff check clean on all touched files.
  • Frontend: tsc --noEmit clean, eslint clean on touched files, 88 vitest tests pass.
  • New tests: test_auth_stub_promotion.py (7), rewritten test_social_students.py (scope/visibility/payload + school_peer_user_ids traversal), test_profile_routes.py visibility-validation.

Not included

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a school-scoped student directory that shows peers based on shared school enrollment.
    • Added profile visibility options: Public, School, and Private.
    • Directory entries now display student names, courses, and learning streaks.
  • Bug Fixes

    • Improved Google sign-in for accounts with pre-existing records.
    • Invalid profile visibility values now return a clear validation error instead of a server error.
    • Private profiles are excluded from the school directory.

AndresL230and others added 3 commits July 17, 2026 11:11
CodeRabbit reviews only the default branch (main) unless base branches are
listed explicitly, and this repo had no .coderabbit.yaml at all — so every PR
targeting a long-lived integration branch got "Review skipped" while CI still
went green, making the absence of a review read as "nothing to flag."
The gap that still matters is `production`: main -> production promotion PRs
(#305, #314) are the last gate before prod and were never machine-reviewed.
`staging` is listed defensively — that branch was deleted 2026-07-15 (after #334
merged / #337 closed) and no open PR currently targets a non-main base, but it
was a real integration branch and should be covered if recreated.
Patterns are anchored regex so `staging` can't also match feature branches like
`docs/staging-environment-plan`. Validated against coderabbit schema.v2.json.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Google sign-in 500'd whenever a stub `users` row existed (id set, google_id
NULL) — created by `graph_service.ensure_user_exists` for any authenticated
graph request, and reachable after a row delete because the HMAC-signed
`sapling_session` cookie outlives it. The new-user branch looked users up by
google_id only (NULL never matches), fell through to a blind INSERT on the
deterministic id `user_{google_id}`, and collided on users_pkey -> unhandled
409 -> permanent sign-in 500 loop.
Swap both blind inserts (users and user_profiles — the latter's user_id is also
a PK and 409s for a stub that reached onboarding) for upserts. on_conflict is
the primary key, not google_id: the stub's google_id is NULL and NULLs never
conflict, so only an id-conflict resolves it; merge-duplicates fills the stub's
NULL auth columns in, promoting it to a real user. The existing-user branch is
left untouched so a legacy row whose id != user_{google_id} keeps its id.
Tests drive the real /google/callback with the mocked users/user_profiles
tables raising the exact production 409 on insert, so any regression to a blind
insert fails loudly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
get_students returned a profile for every user in the DB — name, streak,
courses, and per-concept mastery — to any authenticated caller; the session
user_id was bound and never used, so it authenticated without authorizing.
Two boundaries now apply, matching what the UI already claims ("Students at
your school") and the existing profile_visibility precedent:
- School scope via a new bulk helper `academics.school_peer_user_ids`, which
walks enrollments -> course_offerings.course_id -> courses.school_id and back
to every user enrolled at those schools. Multi-step reads per the module's
house style; not cached (it's a mutable visibility boundary); fails closed on
an empty scope, mirroring the enrollment-scoping pattern in calendar.py.
- profile_visibility: 'private' users are dropped from the listing. 0031 widens
the user_settings CHECK to allow the 'school' tier the Settings UI has always
offered but the DB rejected (a latent 500), and update_settings now validates
the value so a bad one returns 400 instead of a raw CHECK violation.
The payload is trimmed to name/streak/courses — the mastery histogram and top
concepts are academic-performance data that belong on the profile page (already
gated on profile_visibility), not in a browsable directory. Frontend directory,
StudentRow type, and local-mode fixture updated to match.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitaiBot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: b3532c9e-8a23-43de-ac11-61c4e3854bbb

📥 Commits

Reviewing files that changed from the base of the PR and between 9adf8d8 and 6a99676.

📒 Files selected for processing (12)
  • .coderabbit.yaml
  • backend/db/migrations/0031_profile_visibility_school.sql
  • backend/routes/auth.py
  • backend/routes/profile.py
  • backend/routes/social.py
  • backend/services/academics.py
  • backend/tests/test_auth_stub_promotion.py
  • backend/tests/test_profile_routes.py
  • backend/tests/test_social_students.py
  • frontend/src/components/screens/Social.tsx
  • frontend/src/lib/api.ts
  • frontend/src/lib/localData.ts

📝 Walkthrough

Walkthrough

The PR adds school-scoped, visibility-aware student directories with reduced mastery-free payloads, updates frontend rendering and local data, makes Google OAuth provisioning conflict-safe for stub users, validates profile visibility values, and configures automated review branches.

Changes

School Directory Visibility

Layer / File(s)Summary
Profile visibility contract
backend/db/migrations/0031_profile_visibility_school.sql, backend/routes/profile.py, backend/tests/test_profile_routes.py
The profile_visibility constraint accepts public, school, and private, while the settings route rejects other values with HTTP 400.
School-scoped directory flow
backend/services/academics.py, backend/routes/social.py, backend/tests/test_social_students.py
The students endpoint resolves school peers, excludes private profiles, fails closed without scope, and returns only user_id, name, streak, and deduplicated courses.
Directory payload and presentation
frontend/src/lib/api.ts, frontend/src/lib/localData.ts, frontend/src/components/screens/Social.tsx
Frontend types, local records, search filtering, and roster rows no longer use mastery fields and display streaks instead.

OAuth Stub Promotion

Layer / File(s)Summary
Google user provisioning
backend/routes/auth.py, backend/tests/test_auth_stub_promotion.py
Google sign-in uses ID-keyed upserts for new users and profiles, while existing approved users continue through the update path and related redirect behavior is tested.

Review Configuration

Layer / File(s)Summary
Automated review branch rules
.coderabbit.yaml
Repository language is set to en-US, and automatic reviews target only production and staging base branches.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
participant Viewer
participant StudentsRoute
participant Academics
participant Database
Viewer->>StudentsRoute: Request student directory
StudentsRoute->>Academics: Resolve school peers
Academics->>Database: Traverse enrollment and school relationships
Database-->>Academics: Peer user IDs
StudentsRoute->>Database: Read visibility and directory fields
Database-->>StudentsRoute: Visible users and courses
StudentsRoute-->>Viewer: Reduced student directory
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging6a99676Commit Preview URL

Branch Preview URL
Jul 17 2026, 03:15 PM

@AndresL230
AndresL230 marked this pull request as ready for review July 17, 2026 16:20
@AndresL230
AndresL230 merged commit 4227689 into mainJul 17, 2026
6 checks passed
@AndresL230
AndresL230 deleted the worktree-issue-batch-342-343-285 branch July 17, 2026 16:26
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343) - #353

Merged
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285
Jul 17, 2026
Merged

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343)#353
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285

Conversation

@AndresL230

@AndresL230AndresL230 commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator

Three independent fixes from the issue batch. Each is a self-contained commit; reviewable commit-by-commit.

Closes#342
Closes#285
Closes#343


#342 — scope /api/social/students to the viewer's school (security, P2)

get_students returned a profile for every user in the DB — name, streak, courses, and per-concept mastery — to any authenticated caller. The session user_id was bound and never used, so the endpoint authenticated without authorizing.

Decision (product call, confirmed): scope to school + honor profile_visibility; trim mastery from the payload.

  • School scope via a new bulk helper academics.school_peer_user_ids(user_id) — walks enrollments → course_offerings.course_id → courses.school_id and back to every user enrolled at those schools. Multi-step reads per the module's house style; not cached (mutable visibility boundary); fails closed on empty scope, mirroring the enrollment-scoping pattern in calendar.py.
  • Visibility:profile_visibility == 'private' users are dropped from the listing. Migration 0031 widens the user_settings CHECK to allow the 'school' tier the Settings UI has always offered but the DB rejected (a latent 500 on selecting it); update_settings now validates the value → 400 instead of a raw CHECK violation.
  • Payload trimmed to name/streak/courses. The mastery histogram + top concepts are academic-performance data that belong on the profile page (already gated on profile_visibility), not a browsable directory. Frontend directory, StudentRow type, and local-mode fixture updated to match.

⚠️Deploy note — migration 0031 is applied per-environment, not by merge:

  • Staging DB: already applied + verified (2026-07-17). The staging project has a clean schema_migrations ledger; only 0031 was pending. Constraint is now CHECK (profile_visibility = ANY (ARRAY['public','school','private'])). Safe to have applied ahead of the code — it only removes the pre-existing 'school' 500 in Settings.
  • Prod DB: NOT applied — do NOT run a plain db.migrate against prod. Prod has no schema_migrations ledger (Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317), so the runner would treat all 34 migrations as pending and try to re-run them from scratch. --baseline alone is also wrong (it would mark 0031 applied without running it). Correct sequence as part of the main→production promotion: (1) baseline 00010030 on prod so the already-present schema is recorded, (2) then apply only 0031 for real. This fixes the Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317 gap for prod as a side effect and needs a human watching.

#285 — promote stub users on sign-in instead of 409'ing (auth)

Sign-in 500'd whenever a stubusers row existed (id set, google_id NULL — created by graph_service.ensure_user_exists, reachable after a row delete because the HMAC sapling_session cookie outlives it). The new-user branch looked up by google_id only (NULL never matches), fell through to a blind INSERT on the deterministic id user_{google_id}, and collided on users_pkey → unhandled 409 → permanent sign-in 500 loop.

  • Both blind inserts (usersanduser_profiles — its user_id is also a PK and 409s for a stub that reached onboarding) become upserts.
  • on_conflict is the primary key, not google_id: the stub's google_id is NULL and NULLs never conflict, so only an id-conflict resolves it; merge-duplicates fills the NULL auth columns in.
  • The existing-user branch is untouched, so a legacy row whose id ≠ user_{google_id} keeps its id.
  • Tests drive the real/google/callback with the mocked tables raising the exact production 409 on insert — a regression to a blind insert fails loudly.

#343 — enable CodeRabbit on long-lived integration branches (CI, P2)

CodeRabbit reviews only the default branch unless base branches are listed, and the repo had no .coderabbit.yaml at all — so PRs targeting an integration branch got "Review skipped" while CI stayed green.


Verification

  • Backend: 966 passed, only the 3 pre-existing failures on clean main (test_storage_service ×2, test_ocr_pipeline event-loop error). ruff check clean on all touched files.
  • Frontend: tsc --noEmit clean, eslint clean on touched files, 88 vitest tests pass.
  • New tests: test_auth_stub_promotion.py (7), rewritten test_social_students.py (scope/visibility/payload + school_peer_user_ids traversal), test_profile_routes.py visibility-validation.

Not included

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a school-scoped student directory that shows peers based on shared school enrollment.
    • Added profile visibility options: Public, School, and Private.
    • Directory entries now display student names, courses, and learning streaks.
  • Bug Fixes

    • Improved Google sign-in for accounts with pre-existing records.
    • Invalid profile visibility values now return a clear validation error instead of a server error.
    • Private profiles are excluded from the school directory.

AndresL230and others added 3 commits July 17, 2026 11:11
CodeRabbit reviews only the default branch (main) unless base branches are
listed explicitly, and this repo had no .coderabbit.yaml at all — so every PR
targeting a long-lived integration branch got "Review skipped" while CI still
went green, making the absence of a review read as "nothing to flag."
The gap that still matters is `production`: main -> production promotion PRs
(#305, #314) are the last gate before prod and were never machine-reviewed.
`staging` is listed defensively — that branch was deleted 2026-07-15 (after #334
merged / #337 closed) and no open PR currently targets a non-main base, but it
was a real integration branch and should be covered if recreated.
Patterns are anchored regex so `staging` can't also match feature branches like
`docs/staging-environment-plan`. Validated against coderabbit schema.v2.json.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Google sign-in 500'd whenever a stub `users` row existed (id set, google_id
NULL) — created by `graph_service.ensure_user_exists` for any authenticated
graph request, and reachable after a row delete because the HMAC-signed
`sapling_session` cookie outlives it. The new-user branch looked users up by
google_id only (NULL never matches), fell through to a blind INSERT on the
deterministic id `user_{google_id}`, and collided on users_pkey -> unhandled
409 -> permanent sign-in 500 loop.
Swap both blind inserts (users and user_profiles — the latter's user_id is also
a PK and 409s for a stub that reached onboarding) for upserts. on_conflict is
the primary key, not google_id: the stub's google_id is NULL and NULLs never
conflict, so only an id-conflict resolves it; merge-duplicates fills the stub's
NULL auth columns in, promoting it to a real user. The existing-user branch is
left untouched so a legacy row whose id != user_{google_id} keeps its id.
Tests drive the real /google/callback with the mocked users/user_profiles
tables raising the exact production 409 on insert, so any regression to a blind
insert fails loudly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
get_students returned a profile for every user in the DB — name, streak,
courses, and per-concept mastery — to any authenticated caller; the session
user_id was bound and never used, so it authenticated without authorizing.
Two boundaries now apply, matching what the UI already claims ("Students at
your school") and the existing profile_visibility precedent:
- School scope via a new bulk helper `academics.school_peer_user_ids`, which
walks enrollments -> course_offerings.course_id -> courses.school_id and back
to every user enrolled at those schools. Multi-step reads per the module's
house style; not cached (it's a mutable visibility boundary); fails closed on
an empty scope, mirroring the enrollment-scoping pattern in calendar.py.
- profile_visibility: 'private' users are dropped from the listing. 0031 widens
the user_settings CHECK to allow the 'school' tier the Settings UI has always
offered but the DB rejected (a latent 500), and update_settings now validates
the value so a bad one returns 400 instead of a raw CHECK violation.
The payload is trimmed to name/streak/courses — the mastery histogram and top
concepts are academic-performance data that belong on the profile page (already
gated on profile_visibility), not in a browsable directory. Frontend directory,
StudentRow type, and local-mode fixture updated to match.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitaiBot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: b3532c9e-8a23-43de-ac11-61c4e3854bbb

📥 Commits

Reviewing files that changed from the base of the PR and between 9adf8d8 and 6a99676.

📒 Files selected for processing (12)
  • .coderabbit.yaml
  • backend/db/migrations/0031_profile_visibility_school.sql
  • backend/routes/auth.py
  • backend/routes/profile.py
  • backend/routes/social.py
  • backend/services/academics.py
  • backend/tests/test_auth_stub_promotion.py
  • backend/tests/test_profile_routes.py
  • backend/tests/test_social_students.py
  • frontend/src/components/screens/Social.tsx
  • frontend/src/lib/api.ts
  • frontend/src/lib/localData.ts

📝 Walkthrough

Walkthrough

The PR adds school-scoped, visibility-aware student directories with reduced mastery-free payloads, updates frontend rendering and local data, makes Google OAuth provisioning conflict-safe for stub users, validates profile visibility values, and configures automated review branches.

Changes

School Directory Visibility

Layer / File(s)Summary
Profile visibility contract
backend/db/migrations/0031_profile_visibility_school.sql, backend/routes/profile.py, backend/tests/test_profile_routes.py
The profile_visibility constraint accepts public, school, and private, while the settings route rejects other values with HTTP 400.
School-scoped directory flow
backend/services/academics.py, backend/routes/social.py, backend/tests/test_social_students.py
The students endpoint resolves school peers, excludes private profiles, fails closed without scope, and returns only user_id, name, streak, and deduplicated courses.
Directory payload and presentation
frontend/src/lib/api.ts, frontend/src/lib/localData.ts, frontend/src/components/screens/Social.tsx
Frontend types, local records, search filtering, and roster rows no longer use mastery fields and display streaks instead.

OAuth Stub Promotion

Layer / File(s)Summary
Google user provisioning
backend/routes/auth.py, backend/tests/test_auth_stub_promotion.py
Google sign-in uses ID-keyed upserts for new users and profiles, while existing approved users continue through the update path and related redirect behavior is tested.

Review Configuration

Layer / File(s)Summary
Automated review branch rules
.coderabbit.yaml
Repository language is set to en-US, and automatic reviews target only production and staging base branches.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
participant Viewer
participant StudentsRoute
participant Academics
participant Database
Viewer->>StudentsRoute: Request student directory
StudentsRoute->>Academics: Resolve school peers
Academics->>Database: Traverse enrollment and school relationships
Database-->>Academics: Peer user IDs
StudentsRoute->>Database: Read visibility and directory fields
Database-->>StudentsRoute: Visible users and courses
StudentsRoute-->>Viewer: Reduced student directory
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging6a99676Commit Preview URL

Branch Preview URL
Jul 17 2026, 03:15 PM

@AndresL230
AndresL230 marked this pull request as ready for review July 17, 2026 16:20
@AndresL230
AndresL230 merged commit 4227689 into mainJul 17, 2026
6 checks passed
@AndresL230
AndresL230 deleted the worktree-issue-batch-342-343-285 branch July 17, 2026 16:26
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343) - #353

Merged
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285
Jul 17, 2026
Merged

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343)#353
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285

Conversation

@AndresL230

@AndresL230AndresL230 commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator

Three independent fixes from the issue batch. Each is a self-contained commit; reviewable commit-by-commit.

Closes#342
Closes#285
Closes#343


#342 — scope /api/social/students to the viewer's school (security, P2)

get_students returned a profile for every user in the DB — name, streak, courses, and per-concept mastery — to any authenticated caller. The session user_id was bound and never used, so the endpoint authenticated without authorizing.

Decision (product call, confirmed): scope to school + honor profile_visibility; trim mastery from the payload.

  • School scope via a new bulk helper academics.school_peer_user_ids(user_id) — walks enrollments → course_offerings.course_id → courses.school_id and back to every user enrolled at those schools. Multi-step reads per the module's house style; not cached (mutable visibility boundary); fails closed on empty scope, mirroring the enrollment-scoping pattern in calendar.py.
  • Visibility:profile_visibility == 'private' users are dropped from the listing. Migration 0031 widens the user_settings CHECK to allow the 'school' tier the Settings UI has always offered but the DB rejected (a latent 500 on selecting it); update_settings now validates the value → 400 instead of a raw CHECK violation.
  • Payload trimmed to name/streak/courses. The mastery histogram + top concepts are academic-performance data that belong on the profile page (already gated on profile_visibility), not a browsable directory. Frontend directory, StudentRow type, and local-mode fixture updated to match.

⚠️Deploy note — migration 0031 is applied per-environment, not by merge:

  • Staging DB: already applied + verified (2026-07-17). The staging project has a clean schema_migrations ledger; only 0031 was pending. Constraint is now CHECK (profile_visibility = ANY (ARRAY['public','school','private'])). Safe to have applied ahead of the code — it only removes the pre-existing 'school' 500 in Settings.
  • Prod DB: NOT applied — do NOT run a plain db.migrate against prod. Prod has no schema_migrations ledger (Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317), so the runner would treat all 34 migrations as pending and try to re-run them from scratch. --baseline alone is also wrong (it would mark 0031 applied without running it). Correct sequence as part of the main→production promotion: (1) baseline 00010030 on prod so the already-present schema is recorded, (2) then apply only 0031 for real. This fixes the Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317 gap for prod as a side effect and needs a human watching.

#285 — promote stub users on sign-in instead of 409'ing (auth)

Sign-in 500'd whenever a stubusers row existed (id set, google_id NULL — created by graph_service.ensure_user_exists, reachable after a row delete because the HMAC sapling_session cookie outlives it). The new-user branch looked up by google_id only (NULL never matches), fell through to a blind INSERT on the deterministic id user_{google_id}, and collided on users_pkey → unhandled 409 → permanent sign-in 500 loop.

  • Both blind inserts (usersanduser_profiles — its user_id is also a PK and 409s for a stub that reached onboarding) become upserts.
  • on_conflict is the primary key, not google_id: the stub's google_id is NULL and NULLs never conflict, so only an id-conflict resolves it; merge-duplicates fills the NULL auth columns in.
  • The existing-user branch is untouched, so a legacy row whose id ≠ user_{google_id} keeps its id.
  • Tests drive the real/google/callback with the mocked tables raising the exact production 409 on insert — a regression to a blind insert fails loudly.

#343 — enable CodeRabbit on long-lived integration branches (CI, P2)

CodeRabbit reviews only the default branch unless base branches are listed, and the repo had no .coderabbit.yaml at all — so PRs targeting an integration branch got "Review skipped" while CI stayed green.


Verification

  • Backend: 966 passed, only the 3 pre-existing failures on clean main (test_storage_service ×2, test_ocr_pipeline event-loop error). ruff check clean on all touched files.
  • Frontend: tsc --noEmit clean, eslint clean on touched files, 88 vitest tests pass.
  • New tests: test_auth_stub_promotion.py (7), rewritten test_social_students.py (scope/visibility/payload + school_peer_user_ids traversal), test_profile_routes.py visibility-validation.

Not included

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a school-scoped student directory that shows peers based on shared school enrollment.
    • Added profile visibility options: Public, School, and Private.
    • Directory entries now display student names, courses, and learning streaks.
  • Bug Fixes

    • Improved Google sign-in for accounts with pre-existing records.
    • Invalid profile visibility values now return a clear validation error instead of a server error.
    • Private profiles are excluded from the school directory.

AndresL230and others added 3 commits July 17, 2026 11:11
CodeRabbit reviews only the default branch (main) unless base branches are
listed explicitly, and this repo had no .coderabbit.yaml at all — so every PR
targeting a long-lived integration branch got "Review skipped" while CI still
went green, making the absence of a review read as "nothing to flag."
The gap that still matters is `production`: main -> production promotion PRs
(#305, #314) are the last gate before prod and were never machine-reviewed.
`staging` is listed defensively — that branch was deleted 2026-07-15 (after #334
merged / #337 closed) and no open PR currently targets a non-main base, but it
was a real integration branch and should be covered if recreated.
Patterns are anchored regex so `staging` can't also match feature branches like
`docs/staging-environment-plan`. Validated against coderabbit schema.v2.json.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Google sign-in 500'd whenever a stub `users` row existed (id set, google_id
NULL) — created by `graph_service.ensure_user_exists` for any authenticated
graph request, and reachable after a row delete because the HMAC-signed
`sapling_session` cookie outlives it. The new-user branch looked users up by
google_id only (NULL never matches), fell through to a blind INSERT on the
deterministic id `user_{google_id}`, and collided on users_pkey -> unhandled
409 -> permanent sign-in 500 loop.
Swap both blind inserts (users and user_profiles — the latter's user_id is also
a PK and 409s for a stub that reached onboarding) for upserts. on_conflict is
the primary key, not google_id: the stub's google_id is NULL and NULLs never
conflict, so only an id-conflict resolves it; merge-duplicates fills the stub's
NULL auth columns in, promoting it to a real user. The existing-user branch is
left untouched so a legacy row whose id != user_{google_id} keeps its id.
Tests drive the real /google/callback with the mocked users/user_profiles
tables raising the exact production 409 on insert, so any regression to a blind
insert fails loudly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
get_students returned a profile for every user in the DB — name, streak,
courses, and per-concept mastery — to any authenticated caller; the session
user_id was bound and never used, so it authenticated without authorizing.
Two boundaries now apply, matching what the UI already claims ("Students at
your school") and the existing profile_visibility precedent:
- School scope via a new bulk helper `academics.school_peer_user_ids`, which
walks enrollments -> course_offerings.course_id -> courses.school_id and back
to every user enrolled at those schools. Multi-step reads per the module's
house style; not cached (it's a mutable visibility boundary); fails closed on
an empty scope, mirroring the enrollment-scoping pattern in calendar.py.
- profile_visibility: 'private' users are dropped from the listing. 0031 widens
the user_settings CHECK to allow the 'school' tier the Settings UI has always
offered but the DB rejected (a latent 500), and update_settings now validates
the value so a bad one returns 400 instead of a raw CHECK violation.
The payload is trimmed to name/streak/courses — the mastery histogram and top
concepts are academic-performance data that belong on the profile page (already
gated on profile_visibility), not in a browsable directory. Frontend directory,
StudentRow type, and local-mode fixture updated to match.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitaiBot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: b3532c9e-8a23-43de-ac11-61c4e3854bbb

📥 Commits

Reviewing files that changed from the base of the PR and between 9adf8d8 and 6a99676.

📒 Files selected for processing (12)
  • .coderabbit.yaml
  • backend/db/migrations/0031_profile_visibility_school.sql
  • backend/routes/auth.py
  • backend/routes/profile.py
  • backend/routes/social.py
  • backend/services/academics.py
  • backend/tests/test_auth_stub_promotion.py
  • backend/tests/test_profile_routes.py
  • backend/tests/test_social_students.py
  • frontend/src/components/screens/Social.tsx
  • frontend/src/lib/api.ts
  • frontend/src/lib/localData.ts

📝 Walkthrough

Walkthrough

The PR adds school-scoped, visibility-aware student directories with reduced mastery-free payloads, updates frontend rendering and local data, makes Google OAuth provisioning conflict-safe for stub users, validates profile visibility values, and configures automated review branches.

Changes

School Directory Visibility

Layer / File(s)Summary
Profile visibility contract
backend/db/migrations/0031_profile_visibility_school.sql, backend/routes/profile.py, backend/tests/test_profile_routes.py
The profile_visibility constraint accepts public, school, and private, while the settings route rejects other values with HTTP 400.
School-scoped directory flow
backend/services/academics.py, backend/routes/social.py, backend/tests/test_social_students.py
The students endpoint resolves school peers, excludes private profiles, fails closed without scope, and returns only user_id, name, streak, and deduplicated courses.
Directory payload and presentation
frontend/src/lib/api.ts, frontend/src/lib/localData.ts, frontend/src/components/screens/Social.tsx
Frontend types, local records, search filtering, and roster rows no longer use mastery fields and display streaks instead.

OAuth Stub Promotion

Layer / File(s)Summary
Google user provisioning
backend/routes/auth.py, backend/tests/test_auth_stub_promotion.py
Google sign-in uses ID-keyed upserts for new users and profiles, while existing approved users continue through the update path and related redirect behavior is tested.

Review Configuration

Layer / File(s)Summary
Automated review branch rules
.coderabbit.yaml
Repository language is set to en-US, and automatic reviews target only production and staging base branches.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
participant Viewer
participant StudentsRoute
participant Academics
participant Database
Viewer->>StudentsRoute: Request student directory
StudentsRoute->>Academics: Resolve school peers
Academics->>Database: Traverse enrollment and school relationships
Database-->>Academics: Peer user IDs
StudentsRoute->>Database: Read visibility and directory fields
Database-->>StudentsRoute: Visible users and courses
StudentsRoute-->>Viewer: Reduced student directory
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging6a99676Commit Preview URL

Branch Preview URL
Jul 17 2026, 03:15 PM

@AndresL230
AndresL230 marked this pull request as ready for review July 17, 2026 16:20
@AndresL230
AndresL230 merged commit 4227689 into mainJul 17, 2026
6 checks passed
@AndresL230
AndresL230 deleted the worktree-issue-batch-342-343-285 branch July 17, 2026 16:26
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343) - #353

Merged
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285
Jul 17, 2026
Merged

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343)#353
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285

Conversation

@AndresL230

@AndresL230AndresL230 commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator

Three independent fixes from the issue batch. Each is a self-contained commit; reviewable commit-by-commit.

Closes#342
Closes#285
Closes#343


#342 — scope /api/social/students to the viewer's school (security, P2)

get_students returned a profile for every user in the DB — name, streak, courses, and per-concept mastery — to any authenticated caller. The session user_id was bound and never used, so the endpoint authenticated without authorizing.

Decision (product call, confirmed): scope to school + honor profile_visibility; trim mastery from the payload.

  • School scope via a new bulk helper academics.school_peer_user_ids(user_id) — walks enrollments → course_offerings.course_id → courses.school_id and back to every user enrolled at those schools. Multi-step reads per the module's house style; not cached (mutable visibility boundary); fails closed on empty scope, mirroring the enrollment-scoping pattern in calendar.py.
  • Visibility:profile_visibility == 'private' users are dropped from the listing. Migration 0031 widens the user_settings CHECK to allow the 'school' tier the Settings UI has always offered but the DB rejected (a latent 500 on selecting it); update_settings now validates the value → 400 instead of a raw CHECK violation.
  • Payload trimmed to name/streak/courses. The mastery histogram + top concepts are academic-performance data that belong on the profile page (already gated on profile_visibility), not a browsable directory. Frontend directory, StudentRow type, and local-mode fixture updated to match.

⚠️Deploy note — migration 0031 is applied per-environment, not by merge:

  • Staging DB: already applied + verified (2026-07-17). The staging project has a clean schema_migrations ledger; only 0031 was pending. Constraint is now CHECK (profile_visibility = ANY (ARRAY['public','school','private'])). Safe to have applied ahead of the code — it only removes the pre-existing 'school' 500 in Settings.
  • Prod DB: NOT applied — do NOT run a plain db.migrate against prod. Prod has no schema_migrations ledger (Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317), so the runner would treat all 34 migrations as pending and try to re-run them from scratch. --baseline alone is also wrong (it would mark 0031 applied without running it). Correct sequence as part of the main→production promotion: (1) baseline 00010030 on prod so the already-present schema is recorded, (2) then apply only 0031 for real. This fixes the Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317 gap for prod as a side effect and needs a human watching.

#285 — promote stub users on sign-in instead of 409'ing (auth)

Sign-in 500'd whenever a stubusers row existed (id set, google_id NULL — created by graph_service.ensure_user_exists, reachable after a row delete because the HMAC sapling_session cookie outlives it). The new-user branch looked up by google_id only (NULL never matches), fell through to a blind INSERT on the deterministic id user_{google_id}, and collided on users_pkey → unhandled 409 → permanent sign-in 500 loop.

  • Both blind inserts (usersanduser_profiles — its user_id is also a PK and 409s for a stub that reached onboarding) become upserts.
  • on_conflict is the primary key, not google_id: the stub's google_id is NULL and NULLs never conflict, so only an id-conflict resolves it; merge-duplicates fills the NULL auth columns in.
  • The existing-user branch is untouched, so a legacy row whose id ≠ user_{google_id} keeps its id.
  • Tests drive the real/google/callback with the mocked tables raising the exact production 409 on insert — a regression to a blind insert fails loudly.

#343 — enable CodeRabbit on long-lived integration branches (CI, P2)

CodeRabbit reviews only the default branch unless base branches are listed, and the repo had no .coderabbit.yaml at all — so PRs targeting an integration branch got "Review skipped" while CI stayed green.


Verification

  • Backend: 966 passed, only the 3 pre-existing failures on clean main (test_storage_service ×2, test_ocr_pipeline event-loop error). ruff check clean on all touched files.
  • Frontend: tsc --noEmit clean, eslint clean on touched files, 88 vitest tests pass.
  • New tests: test_auth_stub_promotion.py (7), rewritten test_social_students.py (scope/visibility/payload + school_peer_user_ids traversal), test_profile_routes.py visibility-validation.

Not included

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a school-scoped student directory that shows peers based on shared school enrollment.
    • Added profile visibility options: Public, School, and Private.
    • Directory entries now display student names, courses, and learning streaks.
  • Bug Fixes

    • Improved Google sign-in for accounts with pre-existing records.
    • Invalid profile visibility values now return a clear validation error instead of a server error.
    • Private profiles are excluded from the school directory.

AndresL230and others added 3 commits July 17, 2026 11:11
CodeRabbit reviews only the default branch (main) unless base branches are
listed explicitly, and this repo had no .coderabbit.yaml at all — so every PR
targeting a long-lived integration branch got "Review skipped" while CI still
went green, making the absence of a review read as "nothing to flag."
The gap that still matters is `production`: main -> production promotion PRs
(#305, #314) are the last gate before prod and were never machine-reviewed.
`staging` is listed defensively — that branch was deleted 2026-07-15 (after #334
merged / #337 closed) and no open PR currently targets a non-main base, but it
was a real integration branch and should be covered if recreated.
Patterns are anchored regex so `staging` can't also match feature branches like
`docs/staging-environment-plan`. Validated against coderabbit schema.v2.json.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Google sign-in 500'd whenever a stub `users` row existed (id set, google_id
NULL) — created by `graph_service.ensure_user_exists` for any authenticated
graph request, and reachable after a row delete because the HMAC-signed
`sapling_session` cookie outlives it. The new-user branch looked users up by
google_id only (NULL never matches), fell through to a blind INSERT on the
deterministic id `user_{google_id}`, and collided on users_pkey -> unhandled
409 -> permanent sign-in 500 loop.
Swap both blind inserts (users and user_profiles — the latter's user_id is also
a PK and 409s for a stub that reached onboarding) for upserts. on_conflict is
the primary key, not google_id: the stub's google_id is NULL and NULLs never
conflict, so only an id-conflict resolves it; merge-duplicates fills the stub's
NULL auth columns in, promoting it to a real user. The existing-user branch is
left untouched so a legacy row whose id != user_{google_id} keeps its id.
Tests drive the real /google/callback with the mocked users/user_profiles
tables raising the exact production 409 on insert, so any regression to a blind
insert fails loudly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
get_students returned a profile for every user in the DB — name, streak,
courses, and per-concept mastery — to any authenticated caller; the session
user_id was bound and never used, so it authenticated without authorizing.
Two boundaries now apply, matching what the UI already claims ("Students at
your school") and the existing profile_visibility precedent:
- School scope via a new bulk helper `academics.school_peer_user_ids`, which
walks enrollments -> course_offerings.course_id -> courses.school_id and back
to every user enrolled at those schools. Multi-step reads per the module's
house style; not cached (it's a mutable visibility boundary); fails closed on
an empty scope, mirroring the enrollment-scoping pattern in calendar.py.
- profile_visibility: 'private' users are dropped from the listing. 0031 widens
the user_settings CHECK to allow the 'school' tier the Settings UI has always
offered but the DB rejected (a latent 500), and update_settings now validates
the value so a bad one returns 400 instead of a raw CHECK violation.
The payload is trimmed to name/streak/courses — the mastery histogram and top
concepts are academic-performance data that belong on the profile page (already
gated on profile_visibility), not in a browsable directory. Frontend directory,
StudentRow type, and local-mode fixture updated to match.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitaiBot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: b3532c9e-8a23-43de-ac11-61c4e3854bbb

📥 Commits

Reviewing files that changed from the base of the PR and between 9adf8d8 and 6a99676.

📒 Files selected for processing (12)
  • .coderabbit.yaml
  • backend/db/migrations/0031_profile_visibility_school.sql
  • backend/routes/auth.py
  • backend/routes/profile.py
  • backend/routes/social.py
  • backend/services/academics.py
  • backend/tests/test_auth_stub_promotion.py
  • backend/tests/test_profile_routes.py
  • backend/tests/test_social_students.py
  • frontend/src/components/screens/Social.tsx
  • frontend/src/lib/api.ts
  • frontend/src/lib/localData.ts

📝 Walkthrough

Walkthrough

The PR adds school-scoped, visibility-aware student directories with reduced mastery-free payloads, updates frontend rendering and local data, makes Google OAuth provisioning conflict-safe for stub users, validates profile visibility values, and configures automated review branches.

Changes

School Directory Visibility

Layer / File(s)Summary
Profile visibility contract
backend/db/migrations/0031_profile_visibility_school.sql, backend/routes/profile.py, backend/tests/test_profile_routes.py
The profile_visibility constraint accepts public, school, and private, while the settings route rejects other values with HTTP 400.
School-scoped directory flow
backend/services/academics.py, backend/routes/social.py, backend/tests/test_social_students.py
The students endpoint resolves school peers, excludes private profiles, fails closed without scope, and returns only user_id, name, streak, and deduplicated courses.
Directory payload and presentation
frontend/src/lib/api.ts, frontend/src/lib/localData.ts, frontend/src/components/screens/Social.tsx
Frontend types, local records, search filtering, and roster rows no longer use mastery fields and display streaks instead.

OAuth Stub Promotion

Layer / File(s)Summary
Google user provisioning
backend/routes/auth.py, backend/tests/test_auth_stub_promotion.py
Google sign-in uses ID-keyed upserts for new users and profiles, while existing approved users continue through the update path and related redirect behavior is tested.

Review Configuration

Layer / File(s)Summary
Automated review branch rules
.coderabbit.yaml
Repository language is set to en-US, and automatic reviews target only production and staging base branches.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
participant Viewer
participant StudentsRoute
participant Academics
participant Database
Viewer->>StudentsRoute: Request student directory
StudentsRoute->>Academics: Resolve school peers
Academics->>Database: Traverse enrollment and school relationships
Database-->>Academics: Peer user IDs
StudentsRoute->>Database: Read visibility and directory fields
Database-->>StudentsRoute: Visible users and courses
StudentsRoute-->>Viewer: Reduced student directory
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging6a99676Commit Preview URL

Branch Preview URL
Jul 17 2026, 03:15 PM

@AndresL230
AndresL230 marked this pull request as ready for review July 17, 2026 16:20
@AndresL230
AndresL230 merged commit 4227689 into mainJul 17, 2026
6 checks passed
@AndresL230
AndresL230 deleted the worktree-issue-batch-342-343-285 branch July 17, 2026 16:26
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343) - #353

Merged
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285
Jul 17, 2026
Merged

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343)#353
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285

Conversation

@AndresL230

@AndresL230AndresL230 commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator

Three independent fixes from the issue batch. Each is a self-contained commit; reviewable commit-by-commit.

Closes#342
Closes#285
Closes#343


#342 — scope /api/social/students to the viewer's school (security, P2)

get_students returned a profile for every user in the DB — name, streak, courses, and per-concept mastery — to any authenticated caller. The session user_id was bound and never used, so the endpoint authenticated without authorizing.

Decision (product call, confirmed): scope to school + honor profile_visibility; trim mastery from the payload.

  • School scope via a new bulk helper academics.school_peer_user_ids(user_id) — walks enrollments → course_offerings.course_id → courses.school_id and back to every user enrolled at those schools. Multi-step reads per the module's house style; not cached (mutable visibility boundary); fails closed on empty scope, mirroring the enrollment-scoping pattern in calendar.py.
  • Visibility:profile_visibility == 'private' users are dropped from the listing. Migration 0031 widens the user_settings CHECK to allow the 'school' tier the Settings UI has always offered but the DB rejected (a latent 500 on selecting it); update_settings now validates the value → 400 instead of a raw CHECK violation.
  • Payload trimmed to name/streak/courses. The mastery histogram + top concepts are academic-performance data that belong on the profile page (already gated on profile_visibility), not a browsable directory. Frontend directory, StudentRow type, and local-mode fixture updated to match.

⚠️Deploy note — migration 0031 is applied per-environment, not by merge:

  • Staging DB: already applied + verified (2026-07-17). The staging project has a clean schema_migrations ledger; only 0031 was pending. Constraint is now CHECK (profile_visibility = ANY (ARRAY['public','school','private'])). Safe to have applied ahead of the code — it only removes the pre-existing 'school' 500 in Settings.
  • Prod DB: NOT applied — do NOT run a plain db.migrate against prod. Prod has no schema_migrations ledger (Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317), so the runner would treat all 34 migrations as pending and try to re-run them from scratch. --baseline alone is also wrong (it would mark 0031 applied without running it). Correct sequence as part of the main→production promotion: (1) baseline 00010030 on prod so the already-present schema is recorded, (2) then apply only 0031 for real. This fixes the Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317 gap for prod as a side effect and needs a human watching.

#285 — promote stub users on sign-in instead of 409'ing (auth)

Sign-in 500'd whenever a stubusers row existed (id set, google_id NULL — created by graph_service.ensure_user_exists, reachable after a row delete because the HMAC sapling_session cookie outlives it). The new-user branch looked up by google_id only (NULL never matches), fell through to a blind INSERT on the deterministic id user_{google_id}, and collided on users_pkey → unhandled 409 → permanent sign-in 500 loop.

  • Both blind inserts (usersanduser_profiles — its user_id is also a PK and 409s for a stub that reached onboarding) become upserts.
  • on_conflict is the primary key, not google_id: the stub's google_id is NULL and NULLs never conflict, so only an id-conflict resolves it; merge-duplicates fills the NULL auth columns in.
  • The existing-user branch is untouched, so a legacy row whose id ≠ user_{google_id} keeps its id.
  • Tests drive the real/google/callback with the mocked tables raising the exact production 409 on insert — a regression to a blind insert fails loudly.

#343 — enable CodeRabbit on long-lived integration branches (CI, P2)

CodeRabbit reviews only the default branch unless base branches are listed, and the repo had no .coderabbit.yaml at all — so PRs targeting an integration branch got "Review skipped" while CI stayed green.


Verification

  • Backend: 966 passed, only the 3 pre-existing failures on clean main (test_storage_service ×2, test_ocr_pipeline event-loop error). ruff check clean on all touched files.
  • Frontend: tsc --noEmit clean, eslint clean on touched files, 88 vitest tests pass.
  • New tests: test_auth_stub_promotion.py (7), rewritten test_social_students.py (scope/visibility/payload + school_peer_user_ids traversal), test_profile_routes.py visibility-validation.

Not included

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a school-scoped student directory that shows peers based on shared school enrollment.
    • Added profile visibility options: Public, School, and Private.
    • Directory entries now display student names, courses, and learning streaks.
  • Bug Fixes

    • Improved Google sign-in for accounts with pre-existing records.
    • Invalid profile visibility values now return a clear validation error instead of a server error.
    • Private profiles are excluded from the school directory.

AndresL230and others added 3 commits July 17, 2026 11:11
CodeRabbit reviews only the default branch (main) unless base branches are
listed explicitly, and this repo had no .coderabbit.yaml at all — so every PR
targeting a long-lived integration branch got "Review skipped" while CI still
went green, making the absence of a review read as "nothing to flag."
The gap that still matters is `production`: main -> production promotion PRs
(#305, #314) are the last gate before prod and were never machine-reviewed.
`staging` is listed defensively — that branch was deleted 2026-07-15 (after #334
merged / #337 closed) and no open PR currently targets a non-main base, but it
was a real integration branch and should be covered if recreated.
Patterns are anchored regex so `staging` can't also match feature branches like
`docs/staging-environment-plan`. Validated against coderabbit schema.v2.json.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Google sign-in 500'd whenever a stub `users` row existed (id set, google_id
NULL) — created by `graph_service.ensure_user_exists` for any authenticated
graph request, and reachable after a row delete because the HMAC-signed
`sapling_session` cookie outlives it. The new-user branch looked users up by
google_id only (NULL never matches), fell through to a blind INSERT on the
deterministic id `user_{google_id}`, and collided on users_pkey -> unhandled
409 -> permanent sign-in 500 loop.
Swap both blind inserts (users and user_profiles — the latter's user_id is also
a PK and 409s for a stub that reached onboarding) for upserts. on_conflict is
the primary key, not google_id: the stub's google_id is NULL and NULLs never
conflict, so only an id-conflict resolves it; merge-duplicates fills the stub's
NULL auth columns in, promoting it to a real user. The existing-user branch is
left untouched so a legacy row whose id != user_{google_id} keeps its id.
Tests drive the real /google/callback with the mocked users/user_profiles
tables raising the exact production 409 on insert, so any regression to a blind
insert fails loudly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
get_students returned a profile for every user in the DB — name, streak,
courses, and per-concept mastery — to any authenticated caller; the session
user_id was bound and never used, so it authenticated without authorizing.
Two boundaries now apply, matching what the UI already claims ("Students at
your school") and the existing profile_visibility precedent:
- School scope via a new bulk helper `academics.school_peer_user_ids`, which
walks enrollments -> course_offerings.course_id -> courses.school_id and back
to every user enrolled at those schools. Multi-step reads per the module's
house style; not cached (it's a mutable visibility boundary); fails closed on
an empty scope, mirroring the enrollment-scoping pattern in calendar.py.
- profile_visibility: 'private' users are dropped from the listing. 0031 widens
the user_settings CHECK to allow the 'school' tier the Settings UI has always
offered but the DB rejected (a latent 500), and update_settings now validates
the value so a bad one returns 400 instead of a raw CHECK violation.
The payload is trimmed to name/streak/courses — the mastery histogram and top
concepts are academic-performance data that belong on the profile page (already
gated on profile_visibility), not in a browsable directory. Frontend directory,
StudentRow type, and local-mode fixture updated to match.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitaiBot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: b3532c9e-8a23-43de-ac11-61c4e3854bbb

📥 Commits

Reviewing files that changed from the base of the PR and between 9adf8d8 and 6a99676.

📒 Files selected for processing (12)
  • .coderabbit.yaml
  • backend/db/migrations/0031_profile_visibility_school.sql
  • backend/routes/auth.py
  • backend/routes/profile.py
  • backend/routes/social.py
  • backend/services/academics.py
  • backend/tests/test_auth_stub_promotion.py
  • backend/tests/test_profile_routes.py
  • backend/tests/test_social_students.py
  • frontend/src/components/screens/Social.tsx
  • frontend/src/lib/api.ts
  • frontend/src/lib/localData.ts

📝 Walkthrough

Walkthrough

The PR adds school-scoped, visibility-aware student directories with reduced mastery-free payloads, updates frontend rendering and local data, makes Google OAuth provisioning conflict-safe for stub users, validates profile visibility values, and configures automated review branches.

Changes

School Directory Visibility

Layer / File(s)Summary
Profile visibility contract
backend/db/migrations/0031_profile_visibility_school.sql, backend/routes/profile.py, backend/tests/test_profile_routes.py
The profile_visibility constraint accepts public, school, and private, while the settings route rejects other values with HTTP 400.
School-scoped directory flow
backend/services/academics.py, backend/routes/social.py, backend/tests/test_social_students.py
The students endpoint resolves school peers, excludes private profiles, fails closed without scope, and returns only user_id, name, streak, and deduplicated courses.
Directory payload and presentation
frontend/src/lib/api.ts, frontend/src/lib/localData.ts, frontend/src/components/screens/Social.tsx
Frontend types, local records, search filtering, and roster rows no longer use mastery fields and display streaks instead.

OAuth Stub Promotion

Layer / File(s)Summary
Google user provisioning
backend/routes/auth.py, backend/tests/test_auth_stub_promotion.py
Google sign-in uses ID-keyed upserts for new users and profiles, while existing approved users continue through the update path and related redirect behavior is tested.

Review Configuration

Layer / File(s)Summary
Automated review branch rules
.coderabbit.yaml
Repository language is set to en-US, and automatic reviews target only production and staging base branches.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
participant Viewer
participant StudentsRoute
participant Academics
participant Database
Viewer->>StudentsRoute: Request student directory
StudentsRoute->>Academics: Resolve school peers
Academics->>Database: Traverse enrollment and school relationships
Database-->>Academics: Peer user IDs
StudentsRoute->>Database: Read visibility and directory fields
Database-->>StudentsRoute: Visible users and courses
StudentsRoute-->>Viewer: Reduced student directory
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging6a99676Commit Preview URL

Branch Preview URL
Jul 17 2026, 03:15 PM

@AndresL230
AndresL230 marked this pull request as ready for review July 17, 2026 16:20
@AndresL230
AndresL230 merged commit 4227689 into mainJul 17, 2026
6 checks passed
@AndresL230
AndresL230 deleted the worktree-issue-batch-342-343-285 branch July 17, 2026 16:26
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343) - #353

Merged
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285
Jul 17, 2026
Merged

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343)#353
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285

Conversation

@AndresL230

@AndresL230AndresL230 commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator

Three independent fixes from the issue batch. Each is a self-contained commit; reviewable commit-by-commit.

Closes#342
Closes#285
Closes#343


#342 — scope /api/social/students to the viewer's school (security, P2)

get_students returned a profile for every user in the DB — name, streak, courses, and per-concept mastery — to any authenticated caller. The session user_id was bound and never used, so the endpoint authenticated without authorizing.

Decision (product call, confirmed): scope to school + honor profile_visibility; trim mastery from the payload.

  • School scope via a new bulk helper academics.school_peer_user_ids(user_id) — walks enrollments → course_offerings.course_id → courses.school_id and back to every user enrolled at those schools. Multi-step reads per the module's house style; not cached (mutable visibility boundary); fails closed on empty scope, mirroring the enrollment-scoping pattern in calendar.py.
  • Visibility:profile_visibility == 'private' users are dropped from the listing. Migration 0031 widens the user_settings CHECK to allow the 'school' tier the Settings UI has always offered but the DB rejected (a latent 500 on selecting it); update_settings now validates the value → 400 instead of a raw CHECK violation.
  • Payload trimmed to name/streak/courses. The mastery histogram + top concepts are academic-performance data that belong on the profile page (already gated on profile_visibility), not a browsable directory. Frontend directory, StudentRow type, and local-mode fixture updated to match.

⚠️Deploy note — migration 0031 is applied per-environment, not by merge:

  • Staging DB: already applied + verified (2026-07-17). The staging project has a clean schema_migrations ledger; only 0031 was pending. Constraint is now CHECK (profile_visibility = ANY (ARRAY['public','school','private'])). Safe to have applied ahead of the code — it only removes the pre-existing 'school' 500 in Settings.
  • Prod DB: NOT applied — do NOT run a plain db.migrate against prod. Prod has no schema_migrations ledger (Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317), so the runner would treat all 34 migrations as pending and try to re-run them from scratch. --baseline alone is also wrong (it would mark 0031 applied without running it). Correct sequence as part of the main→production promotion: (1) baseline 00010030 on prod so the already-present schema is recorded, (2) then apply only 0031 for real. This fixes the Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317 gap for prod as a side effect and needs a human watching.

#285 — promote stub users on sign-in instead of 409'ing (auth)

Sign-in 500'd whenever a stubusers row existed (id set, google_id NULL — created by graph_service.ensure_user_exists, reachable after a row delete because the HMAC sapling_session cookie outlives it). The new-user branch looked up by google_id only (NULL never matches), fell through to a blind INSERT on the deterministic id user_{google_id}, and collided on users_pkey → unhandled 409 → permanent sign-in 500 loop.

  • Both blind inserts (usersanduser_profiles — its user_id is also a PK and 409s for a stub that reached onboarding) become upserts.
  • on_conflict is the primary key, not google_id: the stub's google_id is NULL and NULLs never conflict, so only an id-conflict resolves it; merge-duplicates fills the NULL auth columns in.
  • The existing-user branch is untouched, so a legacy row whose id ≠ user_{google_id} keeps its id.
  • Tests drive the real/google/callback with the mocked tables raising the exact production 409 on insert — a regression to a blind insert fails loudly.

#343 — enable CodeRabbit on long-lived integration branches (CI, P2)

CodeRabbit reviews only the default branch unless base branches are listed, and the repo had no .coderabbit.yaml at all — so PRs targeting an integration branch got "Review skipped" while CI stayed green.


Verification

  • Backend: 966 passed, only the 3 pre-existing failures on clean main (test_storage_service ×2, test_ocr_pipeline event-loop error). ruff check clean on all touched files.
  • Frontend: tsc --noEmit clean, eslint clean on touched files, 88 vitest tests pass.
  • New tests: test_auth_stub_promotion.py (7), rewritten test_social_students.py (scope/visibility/payload + school_peer_user_ids traversal), test_profile_routes.py visibility-validation.

Not included

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a school-scoped student directory that shows peers based on shared school enrollment.
    • Added profile visibility options: Public, School, and Private.
    • Directory entries now display student names, courses, and learning streaks.
  • Bug Fixes

    • Improved Google sign-in for accounts with pre-existing records.
    • Invalid profile visibility values now return a clear validation error instead of a server error.
    • Private profiles are excluded from the school directory.

AndresL230and others added 3 commits July 17, 2026 11:11
CodeRabbit reviews only the default branch (main) unless base branches are
listed explicitly, and this repo had no .coderabbit.yaml at all — so every PR
targeting a long-lived integration branch got "Review skipped" while CI still
went green, making the absence of a review read as "nothing to flag."
The gap that still matters is `production`: main -> production promotion PRs
(#305, #314) are the last gate before prod and were never machine-reviewed.
`staging` is listed defensively — that branch was deleted 2026-07-15 (after #334
merged / #337 closed) and no open PR currently targets a non-main base, but it
was a real integration branch and should be covered if recreated.
Patterns are anchored regex so `staging` can't also match feature branches like
`docs/staging-environment-plan`. Validated against coderabbit schema.v2.json.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Google sign-in 500'd whenever a stub `users` row existed (id set, google_id
NULL) — created by `graph_service.ensure_user_exists` for any authenticated
graph request, and reachable after a row delete because the HMAC-signed
`sapling_session` cookie outlives it. The new-user branch looked users up by
google_id only (NULL never matches), fell through to a blind INSERT on the
deterministic id `user_{google_id}`, and collided on users_pkey -> unhandled
409 -> permanent sign-in 500 loop.
Swap both blind inserts (users and user_profiles — the latter's user_id is also
a PK and 409s for a stub that reached onboarding) for upserts. on_conflict is
the primary key, not google_id: the stub's google_id is NULL and NULLs never
conflict, so only an id-conflict resolves it; merge-duplicates fills the stub's
NULL auth columns in, promoting it to a real user. The existing-user branch is
left untouched so a legacy row whose id != user_{google_id} keeps its id.
Tests drive the real /google/callback with the mocked users/user_profiles
tables raising the exact production 409 on insert, so any regression to a blind
insert fails loudly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
get_students returned a profile for every user in the DB — name, streak,
courses, and per-concept mastery — to any authenticated caller; the session
user_id was bound and never used, so it authenticated without authorizing.
Two boundaries now apply, matching what the UI already claims ("Students at
your school") and the existing profile_visibility precedent:
- School scope via a new bulk helper `academics.school_peer_user_ids`, which
walks enrollments -> course_offerings.course_id -> courses.school_id and back
to every user enrolled at those schools. Multi-step reads per the module's
house style; not cached (it's a mutable visibility boundary); fails closed on
an empty scope, mirroring the enrollment-scoping pattern in calendar.py.
- profile_visibility: 'private' users are dropped from the listing. 0031 widens
the user_settings CHECK to allow the 'school' tier the Settings UI has always
offered but the DB rejected (a latent 500), and update_settings now validates
the value so a bad one returns 400 instead of a raw CHECK violation.
The payload is trimmed to name/streak/courses — the mastery histogram and top
concepts are academic-performance data that belong on the profile page (already
gated on profile_visibility), not in a browsable directory. Frontend directory,
StudentRow type, and local-mode fixture updated to match.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitaiBot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: b3532c9e-8a23-43de-ac11-61c4e3854bbb

📥 Commits

Reviewing files that changed from the base of the PR and between 9adf8d8 and 6a99676.

📒 Files selected for processing (12)
  • .coderabbit.yaml
  • backend/db/migrations/0031_profile_visibility_school.sql
  • backend/routes/auth.py
  • backend/routes/profile.py
  • backend/routes/social.py
  • backend/services/academics.py
  • backend/tests/test_auth_stub_promotion.py
  • backend/tests/test_profile_routes.py
  • backend/tests/test_social_students.py
  • frontend/src/components/screens/Social.tsx
  • frontend/src/lib/api.ts
  • frontend/src/lib/localData.ts

📝 Walkthrough

Walkthrough

The PR adds school-scoped, visibility-aware student directories with reduced mastery-free payloads, updates frontend rendering and local data, makes Google OAuth provisioning conflict-safe for stub users, validates profile visibility values, and configures automated review branches.

Changes

School Directory Visibility

Layer / File(s)Summary
Profile visibility contract
backend/db/migrations/0031_profile_visibility_school.sql, backend/routes/profile.py, backend/tests/test_profile_routes.py
The profile_visibility constraint accepts public, school, and private, while the settings route rejects other values with HTTP 400.
School-scoped directory flow
backend/services/academics.py, backend/routes/social.py, backend/tests/test_social_students.py
The students endpoint resolves school peers, excludes private profiles, fails closed without scope, and returns only user_id, name, streak, and deduplicated courses.
Directory payload and presentation
frontend/src/lib/api.ts, frontend/src/lib/localData.ts, frontend/src/components/screens/Social.tsx
Frontend types, local records, search filtering, and roster rows no longer use mastery fields and display streaks instead.

OAuth Stub Promotion

Layer / File(s)Summary
Google user provisioning
backend/routes/auth.py, backend/tests/test_auth_stub_promotion.py
Google sign-in uses ID-keyed upserts for new users and profiles, while existing approved users continue through the update path and related redirect behavior is tested.

Review Configuration

Layer / File(s)Summary
Automated review branch rules
.coderabbit.yaml
Repository language is set to en-US, and automatic reviews target only production and staging base branches.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
participant Viewer
participant StudentsRoute
participant Academics
participant Database
Viewer->>StudentsRoute: Request student directory
StudentsRoute->>Academics: Resolve school peers
Academics->>Database: Traverse enrollment and school relationships
Database-->>Academics: Peer user IDs
StudentsRoute->>Database: Read visibility and directory fields
Database-->>StudentsRoute: Visible users and courses
StudentsRoute-->>Viewer: Reduced student directory
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging6a99676Commit Preview URL

Branch Preview URL
Jul 17 2026, 03:15 PM

@AndresL230
AndresL230 marked this pull request as ready for review July 17, 2026 16:20
@AndresL230
AndresL230 merged commit 4227689 into mainJul 17, 2026
6 checks passed
@AndresL230
AndresL230 deleted the worktree-issue-batch-342-343-285 branch July 17, 2026 16:26
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343) - #353

Merged
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285
Jul 17, 2026
Merged

Batch: social-directory scoping (#342), auth stub promotion (#285), CodeRabbit on integration branches (#343)#353
AndresL230 merged 3 commits into
mainfrom
worktree-issue-batch-342-343-285

Conversation

@AndresL230

@AndresL230AndresL230 commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator

Three independent fixes from the issue batch. Each is a self-contained commit; reviewable commit-by-commit.

Closes#342
Closes#285
Closes#343


#342 — scope /api/social/students to the viewer's school (security, P2)

get_students returned a profile for every user in the DB — name, streak, courses, and per-concept mastery — to any authenticated caller. The session user_id was bound and never used, so the endpoint authenticated without authorizing.

Decision (product call, confirmed): scope to school + honor profile_visibility; trim mastery from the payload.

  • School scope via a new bulk helper academics.school_peer_user_ids(user_id) — walks enrollments → course_offerings.course_id → courses.school_id and back to every user enrolled at those schools. Multi-step reads per the module's house style; not cached (mutable visibility boundary); fails closed on empty scope, mirroring the enrollment-scoping pattern in calendar.py.
  • Visibility:profile_visibility == 'private' users are dropped from the listing. Migration 0031 widens the user_settings CHECK to allow the 'school' tier the Settings UI has always offered but the DB rejected (a latent 500 on selecting it); update_settings now validates the value → 400 instead of a raw CHECK violation.
  • Payload trimmed to name/streak/courses. The mastery histogram + top concepts are academic-performance data that belong on the profile page (already gated on profile_visibility), not a browsable directory. Frontend directory, StudentRow type, and local-mode fixture updated to match.

⚠️Deploy note — migration 0031 is applied per-environment, not by merge:

  • Staging DB: already applied + verified (2026-07-17). The staging project has a clean schema_migrations ledger; only 0031 was pending. Constraint is now CHECK (profile_visibility = ANY (ARRAY['public','school','private'])). Safe to have applied ahead of the code — it only removes the pre-existing 'school' 500 in Settings.
  • Prod DB: NOT applied — do NOT run a plain db.migrate against prod. Prod has no schema_migrations ledger (Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317), so the runner would treat all 34 migrations as pending and try to re-run them from scratch. --baseline alone is also wrong (it would mark 0031 applied without running it). Correct sequence as part of the main→production promotion: (1) baseline 00010030 on prod so the already-present schema is recorded, (2) then apply only 0031 for real. This fixes the Prod migration ledger may have drifted from repo (staging did — 4 unrecorded migrations) #317 gap for prod as a side effect and needs a human watching.

#285 — promote stub users on sign-in instead of 409'ing (auth)

Sign-in 500'd whenever a stubusers row existed (id set, google_id NULL — created by graph_service.ensure_user_exists, reachable after a row delete because the HMAC sapling_session cookie outlives it). The new-user branch looked up by google_id only (NULL never matches), fell through to a blind INSERT on the deterministic id user_{google_id}, and collided on users_pkey → unhandled 409 → permanent sign-in 500 loop.

  • Both blind inserts (usersanduser_profiles — its user_id is also a PK and 409s for a stub that reached onboarding) become upserts.
  • on_conflict is the primary key, not google_id: the stub's google_id is NULL and NULLs never conflict, so only an id-conflict resolves it; merge-duplicates fills the NULL auth columns in.
  • The existing-user branch is untouched, so a legacy row whose id ≠ user_{google_id} keeps its id.
  • Tests drive the real/google/callback with the mocked tables raising the exact production 409 on insert — a regression to a blind insert fails loudly.

#343 — enable CodeRabbit on long-lived integration branches (CI, P2)

CodeRabbit reviews only the default branch unless base branches are listed, and the repo had no .coderabbit.yaml at all — so PRs targeting an integration branch got "Review skipped" while CI stayed green.


Verification

  • Backend: 966 passed, only the 3 pre-existing failures on clean main (test_storage_service ×2, test_ocr_pipeline event-loop error). ruff check clean on all touched files.
  • Frontend: tsc --noEmit clean, eslint clean on touched files, 88 vitest tests pass.
  • New tests: test_auth_stub_promotion.py (7), rewritten test_social_students.py (scope/visibility/payload + school_peer_user_ids traversal), test_profile_routes.py visibility-validation.

Not included

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a school-scoped student directory that shows peers based on shared school enrollment.
    • Added profile visibility options: Public, School, and Private.
    • Directory entries now display student names, courses, and learning streaks.
  • Bug Fixes

    • Improved Google sign-in for accounts with pre-existing records.
    • Invalid profile visibility values now return a clear validation error instead of a server error.
    • Private profiles are excluded from the school directory.

AndresL230and others added 3 commits July 17, 2026 11:11
CodeRabbit reviews only the default branch (main) unless base branches are
listed explicitly, and this repo had no .coderabbit.yaml at all — so every PR
targeting a long-lived integration branch got "Review skipped" while CI still
went green, making the absence of a review read as "nothing to flag."
The gap that still matters is `production`: main -> production promotion PRs
(#305, #314) are the last gate before prod and were never machine-reviewed.
`staging` is listed defensively — that branch was deleted 2026-07-15 (after #334
merged / #337 closed) and no open PR currently targets a non-main base, but it
was a real integration branch and should be covered if recreated.
Patterns are anchored regex so `staging` can't also match feature branches like
`docs/staging-environment-plan`. Validated against coderabbit schema.v2.json.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Google sign-in 500'd whenever a stub `users` row existed (id set, google_id
NULL) — created by `graph_service.ensure_user_exists` for any authenticated
graph request, and reachable after a row delete because the HMAC-signed
`sapling_session` cookie outlives it. The new-user branch looked users up by
google_id only (NULL never matches), fell through to a blind INSERT on the
deterministic id `user_{google_id}`, and collided on users_pkey -> unhandled
409 -> permanent sign-in 500 loop.
Swap both blind inserts (users and user_profiles — the latter's user_id is also
a PK and 409s for a stub that reached onboarding) for upserts. on_conflict is
the primary key, not google_id: the stub's google_id is NULL and NULLs never
conflict, so only an id-conflict resolves it; merge-duplicates fills the stub's
NULL auth columns in, promoting it to a real user. The existing-user branch is
left untouched so a legacy row whose id != user_{google_id} keeps its id.
Tests drive the real /google/callback with the mocked users/user_profiles
tables raising the exact production 409 on insert, so any regression to a blind
insert fails loudly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
get_students returned a profile for every user in the DB — name, streak,
courses, and per-concept mastery — to any authenticated caller; the session
user_id was bound and never used, so it authenticated without authorizing.
Two boundaries now apply, matching what the UI already claims ("Students at
your school") and the existing profile_visibility precedent:
- School scope via a new bulk helper `academics.school_peer_user_ids`, which
walks enrollments -> course_offerings.course_id -> courses.school_id and back
to every user enrolled at those schools. Multi-step reads per the module's
house style; not cached (it's a mutable visibility boundary); fails closed on
an empty scope, mirroring the enrollment-scoping pattern in calendar.py.
- profile_visibility: 'private' users are dropped from the listing. 0031 widens
the user_settings CHECK to allow the 'school' tier the Settings UI has always
offered but the DB rejected (a latent 500), and update_settings now validates
the value so a bad one returns 400 instead of a raw CHECK violation.
The payload is trimmed to name/streak/courses — the mastery histogram and top
concepts are academic-performance data that belong on the profile page (already
gated on profile_visibility), not in a browsable directory. Frontend directory,
StudentRow type, and local-mode fixture updated to match.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitaiBot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: b3532c9e-8a23-43de-ac11-61c4e3854bbb

📥 Commits

Reviewing files that changed from the base of the PR and between 9adf8d8 and 6a99676.

📒 Files selected for processing (12)
  • .coderabbit.yaml
  • backend/db/migrations/0031_profile_visibility_school.sql
  • backend/routes/auth.py
  • backend/routes/profile.py
  • backend/routes/social.py
  • backend/services/academics.py
  • backend/tests/test_auth_stub_promotion.py
  • backend/tests/test_profile_routes.py
  • backend/tests/test_social_students.py
  • frontend/src/components/screens/Social.tsx
  • frontend/src/lib/api.ts
  • frontend/src/lib/localData.ts

📝 Walkthrough

Walkthrough

The PR adds school-scoped, visibility-aware student directories with reduced mastery-free payloads, updates frontend rendering and local data, makes Google OAuth provisioning conflict-safe for stub users, validates profile visibility values, and configures automated review branches.

Changes

School Directory Visibility

Layer / File(s)Summary
Profile visibility contract
backend/db/migrations/0031_profile_visibility_school.sql, backend/routes/profile.py, backend/tests/test_profile_routes.py
The profile_visibility constraint accepts public, school, and private, while the settings route rejects other values with HTTP 400.
School-scoped directory flow
backend/services/academics.py, backend/routes/social.py, backend/tests/test_social_students.py
The students endpoint resolves school peers, excludes private profiles, fails closed without scope, and returns only user_id, name, streak, and deduplicated courses.
Directory payload and presentation
frontend/src/lib/api.ts, frontend/src/lib/localData.ts, frontend/src/components/screens/Social.tsx
Frontend types, local records, search filtering, and roster rows no longer use mastery fields and display streaks instead.

OAuth Stub Promotion

Layer / File(s)Summary
Google user provisioning
backend/routes/auth.py, backend/tests/test_auth_stub_promotion.py
Google sign-in uses ID-keyed upserts for new users and profiles, while existing approved users continue through the update path and related redirect behavior is tested.

Review Configuration

Layer / File(s)Summary
Automated review branch rules
.coderabbit.yaml
Repository language is set to en-US, and automatic reviews target only production and staging base branches.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
participant Viewer
participant StudentsRoute
participant Academics
participant Database
Viewer->>StudentsRoute: Request student directory
StudentsRoute->>Academics: Resolve school peers
Academics->>Database: Traverse enrollment and school relationships
Database-->>Academics: Peer user IDs
StudentsRoute->>Database: Read visibility and directory fields
Database-->>StudentsRoute: Visible users and courses
StudentsRoute-->>Viewer: Reduced student directory
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging6a99676Commit Preview URL

Branch Preview URL
Jul 17 2026, 03:15 PM

@AndresL230
AndresL230 marked this pull request as ready for review July 17, 2026 16:20
@AndresL230
AndresL230 merged commit 4227689 into mainJul 17, 2026
6 checks passed
@AndresL230
AndresL230 deleted the worktree-issue-batch-342-343-285 branch July 17, 2026 16:26
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant

@AndresL230