Skip to content

Add user context to frontend logs#1023

Open
tdewanNvidia wants to merge 1 commit into
mainfrom
tdewan/ui-user-context-logs
Open

Add user context to frontend logs#1023
tdewanNvidia wants to merge 1 commit into
mainfrom
tdewan/ui-user-context-logs

Conversation

@tdewanNvidia

@tdewanNvidia tdewanNvidia commented May 15, 2026

Copy link
Copy Markdown
Collaborator

Description

Adds frontend user context to OSMO UI logs so log messages emitted during an authenticated UserProvider session include the active user ID.

  • Adds setLogUserId / clearLogUserId helpers in the UI logger.
  • Prefixes frontend log output with [user=<id>] when a user ID is available.
  • Wires UserProvider to set and clear the log user ID as the active user changes.

Issue - None

Checklist

  • I am familiar with the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.

Summary by CodeRabbit

  • Improvements
    • Diagnostics and logs now include per-user and per-job context (user_id/job_id) and emit richer JSON fields for easier troubleshooting.
    • Server requests and job lifecycles log request method/path and status, and background jobs/uploads are associated with the submitting user for clearer traceability.
    • Dev-mode debug/info logs added for more verbose local debugging.

@tdewanNvidia tdewanNvidia requested a review from a team as a code owner May 15, 2026 00:35
@coderabbitai

coderabbitai Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 85f31a18-3fa8-4b5b-a581-bc5fde93d416

📥 Commits

Reviewing files that changed from the base of the PR and between 0085ebc and d2a44cc.

📒 Files selected for processing (14)
  • src/lib/utils/logging.py
  • src/lib/utils/tests/test_logging.py
  • src/operator/backend_worker.py
  • src/service/agent/objects.py
  • src/service/core/service.py
  • src/service/core/workflow/objects.py
  • src/service/logger/ctrl_websocket.py
  • src/service/worker/worker.py
  • src/ui/src/lib/auth/user-context.tsx
  • src/ui/src/lib/logger.ts
  • src/utils/job/backend_jobs.py
  • src/utils/job/jobs.py
  • src/utils/logging/logging.go
  • src/utils/logging/logging_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/ui/src/lib/auth/user-context.tsx
  • src/ui/src/lib/logger.ts

📝 Walkthrough

Walkthrough

Thread user_id/job_id into logging: add ContextVar-based UserLogContext/JobLogContext and WorkflowLogContext wiring, update JSON formatters (Python/Go), propagate user through job models and job enqueue sites, wrap runtime handlers/workers, extend UI logger and sync via UserProvider, and add tests.

Changes

Per-user logging context

Layer / File(s) Summary
Python logging context & formatter
src/lib/utils/logging.py
Add _user_id_context/_job_id_context, UserLogContext/JobLogContext, extend WorkflowLogContext to enter these contexts, and emit user_id/job_id/status_code in JsonServiceFormatter.
Python logging tests
src/lib/utils/tests/test_logging.py
Extend _make_record to accept user_id/job_id/status_code; add tests for direct propagation and context-driven emission/masking.
Job models and propagation
src/utils/job/backend_jobs.py, src/utils/job/jobs.py
Add user fields to job classes, thread user=self.user into enqueued jobs (uploads, cleanup, timeouts), include user_id in log labels, and adjust CancelWorkflow cancelled_by for timeouts.
Service/worker runtime contexts & logging
src/service/core/service.py, src/service/worker/worker.py, src/service/logger/ctrl_websocket.py
Wrap middleware and worker execution in UserLogContext/WorkflowLogContext (now accepting user_id/job_id); log request method/path/status and pass user into websocket workflow contexts.
Backend worker and agent logs
src/operator/backend_worker.py, src/service/agent/objects.py
Run BackendWorker job execution inside UserLogContext/JobLogContext; include user_id in completed-job log extra.
UI logger and UserProvider integration
src/ui/src/lib/logger.ts, src/ui/src/lib/auth/user-context.tsx
UI logger: module-level currentUserId, setLogUserId/clearLogUserId, buildPrefix(), logInfo/logDebug, updated logError/logWarn. UserProvider uses useEffect to call setLogUserId(initialUser?.id ?? null) and clears on cleanup.
Go JSON handler key rename & tests
src/utils/logging/logging.go, src/utils/logging/logging_test.go
JSON handler ReplaceAttr rewrites top-level useruser_id; tests now assert user_id present and no top-level user.

🎯 4 (Complex) | ⏱️ ~45 minutes

  • NVIDIA/OSMO#1005: Overlapping work that adds user_id to JSON service logs and related logging contexts.

Suggested reviewers:

  • xutongNV
  • jiaenren
  • vvnpn-nv

"I hop and I log with cheer,
user ids now appear clear,
contexts set, prefixes true,
little rabbit logs with you! 🐰"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.41% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'Add user context to frontend logs' directly and clearly summarizes the main change: adding user context to frontend logging, which is reflected across the UI logger and UserProvider updates.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tdewan/ui-user-context-logs

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


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

@tdewanNvidia tdewanNvidia changed the title #None - Add user context to frontend logs Add user context to frontend logs May 15, 2026
@codecov

codecov Bot commented May 15, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 7.69231% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 46.03%. Comparing base (663bfe9) to head (0085ebc).

Files with missing lines Patch % Lines
src/ui/src/lib/logger.ts 10.00% 9 Missing ⚠️
src/ui/src/lib/auth/user-context.tsx 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1023      +/-   ##
==========================================
- Coverage   46.04%   46.03%   -0.02%     
==========================================
  Files         220      220              
  Lines       28572    28583      +11     
  Branches     4268     4272       +4     
==========================================
+ Hits        13155    13157       +2     
- Misses      14775    14784       +9     
  Partials      642      642              
Flag Coverage Δ
backend 47.05% <ø> (ø)
ui 34.73% <7.69%> (-0.08%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/ui/src/lib/auth/user-context.tsx 14.28% <0.00%> (-3.90%) ⬇️
src/ui/src/lib/logger.ts 16.66% <10.00%> (+16.66%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

* #None - Add user_id to JSON service logs

Signed-off-by: Trasha Dewan <tdewan@nvidia.com>

* #None - Propagate user_id to all workflow job logs

Threads the workflow submitter through CleanupWorkflow, UploadWorkflowFiles,
CleanupGroup, RescheduleTask, CheckRunTimeout, and CheckQueueTimeout so their
service logs include user_id. Adds user as a default-empty field on
WorkflowJob and BackendWorkflowJob, and replaces the user='osmo' sentinel
on timeout-spawned UpdateGroup and CancelWorkflow jobs with the workflow
owner. CancelWorkflow.execute still writes 'osmo' to cancelled_by for
timeout-driven cancels so the UI can distinguish them from user-initiated
cancels.

Signed-off-by: Trasha Dewan <tdewan@nvidia.com>

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* #None - Fix UserLogContext leaking outer user_id when nested

UserLogContext.__enter__ skipped ContextVar.set() when user_id was empty,
so an empty nested scope would leave the outer user_id live and
misattribute JSON logs emitted inside the inner block. Always call set()
— including with '' — so an empty nested context masks the outer value
within its scope and restores it cleanly on exit.

Signed-off-by: Trasha Dewan <tdewan@nvidia.com>

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* #None - Add job_id and HTTP status_code to JSON service logs

Threads job_id through the same channels as user_id so every log emitted
while a frontend or backend job is executing carries the job's id:

  - Adds JobLogContext (mirrors UserLogContext) and extends
    WorkflowLogContext to also manage a job_id ContextVar.
  - JsonServiceFormatter emits job_id from the record attribute or the
    ContextVar, with empty values masking outer scopes.
  - Worker (service/worker/worker.py) and backend worker pass job.job_id
    into the surrounding log context.
  - WorkflowJob.log_labels() and BackendWorkflowJob.log_labels() include
    job_id so explicit logs that pass extra=self.log_labels() carry it too.

Adds status_code emission to JSON service logs. The check_client_version
middleware now emits one access-log line per request after the response
is ready, attaching status_code via extra=, so all three return paths
(version mismatch, expired token, normal pass-through) are covered.

Signed-off-by: Trasha Dewan <tdewan@nvidia.com>

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* #None - Add user context to frontend logs

---------

Signed-off-by: Trasha Dewan <tdewan@nvidia.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@tdewanNvidia tdewanNvidia force-pushed the tdewan/ui-user-context-logs branch from 0085ebc to d2a44cc Compare June 2, 2026 17:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant