Skip to content

sys_audit_log 缺 (created_at, action/user_id) 复合索引:系统概览的审计统计在 SQLite 上冷缓存每条 4 秒,期间整个服务卡住 #39267

Description

@os-bob

现象

本地 objectstack serve --dev(SQLite,审计日志在自动建的遥测库里)跑了几天后,管理员进入「系统设置」,再点「用户」,16 条用户的列表要等 10 秒左右才出来。用户列表接口本身只要十几毫秒。

原因

  1. 「系统设置」默认打开「系统概览」仪表盘,它通过 POST /api/v1/analytics/dataset/query/batch 查 sys_audit_log_metrics,其中 3 条是近 7 天按 action / user_id 分组的统计。
  2. 生成的 SQL:SELECT action, COUNT(*) FROM sys_audit_log WHERE created_at >= ? AND created_at < ? GROUP BY action。表上只有单列索引,查询走 created_at 索引找到行之后,还要回表取 action / user_id。
  3. 查询不读 old_value / new_value 的溢出页,但这些大字段把行撑得很宽:一个 4 KB 叶子页平均只放 2.1 行。我们的库里 sys_audit_log 有 20.2 万行,占 9.66 万个叶子页;近 7 天 17.6 万行,一条统计就要读 8 万多页、约 340 MB。
  4. 这些页不在内存里时(冷缓存),单条统计 4.2 秒,稳定复现;在内存里时 0.1–0.6 秒。所以现象是时快时慢。
  5. SQLite 驱动是同步执行的,查询期间 Node 进程整个被卡住。浏览器里实测这个批量请求用了 27 秒,同时发出的 /api/settings、/api/v1/data/sys_user/<id> 等小请求也都等了 27 秒。用户这时点「用户」,列表请求也一起排队。
  6. 另外两点让表涨得很快:
    • ai_messages、ai_conversations、sys_ai_audit_log 不在审计跳过名单(SKIP_OBJECTS)里,每次 AI 问答都写多条审计,我们的环境里合计约 8 万行。
    • 没配 OS_AUDIT_ARCHIVE_URL 时,启动日志写着 sys_audit_log is kept hot forever (… deletes nothing),也就是审计日志永不清理。

已在本地验证的修法

在 packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts 的 indexes 里加两条:

{ fields: ['created_at', 'action'] },
{ fields: ['created_at', 'user_id'] },

重新构建后重启,启动时会自动在已有表上建好这两个索引(各约 8–10 MB)。改动前后对比:

改之前 改之后
查询计划 走 created_at 索引后回表 走覆盖索引,不回表
冷缓存,单条分组统计 4.2 秒 0.02 秒
接口,单条分组统计 0.1–4.1 秒 26–31 毫秒
仪表盘批量请求 浏览器里最长 27 秒 122–162 毫秒
打开仪表盘后马上进用户列表 网页本身等 6.1 秒 网页 26 毫秒,列表接口 28 毫秒

冷缓存的复现方法:用 APFS 克隆(cp -c)复制一份遥测库,新克隆的页不在内存里,用 sqlite3 在克隆上跑上面的 SQL,每次都是 4 秒左右。

其他建议

  1. 仪表盘统计别卡住整个服务:比如给结果加短时缓存、改成预聚合,或者把 SQLite 的重查询放到工作线程里跑。
  2. 评估 ai_messages、ai_conversations、sys_ai_audit_log 这类高频系统写入是否需要记审计。
  3. 没配归档时审计日志永不清理,至少在文档或启动提示里说清楚表会一直涨。

代码位置

  • packages/platform-objects/src/apps/dashboards/system_overview.dashboard.ts
  • packages/platform-objects/src/apps/dashboards/system.datasets.ts(sys_audit_log_metrics)
  • packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts(indexes)
  • packages/plugins/plugin-audit/src/audit-writers.ts(SKIP_OBJECTS)

补充:审计日志列表页也一样(加了上面的索引也不行)

系统设置 → 审计日志的默认视图请求:
GET /api/v1/data/sys_audit_log?top=50&sort=-created_at&filter=[["object_name","not_in",[...]],["or",["object_name","not_in",[...]],["action","equals","config_change"]],["or",["metadata","is_null"],["metadata","not_contains","auth.last_login_stamp"]]]

  • 接口 3.5 秒。取前 50 行只要 0.002 秒,慢在返回的 total:要对 20 万行逐行读 metadata 判断 not_contains,索引用不上,sqlite3 里单跑这个 count 3.4 秒。不带筛选时 43 毫秒。
  • 会随表线性变慢;SQLite 下同样卡住整个服务。
  • 建议:审计这类只增不减的大表,列表别算精确总数(只用 hasMore,或者给个上限);登录戳这个标记别放在 metadata 文本里用 not_contains 过滤,改成单独的可索引列。

Activity

  1. objectstack-fleet commented on Dec 3, 2026

    @objectstack-fleet
    Contributor

    repo:objectstack@os-bob · os-bob · session_012dn2AcfwnfHMghyeNLFvob

    Waiting on triage · 2026-12-03T05:53Z · seat repo:objectstack@os-bob will claim this card once it has a first-touch audit. The maintainer sent it to this seat directly (/pm-dispatch objectstack #39267, this session). It carries no area, type, grade or domain:*, and a lane seat may not write those, so this seat knocked triage@os-warren (mailbox PR #38656).
    Premise read on origin/main a498ead: holds. packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts declares only single-column indexes on sys_audit_log (created_at, user_id, action, …), so the dashboard's GROUP BY action / user_id over a created_at window reads every matching row from the table; SKIP_OBJECTS in packages/plugins/plugin-audit/src/audit-writers.ts does not list ai_messages, ai_conversations or sys_ai_audit_log.
    Split suggested to triage: the composite indexes here; the audit-log list's exact total over the metadata not_contains filter as its own defect; AI-object audit coverage as a maintainer choice; retention without an archive as a docs ask.

  2. objectstack-fleet commented on Dec 3, 2026

    @objectstack-fleet
    Contributor

    triage@os-warren · os-warren · session_01JQwxbZzZ2f5mzcvJbRrRNZ

    First touch · 2026-12-03T05:53Z

    定级:area:data · Bug · p2 · 系统概览的审计分组统计在 SQLite 冷缓存时每条 4 秒,同步驱动期间整个服务卡住,进用户列表要等 10 秒 · 实测(卡上本地复现与加索引前后对比,main a498ead 读码成立)

    • 应 os-bob 席信箱敲门(pm:mailbox — triage@os-warren · os-warren #38656 评论 7369226705)首触。类型 Bug,进 pm:queue。本卡范围 = 两条复合索引 (created_at, action)、(created_at, user_id)。卡上另三项不随本卡交付:(a) 审计列表在 metadata not_contains 过滤下精确计数慢,属另一缺陷,认领席另立卡;(b) ai_messages ai_conversations sys_ai_audit_log 是否记审计,是维护者的覆盖范围决定,认领席立决策卡;(c) 未配归档时审计永不清理,归文档或启动提示,认领席另立卡。
  3. added
    domain:server
    pm:queue
    priority:p2
    on Dec 3, 2026
  4. objectstack-fleet commented on Dec 3, 2026

    @objectstack-fleet
    Contributor

    repo:objectstack@os-bob · os-bob · session_012dn2AcfwnfHMghyeNLFvob

    Claim: PM loop round 3 · 2026-12-03T06:07Z
    Session: session_012dn2AcfwnfHMghyeNLFvob
    Account: os-bob
    Branch: claude/issue-39267-audit-log-composite-indexes
    Worktree: objectstack-issue-39267
    Domain: domain:server
    Seat: repo:objectstack@os-bob
    File surface: packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts (the indexes list: add (created_at, action) and (created_at, user_id)). If measurement shows an existing deployment does not get a declared new index on its existing table at boot (per driver: SQLite, Postgres, MySQL), stop and report the driver path rather than widening this surface. Stop on breach; explain in the report.
    Container & model: S, mode:subagent, model: default (dispatch-gates --tier: no path-derived mandate), effort: medium
    Clause-②: no
    Metadata-protocol: none
    Responsibility: objectstack: plugin-audit's sys_audit_log declares only single-column indexes, so the system-overview dashboard's 7-day GROUP BY action / user_id reads every matching wide row; on SQLite the synchronous driver stalls the whole process meanwhile | none | every admin who opens System settings on a deployment whose audit table has grown (the card measures 202k rows, 27 s stall), reached today
    Thread-read: 7369248653
    Premise: holds (read on origin/main a498ead, comment 7369244596; triage first touch 7369248653)
    Scope of this claim: the two composite indexes only, per the triage first touch. Not here: (a) the audit-log list's exact total under the metadata not_contains filter, (b) whether ai_messages, ai_conversations, sys_ai_audit_log are audited (a maintainer decision), (c) retention without OS_AUDIT_ARCHIVE_URL. The seat files those three cards.
    Serial constraints cleared: check-handover --inflight over packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts, packages/plugins/plugin-audit/src/audit-writers.ts and packages/platform-objects/src/apps/dashboards/system.datasets.ts reads no overlap; #38415 and #35238 (repo:objectstack@os-bill) name no path and were read by hand: neither is about the audit plugin.

  5. added
    pm:dispatched
    and removed
    pm:queue
    on Dec 3, 2026
  6. objectstack-fleet commented on Dec 3, 2026

    @objectstack-fleet
    Contributor

    repo:objectstack@os-bob · os-bob · session_012dn2AcfwnfHMghyeNLFvob

    Dispatched · 2026-12-03T06:09Z · claim 7369478226 · mode:subagent (in-container os-dev, worktree objectstack-issue-39267, model tier default, effort medium). The order: scope = the two composite indexes only (triage 7369248653); measure per SQL driver whether a new declared index reaches an existing table at boot, and stop and report rather than build a migration path if one does not; keep the single-column indexes; regenerate any baseline with its own tool; pin both indexes (fresh and pre-existing table) and the covering query plan, with an ablation. Expected delivery: a draft PR and an os-dev-report comment on this card.

  7. objectstack-fleet commented on Dec 3, 2026

    @objectstack-fleet
    Contributor

    repo:objectstack@os-bob · os-bob · session_012dn2AcfwnfHMghyeNLFvob

    Split of the three asks the triage first touch (7369248653) left to the claiming seat:

    • (a) The audit-log list's exact total under the metadata not_contains filter: filed Audit log list: the default view's exact total scans every row's metadata text (3.5 s on 200k rows, stalls the SQLite process) #39270 (Bug, p2, Blocked-by: #39267 because both edit packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts).
    • (b) Whether ai_messages, ai_conversations and sys_ai_audit_log are audited: a maintainer decision card is being written at the contract-review tier; it is linked here when filed.
    • (c) Retention without an archive: no card. The startup notice already says it in words: cloud packages/security-enterprise/src/audit/archive-datasource.ts:289 logs "no archive datasource (OS_AUDIT_ARCHIVE_URL unset): sys_audit_log is kept hot forever (the framework reports it archive-pending and deletes nothing). Set it to enable the 90d-hot / 7y-archive policy." and cloud apps/objectos-ee/deploy/INSTALL.md documents the variable. Neither is a defect under the filing gate; a different wording is a docs preference, not a card.
  8. objectstack-fleet commented on Dec 3, 2026

    @objectstack-fleet
    Contributor

    repo:objectstack@os-bob · os-bob · session_012dn2AcfwnfHMghyeNLFvob

    Split item (b) filed: decision card #39273 (needs-user-decision, analysis at the contract-review tier, read back at-tier). This card stays the two composite indexes only.

  9. objectstack-fleet commented on Dec 3, 2026

    @objectstack-fleet
    Contributor

    repo:objectstack@os-bob · os-bob · session_012dn2AcfwnfHMghyeNLFvob
    os-dev-report

    {
      "issue": 39267,
      "status": "done",
      "branch": "claude/issue-39267-audit-log-composite-indexes",
      "pr": "https://github.com/objectstack-ai/objectstack/pull/39284",
      "session": "session_012dn2AcfwnfHMghyeNLFvob",
      "premise_still_valid": true,
      "summary": "sys_audit_log now declares (created_at, action) and (created_at, user_id). A new integration test on ObjectQL + SqliteWasmDriver pins that schema sync builds both on a new table and on a filled table built from the earlier declaration (an upgrade). It also pins that the SQL the engine emits for each dashboard group-by is planned as SEARCH sys_audit_log USING COVERING INDEX on the created_at range. Mechanism readings: A holds. Every SQL driver (driver-sql for SQLite/PG/MySQL, plus sqlite-wasm and turso, which extend SqlDriver) builds a missing declared index on an existing table at boot (initObjects -> syncTableIndexes with existingTable; PG does it CONCURRENTLY, live-pinned by sql-driver-33695). SQLite is measured here; MySQL is read from code only. B: no single-column key is redundant, so none was removed. C: no generated artifact records indexes, so nothing was regenerated. D: organization-scoped readers (row scope sys_audit_log_org) add tenant_id = ?, and that shape stays on idx_tenant_id plus a table lookup. Card assignee was not touched.",
      "tests": "HEAD b5c930063. New test file: pnpm --filter @objectstack/plugin-audit exec vitest run --maxWorkers=2 src/objects/sys-audit-log-dashboard-indexes.integration.test.ts -> 'Test Files 1 passed (1) / Tests 5 passed (5)' (os-verify-lock VERDICT command-exit 0). Full package test (on 9889d5014; the later commit only types two option objects in the new test file, after which that file and typecheck were re-run on b5c930063): pnpm --filter @objectstack/plugin-audit test -> 'Test Files 119 passed (119) / Tests 1971 passed (1971)', VERDICT command-exit 0. pnpm --filter @objectstack/plugin-audit typecheck -> exit 0, 'check:test-typecheck: OK ... 0 error(s)'. Ablation via node scripts/ablation-replace.mjs --delete of the two index lines (anchor 1 -> 0, blob 817e6e91d2d3 -> 0fc46b43272e; restored, blob == HEAD, git diff HEAD empty): all 5 cases red. The plan cases then read 'SEARCH sys_audit_log USING INDEX idx_sys_audit_log_created_at (created_at range)'. No build was needed: the test imports the object from src relatively, and the vitest config aliases workspace deps to src. Plan probe (temporary test file, deleted), SQLite 3.49.1, no ANALYZE: window count -> COVERING idx_created_at; action=? + window -> idx_action (table lookup); tenant_id=? + window group-by -> idx_tenant_id (table lookup); action-only / user_id-only -> their single-column keys.",
      "gates": "Local derived set on HEAD b5c930063 (dispatch-gates --commands, 69 families), each exit captured before any pipe. 66 exit 0: all of them, including check:nul-bytes, check:issue-citations, check:cross-package-test-inputs, check:test-source-alias, check:undeclared-dep-imports, check:platform-object-tenancy-census, check:query-options-erasure (it first went red 236 -> 238 on two untyped test option objects in my file; I typed them in b5c930063 and it is green), check:slot-lookup, check:type-check-debt, check:type-check-coverage and the changeset family (check-empty-changeset, check-adr-0087-registration, check-changeset-no-major, check:changeset-gate-self-tests). 3 NOT MEASURED, all exit 3: check:i18n (PREREQUISITE NOT MET, needs CLI plus 11 package builds; no label or translatable text in the diff), check:dual-build-cjs-loads (needs dist of ~68 packages), and check-plugin-teardown-shape.mjs --self-test (the shallow clone cannot read its pinned positive-control commit; script untouched). dispatch-gates --ran: '69 derived famil(ies) accounted for — 66 run, 3 NOT-MEASURED', exit 0. check-platform-checklist not owed (no export renamed or removed). test:repo not run locally (CI-owned; the diff does not touch that project). PR check-runs: NOT MEASURED, CI had not concluded at report time.",
      "line_budget": "193 changed lines (+193 / -0) across 3 files, under the 3000 human-merge threshold",
      "files_changed": [
        "packages/plugins/plugin-audit/src/objects/sys-audit-log.object.ts",
        "packages/plugins/plugin-audit/src/objects/sys-audit-log-dashboard-indexes.integration.test.ts",
        ".changeset/39267-audit-log-composite-indexes.md"
      ],
      "deviations": [
        "The harness moved one gate loop to the background when it hit the 600 s foreground cap. I stopped it at once with TaskStop and re-ran the remaining gates in shorter foreground batches. Every family in the record above comes from a foreground run.",
        "A new test file, not an existing harness: no file in plugin-audit or driver-sql pins sys_audit_log indexes. The test follows the shape of service-messaging's inbox-feed-window-indexes.integration.test.ts. It uses SqliteWasmDriver (already a plugin-audit devDependency) instead of better-sqlite3, so the package manifest and lockfile do not change.",
        "Commit trailers are the model-free pair from AGENTS.md (Claude-Session + Co-authored-by: Claude), not the harness reminder's model-named Co-Authored-By. The PR footer is the session-URL form from AGENTS.md."
      ],
      "mcp_calls": "0",
      "api_writes": "2 — relay pr_create (POST /repos/objectstack-ai/objectstack/dispatches -> fleet-write run 47059745574: POST /pulls #39284 + POST /issues/39284/assignees os-bob); this os-dev-report comment via post-stamped.mjs (POST /issues/39267/comments). Plus git push of the branch (not REST).",
      "classifier_refusals": [],
      "open_questions": [],
      "security_findings": "none",
      "out_of_scope_findings": [
        "carrier: none · noted, not filed (observation, PR Acceptance notes): organization-scoped readers of the system overview (row scope sys_audit_log_org adds tenant_id = ?) are planned on idx_sys_audit_log_tenant_id plus a table lookup, so the new keys do not serve them; a (tenant_id, created_at, ...) key would. This is a plan reading only, not measured on a large ledger. Dedupe words: sys_audit_log tenant_id dashboard index, audit metrics organization scope, sys_audit_log_org plan",
        "carrier: none · noted, not filed (observation, PR Acceptance notes): the Login Events / Config Changes metric widgets (action = ? plus the created_at window) are planned on idx_sys_audit_log_action with a table lookup for every matching row of all time. An (action, created_at) key would cover them. This is a plan reading only, not reproduced as slow. Dedupe words: sys_audit_log action created_at index, login events widget slow, audit metric filter plan"
      ]
    }
  10. objectstack-fleet commented on Dec 3, 2026

    @objectstack-fleet
    Contributor

    repo:objectstack@os-bob · os-bob · session_012dn2AcfwnfHMghyeNLFvob

    Closed out · 2026-12-03T08:34Z · PR #39284 merged and closed this card (Fixes #39267); the state label pm:dispatched comes off in this stroke.
    The seat landed it after its L1 ACCEPT (PR comment 7371857488); it merged through the queue at 2026-12-03T08:33Z. Follow-ups: #39270 (the audit-log list total) is already in pm:queue from triage and its Blocked-by: target is now closed; #39273 (AI-object audit coverage) waits on the maintainer.

  11. removed
    pm:dispatched
    on Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:datadomain:serverpriority:p2

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions