Skip to content

feat(chat): charge agent-created conversation files to their human owner (#20678) - #21124

Closed
mrveiss wants to merge 2 commits into
mainfrom
issue-20678-quota-owner
Closed

mrveiss wants to merge 2 commits into
mainfrom
issue-20678-quota-owner

Conversation

@mrveiss

@mrveiss mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner

Refs #20678

Thinking Path

Agent-created conversation files were charged to the agent's name, so every user shared one agent quota and one user's agent could lock out everyone else's. Option B from #20678: add a quota_owner column, charge agent writes to the human owner, and keep uploaded_by as the record of who wrote the file.

Explicit rule

  • An agent write is charged to the conversation owner.
  • If the conversation records no owner, it is charged to the authenticated caller.
  • uploaded_by still records the writer.
  • Old rows keep COALESCE(quota_owner, uploaded_by); no stored row is rewritten.

The ownerless default (authenticated caller) awaits the maintainer's confirmation on #20678 (needs-decision).

AC3 (existing rows handled only through a human-approved proposal) is tracked in #21123, so this PR uses Refs, not Closes.

What Changed

  • autobot-backend/conversation_file_quota_owner.py (new): resolves the quota owner for agent writes and MCP session_write_file.
  • autobot-backend/api/conversation_files.py: agent_generate_file and _dispatch_mcp_tool pass quota_owner through.
  • autobot-backend/conversation_file_manager.py, conversation_file_quota.py, conversation_file_upload_info.py: store and charge by quota_owner.
  • Schema and migration 001_create_conversation_files: nullable quota_owner column.
  • autobot-backend/conversation_file_quota_owner_20678_test.py (new).
  • Merged current main (includes chore(merge-train): #20609 #20990 #20994 #20998 #21015 #21105, fix(chat): STRICT routes answer not-yours exactly like not-found (#20413) #21015); api/conversation_files.py merged without conflicts and both file-size ceilings are unchanged.

Verification

Run from a scratch copy of the merged tree: 83 passed (quota-owner 20678, quota-store 20217, manager init, real-manager 20225, review 20225, upload-limits 20217, strict-routes 20413). flake8 clean and black --check clean on the 7 changed Python files. CI is the confirming run.

Model Used

Claude Sonnet 5.5

@mrveiss mrveiss added this to the M3 - Refined GUI complete milestone Nov 8, 2026
@mrveiss mrveiss added the phase:M3.9 Chat, Agents, Analytics and Settings screens label Nov 8, 2026
@coderabbitai

coderabbitai Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 5 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between ecdcded and 4d91998.

Files ignored due to path filters: 1

  • scripts/python_file_size_known_large.py is excluded by !scripts/python_file_size_known_large.py
Files selected for processing: 11

  • autobot-backend/api/conversation_files.py
  • autobot-backend/conversation_file_manager.py
  • autobot-backend/conversation_file_mcp_dispatch.py
  • autobot-backend/conversation_file_quota.py
  • autobot-backend/conversation_file_quota_owner.py
  • autobot-backend/conversation_file_quota_owner_20678_test.py
  • autobot-backend/conversation_file_quota_owner_schema.py
  • autobot-backend/conversation_file_schema_version.py
  • autobot-backend/conversation_file_upload_info.py
  • autobot-backend/database/migrations/001_create_conversation_files.py
  • autobot-backend/database/schemas/conversation_files_schema.sql
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Share

@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Notice: 29 open PRs — past the runaway threshold (25)

This is not a request to defer this PR. There is no cap on open PRs (#19397) -- nothing blocks opening or pushing a PR.

This notice only means the count is high enough to be worth a glance for a runaway — something opening PRs in a loop, or a merge pipeline that has stalled so nothing is draining.

Currently open:

If the queue is draining normally, ignore this. Otherwise:

  1. Check whether CI is dispatching at all — see the ci-dispatch-watchdog status on these PRs
  2. Approved PRs land through the merge train the coordinator sequences (merge commits, never squash) -- check the open chore(merge-train) PR is moving, not each PR on its own
  3. Look for a loop opening near-identical PRs

Warn-only runaway detector — .github/workflows/pr-queue-gate.yml. It never blocks a merge.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Code review (code-reviewer pass) follow-up at 171aa40

#20678 AC Status Evidence
AC1: decision recorded met on the issue Option B, implemented here
AC2: one user's agent cannot refuse another user's agent writes, with a test met autobot-backend/conversation_file_quota_owner.py:resolve_agent_quota_owner and mcp_quota_owner; charge key _CHARGED = COALESCE(quota_owner, uploaded_by) in conversation_file_quota.py; test test_one_users_agent_cannot_exhaust_another_users_quota in conversation_file_quota_owner_20678_test.py
AC3: existing rows only through a human-approved proposal not in this PR tracked in #21123; this PR rewrites no stored row (test_the_column_is_added_to_an_older_database_and_no_row_changes, test_a_row_stored_before_the_column_is_still_charged_to_its_uploaded_by)

Pass-through: agent_generate_file and _dispatch_mcp_tool in autobot-backend/api/conversation_files.py. Column: quota_owner in conversation_files_schema.sql and ensure_quota_owner_schema.

Open: the ownerless default (charge the authenticated caller) awaits the maintainer's confirmation on #20678.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Code review (code-reviewer pass) follow-up at 171aa40

Verdict: APPROVE-equivalent. Option B is implemented as ruled; no blocking defect found. Four non-blocking findings below. This was a read-only review of git diff origin/main...origin/issue-20678-quota-owner; no code was run.

Severity file:line finding fix
LOW (test gap) autobot-backend/conversation_file_quota_owner_20678_test.py There is no test that a caller who does not own the conversation is refused before any charge. The code is correct (_authorize_file_operation runs validate_session_ownership(..., STRICT) in api/conversation_files.py before resolve_agent_quota_owner), but nothing pins that order. Also untested: read_owner raising denies instead of falling back to the caller, and the resize_within_quota path (row["quota_owner"] or row["uploaded_by"]) for an edit of an agent-written file. Add a non-owner /generate and /mcp/call case (404/403, zero rows); add a case where get_session_owner raises; add an update-content case where the edit is charged to quota_owner.
LOW (coupling) autobot-backend/database/migrations/001_create_conversation_files.py:19 The migration now imports conversation_file_quota_owner, which imports fastapi and security.session_posture at module level, only to reach the DDL helper ensure_quota_owner_schema. A schema migration should not depend on request-handling modules. Move ensure_quota_owner_schema and its SQL constants to a request-free module (or have it live beside the schema), and import that from both init paths.
LOW (scope) autobot-backend/api/conversation_files.py (agent_generate_file, _dispatch_mcp_tool), autobot-backend/conversation_file_manager.py (_initialize_schema docstring, migration comments) Unrelated edits ride along: the content and query variables are inlined, the agent_metadata merge is rewritten, and explanatory comments and a docstring are removed. They are behavior-preserving but add review noise. _dispatch_mcp_tool is also still well over 30 lines (pre-existing; it grew by one parameter and a line). Both touched files sit exactly at their ceilings in scripts/python_file_size_known_large.py (960 and 1199), so there is no headroom for later work. Drop the drive-by edits from this PR. Split _dispatch_mcp_tool per tool, in a separate PR if the file-size ceilings stay tight.
INFO autobot-backend/conversation_file_quota_owner.py:resolve_agent_quota_owner The conversation owner is looked up a second time after the ownership check (one extra history-manager read per write). An admin writing into another user's conversation charges that user, which is what option B and the ownerless rule specify. The rule text still says "confirm default" on #20678 (comment of 2026-11-08), so the PR should stay Refs, not Closes, until the maintainer confirms it. None required. Optionally reuse the owner already read by the ownership check.

Checked and found correct:

  • Option B: quota_owner is added; uploaded_by still records the writer. Agent writes via /generate and MCP session_write_file are charged to the conversation owner. The ownerless rule (conversation owner, else the authenticated caller) is stated once as OWNERLESS_AGENT_WRITE_RULE and in the module docstrings.
  • Lookup safety: the access check precedes the charge on both routes. read_owner denies on any lookup failure rather than falling through to the caller. Only a session that records no owner is charged to the caller; STRICT posture already limits that case to admins.
  • Migration: ensure_quota_owner_schema checks PRAGMA table_info before ALTER TABLE ADD COLUMN, then runs CREATE INDEX IF NOT EXISTS. It is idempotent and updates no rows. It is wired into both _initialize_schema and ConversationFilesMigration._execute_schema, and the schema file carries the column for fresh databases. The test asserts idempotence, an unchanged row and the index.
  • COALESCE consistency: the SQL expression is defined once as _CHARGED and used in _HELD, so the usage sum, the insert guard and the resize guard all share it. The resize owner is derived in Python the same way. insert_within_quota and UploadInfo.to_db_tuple both use charged_to. The expression index matches.
  • SQL injection: _CHARGED and _HELD are module constants; the owner and sizes are bound ? parameters. The # nosec B608 is justified.
  • No stored-row rewrite: no UPDATE or DELETE of existing rows. Pre-fix(chat): decide who pays quota for agent-created conversation files #20678 rows keep their old charge until a Umbrella: SLM Data hygiene page — detect and safely clean up orphaned data across services #17038 proposal is approved.
  • Tests: the behavior tests (one user's agent fills only its own quota, MCP writer agent, legacy no-owner session, human upload, NULL quota_owner row) fail without the fix. Before it, charges key on uploaded_by, so bob's scribe write would be refused at 413.
  • Config and store authority: nothing is hardcoded; USER_QUOTA_BYTES is still the existing constant. No store-authority concern.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Code review (code-reviewer pass) follow-up at f0218c2

All findings addressed in one commit, f0218c2. Still Refs #20678.

Finding Resolution (file:symbol)
Scope: unrelated edits, ceilings pinned api/conversation_files.py and conversation_file_manager.py restored to their origin/main text (inlined content/query, agent_metadata merge, comments and the _initialize_schema docstring all back); only quota_owner changes remain. Nothing was trimmed to fit: _dispatch_mcp_tool moved to conversation_file_mcp_dispatch.py:dispatch_mcp_tool (one handler per tool, each under 30 lines, dispatcher 8 lines), and _query_schema_version_sync body moved to conversation_file_schema_version.py:query_schema_version. Ceilings in scripts/python_file_size_known_large.py lowered: api/conversation_files.py 960 to 916, conversation_file_manager.py 1199 to 1193 (each equals the file's new size).
Coupling: migration imported request-handling module ensure_quota_owner_schema and its SQL moved to conversation_file_quota_owner_schema.py (imports only sqlite3 and the logger). Both callers updated: database/migrations/001_create_conversation_files.py and ConversationFileManager._initialize_schema.
Tests Added to conversation_file_quota_owner_20678_test.py: test_a_non_owner_is_refused_before_any_charge_on_both_agent_write_routes, test_an_owner_lookup_that_raises_denies_the_write_and_charges_nobody, test_editing_an_agent_written_file_is_charged_to_the_quota_owner_not_the_agent (the resize_within_quota path). Each fails with its guard removed in a scratch copy: authorization guards removed (1 failed), resolve_agent_quota_owner falling back to the caller on a raising lookup (1 failed), resize_within_quota using uploaded_by instead of quota_owner (1 failed).
INFO: owner read twice Not changed. These routes are on the admin-only router, and validate_strict returns for an admin before reading the owner, so there is one owner read per write, in resolve_agent_quota_owner. Nothing to pass through.

Verification (scratch copy of HEAD, project interpreter): the 7 quota/upload/strict-route test files, 86 passed; flake8 and black clean on the changed files.

Note on test (a): both the admin gate and the STRICT ownership check refuse a non-owner; the test accepts 403 or 404 and asserts zero rows, and the mutation removed both layers.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Code review (code-reviewer pass) at f0218c2

Verdict: APPROVE. 0 behind main (3 ahead), mergeable. 0 inline review comments via REST (thread resolved-state itself not checkable here: GraphQL rate limited).

# Severity Area Finding
1 INFO Correctness Rule is stated explicitly in the PR body and in conversation_file_quota_owner.py:OWNERLESS_AGENT_WRITE_RULE (conversation owner; no recorded owner -> authenticated caller; pending maintainer confirmation on #20678). Resize uses row["quota_owner"] or row["uploaded_by"]; charged_to and _CHARGED COALESCE keep pre-change rows on their old charge; nothing rewrites rows (backfill stays in #21123, Refs not Closes). OK.
2 INFO Security Auth runs first in both routes: _authorize_file_operation precedes resolve_agent_quota_owner/mcp_quota_owner, which precede create_file. read_owner raises on a failing/non-string lookup, so it fails closed and never falls back to the caller. The MCP handlers sit behind the same admin-gated api_router and the same STRICT check as /generate (one dispatch_mcp_tool, owner resolved in the route); behaviour matches across HTTP and MCP. SQL: new DDL/queries use constants only, owner and sizes are bound. OK.
3 INFO Author claim Verified TRUE. api_router carries Depends(check_admin_permission); validate_strict returns for an admin at the is_admin_role branch before _strict_owner_check reads the owner, so there is exactly one owner read per write (in resolve_agent_quota_owner). A non-admin never reaches it. Consequence: an admin writing into another user's conversation charges that user's quota. That is the stated rule, noted only for awareness.
4 INFO Migration No alembic revision is added (this store is a SQLite file DB, not migrations/versions), so the alembic head is unchanged: main's latest is 20261106_113_.... Change is additive: nullable ADD COLUMN plus CREATE INDEX IF NOT EXISTS, guarded by PRAGMA table_info, idempotent, no row touched, so no data lost (nothing dropped; the #15776 hook only scans versions/ for drops). conversation_file_quota_owner_schema.py imports only sqlite3 and the logger (no fastapi). Called from both the manager init and migration 001. No downgrade; dropping the column later would lose only the new charge info.
5 INFO Size/style api/conversation_files.py 916 and conversation_file_manager.py 1193 lines, matching the lowered ceilings (960->916, 1199->1193); diffs against main contain only quota_owner changes and the two extractions. New modules are all under 600 lines; every new function is under 30 lines; no sleeps; no line-number comments.
6 INFO Tests The 3 new tests each bite by reasoning from the code. Resize test: with uploaded_by as owner, "scribe" has 3 bytes so the 8-byte edit would be allowed, not 413. Raising-owner test: an admin passes validate_strict without reading the owner, so only the read_owner raise in the resolver refuses; a caller fallback would write a row. Non-owner test mostly exercises the pre-existing admin gate and STRICT check (it guards against their removal, not this PR's code); it accepts 403 or 404, which is fine.

No blocking findings.

@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Landed via #21176 (merge train T96b), merge commit 250ddc4 on main. Frozen head is an ancestor of the merge commit. Closing this PR.

@mrveiss mrveiss closed this Nov 8, 2026
@mrveiss
mrveiss deleted the issue-20678-quota-owner branch November 8, 2026 13:13
@mrveiss

mrveiss commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Branch issue-20678-quota-owner deleted after verification (no unmerged commits, no file diff against main). It can be restored from this PR.

timothybrush pushed a commit to timothybrush/AutoBot-AI that referenced this pull request Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

phase:M3.9 Chat, Agents, Analytics and Settings screens

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant