Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion cdk/src/constructs/concurrency-reconciler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { Duration } from 'aws-cdk-lib';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as events from 'aws-cdk-lib/aws-events';
import * as targets from 'aws-cdk-lib/aws-events-targets';
import { Runtime, Architecture } from 'aws-cdk-lib/aws-lambda';
import { Runtime, Architecture, type IFunction } from 'aws-cdk-lib/aws-lambda';
import * as lambda from 'aws-cdk-lib/aws-lambda-nodejs';
import { NagSuppressions } from 'cdk-nag';
import { Construct } from 'constructs';
Expand Down Expand Up @@ -92,6 +92,7 @@ export class ConcurrencyReconciler extends Construct {
props.userConcurrencyTable.grantReadWriteData(this.fn);

const schedule = props.schedule ?? Duration.minutes(DEFAULT_SCHEDULE_MINUTES);
this.fn.addEnvironment('RECONCILER_TICK_MINUTES', String(schedule.toMinutes()));
const rule = new events.Rule(this, 'ReconcilerSchedule', {
schedule: events.Schedule.rate(schedule),
});
Expand All @@ -108,4 +109,20 @@ export class ConcurrencyReconciler extends Construct {
},
], true);
}

/**
* Have this reconciler invoke the Linear webhook processor's grant health probe
* (#1004) on one tick every 12 h.
*
* Revocation detection (#812) only runs when a Linear event needs a token, so an
* idle workspace or a dead webhook never re-detects a dead grant, and an unused
* refresh token simply expires. The probe refreshes expiring tokens and sends a
* rejected grant down the existing latch-and-announce path. It rides this
* schedule by async invoke because the root stack has no resource budget for a
* rule of its own: this adds only an IAM statement and two env vars.
*/
public triggerLinearGrantProbe(processor: IFunction): void {
this.fn.addEnvironment('LINEAR_GRANT_PROBE_FUNCTION_ARN', processor.functionArn);
processor.grantInvoke(this.fn);
}
}
33 changes: 32 additions & 1 deletion cdk/src/handlers/linear-webhook-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
fetchRecentComments,
type RenderedComment,
} from './shared/linear-feedback';
import { type GRANT_HEALTH_PROBE_EVENT, isGrantHealthProbe, probeLinearGrants } from './shared/linear-grant-health';
import {
probeLinearIssueContext,
renderIssueContextHint,
Expand Down Expand Up @@ -687,8 +688,38 @@ type BuilderResolvedToken = {
vaultUserId?: string;
};

/**
* Grant health probe (#1004), invoked twice a day by the concurrency reconciler. Runs
* in this Lambda because it already holds
* the token-refresh grants, the registry write for the revocation latch and the
* OperationalAlerts publish, so a dead grant reuses the #812 announce path.
*/
async function runGrantHealthProbe(): Promise<void> {
if (!WORKSPACE_REGISTRY_TABLE) {
logger.error('Linear grant health probe skipped: LINEAR_WORKSPACE_REGISTRY_TABLE_NAME not set');
return;
}
const table = WORKSPACE_REGISTRY_TABLE;
const report = await probeLinearGrants(ddb, table, id => resolveLinearOauthToken(id, table));
const fields = {
checked: report.checked,
healthy: report.healthy,
unhealthy: report.unhealthy,
revoked: report.revoked,
};
if (report.unhealthy.length > 0) {
logger.warn('Linear grant health probe: some workspaces have no usable token — run `bgagent linear setup <slug>`', fields);
} else {
logger.info('Linear grant health probe', fields);
}
}

// eslint-disable-next-line complexity -- predates the ceiling (120 when it landed); must not grow
export async function handler(event: ProcessorEvent): Promise<void> {
export async function handler(event: ProcessorEvent | typeof GRANT_HEALTH_PROBE_EVENT): Promise<void> {
if (isGrantHealthProbe(event)) {
await runGrantHealthProbe();
return;
}
if (!event.raw_body) {
logger.error('Linear webhook processor invoked without raw_body');
return;
Expand Down
31 changes: 31 additions & 0 deletions cdk/src/handlers/reconcile-concurrency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
*/

import { DynamoDBClient, ScanCommand, QueryCommand, UpdateItemCommand } from '@aws-sdk/client-dynamodb';
import { InvocationType, InvokeCommand, LambdaClient } from '@aws-sdk/client-lambda';
import { GRANT_HEALTH_PROBE_EVENT, isProbeTick } from './shared/linear-grant-health';
import { logger } from './shared/logger';
import { makeClient } from './shared/ua';

Expand Down Expand Up @@ -60,8 +62,37 @@ async function countActiveTasks(userId: string): Promise<number> {
* Scheduled handler: scan the concurrency table and reconcile each user's
* active_count against actual active tasks in the task table.
*/
const LINEAR_GRANT_PROBE_FUNCTION_ARN = process.env.LINEAR_GRANT_PROBE_FUNCTION_ARN;
const RECONCILER_TICK_MINUTES = Number(process.env.RECONCILER_TICK_MINUTES);
const lambdaClient = LINEAR_GRANT_PROBE_FUNCTION_ARN ? makeClient(LambdaClient) : undefined;

/**
* Kick the Linear grant health probe (#1004) on one tick per 12 h. Fire-and-forget
* (async invoke) and best-effort: a probe problem must never affect reconciliation.
*/
export async function triggerLinearGrantProbe(nowMs: number = Date.now()): Promise<boolean> {
if (!lambdaClient || !LINEAR_GRANT_PROBE_FUNCTION_ARN || !isProbeTick(nowMs, RECONCILER_TICK_MINUTES)) {
return false;
}
try {
await lambdaClient.send(new InvokeCommand({
FunctionName: LINEAR_GRANT_PROBE_FUNCTION_ARN,
InvocationType: InvocationType.Event,
Payload: Buffer.from(JSON.stringify(GRANT_HEALTH_PROBE_EVENT)),
}));
logger.info('Triggered the Linear grant health probe');
return true;
} catch (err) {
logger.warn('Could not trigger the Linear grant health probe', {
error: err instanceof Error ? err.message : String(err),
});
return false;
}
}

export async function handler(): Promise<void> {
logger.info('Concurrency reconciler started');
await triggerLinearGrantProbe();
let corrected = 0;
let scanned = 0;
let errors = 0;
Expand Down
128 changes: 128 additions & 0 deletions cdk/src/handlers/shared/linear-grant-health.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/**
* MIT No Attribution
*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

/**
* Scheduled Linear grant health probe (#1004).
*
* Revocation detection (#812) runs only when something needs a Linear token, which
* means when a Linear event arrives. A workspace whose webhook stopped delivering, or
* that nobody used for a while, therefore never re-detects a dead grant: observed
* live, a workspace sat with an expired refresh token for months with one ERROR log
* line. Linear refresh tokens also expire when unused, so the outage was preventable.
*
* The probe resolves a token for every active workspace on a schedule. That does two
* jobs with the existing code path:
* - it refreshes expiring access tokens, which keeps an idle refresh token alive;
* - a grant Linear rejects goes through the resolver's revocation recorder, which
* latches the workspace and announces it on OperationalAlerts (once).
*/

import { ScanCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';

/** How often each workspace is probed. Linear access tokens last about a day. */
const GRANT_HEALTH_PROBE_INTERVAL_HOURS = 12;

const MS_PER_MINUTE = 60_000;
const MS_PER_HOUR = 3_600_000;

/** Async invocation payload that selects probe mode in the webhook processor. */
export const GRANT_HEALTH_PROBE_EVENT = { grant_health_probe: true } as const;

export function isGrantHealthProbe(event: unknown): event is typeof GRANT_HEALTH_PROBE_EVENT {
return typeof event === 'object' && event !== null
&& (event as Record<string, unknown>).grant_health_probe === true;
}

/**
* True on exactly one tick per interval for a job that runs every `tickMinutes`:
* the tick falling in the half-open window `[k * interval, k * interval + tick)`.
* Ticks are `tick` apart, so each window holds exactly one. A nonsensical cadence
* probes every tick rather than never, so a misconfiguration cannot silently
* disable detection.
*/
export function isProbeTick(
nowMs: number,
tickMinutes: number,
intervalHours: number = GRANT_HEALTH_PROBE_INTERVAL_HOURS,
): boolean {
const tickMs = tickMinutes * MS_PER_MINUTE;
const intervalMs = intervalHours * MS_PER_HOUR;
if (!(tickMs > 0) || !(intervalMs > 0) || tickMs >= intervalMs) return true;
return nowMs % intervalMs < tickMs;
}

export interface GrantHealthReport {
readonly checked: number;
readonly healthy: number;
/** Slugs (or ids when a row has no slug) whose token could not be resolved. */
readonly unhealthy: readonly string[];
/** Rows already latched `revoked`; not re-probed, they were already announced. */
readonly revoked: readonly string[];
}

interface RegistryRow {
readonly linear_workspace_id?: string;
readonly workspace_slug?: string;
readonly status?: string;
}

/**
* Resolve a token for every active registry row, sequentially (a handful of
* workspaces; sequential keeps the probe gentle on Linear's token endpoint).
*/
export async function probeLinearGrants(
ddb: DynamoDBDocumentClient,
registryTableName: string,
resolve: (linearWorkspaceId: string) => Promise<unknown | null>,
): Promise<GrantHealthReport> {
const rows: RegistryRow[] = [];
let startKey: Record<string, unknown> | undefined;
do {
const page = await ddb.send(new ScanCommand({
TableName: registryTableName,
ProjectionExpression: 'linear_workspace_id, workspace_slug, #status',
ExpressionAttributeNames: { '#status': 'status' },
ExclusiveStartKey: startKey,
}));
rows.push(...(page.Items ?? []) as RegistryRow[]);
startKey = page.LastEvaluatedKey;
} while (startKey);

let healthy = 0;
const unhealthy: string[] = [];
const revoked: string[] = [];
let checked = 0;
for (const row of rows) {
if (!row.linear_workspace_id) continue;
const label = row.workspace_slug ?? row.linear_workspace_id;
if (row.status !== 'active') {
revoked.push(label);
continue;
}
checked++;
try {
if (await resolve(row.linear_workspace_id)) healthy++;
else unhealthy.push(label);
} catch {
// One workspace's failure must not hide the others.
unhealthy.push(label);
}
}
return { checked, healthy, unhealthy, revoked };
}
5 changes: 4 additions & 1 deletion cdk/src/stacks/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1351,7 +1351,7 @@ export class AgentStack extends Stack {
agentMemory.grantReadWrite(orchestrator.fn);

// --- Concurrency counter reconciler (drift correction) ---
new ConcurrencyReconciler(this, 'ConcurrencyReconciler', {
const concurrencyReconciler = new ConcurrencyReconciler(this, 'ConcurrencyReconciler', {
taskTable: taskTable.table,
userConcurrencyTable: userConcurrencyTable.table,
});
Expand Down Expand Up @@ -2024,6 +2024,9 @@ export class AgentStack extends Stack {
// not exist yet at this point in the constructor.
if (linearIntegration) {
operationalAlerts.grantPublish(linearIntegration.webhookProcessorFn);
// #1004: the reconciler kicks the processor's grant health probe twice a day, so a
// grant that dies while nobody uses Linear is still detected and announced here.
concurrencyReconciler.triggerLinearGrantProbe(linearIntegration.webhookProcessorFn);
linearIntegration.webhookProcessorFn.addEnvironment(
'OPERATIONAL_ALERT_TOPIC_ARN',
operationalAlerts.topic.topicArn,
Expand Down
39 changes: 39 additions & 0 deletions cdk/test/constructs/concurrency-reconciler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import { App, Stack } from 'aws-cdk-lib';
import { Template, Match } from 'aws-cdk-lib/assertions';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { ConcurrencyReconciler } from '../../src/constructs/concurrency-reconciler';

function createStack(): Template {
Expand Down Expand Up @@ -70,3 +71,41 @@ describe('ConcurrencyReconciler construct', () => {
});
});
});

describe('ConcurrencyReconciler Linear grant probe trigger (#1004)', () => {
function build(withProbe: boolean): Template {
const stack = new Stack(new App(), 'ProbeStack');
const table = (id: string, pk: string) => new dynamodb.Table(stack, id, {
partitionKey: { name: pk, type: dynamodb.AttributeType.STRING },
});
const reconciler = new ConcurrencyReconciler(stack, 'ConcurrencyReconciler', {
taskTable: table('Tasks', 'task_id'),
userConcurrencyTable: table('Users', 'user_id'),
});
const processor = new lambda.Function(stack, 'Processor', {
runtime: lambda.Runtime.NODEJS_22_X, handler: 'index.handler', code: lambda.Code.fromInline('exports.handler=async()=>{}'),
});
if (withProbe) reconciler.triggerLinearGrantProbe(processor);
return Template.fromStack(stack);
}

test('grants invoke and passes the target without adding any resource', () => {
const without = build(false);
const template = build(true);
const types = (t: Template) => Object.entries(t.toJSON().Resources as Record<string, { Type: string }>)
.map(([id, r]) => `${r.Type} ${id}`).sort();

expect(types(template)).toEqual(types(without));
template.hasResourceProperties('AWS::Lambda::Function', {
Environment: {
Variables: Match.objectLike({
RECONCILER_TICK_MINUTES: '15',
LINEAR_GRANT_PROBE_FUNCTION_ARN: { 'Fn::GetAtt': [Match.stringLikeRegexp('Processor'), 'Arn'] },
}),
},
});
template.hasResourceProperties('AWS::IAM::Policy', {
PolicyDocument: { Statement: Match.arrayWith([Match.objectLike({ Action: 'lambda:InvokeFunction' })]) },
});
});
});
29 changes: 29 additions & 0 deletions cdk/test/handlers/linear-webhook-processor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({}
jest.mock('@aws-sdk/lib-dynamodb', () => ({
DynamoDBDocumentClient: { from: jest.fn(() => ({ send: ddbSend })) },
GetCommand: jest.fn((input: unknown) => ({ _type: 'Get', input })),
ScanCommand: jest.fn((input: unknown) => ({ _type: 'Scan', input })),
}));

const createTaskCoreMock = jest.fn();
Expand Down Expand Up @@ -117,6 +118,34 @@ function issue(overrides: Record<string, unknown> = {}): Record<string, unknown>
};
}

describe('linear-webhook-processor scheduled grant health probe (#1004)', () => {
beforeEach(() => {
ddbSend.mockReset();
createTaskCoreMock.mockReset();
resolveLinearOauthTokenMock.mockReset();
});

test('the probe event resolves every active workspace and never takes the webhook path', async () => {
ddbSend.mockResolvedValueOnce({
Items: [
{ linear_workspace_id: 'ws-live', workspace_slug: 'live', status: 'active' },
{ linear_workspace_id: 'ws-dead', workspace_slug: 'dead', status: 'active' },
{ linear_workspace_id: 'ws-latched', workspace_slug: 'latched', status: 'revoked' },
],
});
resolveLinearOauthTokenMock.mockImplementation(async (id: string) => (id === 'ws-live' ? { access_token: 't' } : null));

await handler({ grant_health_probe: true });

expect(ddbSend.mock.calls[0][0]).toMatchObject({ _type: 'Scan', input: { TableName: 'LinearWorkspaceRegistry' } });
expect(resolveLinearOauthTokenMock.mock.calls).toEqual([
['ws-live', 'LinearWorkspaceRegistry'],
['ws-dead', 'LinearWorkspaceRegistry'],
]);
expect(createTaskCoreMock).not.toHaveBeenCalled();
});
});

describe('linear-webhook-processor handler', () => {
beforeEach(() => {
ddbSend.mockReset();
Expand Down
Loading
Loading