Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(auth): a last_used_at touch never locks a legacy token row its first read must convert (#6230); test(list_pages): count only the listing notice on an aged snapshot brain

garrytan646681e378bd
diff --git a/src/core/grants/legacy-token.ts b/src/core/grants/legacy-token.ts
index 82e513221b..ffee6f2854 100644
--- a/src/core/grants/legacy-token.ts
+++ b/src/core/grants/legacy-token.ts
@@ -348,7 +348,8 @@ export async function resolveTokenGrant(sql: SqlQuery, row: Record<string, unkno
try {
const [converted] = await sql`
UPDATE access_tokens SET source_grant = ${kind}, source_id = ${write}, federated_read = ${reads}::text[],
- allowed_operations = ${ops}::text[], takes_holders = ${holders}::text[], grant_revision = grant_revision + 1
+ allowed_operations = ${ops}::text[], takes_holders = ${holders}::text[], grant_revision = grant_revision + 1,
+ last_used_at = now()
WHERE id IN (SELECT id FROM access_tokens WHERE id = ${String(row.id)}::uuid AND source_grant IS NULL FOR UPDATE SKIP LOCKED)
RETURNING *
`;
@@ -359,6 +360,26 @@ export async function resolveTokenGrant(sql: SqlQuery, row: Record<string, unkno
return grant;
}
+/**
+ * Debounced, fire-and-forget `last_used_at` write for a token row the auth
+ * paths just read (once per token per 60 s; SKIP LOCKED so a lock held
+ * elsewhere never parks a pool slot, #5730). A row still on the legacy shape
+ * is left to `resolveTokenGrant`, whose conversion records first use itself:
+ * a touch holding that row's lock made every concurrent conversion skip it
+ * (SKIP LOCKED), so a burst of first reads could leave it unconverted (#6230).
+ */
+export function touchTokenLastUsed(sql: SqlQuery, row: Record<string, unknown>): Promise<unknown> {
+ const id = String(row.id);
+ const touch = 'source_grant' in row
+ ? sql`UPDATE access_tokens SET last_used_at = now()
+ WHERE id IN (SELECT id FROM access_tokens WHERE id = ${id}::uuid AND source_grant IS NOT NULL
+ AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds') FOR UPDATE SKIP LOCKED)`
+ : sql`UPDATE access_tokens SET last_used_at = now()
+ WHERE id IN (SELECT id FROM access_tokens WHERE id = ${id}::uuid
+ AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds') FOR UPDATE SKIP LOCKED)`;
+ return Promise.resolve(touch).catch(() => { /* fire-and-forget */ });
+}
+
/** A bare `auth rescope <name>`: a token name, an OAuth client id, or a client name. Both kinds matching refuses. */
export async function resolveRescopeTarget(engine: BrainEngine, name: string): Promise<{ kind: 'token' } | { kind: 'client'; clientId: string }> {
const tokens = await engine.executeRaw<{ id: string }>('SELECT id FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]);
diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.ts
index 9529328f36..e32ba42bdd 100644
--- a/src/core/oauth-provider.ts
+++ b/src/core/oauth-provider.ts
@@ -41,7 +41,7 @@ import { TOKEN_TTL_MAX_SECONDS, authSourcesFromGrant, grantFromRow, normalizeGra
import { assertValidSlugPrefixes, pgArray } from './grants/encoding.ts';
import { rescopeOAuthClient, type RescopeClientOptions, type RescopeClientResult } from './grants/rescope.ts';
import { grantValidationContext, validateClientGrant, insertClientGrant, assertGrantPatch } from './grants/service.ts';
-import { resolveTokenGrant } from './grants/legacy-token.ts';
+import { resolveTokenGrant, touchTokenLastUsed } from './grants/legacy-token.ts';
import { NO_SOURCES } from './source-id.ts';
/**
@@ -912,17 +912,9 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
if (legacyRows.length > 0) {
// For legacy tokens, name = clientId = clientName (single identifier).
- // #2833: debounced fire-and-forget last_used_at update — only writes
- // once per token per 60s, and NEVER blocks or fails verification (a
- // slow/broken UPDATE used to hang or 401 every legacy-token request).
- // Mirrors src/mcp/http-transport.ts validateToken; the SQL-level WHERE
- // keeps the debounce race-tolerant under concurrent requests; SKIP LOCKED
- // keeps a row lock held elsewhere from parking a pool slot (#5730).
- this.sql`
- UPDATE access_tokens SET last_used_at = now()
- WHERE id IN (SELECT id FROM access_tokens WHERE token_hash = ${tokenHash}
- AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds') FOR UPDATE SKIP LOCKED)
- `.catch(() => { /* fire-and-forget */ });
+ // #2833: debounced fire-and-forget last_used_at update that never blocks
+ // or fails verification; shared with src/mcp/http-transport.ts.
+ void touchTokenLastUsed(this.sql, legacyRows[0]);
const name = legacyRows[0].name as string;
// One grant shape (grants/model.ts), shared with the legacy HTTP
// transport so the two cannot drift. Unified rows read the columns,
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index 4575aec9d0..6460221a06 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -53,7 +53,7 @@ import { classifyPgAccessError } from '../core/pg-access-classify.ts';
import { redactConnectionInfo } from '../core/audit/redact-connection-info.ts';
import { redactUrlsInText } from '../core/url-redact.ts';
import { authSourcesFromGrant } from '../core/grants/model.ts';
-import { resolveTokenGrant } from '../core/grants/legacy-token.ts';
+import { resolveTokenGrant, touchTokenLastUsed } from '../core/grants/legacy-token.ts';
export { parseLegacyTokenScope } from '../core/legacy-token-scope.ts';
const DEFAULT_BODY_CAP = 1024 * 1024; // 1 MiB
@@ -270,13 +270,8 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
if (!row) return { ok: false };
const rowId = row.id as string;
const rowName = row.name as string;
- // Debounced last_used_at update — only writes once per token per 60s.
- // SQL-level WHERE clause keeps this race-tolerant even under concurrent requests;
- // SKIP LOCKED keeps a row lock held elsewhere from parking a pool slot (#5730).
- sql`UPDATE access_tokens SET last_used_at = now()
- WHERE id IN (SELECT id FROM access_tokens WHERE id = ${rowId}
- AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds') FOR UPDATE SKIP LOCKED)`
- .catch(() => { /* fire-and-forget */ });
+ // Debounced fire-and-forget last_used_at update, shared with the OAuth provider.
+ void touchTokenLastUsed(sql, row);
// One grant shape (grants/model.ts) shared with the OAuth provider
// behind `serve --http`, so the two transports cannot drift; a row still
// on the legacy shape is converted on this read. Takes holders fail safe
diff --git a/test/e2e/access-token-grants.test.ts b/test/e2e/access-token-grants.test.ts
index a703d19536..52fa363ca6 100644
--- a/test/e2e/access-token-grants.test.ts
+++ b/test/e2e/access-token-grants.test.ts
@@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';
import { mintLegacyToken } from '../../src/core/token-mint.ts';
-import { migrateLegacyTokens, parseRescopeTokenArgs, rescopeLegacyToken } from '../../src/core/grants/legacy-token.ts';
+import { migrateLegacyTokens, parseRescopeTokenArgs, rescopeLegacyToken, touchTokenLastUsed } from '../../src/core/grants/legacy-token.ts';
import { grantFromTokenRow } from '../../src/core/grants/model.ts';
import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';
import { executeRawJsonb, sqlQueryForEngine } from '../../src/core/sql-query.ts';
@@ -62,6 +62,29 @@ d('F3 token grant columns on Postgres', () => {
expect(await row(late.id)).toMatchObject({ source_grant: 'scalar', source_id: 'other-f3', grant_revision: 1, kind: 'object' });
});
+ test('#6230: a last_used_at touch in flight never makes the first read skip converting a legacy row', async () => {
+ const engine = getEngine();
+ await engine.setConfig('version', '200');
+ await runMigrations(engine);
+ const token = generateToken('gbrain_');
+ const [late] = await executeRawJsonb<{ id: string }>(engine, 'INSERT INTO access_tokens (name, token_hash, scopes, permissions) VALUES ($1, $2, $3::text[], $4::jsonb) RETURNING id',
+ [`touch-${randomUUID().slice(0, 8)}`, hashToken(token), '{read}'], [{ takes_holders: ['world'], source_id: 'other-f3' }]);
+ const before = await row(late.id);
+ // Another request's touch holds its transaction open while this read converts.
+ let release!: () => void;
+ const held = new Promise<void>(resolve => { release = resolve; });
+ let touched!: () => void;
+ const touchedNow = new Promise<void>(resolve => { touched = resolve; });
+ const touching = engine.transaction(async tx => { await touchTokenLastUsed(sqlQueryForEngine(tx), before); touched(); await held; });
+ await touchedNow;
+ try {
+ const auth = await provider().verifyAccessToken(token);
+ expect(auth).toMatchObject({ sourceId: 'other-f3', hasSourceGrant: true, scopes: ['read'] });
+ expect(await row(late.id)).toMatchObject({ source_grant: 'scalar', source_id: 'other-f3', grant_revision: 1, kind: 'object' });
+ expect((await row(late.id)).last_used_at).not.toBeNull();
+ } finally { release(); await touching; }
+ });
+
test('mint and rescope write text[] columns with quoting intact and an object mirror', async () => {
const engine = getEngine();
const name = `f3-e2e-${randomUUID().slice(0, 8)}`;
diff --git a/test/list-pages-truncation.test.ts b/test/list-pages-truncation.test.ts
index c0eeb64d90..fd59afe859 100644
--- a/test/list-pages-truncation.test.ts
+++ b/test/list-pages-truncation.test.ts
@@ -35,6 +35,10 @@ import { operations, type OperationContext } from '../src/core/operations.ts';
import { dispatchToolCall, __resetBackupNoticeForTests } from '../src/mcp/dispatch.ts';
import { __resetFactsDrainNoticesForTests } from '../src/core/facts/drain.ts';
import { withEnv } from './helpers/with-env.ts';
+import { __resetBehaviorNoticeForTests } from '../src/core/behavior-change-notice.ts';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import type { ListPagesPagination } from '../src/core/ops/list-pages-pagination.ts';
const list_pages = operations.find(o => o.name === 'list_pages')!;
@@ -242,7 +246,12 @@ describe('list_pages pagination meta for remote callers', () => {
await seed(12);
// Once-per-process notices (backup coverage, post-upgrade, a pending facts-drain notice) depend on what other tests
// in the same shard leave behind; switch them off or clear them so this test counts only the listing notice.
- await withEnv({ GBRAIN_BACKUP_CHECK: 'off', GBRAIN_NO_ONBOARD_NUDGE: '1' }, async () => {
+ // The one-time behavior_changes disclosure fires on a brain older than its fresh-install grace (the restored PGLite
+ // snapshot is), once per brain per GBRAIN_HOME; a fresh brain in its own GBRAIN_HOME never owes it.
+ await engine.executeRaw('UPDATE sources SET created_at = now()');
+ __resetBehaviorNoticeForTests();
+ const noticeHome = mkdtempSync(join(tmpdir(), 'gbrain-list-pages-notice-'));
+ await withEnv({ GBRAIN_BACKUP_CHECK: 'off', GBRAIN_NO_ONBOARD_NUDGE: '1', GBRAIN_HOME: noticeHome }, async () => {
const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
const res = await dispatchToolCall(engine as any, 'list_pages', { limit: 10, type: 'note' }, opts);
expect(res.isError).toBeUndefined();