Superpositional
AboutReview principlesPricingBlogGalleryAsk a RepoFAQ…

Real reviews of open-source pull requests

Read the reviews our automated pipeline produced across 7 repositories. Each includes the verdict, the exact commit reviewed and an independent judge’s score.

6 of 13, withastro/astro#18714
Ask this repo
concerns · 1 retained findingHistorical review — archived before analysis attestation, re-judged by the independent oracle for this gallerydrizzle-team/drizzle-orm#6482Review permalink

[All-kit]: Build one `identifier` function per push command from the renames and standardize the data loss warnings

Input

PR author’s description

The data loss checks of drizzle-kit push run before any statement, so they query a table by the name that the database still has. Each call site did that lookup by hand with tableBefore or schemaBefore before it…

PR diff

Current GitHub diff ↗
drizzle-kit/src/cli/commands/warnings.ts · patch excerpt
+type TableName = { schema?: string; name: string };++export const nameWithRename = (before: string, after: string) => {+	return before === after ? before : `${before} (would become ${after})`;
Browse 20 changed files
drizzle-kit/src/cli/commands/warnings.ts+62 −0
@@ -0,0 +1,62 @@+type TableName = { schema?: string; name: string };++export const nameWithRename = (before: string, after: string) => {+	return before === after ? before : `${before} (would become ${after})`;+};++// Statements name a table as it is after the diff. A data loss check runs before any statement,+// so it must query the table by the name that the database still has.+// `'dropped'` applies only the schema rename, because a table can be renamed or moved to the name+// of a dropped view.+export const tableNamesBeforeRenames = (+	renames: {+		schemas?: readonly { from: { name: string }; to: { name: string } }[];+		tables: readonly { schema?: string; from: string; to: string }[];+		moves?: readonly { name: string; from: string; to: string }[];+	},+	quoteTable: (table: TableName) => string,+) => {+	const identifier = (table: TableName, diffResult: 'kept' | 'dropped'): string => {+		let { schema, name } = table;+		if (diffResult === 'kept') {+			schema = renames.moves?.find((it) => it.name === name && it.to === schema)?.from ?? schema;+			name = renames.tables.find((it) => it.to === name && it.schema === schema)?.from ?? name;+		}+		schema = renames.schemas?.find((it) => it.to.name === schema)?.from.name ?? schema;++		return quoteTable({ schema, name });+	};++	const label = (table: TableName) => nameWithRename(identifier(table, 'kept'), quoteTable(table));++	return { identifier, label };+};++export const dropTableWarning = (table: string) => `You're about to delete non-empty ${table} table`;++export const dropViewWarning = (view: string) => `You're about to delete non-empty ${view} materialized view`;++export const dropColumnWarning = (column: string, table: string) => {+	return `You're about to delete non-empty ${column} column in ${table} table`;+};++export const dropSchemaWarning = (schema: string, tableCount: number) => {+	return `You're about to delete ${schema} schema with ${tableCount} ${tableCount === 1 ? 'table' : 'tables'}`;+};++export const dropPrimaryKeyWarning = (table: string) => {+	return `You're about to drop the primary key of ${table} table. The statements may fail, and the table may lose its primary key`;+};++export const addNotNullColumnWarning = (column: string, table: string) => {+	return `You're about to add not-null ${column} column without default value to non-empty ${table} table`;+};++export const changeColumnTypeWarning = (column: string, table: string, from: string, to: string) => {+	return `You're about to change ${column} column type in ${table} table from ${from} to ${to}`;+};++export const dropReferencedPrimaryKeyWarning = (table: string, columns: string[]) => {+	const columnNames = columns.join(', ');+	return `You are trying to drop primary key from ${table} (${columnNames}), but there is an existing reference on this column. You must either add a UNIQUE constraint to (${columnNames}) or drop the foreign key constraint that references this column.`;+};
drizzle-kit/tests/postgres/pg-tables.test.ts+111 −7
@@ -7,6 +7,7 @@ import { 	geometry, 	index, 	integer,+	pgMaterializedView, 	PgSchema, 	pgSchema, 	pgTable,@@ -23,6 +24,10 @@ import { 	vector, } from 'drizzle-orm/pg-core'; import { stripAnsi } from 'hanji/utils';+import { suggestions } from 'src/cli/commands/push-postgres';+import { runWithCliContext } from 'src/cli/context';+import { HintsHandler } from 'src/cli/hints';+import { prepareStatement } from 'src/dialects/postgres/statements'; import { afterAll, beforeAll, beforeEach, expect, test } from 'vitest'; import { diff, prepareTestDatabase, push, TestDatabase } from './mocks'; @@ -1706,7 +1711,7 @@ test('drop column in a renamed table with data', async () => { 		'ALTER TABLE "accounts" DROP COLUMN "name";', 	]); 	expect(phints).toStrictEqual([-		{ hint: `You're about to delete non-empty name column in "accounts" table` },+		{ hint: `You're about to delete non-empty "name" column in "users" (would become "accounts") table` }, 	]); }); @@ -1735,7 +1740,7 @@ test('drop column in a table with data that moves to another schema', async () = 		'ALTER TABLE "app"."users" DROP COLUMN "name";', 	]); 	expect(phints).toStrictEqual([-		{ hint: `You're about to delete non-empty name column in "app"."users" table` },+		{ hint: `You're about to delete non-empty "name" column in "users" (would become "app"."users") table` }, 	]); }); @@ -1761,7 +1766,7 @@ test('drop column in a table with data in a renamed schema', async () => { 		'ALTER TABLE "after"."users" DROP COLUMN "name";', 	]); 	expect(phints).toStrictEqual([-		{ hint: `You're about to delete non-empty name column in "after"."users" table` },+		{ hint: `You're about to delete non-empty "name" column in "before"."users" (would become "after"."users") table` }, 	]); }); @@ -1791,7 +1796,7 @@ test('drop column in a table with data that is renamed and moves to another sche 		'ALTER TABLE "app"."accounts" DROP COLUMN "name";', 	]); 	expect(phints).toStrictEqual([-		{ hint: `You're about to delete non-empty name column in "app"."accounts" table` },+		{ hint: `You're about to delete non-empty "name" column in "users" (would become "app"."accounts") table` }, 	]); }); @@ -1822,7 +1827,10 @@ test('drop column in a renamed table with data in a renamed schema', async () => 		'ALTER TABLE "after"."accounts" DROP COLUMN "name";', 	]); 	expect(phints).toStrictEqual([-		{ hint: `You're about to delete non-empty name column in "after"."accounts" table` },+		{+			hint:+				`You're about to delete non-empty "name" column in "before"."users" (would become "after"."accounts") table`,+		}, 	]); }); @@ -1849,7 +1857,7 @@ test('drop primary key in a renamed table with data', async () => { 	]); 	expect(phints.map((it) => ({ ...it, hint: stripAnsi(it.hint) }))).toStrictEqual([{ 		hint:-			`You're about to drop "public"."accounts" primary key, this statements may fail and your table may lose primary key`,+			`You're about to drop the primary key of "users" (would become "accounts") table. The statements may fail, and the table may lose its primary key`, 	}]); }); @@ -1877,6 +1885,102 @@ test('drop materialized view with data in a renamed schema', async () => { 		'DROP MATERIALIZED VIEW "after"."view";', 	]); 	expect(phints).toStrictEqual([-		{ hint: `You're about to delete non-empty "after"."view" materialized view` },+		{ hint: `You're about to delete non-empty "before"."view" materialized view` },+	]);+});++test('drop primary key with an implicit name in a renamed table with data', async () => {+	await db.query(`CREATE TABLE "orders" ("id" integer CONSTRAINT "orders_custom_pk" PRIMARY KEY);`);+	await db.query(`INSERT INTO "orders" ("id") VALUES (1);`);++	const hints = await runWithCliContext({ output: 'text', interactive: true }, () =>+		suggestions(db, [+			prepareStatement('rename_table', { schema: 'public', from: 'orders', to: 'purchases' }),+			prepareStatement('drop_pk', {+				pk: {+					entityType: 'pks',+					schema: 'public',+					table: 'purchases',+					name: 'purchases_pkey',+					nameExplicit: false,+					columns: ['id'],+				},+			}),+		], new HintsHandler()));++	for (const it of hints) {+		if (it.statement) await db.query(it.statement);+	}++	const primaryKeys = await db.query(+		`select conname from pg_constraint where conrelid = '"orders"'::regclass and contype = 'p';`,+	);+	expect(hints).toHaveLength(1);+	expect(primaryKeys).toStrictEqual([]);+});++test('drop column without values in a table with data', async () => {+	const schema1 = {+		users: pgTable('users', { id: integer('id').primaryKey(), name: text('name') }),+	};+	const schema2 = {+		users: pgTable('users', { id: integer('id').primaryKey() }),+	};++	await push({ db, to: schema1 });+	await db.query(`INSERT INTO "users" ("id") VALUES (1);`);++	const { hints: phints } = await push({ db, to: schema2 });++	expect(phints).toStrictEqual([]);+});++test('drop table with data in a renamed schema', async () => {+	const before = pgSchema('before');+	const after = pgSchema('after');+	const schema1 = {+		before,+		users: before.table('users', { id: integer('id').primaryKey() }),+	};+	const schema2 = { after };++	await push({ db, to: schema1 });+	await db.query(`INSERT INTO "before"."users" ("id") VALUES (1);`);++	const { hints: phints } = await push({ db, to: schema2, renames: ['before->after'] });++	expect(phints).toStrictEqual([+		{ hint: `You're about to delete non-empty "before"."users" table` },+	]);+});++test('drop materialized view with data when a renamed table takes its name', async () => {+	const users = pgTable('users', { id: integer('id').primaryKey() });+	const schema1 = {+		users,+		accounts: pgTable('accounts', { id: integer('id').primaryKey() }),+		report: pgMaterializedView('report', { id: integer('id') }).as(sql`SELECT "id" FROM "users"`),+	};+	const schema2 = {+		users,+		report: pgTable('report', { id: integer('id').primaryKey() }),+	};++	await push({ db, to: schema1 });+	await db.query(`INSERT INTO "users" ("id") VALUES (1);`);+	await db.query(`REFRESH MATERIALIZED VIEW "report";`);++	const { sqlStatements: pst, hints: phints } = await push({+		db,+		to: schema2,+		renames: ['public.accounts->public.report'],+	});++	expect(pst).toStrictEqual([+		'DROP MATERIALIZED VIEW "report";',+		'ALTER TABLE "accounts" RENAME TO "report";',+	]);+	expect(phints).toStrictEqual([+		{ hint: `You're about to delete non-empty "report" materialized view` }, 	]); });
drizzle-kit/src/cli/commands/push-mysql.ts+33 −40
@@ -6,7 +6,6 @@ import { interimToDDL } from '../../dialects/mysql/ddl'; import { ddlDiff } from '../../dialects/mysql/diff'; import type { JsonStatement } from '../../dialects/mysql/statements'; import { prepareEntityFilter } from '../../dialects/pull-utils';-import { tableBeforeRenames } from '../../dialects/utils'; import type { DB } from '../../utils'; import { connectToMySQL } from '../connections'; import { isInteractive, outputFormat } from '../context';@@ -26,6 +25,15 @@ import { 	ProgressView, } from '../views'; import { introspect } from './pull-mysql';+import {+	changeColumnTypeWarning,+	dropColumnWarning,+	dropPrimaryKeyWarning,+	dropReferencedPrimaryKeyWarning,+	dropTableWarning,+	nameWithRename,+	tableNamesBeforeRenames,+} from './warnings';  export const handle = async ( 	filenames: string[],@@ -131,14 +139,16 @@ export const handle = async ( 	return { status: 'ok' as const, dialect: 'mysql' }; }; -const identifier = ({ table, column }: { table?: string; column?: string }) => {-	return [table, column].filter(Boolean).map((t) => `\`${t}\``).join('.');-};+const quote = (name: string) => `\`${name}\``;+ export const suggestions = async (db: DB, jsonStatements: JsonStatement[], ddl2: MysqlDDL, hints: HintsHandler) => { 	const json = outputFormat() === 'json'; 	const useHints = json || !isInteractive(); 	const grouped: { hint: string; statement?: string }[] = [];-	const tableBefore = tableBeforeRenames({ tables: jsonStatements.filter((it) => it.type === 'rename_table') });+	const { identifier, label } = tableNamesBeforeRenames(+		{ tables: jsonStatements.filter((it) => it.type === 'rename_table') },+		(it) => quote(it.name),+	);  	const filtered = jsonStatements.filter((it) => { 		if (it.type === 'alter_column' && it.diff.generated) return false;@@ -148,59 +158,54 @@ export const suggestions = async (db: DB, jsonStatements: JsonStatement[], ddl2:  	for (const statement of filtered) { 		if (statement.type === 'drop_table') {+			const id = identifier({ name: statement.table }, 'dropped'); 			const entity = ['public', statement.table] as const; 			if (hints.matchConfirm('table', entity)) continue;-			const res = await db.query(`select 1 from ${identifier({ table: statement.table })} limit 1`);+			const res = await db.query(`select 1 from ${id} limit 1`);  			if (res.length > 0) { 				if (useHints) { 					hints.pushMissingHint({ type: 'confirm_data_loss', kind: 'table', entity, reason: 'non_empty' }); 				} else {-					grouped.push({ hint: `You're about to delete non-empty ${chalk.underline(statement.table)} table` });+					grouped.push({ hint: dropTableWarning(id) }); 				} 			} 			continue; 		}  		if (statement.type === 'drop_column') { 			const column = statement.column;+			const table = { name: column.table }; 			const entity = ['public', column.table, column.name] as const; 			if (hints.matchConfirm('column', entity)) continue;-			const tableInDb = tableBefore({ name: column.table }).name;-			const res = await db.query(`select 1 from ${identifier({ table: tableInDb })} limit 1`);+			const res = await db.query(+				`select 1 from ${identifier(table, 'kept')} where ${quote(column.name)} is not null limit 1`,+			); 			if (res.length === 0) continue;  			if (useHints) { 				hints.pushMissingHint({ type: 'confirm_data_loss', kind: 'column', entity, reason: 'non_empty' }); 			} else {-				grouped.push({-					hint: `You're about to delete non-empty ${chalk.underline(column.name)} column in ${-						chalk.underline(column.table)-					} table`,-				});+				grouped.push({ hint: dropColumnWarning(quote(column.name), label(table)) }); 			} 			continue; 		}  		// drop pk 		if (statement.type === 'drop_pk') { 			const { table, columns } = statement.pk;-			const id = identifier({ table: tableBefore({ name: table }).name });+			const id = identifier({ name: table }, 'kept'); 			const entity = ['public', table, statement.pk.name] as const; 			if (hints.matchConfirm('primary_key', entity)) continue; 			const res = await db.query( 				`select 1 from ${id} limit 1`, 			);  			if (res.length > 0) {-				const hint = `You're about to drop ${-					chalk.underline(table)-				} primary key, this statements may fail and your table may lose primary key`;- 				if (useHints) { 					hints.pushMissingHint({ type: 'confirm_data_loss', kind: 'primary_key', entity, reason: 'non_empty' }); 				} else {-					grouped.push({ hint });+					grouped.push({ hint: dropPrimaryKeyWarning(label({ name: table })) }); 				} 			} @@ -233,20 +238,11 @@ export const suggestions = async (db: DB, jsonStatements: JsonStatement[], ddl2: 					blocking_fks: fkFound.map((fk) => fk.name), 				}); 			}-			grouped.push({-				hint: `You are trying to drop primary key from "${table}" ("${-					columns.join('", ')-				}"), but there is an existing reference on this column. You must either add a UNIQUE constraint to ("${-					columns.join('", ')-				}") or drop the foreign key constraint that references this column.`,-			});+			grouped.push({ hint: dropReferencedPrimaryKeyWarning(label({ name: table }), columns.map(quote)) }); 			continue; 		}  		if (statement.type === 'alter_column') {-			const tableName = identifier({ table: statement.origin.table });-			const columnName = identifier({ column: statement.origin.column });- 			if (statement.diff.type) { 				const entity = ['public', statement.column.table, statement.column.name] as const; 				if (!hints.matchConfirm('column', entity)) {@@ -259,17 +255,14 @@ export const suggestions = async (db: DB, jsonStatements: JsonStatement[], ddl2: 							reason_details: { from: statement.diff.type.from, to: statement.diff.type.to }, 						}); 					} else {-						const hint = `You're about to change ${-							chalk.underline(-								columnName,-							)-						} column type in ${tableName} from ${-							chalk.underline(+						grouped.push({+							hint: changeColumnTypeWarning(+								nameWithRename(quote(statement.origin.column), quote(statement.column.name)),+								label({ name: statement.column.table }), 								statement.diff.type.from,-							)-						} to ${chalk.underline(statement.diff.type.to)}`;--						grouped.push({ hint });+								statement.diff.type.to,+							),+						}); 					} 				} 			}

→ Outcome

Why this verdict

concerns — Updated data loss warnings in drizzle-kit push → unified warning texts and SQL quoting across dialects → users now see quoted identifiers and only confirm dropped columns with non-null values

  • 🟡 drizzle-kit/src/cli/commands/push-cockroach.ts:quote — 1 finding ↳ 20 callers (drizzle-kit/src/cli/commands/generate-mysql.ts:53, drizzle-kit/src/cli/commands/generate-mysql.ts:54, drizzle-kit/src/cli/commands/generate-mysql.ts:87) — downstream impact 🔴 narrator-identified-concern

  • Ordinary source not in the index yet (a re-sync/overlay rebuild may cover them): changelogs/drizzle-kit/1.0.0-rc.5.md, drizzle-kit/skills/drizzle-hints/SKILL.md, drizzle-kit/skills/drizzle/SKILL.md, drizzle-kit/tests/other/payload-push.test.ts, drizzle-kit/tests/sqlite/sqlite-columns.test.ts

Evidence and perspectives

  • Observation · Narrated concernUpdated data loss warnings in `drizzle-kit push` → unified warning texts and SQL quoting across dialects → users now see quoted identifiers and only confirm dropped columns with non-null values

    Recorded location drizzle-kit/src/cli/commands/push-cockroach.ts:19

Supporting evidence

Reviewed 3 Nov 2026Revision 268e4c5e089020 changed files+400 −235Judge score 5/5
Approved · 0 retained findingsdrizzle-team/drizzle-orm#6672Review permalink

postgres driver release preparations

Input

PR diff

Current GitHub diff ↗
drizzle-orm/src/pg-core/async/session.ts · patch excerpt
+/**+ * A prepared query with its placeholder values bound, so it can run as one item of a batch:+ *+ * ```ts
Browse 30 changed files
drizzle-orm/src/pg-core/async/session.ts+47 −0
@@ -17,6 +17,32 @@ import type { PgQueryResultHKT, PgTransactionConfig, PreparedQueryConfig } from import { PgBasePreparedQuery, PgSession } from '../session.ts'; import { PgAsyncDatabase } from './db.ts'; +/**+ * A prepared query with its placeholder values bound, so it can run as one item of a batch:+ *+ * ```ts+ * const getUser = db.select().from(users).where(eq(users.id, sql.placeholder('id'))).prepare('get_user');+ * const [alice, bob] = await db.batch([getUser.bind({ id: 1 }), getUser.bind({ id: 2 })]);+ * ```+ *+ * Accepted by `batch`, `pipeline` and `parallel` of the `drizzle-orm/postgres` driver, which run it under the+ * prepared statement's name. Created by {@link PgAsyncPreparedQuery.bind}.+ */+export class PgAsyncBoundQuery<T extends PreparedQueryConfig> {+	static readonly [entityKind]: string = 'PgAsyncBoundQuery';+	static [Symbol.hasInstance](value: unknown): boolean {+		return is(value, this);+	}++	// No `_` result marker on purpose: with it, this class would match the builder-only batch item type that the+	// other pg drivers take (their declarations keep only `_`), and they would send its placeholders unfilled.++	constructor(+		readonly prepared: PgAsyncPreparedQuery<T>,+		readonly placeholderValues: Record<string, unknown>,+	) {}+}+ export class PgAsyncPreparedQuery<T extends PreparedQueryConfig> extends PgBasePreparedQuery { 	static override readonly [entityKind]: string = 'PgAsyncPreparedQuery'; @@ -56,6 +82,27 @@ export class PgAsyncPreparedQuery<T extends PreparedQueryConfig> extends PgBaseP 			&& !hasTelemetry; 	} +	/**+	 * Pairs this query with values for its placeholders without running it: the lazy counterpart of+	 * {@link execute}. Nothing is sent until the result is run as an item of `batch`, `pipeline` or `parallel`+	 * of the `drizzle-orm/postgres` driver, which runs it under this query's statement name:+	 *+	 * ```ts+	 * const [alice, bob] = await db.batch([getUser.bind({ id: 1 }), getUser.bind({ id: 2 })]);+	 * ```+	 *+	 * Other drivers' batches don't accept it.+	 */+	bind(placeholderValues: Record<string, unknown> = {}): PgAsyncBoundQuery<T> {+		return new PgAsyncBoundQuery(this, placeholderValues);+	}++	/**+	 * Runs the query with values for its placeholders and returns a Promise of the result.+	 *+	 * Eager: the query is sent as soon as `execute` is called, whether or not the Promise is awaited. To hand the+	 * query and its values to something that runs it later, such as a batch, use {@link bind}.+	 */ 	override async execute(placeholderValues: Record<string, unknown> = {}): Promise<T['execute']> { 		const { query, logger, executor, mapper, fastPath } = this; 
pnpm-lock.yaml+795 −3
postgres/src/compat/prisma7.ts+543 −0

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Failure HandlingCatch block in compat/prisma7.ts returns normal value without rethrowing or rejecting, converting failure to success

    Principle · Keep Failure Visible to the Caller

    Recorded file postgres/src/compat/prisma7.ts · no line recorded

  • Observation · OperabilityThe new batch() function returns BatchMetrics but the diff does not show integration with existing telemetry or alerting for this path. Operators cannot observe batch performance or failures through established signals.

    Principle · Measure User Impact and Recovery

    Recorded location drizzle-orm/src/postgres/driver-core.ts:68

Supporting evidence

Reviewed 29 Nov 2026Revision 33d0f350e28d30 changed files+4773 −246Judge score 5/5
Approved · 0 retained findingswikimedia/apps-android-wikipedia#7116Review permalink

Year-in-Review: swipe tutorial dialog.

Input

PR author’s description

https://phabricator.wikimedia.org/T442102

PR diff

Current GitHub diff ↗
app/src/main/java/org/wikipedia/settings/Prefs.kt · patch excerpt
+    var isYearInReviewSwipeTutorialShown+        get() = PrefsIoUtil.getBoolean(R.string.preference_key_year_in_review_swipe_tutorial_shown, false)+        set(value) = PrefsIoUtil.setBoolean(R.string.preference_key_year_in_review_swipe_tutorial_shown, value)+
Browse 7 changed files
app/src/main/java/org/wikipedia/settings/Prefs.kt+4 −0
@@ -1000,6 +1000,10 @@ object Prefs {         get() = PrefsIoUtil.getBoolean(R.string.preference_key_home_swipe_to_explore_prompt_shown, false)         set(value) = PrefsIoUtil.setBoolean(R.string.preference_key_home_swipe_to_explore_prompt_shown, value) +    var isYearInReviewSwipeTutorialShown+        get() = PrefsIoUtil.getBoolean(R.string.preference_key_year_in_review_swipe_tutorial_shown, false)+        set(value) = PrefsIoUtil.setBoolean(R.string.preference_key_year_in_review_swipe_tutorial_shown, value)+     var searchWidgetInstallPromptShown         get() = PrefsIoUtil.getBoolean(R.string.preference_key_search_widget_install_prompt_shown, false)         set(value) = PrefsIoUtil.setBoolean(R.string.preference_key_search_widget_install_prompt_shown, value)
app/src/main/java/org/wikipedia/yearinreview/presentation/YearInReviewScreen.kt+44 −0
@@ -1,6 +1,7 @@ package org.wikipedia.yearinreview.presentation  import android.graphics.Bitmap+import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.gestures.Orientation@@ -67,21 +68,27 @@ import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import app.rive.Result import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch+import kotlinx.coroutines.withTimeoutOrNull import org.wikipedia.R import org.wikipedia.compose.ComposeColors import org.wikipedia.compose.components.AppButton+import org.wikipedia.compose.components.WikipediaAlertDialog import org.wikipedia.compose.components.error.WikiErrorClickEvents import org.wikipedia.compose.components.error.WikiErrorView import org.wikipedia.compose.theme.BaseTheme import org.wikipedia.compose.theme.WikipediaTheme+import org.wikipedia.settings.Prefs import org.wikipedia.theme.Theme import org.wikipedia.yearinreview.data.YearInReviewEndScreenABTest import org.wikipedia.yearinreview.data.YearInReviewReadingStats import kotlin.math.roundToInt+import kotlin.time.Duration.Companion.milliseconds  private val YearInReviewCardCornerRadius = 28.dp internal val TopAppBarHeight = 64.dp+private const val SWIPE_TUTORIAL_DELAY_MILLIS = 2000L  fun Modifier.placeholderBackground() = background(     brush = Brush.linearGradient(@@ -206,6 +213,43 @@ private fun YearInReviewContent(             pages.getOrNull(position)?.let { currentOnPageImpression(it) }         }     }++    var showSwipeTutorial by remember { mutableStateOf(false) }+    LaunchedEffect(pagerState) {+        if (!Prefs.isYearInReviewSwipeTutorialShown) {+            val swipedBeforeTutorial = withTimeoutOrNull(SWIPE_TUTORIAL_DELAY_MILLIS.milliseconds) {+                snapshotFlow { pagerState.isScrollInProgress }.first { it }+            } != null+            if (swipedBeforeTutorial) {+                Prefs.isYearInReviewSwipeTutorialShown = true+            } else {+                showSwipeTutorial = true+            }+        }+    }+    if (showSwipeTutorial) {+        val dismissSwipeTutorial = {+            showSwipeTutorial = false+            Prefs.isYearInReviewSwipeTutorialShown = true+        }+        BaseTheme(currentTheme = Theme.BLACK) {+            WikipediaAlertDialog(+                title = stringResource(R.string.year_in_review_swipe_tutorial_title),+                titleModifier = Modifier.fillMaxWidth(),+                message = stringResource(R.string.year_in_review_swipe_tutorial_message),+                image = {+                    Image(+                        painter = painterResource(R.drawable.illustration_swipeup),+                        contentDescription = null+                    )+                },+                confirmButtonText = stringResource(R.string.onboarding_got_it),+                onDismissRequest = dismissSwipeTutorial,+                onConfirmButtonClick = dismissSwipeTutorial+            )+        }+    }+     // Slides are restarted once they're off screen, so that scrolling back to one plays it from the beginning     val restartKeysByPageId = remember { mutableStateMapOf<String, Int>() }     LaunchedEffect(pagerState, pages) {
app/src/main/res/drawable/illustration_swipeup.xml+30 −0
@@ -0,0 +1,30 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    xmlns:aapt="http://schemas.android.com/aapt"+    android:width="416dp"+    android:height="296dp"+    android:viewportWidth="416"+    android:viewportHeight="296">+  <path+      android:pathData="M0.62,-0.62h415.95v298.34h-415.95z"+      android:strokeWidth="1.00701"+      android:fillColor="#6699ff"/>+  <path+      android:pathData="m192.65,99.27c2.35,-1.09 5.12,-1.52 7.78,-0.83 2.74,0.71 5.13,2.54 6.62,5.5 4.75,9.49 7.23,15.09 9.47,20.33 0.44,1.02 0.86,2.02 1.29,3.03 1.52,-1.93 3.69,-3.3 5.8,-4.08 3.36,-1.25 7.72,-1.46 11.06,0.83 1.33,0.91 2.39,2.07 3.23,3.27 0.17,-0.27 0.35,-0.53 0.55,-0.8 1.78,-2.36 4.8,-3.55 7.54,-3.8 2.79,-0.26 6.09,0.37 8.5,2.65 0.72,0.68 1.34,1.38 1.88,2.08 0.49,-0.55 1.06,-1.08 1.72,-1.57 2.96,-2.18 6.8,-2.14 9.85,-0.98 3.11,1.18 6.04,3.75 7.09,7.53 0,0.01 0.06,0.16 0.21,0.56 0.15,0.39 0.35,0.89 0.6,1.53 0.5,1.25 1.17,2.95 1.94,4.96 1.53,4.02 3.43,9.33 5.09,15.06 1.65,5.72 3.07,11.95 3.59,17.79 0.51,5.76 0.19,11.56 -2.04,16.13 -4.18,8.56 -12.8,14.7 -21.79,18.68 -9.05,4 -19.02,6.05 -26.64,6.05 -5.29,-0 -13.45,-0.5 -21.26,-5.36 -7.9,-4.92 -14.97,-14 -18.66,-30.2 -1.74,-7.64 -0.36,-12.79 2.09,-16.5 1.17,-1.77 2.51,-3.09 3.55,-4.07 0.36,-0.34 0.65,-0.62 0.89,-0.85l-16.63,-42.72 -0.06,-0.15 -0.04,-0.15c-1.79,-6.48 2.16,-11.77 6.79,-13.92zM198.86,104.54c-1.02,-0.26 -2.29,-0.14 -3.55,0.45 -2.55,1.18 -4.09,3.66 -3.4,6.39l17.27,44.34 8.11,20.03c0.65,1.61 -0.12,3.45 -1.74,4.11 -1.61,0.65 -3.45,-0.12 -4.11,-1.74l-6.32,-15.59c-0.62,0.64 -1.2,1.31 -1.71,2.08 -1.4,2.12 -2.61,5.47 -1.2,11.62 3.4,14.92 9.66,22.39 15.85,26.25 6.29,3.91 13,4.41 17.93,4.41 6.65,0 15.76,-1.83 24.09,-5.51 8.38,-3.7 15.43,-9.04 18.68,-15.68 1.48,-3.03 1.91,-7.44 1.43,-12.8 -0.47,-5.28 -1.78,-11.08 -3.37,-16.6 -1.59,-5.5 -3.43,-10.64 -4.92,-14.56 -0.75,-1.96 -1.41,-3.62 -1.9,-4.87 -0.45,-1.13 -0.88,-2.2 -1.02,-2.72 -0.42,-1.49 -1.65,-2.72 -3.26,-3.33 -1.67,-0.63 -3.11,-0.4 -3.87,0.16 -1.98,1.46 -2.04,3.88 -2.04,4.34 0,0.02 0,0.21 -0.02,0.43 -0.01,0.07 -0.03,0.2 -0.06,0.35 -0.03,0.11 -0.12,0.46 -0.35,0.86 -0.19,0.32 -0.95,1.47 -2.56,1.55 -1.48,0.08 -2.34,-0.85 -2.51,-1.05 -0.27,-0.3 -0.41,-0.58 -0.46,-0.68 -0.07,-0.13 -0.11,-0.24 -0.13,-0.3 -0.05,-0.12 -0.08,-0.22 -0.09,-0.26 -0.03,-0.09 -0.05,-0.17 -0.05,-0.2 -0.05,-0.21 -0.04,-0.17 -0.09,-0.4 -0.08,-0.31 -0.21,-0.79 -0.44,-1.39 -0.47,-1.2 -1.32,-2.81 -2.86,-4.27 -0.71,-0.68 -2.01,-1.1 -3.58,-0.95 -1.62,0.15 -2.71,0.82 -3.09,1.33 -0.81,1.07 -1.1,2.33 -1.22,3.6 -0.07,0.74 -0.05,1.12 -0.1,1.85 -0.02,0.26 -0.04,0.71 -0.15,1.15 -0.05,0.23 -0.35,1.62 -1.76,2.37 -0.61,0.32 -1.35,0.47 -2.11,0.32 -0.7,-0.13 -1.2,-0.46 -1.49,-0.7 -0.52,-0.43 -0.8,-0.93 -0.9,-1.1 -0.23,-0.42 -0.41,-0.92 -0.52,-1.23 -0.29,-0.81 -0.53,-1.59 -0.92,-2.59 -0.8,-2.01 -1.82,-3.8 -3.21,-4.75 -1.06,-0.73 -3.09,-0.94 -5.29,-0.12 -2.21,0.82 -3.46,2.25 -3.71,3.43 -0.15,0.73 -0.12,1.82 0.14,3.19 0.25,1.33 0.68,2.7 1.12,3.89 0.12,0.31 0.23,0.61 0.34,0.89 0.26,0.55 0.52,1.11 0.79,1.69 0.09,0.19 0.17,0.36 0.23,0.5 0.02,0.06 0.07,0.18 0.12,0.31 0.01,0.04 0.08,0.24 0.12,0.49 0.01,0.07 0.09,0.49 0.01,1.03 -0.04,0.26 -0.17,0.92 -0.72,1.56 -0.68,0.79 -1.65,1.16 -2.58,1.1 -0.74,-0.04 -1.26,-0.33 -1.46,-0.45 -0.24,-0.15 -0.41,-0.3 -0.5,-0.38 -0.18,-0.17 -0.3,-0.32 -0.34,-0.37 -0.1,-0.13 -0.18,-0.25 -0.2,-0.29 -0.06,-0.1 -0.12,-0.2 -0.15,-0.26 -0.07,-0.13 -0.15,-0.28 -0.23,-0.44 -0.21,-0.43 -0.51,-1.09 -0.84,-1.89 -3.3,-7.04 -5.19,-11.6 -7.23,-16.38 -2.2,-5.15 -4.63,-10.64 -9.31,-19.99 -0.69,-1.37 -1.61,-1.98 -2.55,-2.22zM259.68,134.55c-0,-0 -0,-0.01 -0,-0.02 -0,-0 -0,-0.01 -0.01,-0.02 0,0.02 0.01,0.03 0.01,0.04z"+      android:strokeWidth="1.57657"+      android:fillColor="#000000"/>+  <path+      android:pathData="m149.04,136.54h-10.08c-1.17,-0 -2.25,-0.65 -2.79,-1.69 -0.54,-1.04 -0.47,-2.29 0.2,-3.26l16.38,-23.65 0.24,-0.3c0.59,-0.67 1.45,-1.05 2.35,-1.05 1.03,0 2,0.51 2.59,1.36l16.38,23.65c0.67,0.96 0.75,2.22 0.2,3.26 -0.54,1.04 -1.62,1.69 -2.79,1.69h-10.08v69.19h-12.61z"+      android:strokeWidth="1.57657">+    <aapt:attr name="android:fillColor">+      <gradient+          android:startX="155.34"+          android:startY="157.81"+          android:endX="155.34"+          android:endY="205.73"+          android:type="linear">+        <item android:offset="0" android:color="#FF000000"/>+        <item android:offset="1" android:color="#00000000"/>+      </gradient>+    </aapt:attr>+  </path>+</vector>

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

The recorded observation did not become a verified finding.

Evidence and perspectives

  • Observation · Complexity maintainabilityAdded drawable SVG with complex compound paths requiring mental model of coordinate transformation and stroke calculation, which increases cognitive load to reason about visual rendering.

    Recorded file app/src/main/res/drawable/illustration_swipeup.xml · no line recorded

Supporting evidence

Reviewed 29 Nov 2026Revision c7d8ab77bd4f7 changed files+87 −0Judge score 5/5
Approved · 0 retained findingsthreeport/threeport#781Review permalink

feat: choose a cluster's Kubernetes version and create it on a supported one

Input

PR author’s description

Part of #732. This is the first of the three parts the issue suggests: the version field, the defaults and the cluster autoscaler's version. GKE's release channel and maintenance window come next, then the update path.…

PR diff

Current GitHub diff ↗
pkg/api/v0/kubernetes_version.go · patch excerpt
+package v0++import (+	"fmt"
Browse 30 changed files
pkg/api/v0/kubernetes_version.go+81 −0
@@ -0,0 +1,81 @@+package v0++import (+	"fmt"+	"slices"+	"strings"++	"gorm.io/gorm"++	lib "github.com/threeport/threeport/pkg/api/lib/v0"+	util "github.com/threeport/threeport/pkg/util/v0"+)++// SupportedKubernetesVersions are the Kubernetes minor versions Threeport+// creates EKS, GKE and OKE clusters on, oldest first.  Each is offered for new+// clusters by all three: in standard support on EKS, in the REGULAR and STABLE+// release channels on GKE, and as a production release on OKE.+var SupportedKubernetesVersions = []string{"1.35", "1.36"}++// DefaultKubernetesVersion is the Kubernetes minor version of a cluster whose+// definition sets none.+const DefaultKubernetesVersion = "1.36"++// ErrMsgKubernetesVersionImmutable is the error a change to a definition's+// KubernetesVersion returns.  Threeport can't upgrade a cluster yet, so a+// changed version would record one its clusters don't run.+const ErrMsgKubernetesVersionImmutable = "KubernetesVersion cannot be changed after creation: upgrading a cluster is not supported yet"++// KubernetesVersionOrDefault returns version, or DefaultKubernetesVersion when+// it is unset.+func KubernetesVersionOrDefault(version *string) string {+	if version == nil || *version == "" {+		return DefaultKubernetesVersion+	}++	return *version+}++// ValidateKubernetesVersion checks a definition's KubernetesVersion: unset, or+// one of SupportedKubernetesVersions on a provider whose version Threeport+// sets.  A kind cluster's version comes with its node image, so it takes none.+func ValidateKubernetesVersion(infraProvider string, version *string) error {+	if version == nil {+		return nil+	}+	if infraProvider == KubernetesRuntimeInfraProviderKind {+		return fmt.Errorf("KubernetesVersion cannot be set on a kind cluster, whose version comes with its node image")+	}+	if !slices.Contains(SupportedKubernetesVersions, *version) {+		return fmt.Errorf(+			"KubernetesVersion %q is not supported: use one of %s, written as a minor version such as %q",+			*version, strings.Join(SupportedKubernetesVersions, ", "), DefaultKubernetesVersion,+		)+	}++	return nil+}++// validateKubernetesVersionCreate checks the KubernetesVersion of a definition+// being created.+func validateKubernetesVersionCreate(infraProvider string, version *string) error {+	if err := ValidateKubernetesVersion(infraProvider, version); err != nil {+		return util.NewBadRequestError(err.Error())+	}++	return nil+}++// validateKubernetesVersionUpdate refuses an update that changes a+// definition's KubernetesVersion.+func validateKubernetesVersionUpdate(tx *gorm.DB) error {+	changed, err := lib.IsFieldChanged(tx, "KubernetesVersion")+	if err != nil {+		return err+	}+	if changed {+		return util.NewBadRequestError(ErrMsgKubernetesVersionImmutable)+	}++	return nil+}
internal/provider/kubernetes_version_test.go+218 −0
@@ -0,0 +1,218 @@+package provider++import (+	"testing"+	"time"++	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"+	"github.com/stretchr/testify/assert"+	"github.com/stretchr/testify/require"++	v0 "github.com/threeport/threeport/pkg/api/v0"+	util "github.com/threeport/threeport/pkg/util/v0"+)++// eksEndOfStandardSupport is when each Kubernetes version Threeport creates+// EKS clusters on leaves EKS standard support, from+// `aws eks describe-cluster-versions --include-all`.  After it, a cluster+// runs in extended support, at a higher hourly charge, until AWS upgrades it.+var eksEndOfStandardSupport = map[string]time.Time{+	"1.35": time.Date(2027, time.March, 27, 0, 0, 0, 0, time.UTC),+	"1.36": time.Date(2027, time.August, 2, 0, 0, 0, 0, time.UTC),+}++// defaultVersionMinimumSupportLeft is how long the default version must have+// left in EKS standard support.+const defaultVersionMinimumSupportLeft = 6 * 30 * 24 * time.Hour++// TestNewEksClustersStartInStandardSupport fails when a version Threeport+// creates EKS clusters on has left standard support, or when the default has+// less than six months of it left.  Move SupportedKubernetesVersions and+// DefaultKubernetesVersion forward then, choosing from `aws eks+// describe-cluster-versions`, and check the version is offered in GKE's+// REGULAR and STABLE channels and as a production release on OKE.+func TestNewEksClustersStartInStandardSupport(t *testing.T) {+	now := time.Now()+	for _, version := range v0.SupportedKubernetesVersions {+		end, ok := eksEndOfStandardSupport[version]+		if !assert.True(t, ok, "no end of EKS standard support is recorded for %s", version) {+			continue+		}+		assert.True(t, now.Before(end), "Kubernetes %s left EKS standard support on %s", version, end.Format(time.DateOnly))+	}++	end := eksEndOfStandardSupport[v0.DefaultKubernetesVersion]+	assert.True(t, end.Sub(now) > defaultVersionMinimumSupportLeft,+		"the default Kubernetes version, %s, leaves EKS standard support on %s",+		v0.DefaultKubernetesVersion, end.Format(time.DateOnly),+	)+}++// TestTheEksClusterAndNodeGroupRunTheDefinitionsVersion covers the version+// the EKS program creates the cluster and its node group on.+func TestTheEksClusterAndNodeGroupRunTheDefinitionsVersion(t *testing.T) {+	infra := testEksInfra(2)+	infra.KubernetesVersion = "1.35"+	mocks := runEksPulumiProgram(t, infra)++	clusters := mocks.byType(eksClusterTypeToken)+	require.Len(t, clusters, 1)+	assert.Equal(t, "1.35", clusters[0].inputs["version"])+	nodeGroups := mocks.byType(eksNodeGroupTypeToken)+	require.Len(t, nodeGroups, 1)+	assert.Equal(t, "1.35", nodeGroups[0].inputs["version"])++	infra.KubernetesVersion = ""+	mocks = runEksPulumiProgram(t, infra)+	assert.Equal(t, v0.DefaultKubernetesVersion, mocks.byType(eksClusterTypeToken)[0].inputs["version"])+}++// TestTheGkeClusterStartsOnTheDefinitionsVersion covers the version the GKE+// program asks for: a minimum for the control plane, which GKE creates on its+// channel's release of that minor version and upgrades past on its own.+func TestTheGkeClusterStartsOnTheDefinitionsVersion(t *testing.T) {+	for asked, want := range map[string]string{"1.35": "1.35", "": v0.DefaultKubernetesVersion} {+		infra := &KubernetesRuntimeInfraGKE{+			PulumiWorkspace:        PulumiWorkspace{RuntimeInstanceName: "gke-version-test", ProjectName: "gke"},+			Version:                asked,+			ProjectID:              "test-project",+			Region:                 "us-central1",+			WorkerNodeInitialCount: 1,+		}+		mocks := &gkeRecordingMocks{}+		require.NoError(t, pulumi.RunErr(infra.pulumiProgram(), pulumi.WithMocks("gke", "test-stack", mocks)))++		var clusters []gkeRecordedResource+		for _, r := range mocks.resources {+			if r.typeToken == gkeClusterTypeToken {+				clusters = append(clusters, r)+			}+		}+		require.Len(t, clusters, 1)+		assert.Equal(t, want, clusters[0].inputs["minMasterVersion"], "asked for %q", asked)+	}+}++// TestAnOkeMinorVersionResolvesToItsNewestReleaseWithAnImage covers the OKE+// release a minor version resolves to: the newest OKE offers that has a+// worker node image for the node shape's architecture.+func TestAnOkeMinorVersionResolvesToItsNewestReleaseWithAnImage(t *testing.T) {+	offered := []string{"v1.34.10", "v1.35.2", "v1.36.1", "v1.36.4", "v1.36.10", "v1.37.0"}+	images := []string{+		"Oracle-Linux-8.10-2026.09.30-0-OKE-1.36.4-1001",+		"Oracle-Linux-8.10-aarch64-2026.09.30-0-OKE-1.36.4-1001",+		"Oracle-Linux-8.10-2026.09.30-0-OKE-1.36.10-1002",+		"Oracle-Linux-8.10-aarch64-2026.07.10-0-OKE-1.36.1-998",+		"Oracle-Linux-8.10-2026.05.01-0-OKE-1.35.2-990",+		"Oracle-Linux-8.10-Gen2-GPU-2026.10.20-0-OKE-1.37.0-1010",+	}++	version, err := newestOkePatch("1.36", offered, images, "x86_64")+	require.NoError(t, err)+	assert.Equal(t, "v1.36.10", version, "1.36.10 sorts after 1.36.4 by number, not by text")++	version, err = newestOkePatch("1.36", offered, images, "aarch64")+	require.NoError(t, err)+	assert.Equal(t, "v1.36.4", version, "the newest release has no Arm image yet")++	_, err = newestOkePatch("1.35", offered, images, "aarch64")+	assert.ErrorContains(t, err, "OKE has no aarch64 worker node image for any release of Kubernetes 1.35")++	_, err = newestOkePatch("1.32", offered, images, "x86_64")+	assert.ErrorContains(t, err, "OKE offers no release of Kubernetes 1.32 for new clusters")++	_, err = newestOkePatch("1.3", offered, images, "x86_64")+	assert.Error(t, err, "1.3 is not a prefix of 1.36")++	_, err = newestOkePatch("1.37", offered, images, "x86_64")+	assert.ErrorContains(t, err, "no x86_64 worker node image", "a GPU image needs a GPU shape")++	assert.Equal(t, "aarch64", okeImageArch("VM.Standard.A1.Flex"))+	assert.Equal(t, "x86_64", okeImageArch("VM.Standard.E4.Flex"))+	assert.Empty(t, okeImageFor(images, "v1.36.1", "x86_64"), "1.36.1 doesn't match an image of 1.36.10")+}++// TestAResumedCreateKeepsItsClustersVersion covers a create resumed on a+// stack that holds the cluster: it keeps the version the cluster was created+// on, which may predate the one its definition records, rather than asking+// for that one.+func TestAResumedCreateKeepsItsClustersVersion(t *testing.T) {+	deployment := []byte(`{"resources":[+		{"type":"oci:core/vcn:Vcn","inputs":{}},+		{"type":"oci:ContainerEngine/cluster:Cluster","inputs":{"kubernetesVersion":"v1.36.1"}},+		{"type":"aws:eks/cluster:Cluster","inputs":{"name":"eks","version":"1.32"}},+		{"type":"gcp:container/cluster:Cluster","inputs":{"name":"gke"}}+	]}`)++	version, held := clusterInputInStack(deployment, "oci:ContainerEngine/cluster:Cluster", "kubernetesVersion")+	assert.True(t, held)+	assert.Equal(t, "v1.36.1", version)+	version, held = clusterInputInStack(deployment, "aws:eks/cluster:Cluster", "version")+	assert.True(t, held)+	assert.Equal(t, "1.32", version)+	version, held = clusterInputInStack(deployment, "gcp:container/cluster:Cluster", "minMasterVersion")+	assert.True(t, held, "a GKE cluster created before the version was set")+	assert.Empty(t, version)++	for name, deployment := range map[string]string{+		"a new stack":          ``,+		"no cluster yet":       `{"resources":[{"type":"oci:core/vcn:Vcn","inputs":{}}]}`,+		"an unreadable record": `{"resources":`,+	} {+		_, held := clusterInputInStack([]byte(deployment), "oci:ContainerEngine/cluster:Cluster", "kubernetesVersion")+		assert.False(t, held, name)+	}++	// each provider keeps what its stack holds over the definition's version+	eks := &KubernetesRuntimeInfraEKS{KubernetesVersion: "1.36"}+	eks.keepStackVersion(deployment)+	assert.Equal(t, "1.32", eks.KubernetesVersion)+	eks = &KubernetesRuntimeInfraEKS{KubernetesVersion: "1.36"}+	eks.keepStackVersion([]byte(`{"resources":[]}`))+	assert.Equal(t, "1.36", eks.KubernetesVersion, "a new stack takes the definition's")++	oke := &KubernetesRuntimeInfraOKE{Version: "1.36"}+	assert.True(t, oke.keepStackVersion(deployment))+	assert.Equal(t, "v1.36.1", oke.Version)+	oke = &KubernetesRuntimeInfraOKE{Version: "1.36"}+	assert.False(t, oke.keepStackVersion([]byte(`{"resources":[]}`)), "a new stack resolves the definition's")+	assert.Equal(t, "1.36", oke.Version)++	gke := &KubernetesRuntimeInfraGKE{Version: "1.36"}+	gke.keepStackMinMasterVersion(deployment)+	require.NotNil(t, gke.stackMinMasterVersion)+	assert.Empty(t, *gke.stackMinMasterVersion)+	gke = &KubernetesRuntimeInfraGKE{Version: "1.36"}+	gke.keepStackMinMasterVersion([]byte(`{"resources":[]}`))+	assert.Nil(t, gke.stackMinMasterVersion)+}++// TestAResumedGkeCreateKeepsTheClustersMinimumVersion covers the minimum+// version the GKE program asks for on a stack that already holds the+// cluster: the one it was created with, and none for a cluster created+// before the version was set, rather than the definition's.+func TestAResumedGkeCreateKeepsTheClustersMinimumVersion(t *testing.T) {+	minMasterVersion := func(stack *string) any {+		infra := &KubernetesRuntimeInfraGKE{+			PulumiWorkspace:        PulumiWorkspace{RuntimeInstanceName: "gke-resume-test", ProjectName: "gke"},+			Version:                "1.36",+			ProjectID:              "test-project",+			Region:                 "us-central1",+			WorkerNodeInitialCount: 1,+			stackMinMasterVersion:  stack,+		}+		mocks := &gkeRecordingMocks{}+		require.NoError(t, pulumi.RunErr(infra.pulumiProgram(), pulumi.WithMocks("gke", "test-stack", mocks)))+		for _, r := range mocks.resources {+			if r.typeToken == gkeClusterTypeToken {+				return r.inputs["minMasterVersion"]+			}+		}+		t.Fatal("the program registered no cluster")+		return nil+	}++	assert.Equal(t, "1.36", minMasterVersion(nil), "a new stack")+	assert.Equal(t, "1.35", minMasterVersion(util.Ptr("1.35")))+	assert.Nil(t, minMasterVersion(util.Ptr("")))+}
pkg/config/v0/kubernetes_version_test.go+214 −0
@@ -0,0 +1,214 @@+package v0++import (+	"encoding/json"+	"net/http"+	"testing"+	"time"++	"github.com/stretchr/testify/assert"+	"github.com/stretchr/testify/require"++	"github.com/threeport/threeport/internal/machinetest"+	apiserver_lib "github.com/threeport/threeport/pkg/api-server/lib/v0"+	api_v0 "github.com/threeport/threeport/pkg/api/v0"+	util "github.com/threeport/threeport/pkg/util/v0"+)++// TestAConfigWithAnUnsupportedKubernetesVersionIsRefusedBeforeItIsSent+// covers the config files that set a version.+func TestAConfigWithAnUnsupportedKubernetesVersionIsRefusedBeforeItIsSent(t *testing.T) {+	definition := KubernetesRuntimeDefinitionConfig{KubernetesRuntimeDefinition: KubernetesRuntimeDefinitionValues{+		Name:              util.Ptr("remote"),+		InfraProvider:     util.Ptr(api_v0.KubernetesRuntimeInfraProviderEKS),+		KubernetesVersion: util.Ptr("1.32"),+	}}+	assert.ErrorContains(t, definition.Validate(), `KubernetesVersion "1.32" is not supported`)+	definition.KubernetesRuntimeDefinition.KubernetesVersion = util.Ptr("1.35")+	assert.NoError(t, definition.Validate())++	oke := okeDefinitionConfig(nil, nil)+	oke.OciOkeKubernetesRuntimeDefinition.KubernetesVersion = util.Ptr("v1.36.4")+	assert.ErrorContains(t, oke.Validate(), `KubernetesVersion "v1.36.4" is not supported`)+}++// TestAKubernetesRuntimeConfigSendsItsKubernetesVersion covers a+// KubernetesRuntime config file setting the version: the definition it+// creates carries it.+func TestAKubernetesRuntimeConfigSendsItsKubernetesVersion(t *testing.T) {+	api := machinetest.NewAPIStub(t)+	var sent api_v0.KubernetesRuntimeDefinition+	api.Mux.HandleFunc(api_v0.PathKubernetesRuntimeDefinitions, func(w http.ResponseWriter, r *http.Request) {+		assert.NoError(t, json.NewDecoder(r.Body).Decode(&sent))+		created := sent+		created.ID = util.Ptr(uint(3))+		created.CreatedAt = util.Ptr(time.Now())+		machinetest.WriteResponse(t, w, http.StatusCreated, []apiserver_lib.Object{created})+	})++	config := KubernetesRuntimeConfig{KubernetesRuntime: KubernetesRuntimeValues{+		Name:              util.Ptr("remote"),+		InfraProvider:     util.Ptr(api_v0.KubernetesRuntimeInfraProviderGKE),+		KubernetesVersion: util.Ptr("1.35"),+	}}+	operations, definitions, _ := config.GetOperations(api.Client, api.Addr)+	require.NoError(t, operations.Operations[0].Create())++	assert.Equal(t, util.Ptr("1.35"), sent.KubernetesVersion)+	assert.Equal(t, util.Ptr("1.35"), (*definitions)[0].KubernetesRuntimeDefinition.KubernetesVersion)+}++// TestReplacingADefinitionKeepsItsKubernetesVersion covers a replace from a+// config that leaves the version out: it sends the stored version, which the+// API refuses to change, rather than clearing it.+func TestReplacingADefinitionKeepsItsKubernetesVersion(t *testing.T) {+	name := "remote"+	stored := api_v0.KubernetesRuntimeDefinition{+		Common:            api_v0.Common{ID: util.Ptr(uint(1))},+		Definition:        api_v0.Definition{Name: &name},+		InfraProvider:     util.Ptr(api_v0.KubernetesRuntimeInfraProviderEKS),+		KubernetesVersion: util.Ptr("1.35"),+	}+	replace := func(version *string) api_v0.KubernetesRuntimeDefinition {+		api := &fakeApi{t: t, objects: map[string]interface{}{api_v0.PathKubernetesRuntimeDefinitions: stored}}+		config := &KubernetesRuntimeDefinitionConfig{KubernetesRuntimeDefinition: KubernetesRuntimeDefinitionValues{+			Name:              &name,+			InfraProvider:     util.Ptr(api_v0.KubernetesRuntimeInfraProviderEKS),+			KubernetesVersion: version,+		}}+		_, err := config.Replace(&http.Client{}, api.serve(), name)+		require.NoError(t, err)+		var sent api_v0.KubernetesRuntimeDefinition+		api.decodeSent(&sent)+		return sent+	}++	assert.Equal(t, util.Ptr("1.35"), replace(nil).KubernetesVersion)+	assert.Equal(t, util.Ptr("1.36"), replace(util.Ptr("1.36")).KubernetesVersion,+		"a version the config gives is sent, for the API to refuse")+}++// TestAnOkeDefinitionRecordsTheVersionItsClustersRun covers the OKE config,+// which creates both definitions itself: the kubernetes runtime definition+// gets the version asked for, and the OKE definition the version its+// clusters are created on, the default when none is asked for.+func TestAnOkeDefinitionRecordsTheVersionItsClustersRun(t *testing.T) {+	t.Run("asked for", func(t *testing.T) {+		api, rec := newOkeAPI(t)+		config := okeDefinitionConfig(nil, nil)+		config.OciOkeKubernetesRuntimeDefinition.KubernetesVersion = util.Ptr("1.35")+		created, err := config.Create(api.Client, api.Addr)+		require.NoError(t, err)++		assert.Equal(t, util.Ptr("1.35"), rec.krdCreated.KubernetesVersion)+		assert.Equal(t, util.Ptr("1.35"), rec.okeCreated.KubernetesVersion)+		assert.Equal(t, util.Ptr("1.35"), created.OciOkeKubernetesRuntimeDefinition.KubernetesVersion)+	})+	t.Run("left out", func(t *testing.T) {+		api, rec := newOkeAPI(t)+		_, err := okeDefinitionConfig(nil, nil).Create(api.Client, api.Addr)+		require.NoError(t, err)++		assert.Nil(t, rec.krdCreated.KubernetesVersion)+		assert.Equal(t, util.Ptr(api_v0.DefaultKubernetesVersion), rec.okeCreated.KubernetesVersion)+	})+	t.Run("replaced without it", func(t *testing.T) {+		api, rec := newOkeAPI(t)+		_, err := okeDefinitionConfig(nil, nil).Replace(api.Client, api.Addr, "oke-remote")+		require.NoError(t, err)++		require.NotNil(t, rec.okeReplaced)+		assert.Nil(t, rec.okeReplaced.KubernetesVersion, "the stored OKE definition sets none, and the replace keeps that")+		assert.NotContains(t, rec.krdPatched, "KubernetesVersion")+	})+}++// TestEksAndGkeDefinitionsRecordTheVersionTheirClustersRun covers the EKS+// and GKE config files, which create both definitions themselves: a version+// the config gives is checked before it is sent, the kubernetes runtime+// definition gets it, and the provider definition the version its clusters+// are created on, the default when none is given.  A replace that leaves it+// out keeps the stored one.+func TestEksAndGkeDefinitionsRecordTheVersionTheirClustersRun(t *testing.T) {+	type sentDefinitions struct{ runtime, provider, replaced map[string]any }+	serve := func(t *testing.T, providerPath string, stored map[string]any) (*machinetest.APIStub, *sentDefinitions) {+		api := machinetest.NewAPIStub(t)+		sent := &sentDefinitions{}+		decode := func(r *http.Request) map[string]any {+			var body map[string]any+			require.NoError(t, json.NewDecoder(r.Body).Decode(&body))+			body["ID"] = 1+			return body+		}+		api.Mux.HandleFunc(api_v0.PathKubernetesRuntimeDefinitions, func(w http.ResponseWriter, r *http.Request) {+			sent.runtime = decode(r)+			machinetest.WriteResponse(t, w, http.StatusCreated, []apiserver_lib.Object{sent.runtime})+		})+		api.Mux.HandleFunc(providerPath, func(w http.ResponseWriter, r *http.Request) {+			if r.Method == http.MethodGet {+				machinetest.WriteResponse(t, w, http.StatusOK, []apiserver_lib.Object{stored})+				return+			}+			sent.provider = decode(r)+			machinetest.WriteResponse(t, w, http.StatusCreated, []apiserver_lib.Object{sent.provider})+		})+		api.Mux.HandleFunc(providerPath+"/", func(w http.ResponseWriter, r *http.Request) {+			sent.replaced = decode(r)+			machinetest.WriteResponse(t, w, http.StatusOK, []apiserver_lib.Object{sent.replaced})+		})+		return api, sent+	}+	stored := map[string]any{"ID": 1, "Name": "remote", "KubernetesVersion": "1.35"}++	t.Run("EKS", func(t *testing.T) {+		config := func(version *string) *AwsEksKubernetesRuntimeDefinitionConfig {+			return &AwsEksKubernetesRuntimeDefinitionConfig{AwsEksKubernetesRuntimeDefinition: AwsEksKubernetesRuntimeDefinitionValues{+				Name: util.Ptr("remote"), ZoneCount: util.Ptr(2), DefaultNodeGroupInstanceType: util.Ptr("t3.medium"),+				DefaultNodeGroupInitialSize: util.Ptr(1), DefaultNodeGroupMinimumSize: util.Ptr(1), DefaultNodeGroupMaximumSize: util.Ptr(3),+				KubernetesVersion: version,+			}}+		}+		assert.ErrorContains(t, config(util.Ptr("1.32")).Validate(), `KubernetesVersion "1.32" is not supported`)++		api, sent := serve(t, api_v0.PathAwsEksKubernetesRuntimeDefinitions, stored)+		created, err := config(util.Ptr("1.35")).Create(api.Client, api.Addr)+		require.NoError(t, err)+		assert.Equal(t, "1.35", sent.runtime["KubernetesVersion"])+		assert.Equal(t, "1.35", sent.provider["KubernetesVersion"])+		assert.Equal(t, util.Ptr("1.35"), created.AwsEksKubernetesRuntimeDefinition.KubernetesVersion)++		_, err = config(nil).Create(api.Client, api.Addr)+		require.NoError(t, err)+		assert.NotContains(t, sent.runtime, "KubernetesVersion")+		assert.Equal(t, api_v0.DefaultKubernetesVersion, sent.provider["KubernetesVersion"])++		_, err = config(nil).Replace(api.Client, api.Addr, "remote")+		require.NoError(t, err)+		assert.Equal(t, "1.35", sent.replaced["KubernetesVersion"], "a replace without it keeps the stored one")+	})+	t.Run("GKE", func(t *testing.T) {+		config := func(version *string) *GcpGkeKubernetesRuntimeDefinitionConfig {+			return &GcpGkeKubernetesRuntimeDefinitionConfig{GcpGkeKubernetesRuntimeDefinition: GcpGkeKubernetesRuntimeDefinitionValues{+				Name: util.Ptr("remote"), ZoneCount: util.Ptr(3), DefaultNodeGroupInstanceType: util.Ptr("e2-medium"),+				DefaultNodeGroupInitialSize: util.Ptr(1), DefaultNodeGroupMinimumSize: util.Ptr(1), DefaultNodeGroupMaximumSize: util.Ptr(3),+				KubernetesVersion: version,+			}}+		}+		assert.ErrorContains(t, config(util.Ptr("v1.36.4")).Validate(), `KubernetesVersion "v1.36.4" is not supported`)++		api, sent := serve(t, api_v0.PathGcpGkeKubernetesRuntimeDefinitions, stored)+		created, err := config(util.Ptr("1.36")).Create(api.Client, api.Addr)+		require.NoError(t, err)+		assert.Equal(t, "1.36", sent.runtime["KubernetesVersion"])+		assert.Equal(t, "1.36", sent.provider["KubernetesVersion"])+		assert.Equal(t, util.Ptr("1.36"), created.GcpGkeKubernetesRuntimeDefinition.KubernetesVersion)++		_, err = config(nil).Create(api.Client, api.Addr)+		require.NoError(t, err)+		assert.Equal(t, api_v0.DefaultKubernetesVersion, sent.provider["KubernetesVersion"])++		_, err = config(nil).Replace(api.Client, api.Addr, "remote")+		require.NoError(t, err)+		assert.Equal(t, "1.35", sent.replaced["KubernetesVersion"], "a replace without it keeps the stored one")+	})+}

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens advisories (not part of the checked findings):

  • dependency_blast_radius: The change adds a KubernetesVersion field that flows from API definitions, validation logic, CLI control-plane creation, and lifecycle code that creates clusters, causing new-proxy-resource and +1EKS deployment failures until runtime definitions are migrated.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Dependency blast radiusThe change adds a KubernetesVersion field that flows from API definitions, validation logic, CLI control-plane creation, and lifecycle code that creates clusters, causing new-proxy-resource and +1EKS deployment failures until runtime definitions are migrated.

    Recorded location pkg/cli/v0/genesis_control_plane.go:241

  • Observation · Historical riskThe EKS autoscaler installer code adds logic to select the cluster autoscaler image based on the Kubernetes minor version and provides an error when the version is not supported, which indicates this area historically has required version-specific image selection logic.

    Recorded file pkg/threeport-installer/v0/eks_autoscaler.go · no line recorded

Supporting evidence

Reviewed 29 Nov 2026Revision d05673c4e74130 changed files+1737 −48Judge score 5/5
Approved · 0 retained findingsvitejs/vite#23292Review permalink

feat(environment): expose build manifest on build environment

Input

PR author’s description

Fixes: https://github.com/vitejs/vite/issues/20052

Description

Framework integrations often need access to an environment’s build manifest during app build orchestration. Currently, this requires enabling…

PR diff

Current GitHub diff ↗
packages/vite/src/node/__tests__/build.spec.ts · patch excerpt
+test('environment.manifest is populated when build.manifest is disabled without emitting a file', async () => {+  const root = resolve(dirname, 'fixtures/watch-rebuild-manifest')+  const builder = await createBuilder({+    root,
Browse 4 changed files
packages/vite/src/node/__tests__/build.spec.ts+99 −0
@@ -2204,6 +2204,105 @@ test('watch rebuild manifest', async (ctx) => {   `) }) +test('environment.manifest is populated when build.manifest is disabled without emitting a file', async () => {+  const root = resolve(dirname, 'fixtures/watch-rebuild-manifest')+  const builder = await createBuilder({+    root,+    logLevel: 'error',+    environments: {+      client: {+        build: {+          rolldownOptions: {+            input: '/entry.js',+          },+        },+      },+    },+    build: {+      write: false,+      manifest: false,+    },+  })++  const environment = builder.environments.client+  const result = (await builder.build(environment)) as RolldownOutput++  // the manifest file should not be emitted+  expect(+    result.output.find((o) => o.fileName === '.vite/manifest.json'),+  ).toBeUndefined()++  // but the manifest should be available on the environment+  expect(environment.manifest).toBeDefined()+  expect(Object.keys(environment.manifest!)).toMatchInlineSnapshot(`+    [+      "dep.js",+      "entry.js",+    ]+  `)+})++test('environment.manifest matches the emitted manifest file when build.manifest is enabled', async () => {+  const root = resolve(dirname, 'fixtures/watch-rebuild-manifest')+  const builder = await createBuilder({+    root,+    logLevel: 'error',+    environments: {+      client: {+        build: {+          rolldownOptions: {+            input: '/entry.js',+          },+        },+      },+    },+    build: {+      write: false,+      manifest: true,+    },+  })++  const environment = builder.environments.client+  const result = (await builder.build(environment)) as RolldownOutput++  const manifestFile = result.output.find(+    (o) => o.fileName === '.vite/manifest.json',+  )+  expect(manifestFile).toBeDefined()+  assert(manifestFile?.type === 'asset')+  expect(environment.manifest).toStrictEqual(+    JSON.parse(manifestFile.source.toString()),+  )+})++test('environment.manifest is populated for the ssr environment', async () => {+  const root = resolve(dirname, 'fixtures/watch-rebuild-manifest')+  const builder = await createBuilder({+    root,+    logLevel: 'error',+    environments: {+      ssr: {+        build: {+          ssr: true,+          rolldownOptions: {+            input: '/entry.js',+          },+        },+      },+    },+    build: {+      write: false,+      manifest: false,+    },+  })++  const environment = builder.environments.ssr+  await builder.build(environment)++  expect(environment.manifest).toBeDefined()+  expect(Object.keys(environment.manifest!)).toContain('entry.js')+})+ test('copies public directory after building same environment with write false first', async (ctx) => {   const root = resolve(dirname, 'fixtures/public-dir-write-false')   ctx.onTestFinished(() =>
packages/vite/src/node/plugins/manifest.ts+23 −8
@@ -2,6 +2,7 @@ import path from 'node:path' import type { OutputChunk, RenderedChunk } from 'rolldown' import { viteManifestPlugin as nativeManifestPlugin } from 'rolldown/experimental' import { type Environment, perEnvironmentPlugin } from '..'+import type { BuildEnvironment } from '../build' import { perEnvironmentState } from '../environment' import type { Plugin } from '../plugin' import { normalizePath } from '../utils'@@ -79,13 +80,11 @@ export function manifestPlugin(): Plugin {   })    return perEnvironmentPlugin('native:manifest', (environment) => {-    if (!environment.config.build.manifest) return false-     const root = environment.config.root     const outPath =-      environment.config.build.manifest === true-        ? '.vite/manifest.json'-        : environment.config.build.manifest+      typeof environment.config.build.manifest === 'string'+        ? environment.config.build.manifest+        : '.vite/manifest.json'      const envs: Record<string, Environment> = {}     function getChunkName(chunk: OutputChunk) {@@ -158,15 +157,31 @@ export function manifestPlugin(): Plugin {                 }               }             }+             const workerManifest = getWorkerManifest(this.environment)             if (workerManifest) {               manifest ??= JSON.parse(asset.source.toString()) as Manifest               Object.assign(manifest, workerManifest)             }++            const environment = this.environment as BuildEnvironment+            // The manifest is always computed and stored on+            // `environment.manifest`. The `build.manifest` option only controls+            // whether the manifest file is written to disk.+            const emitManifestFile = !!environment.config.build.manifest+            const finalize = (finalManifest: Manifest) => {+              environment.manifest = finalManifest+              if (emitManifestFile) {+                asset.source = JSON.stringify(finalManifest, undefined, 2)+              } else {+                delete bundle[outPath]+              }+            }+             const output = this.environment.config.build.rolldownOptions.output             const outputLength = Array.isArray(output) ? output.length : 1-            if (manifest && outputLength === 1) {-              asset.source = JSON.stringify(manifest, undefined, 2)+            if (outputLength === 1) {+              finalize(manifest ?? JSON.parse(asset.source.toString()))               return             } @@ -177,7 +192,7 @@ export function manifestPlugin(): Plugin {               manifest ?? JSON.parse(asset.source.toString()),             )             if (state.outputCount >= outputLength) {-              asset.source = JSON.stringify(state.manifest, undefined, 2)+              finalize(state.manifest)               state.reset()             } else {               delete bundle[outPath]
docs/guide/api-environment-frameworks.md+25 −0
@@ -340,6 +340,31 @@ export default defineConfig({  Besides the `builder.buildApp` config option, plugins can define a `buildApp` hook to participate in the app build. The config option and the plugin hooks run in a defined order: hooks with order `'pre'` or `null` run first, then the configured `builder.buildApp`, then hooks with order `'post'`. Within a hook, `environment.isBuilt` tells you whether an environment has already been built, which lets a plugin avoid building it twice. +### Accessing the build manifest with `environment.manifest`++Once an environment has been built, its [build manifest](/config/build-options#build-manifest) is available on `environment.manifest`. This lets a plugin read the manifest of an already built environment directly in the `buildApp` hook, without having to write to and read from the file system. It is a common pattern, for example, to use the manifest to move assets emitted in a server environment to the client bundle.++The manifest is populated regardless of the [`build.manifest`](/config/build-options#build-manifest) option, which only controls whether the manifest file is written to disk. Each environment has its own manifest.++```js [vite.config.js]+import { defineConfig } from 'vite'++export default defineConfig({+  plugins: [+    {+      name: 'read-manifest',+      async buildApp(builder) {+        const client = builder.environments.client+        if (!client.isBuilt) {+          await builder.build(client)+        }+        console.log('client manifest', client.manifest)+      },+    },+  ],+})+```+ ### Building programmatically with `createBuilder`  To trigger an app build from your own code, use `createBuilder` instead of the standalone `build` function. `createBuilder` is the build-time equivalent of `createServer`: it resolves the config and returns a `ViteBuilder`, whose `buildApp` method builds every configured environment. You can also build a single environment with `builder.build(environment)`.

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

Supporting evidence

Reviewed 29 Nov 2026Revision 9d2f6ed57cd24 changed files+160 −9Judge score 5/5
Approved · 0 retained findingswithastro/astro#18714Review permalink

[ci] release

Input

PR author’s description

This PR was opened by the Changesets release GitHub action. When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're…

PR diff

Current GitHub diff ↗
pnpm-lock.yaml · patch excerpt
-        specifier: ^11.1.12+        specifier: ^11.1.13
Browse 30 changed files
pnpm-lock.yaml+48 −48
@@ -196,10 +196,10 @@ importers:   examples/advanced-routing:     dependencies:       '@astrojs/node':-        specifier: ^11.1.12+        specifier: ^11.1.13         version: link:../../packages/integrations/node       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       hono:         specifier: ^4.13.16@@ -208,22 +208,22 @@ importers:   examples/basics:     dependencies:       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro    examples/blog:     dependencies:       '@astrojs/mdx':-        specifier: ^8.1.5+        specifier: ^8.1.6         version: link:../../packages/integrations/mdx       '@astrojs/rss':         specifier: ^4.0.19         version: link:../../packages/astro-rss       '@astrojs/sitemap':-        specifier: ^3.7.4+        specifier: ^3.7.5         version: link:../../packages/integrations/sitemap       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       sharp:         specifier: ^0.35.0@@ -232,16 +232,16 @@ importers:   examples/component:     devDependencies:       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro    examples/container-with-vitest:     dependencies:       '@astrojs/react':-        specifier: ^7.1.8+        specifier: ^7.1.9         version: link:../../packages/integrations/react       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       react:         specifier: ^19.3.1@@ -272,25 +272,25 @@ importers:         specifier: ^3.17.5         version: 3.17.5       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro    examples/framework-multiple:     dependencies:       '@astrojs/preact':-        specifier: ^6.1.5+        specifier: ^6.1.6         version: link:../../packages/integrations/preact       '@astrojs/react':-        specifier: ^7.1.8+        specifier: ^7.1.9         version: link:../../packages/integrations/react       '@astrojs/solid-js':-        specifier: ^7.1.5+        specifier: ^7.1.6         version: link:../../packages/integrations/solid       '@astrojs/svelte':-        specifier: ^9.1.5+        specifier: ^9.1.6         version: link:../../packages/integrations/svelte       '@astrojs/vue':-        specifier: ^7.1.5+        specifier: ^7.1.6         version: link:../../packages/integrations/vue       '@types/react':         specifier: ^19.3.0@@ -299,7 +299,7 @@ importers:         specifier: ^19.3.0         version: 19.3.0(@types/react@19.3.0)       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       preact:         specifier: ^11.1.1@@ -323,13 +323,13 @@ importers:   examples/framework-preact:     dependencies:       '@astrojs/preact':-        specifier: ^6.1.5+        specifier: ^6.1.6         version: link:../../packages/integrations/preact       '@preact/signals':         specifier: ^2.11.4         version: 2.11.4(preact@11.1.1)       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       preact:         specifier: ^11.1.1@@ -338,7 +338,7 @@ importers:   examples/framework-react:     dependencies:       '@astrojs/react':-        specifier: ^7.1.8+        specifier: ^7.1.9         version: link:../../packages/integrations/react       '@types/react':         specifier: ^19.3.0@@ -347,7 +347,7 @@ importers:         specifier: ^19.3.0         version: 19.3.0(@types/react@19.3.0)       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       react:         specifier: ^19.3.1@@ -359,10 +359,10 @@ importers:   examples/framework-solid:     dependencies:       '@astrojs/solid-js':-        specifier: ^7.1.5+        specifier: ^7.1.6         version: link:../../packages/integrations/solid       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       solid-js:         specifier: ^1.9.18@@ -371,10 +371,10 @@ importers:   examples/framework-svelte:     dependencies:       '@astrojs/svelte':-        specifier: ^9.1.5+        specifier: ^9.1.6         version: link:../../packages/integrations/svelte       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       svelte:         specifier: ^5.57.3@@ -383,10 +383,10 @@ importers:   examples/framework-vue:     dependencies:       '@astrojs/vue':-        specifier: ^7.1.5+        specifier: ^7.1.6         version: link:../../packages/integrations/vue       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       vue:         specifier: ^3.5.45@@ -395,40 +395,40 @@ importers:   examples/hackernews:     dependencies:       '@astrojs/node':-        specifier: ^11.1.12+        specifier: ^11.1.13         version: link:../../packages/integrations/node       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro    examples/integration:     devDependencies:       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro    examples/minimal:     dependencies:       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro    examples/portfolio:     dependencies:       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro    examples/ssr:     dependencies:       '@astrojs/node':-        specifier: ^11.1.12+        specifier: ^11.1.13         version: link:../../packages/integrations/node       '@astrojs/svelte':-        specifier: ^9.1.5+        specifier: ^9.1.6         version: link:../../packages/integrations/svelte       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       svelte:         specifier: ^5.57.3@@ -437,7 +437,7 @@ importers:   examples/starlog:     dependencies:       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       sass:         specifier: ^1.108.0@@ -452,19 +452,19 @@ importers:         specifier: ^22.19.0         version: 22.19.19       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro    examples/vite-plugin-astro-hono:     dependencies:       '@astrojs/react-renderer':-        specifier: ^0.1.2+        specifier: ^0.1.3         version: link:../../packages/renderers/react       '@astrojs/runtime':         specifier: ^0.1.1         version: link:../../packages/runtime       '@astrojs/vite-plugin-astro':-        specifier: ^0.1.2+        specifier: ^0.1.3         version: link:../../packages/vite-plugin-astro       '@hono/node-server':         specifier: ^2.0.4@@ -488,22 +488,22 @@ importers:   examples/with-markdoc:     dependencies:       '@astrojs/markdoc':-        specifier: ^2.1.4+        specifier: ^2.1.5         version: link:../../packages/integrations/markdoc       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro    examples/with-mdx:     dependencies:       '@astrojs/mdx':-        specifier: ^8.1.5+        specifier: ^8.1.6         version: link:../../packages/integrations/mdx       '@astrojs/preact':-        specifier: ^6.1.5+        specifier: ^6.1.6         version: link:../../packages/integrations/preact       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       preact:         specifier: ^11.1.1@@ -512,13 +512,13 @@ importers:   examples/with-nanostores:     dependencies:       '@astrojs/preact':-        specifier: ^6.1.5+        specifier: ^6.1.6         version: link:../../packages/integrations/preact       '@nanostores/preact':         specifier: ^1.1.1         version: 1.1.1(nanostores@1.5.5)(preact@11.1.1)       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       nanostores:         specifier: ^1.5.5@@ -530,7 +530,7 @@ importers:   examples/with-tailwindcss:     dependencies:       '@astrojs/mdx':-        specifier: ^8.1.5+        specifier: ^8.1.6         version: link:../../packages/integrations/mdx       '@tailwindcss/vite':         specifier: ^4.3.4@@ -539,7 +539,7 @@ importers:         specifier: ^1.9.0         version: 1.9.0       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       canvas-confetti:         specifier: ^1.9.4@@ -554,7 +554,7 @@ importers:   examples/with-vitest:     dependencies:       astro:-        specifier: ^7.4.11+        specifier: ^7.4.12         version: link:../../packages/astro       vitest:         specifier: ^5.1.0
.changeset/tough-garlics-do.md+0 −24
@@ -1,24 +0,0 @@-----"@astrojs/cloudflare": patch-"@astrojs/markdoc": patch-"@astrojs/markdown-remark": patch-"@astrojs/markdown-satteri": patch-"@astrojs/mdx": patch-"@astrojs/netlify": patch-"@astrojs/node": patch-"@astrojs/preact": patch-"@astrojs/preact-renderer": patch-"@astrojs/react": patch-"@astrojs/react-renderer": patch-"@astrojs/solid-js": patch-"@astrojs/solid-js-renderer": patch-"@astrojs/svelte": patch-"@astrojs/svelte-renderer": patch-"@astrojs/vercel": patch-"@astrojs/vite-plugin-astro": patch-"@astrojs/vue": patch-"@astrojs/vue-renderer": patch-"astro": patch------Unpins `@astrojs/*` dependencies to allow versions matching the `^` range to be installed
packages/astro/CHANGELOG.md+13 −0
@@ -1,5 +1,18 @@ # astro +## 7.4.12++### Patch Changes++- [#18409](https://github.com/withastro/astro/pull/18409) [`2917650`](https://github.com/withastro/astro/commit/29176503c5bddedb4671eafc468c73a44e076b00) Thanks [@matthewp](https://github.com/matthewp)! - Fixes a typo in the error message shown when a font `cssVariable` is invalid++- [#18709](https://github.com/withastro/astro/pull/18709) [`6f1a2a8`](https://github.com/withastro/astro/commit/6f1a2a82735a1d75799d241276050e71493d656a) Thanks [@ematipico](https://github.com/ematipico)! - Reduces memory usage during `astro build` by releasing content collection entries from memory once the content layer sync is complete.++- [#18713](https://github.com/withastro/astro/pull/18713) [`59052e7`](https://github.com/withastro/astro/commit/59052e72668578a341a2c412769ead56d570fbe5) Thanks [@delucis](https://github.com/delucis)! - Unpins `@astrojs/*` dependencies to allow versions matching the `^` range to be installed+- Updated dependencies [[`59052e7`](https://github.com/withastro/astro/commit/59052e72668578a341a2c412769ead56d570fbe5)]:+  - @astrojs/markdown-satteri@0.4.10+  - @astrojs/vite-plugin-astro@0.1.3+ ## 7.4.11  ### Patch Changes

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

Supporting evidence

Reviewed 29 Nov 2026Revision 5883725906a430 changed files+216 −97Judge score 2/5
Approved · 0 retained findingsdrizzle-team/drizzle-orm#6681Review permalink

Add an Effect connector for Drizzle Postgres

Input

PR author’s description

This PR adds drizzle-orm/effect-drizzle-postgres. It runs the ORM on Effect with DrizzlePostgresClient from drizzle-orm/postgres/client/effect. The connector uses the codecs and the shape generator of the async…

PR diff

Current GitHub diff ↗
postgres/src/effect/DrizzleAuroraClient.ts · patch excerpt
+// Effect's SqlClient over the Aurora Data API (@drizzle-team/postgres/aurora). The Data API holds no connections:+// each statement is one HTTPS request, and a transaction is a transactionId that its statements carry. So a+// "connection" here is a client, and withTransaction's BEGIN, COMMIT and ROLLBACK become the Data API's+// BeginTransaction, CommitTransaction and RollbackTransaction calls; savepoints run as SQL inside the transaction.
Browse 30 changed files
postgres/src/effect/DrizzleAuroraClient.ts+330 −0
@@ -0,0 +1,330 @@+// Effect's SqlClient over the Aurora Data API (@drizzle-team/postgres/aurora). The Data API holds no connections:+// each statement is one HTTPS request, and a transaction is a transactionId that its statements carry. So a+// "connection" here is a client, and withTransaction's BEGIN, COMMIT and ROLLBACK become the Data API's+// BeginTransaction, CommitTransaction and RollbackTransaction calls; savepoints run as SQL inside the transaction.+import * as Config from 'effect/Config';+import * as Context from 'effect/Context';+import * as Effect from 'effect/Effect';+import * as Layer from 'effect/Layer';+import * as Option from 'effect/Option';+import * as Reactivity from 'effect/reactivity/Reactivity';+import * as Redacted from 'effect/Redacted';+import * as Client from 'effect/sql/SqlClient';+import type { Connection as SqlConnection } from 'effect/sql/SqlConnection';+import type { SqlError } from 'effect/sql/SqlError';+import * as Statement from 'effect/sql/Statement';+import * as Stream from 'effect/Stream';+import { AuroraClient, type AuroraConfig, type AuroraQueryOptions as PlainAuroraQueryOptions } from '../aurora.ts';+import { addBrand } from '../brand.ts';+import type { QueryResult } from '../types.ts';+import { makeCompiler, toSqlError } from './DrizzlePostgresClient.ts';+import { setTransaction, type TransactionOptions } from './shared.ts';++export type { TransactionOptions };++export const TypeId = '~@drizzle/postgres/DrizzleAuroraClient';+export type TypeId = typeof TypeId;++/** A SqlClient over the Aurora Data API. Its layers provide it under both this service and SqlClient. */+export interface DrizzleAuroraClient extends Client.SqlClient {+	readonly [TypeId]: TypeId;+	readonly config: DrizzleAuroraClientConfig;+	/** The Data API client that runs statements outside transactions. */+	readonly client: AuroraClient;+	/** SqlClient.withTransaction with transaction settings, in a Data API transaction. A nested call becomes a+	 *  savepoint and ignores the settings, because they apply to the whole transaction. */+	readonly withTransaction: <R, E, A>(+		self: Effect.Effect<A, E, R>,+		options?: TransactionOptions,+	) => Effect.Effect<A, E | SqlError, R>;+	/** Runs one statement with the Aurora client's options. The result type follows `mode`. Inside withTransaction it+	 *  runs in the transaction. */+	readonly query: AuroraQuery;+	/** Runs the Effects in one transaction, one statement at a time (the Data API runs a transaction's statements in+	 *  turn), all or nothing. */+	readonly batch: <A, E, R>(effects: Iterable<Effect.Effect<A, E, R>>) => Effect.Effect<Array<A>, E | SqlError, R>;+	/** Runs the Effects concurrently, without a transaction, so each statement commits on its own. Every statement+	 *  runs to the end, and the first failure in statement order fails the result. Inside withTransaction they run in+	 *  the transaction, in turn. */+	readonly pipeline: <A, E, R>(effects: Iterable<Effect.Effect<A, E, R>>) => Effect.Effect<Array<A>, E | SqlError, R>;+	/** BatchExecuteStatement: one statement over many parameter sets, for insert, update and delete. Inside+	 *  withTransaction it runs in the transaction. */+	readonly batchExecute: (+		sql: string,+		paramSets: unknown[][],+	) => Effect.Effect<{ updateResults: Array<{ generatedFields: unknown[] }> }, SqlError>;+}++/** The Aurora client's query options without the ones that Effect replaces: interrupt the Effect to cancel it. */+export type AuroraQueryOptions = Omit<PlainAuroraQueryOptions, 'signal' | 'timeout'>;++export interface AuroraQuery {+	(+		sql: string,+		params: unknown[],+		options: AuroraQueryOptions & { mode: 'buffer' },+	): Effect.Effect<QueryResult<(Buffer | null)[]>, SqlError>;+	(sql: string, params: unknown[], options: AuroraQueryOptions & { mode: 'raw' }): Effect.Effect<+		QueryResult<Buffer>,+		SqlError+	>;+	(+		sql: string,+		params: unknown[],+		options:+			| (AuroraQueryOptions & { mode: 'object' })+			| (AuroraQueryOptions & { mode?: 'object'; shape: NonNullable<AuroraQueryOptions['shape']> }),+	): Effect.Effect<QueryResult<Record<string, unknown>>, SqlError>;+	(+		sql: string,+		params?: unknown[],+		options?: AuroraQueryOptions & { mode?: 'array' },+	): Effect.Effect<QueryResult<unknown[]>, SqlError>;+}++export const DrizzleAuroraClient = Context.Service<DrizzleAuroraClient>('@drizzle/postgres/DrizzleAuroraClient');++/** The Aurora client's settings, with the AWS secrets as Redacted, plus the SqlClient settings. */+export interface DrizzleAuroraClientConfig extends Omit<AuroraConfig, 'credentials'> {+	readonly credentials?: {+		readonly accessKeyId: string;+		readonly secretAccessKey: Redacted.Redacted;+		readonly sessionToken?: Redacted.Redacted | undefined;+	} | undefined;+	readonly spanAttributes?: Record<string, unknown> | undefined;+	readonly transformResultNames?: ((str: string) => string) | undefined;+	readonly transformQueryNames?: ((str: string) => string) | undefined;+	readonly transformJson?: boolean | undefined;+}++/** The client settings that apply on top of an existing AuroraClient. */+export type FromClientOptions = Pick<+	DrizzleAuroraClientConfig,+	'spanAttributes' | 'transformResultNames' | 'transformQueryNames' | 'transformJson'+>;++// BEGIN with its settings (`BEGIN ISOLATION LEVEL …`, from SqlClient's BeginTransaction), and ROLLBACK, as+// SqlClient sends them. ROLLBACK TO SAVEPOINT runs as SQL in the transaction.+const BEGIN_SQL = /^\s*(?:begin|start\s+transaction)(?:\s+(?:transaction|work)\b)?\s*(.*?)\s*;?\s*$/is;+const ROLLBACK_SQL = /^\s*(?:rollback|abort)(?:\s+(?:transaction|work))?\s*;?\s*$/i;++/** One SqlClient connection: the base client, or a transaction once BEGIN has run on it. */+class AuroraConnection implements SqlConnection {+	tx: AuroraClient | undefined;++	constructor(readonly base: AuroraClient) {}++	get current(): AuroraClient {+		return this.tx ?? this.base;+	}++	private run<A>(operation: string, f: (client: AuroraClient, signal: AbortSignal) => Promise<A>) {+		const client = this.current;+		return Effect.tryPromise({+			try: (signal) => f(client, signal),+			catch: (e) => toSqlError(e, operation, client),+		});+	}++	private begin(settings: string) {+		return this.run('begin', async (client) => {+			const tx = await client.openTransaction();+			this.tx = tx;+			if (settings) await tx.query(`set transaction ${settings}`);+			return [];+		});+	}++	/** CommitTransaction or RollbackTransaction. The transaction is over either way, so the connection is too. */+	end(operation: 'commit' | 'rollback') {+		return this.run(operation, async (tx) => {+			this.tx = undefined;+			await (operation === 'commit' ? tx.commitTransaction() : tx.rollbackTransaction());+		});+	}++	execute(+		sql: string,+		params: ReadonlyArray<unknown>,+		transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined,+	) {+		const rows = Effect.map(+			this.run('execute', (client, signal) => client.query(sql, [...params], { mode: 'object', signal })),+			(r) => r.rows,+		);+		return transformRows ? Effect.map(rows, transformRows) : rows;+	}+	executeUnprepared(+		sql: string,+		params: ReadonlyArray<unknown>,+		transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined,+	) {+		if (params.length === 0 && this.tx === undefined) {+			const begin = BEGIN_SQL.exec(sql);+			if (begin) return this.begin(begin[1]!);+		}+		if (params.length === 0 && this.tx !== undefined && ROLLBACK_SQL.test(sql)) {+			return Effect.as(this.end('rollback'), []);+		}+		return this.execute(sql, params, transformRows);+	}+	executeValues(sql: string, params: ReadonlyArray<unknown>) {+		return Effect.map(+			this.run('execute', (client, signal) => client.query(sql, [...params], { mode: 'array', signal })),+			(r) => r.rows,+		);+	}+	executeValuesUnprepared(sql: string, params: ReadonlyArray<unknown>) {+		return this.executeValues(sql, params);+	}+	executeRaw(sql: string, params: ReadonlyArray<unknown>) {+		return this.run('executeRaw', (client, signal) => client.query(sql, [...params], { mode: 'object', signal }));+	}+	/** The Data API returns a statement's rows in one response, so the Stream emits them from it. */+	executeStream(+		sql: string,+		params: ReadonlyArray<unknown>,+		transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined,+	) {+		return Stream.fromIterableEffect(this.execute(sql, params, transformRows));+	}+}+addBrand(AuroraConnection, 'AuroraConnection');++const spanHost = (client: AuroraClient) => {+	try {+		return new URL(client.endpoint).host;+	} catch {+		return undefined;+	}+};++/** Creates a client over an AuroraClient. */+export const fromClient = Effect.fnUntraced(+	function*(base: AuroraClient, options: FromClientOptions & Partial<DrizzleAuroraClientConfig> = {}) {+		const config = options as DrizzleAuroraClientConfig;+		const compiler = makeCompiler(config.transformQueryNames, config.transformJson);+		const transformRows = config.transformResultNames+			? Statement.defaultTransforms(config.transformResultNames, config.transformJson).array+			: undefined;+		const spanAttributes = [+			...(config.spanAttributes ? Object.entries(config.spanAttributes) : []),+			['db.system.name', 'postgresql'],+			['db.namespace', config.database],+			['server.address', spanHost(base)],+			['driver', 'drizzle-postgres-aurora'],+		] satisfies ReadonlyArray<readonly [string, unknown]>;++		// Statements outside transactions share one stateless connection; a transaction gets one of its own.+		const shared = new AuroraConnection(base);+		const client = yield* Client.make({+			acquirer: Effect.succeed(shared),+			transactionAcquirer: Effect.sync(() => new AuroraConnection(base)),+			compiler,+			commit: (conn) => (conn as AuroraConnection).end('commit'),+			isTransaction: (conn) => (conn as AuroraConnection).tx !== undefined,+			releaseSavepoint: (name) => `RELEASE SAVEPOINT ${name}`,+			spanAttributes,+			transformRows,+			driver: 'drizzle-postgres-aurora',+		});++		const current = Effect.map(+			Effect.serviceOption(client.transactionService),+			(tx) => Option.isSome(tx) ? (tx.value[0] as AuroraConnection).current : base,+		);+		const spanName = Statement.spanName(spanAttributes);+		const traced = <A, E, R>(operation: string, text: string, effect: Effect.Effect<A, E, R>) =>+			Effect.withSpan(effect, spanName, {+				kind: 'client',+				attributes: { ...Object.fromEntries(spanAttributes), 'db.operation.name': operation, 'db.query.text': text },+			});+		const run = <A>(operation: string, text: string, f: (client: AuroraClient, signal: AbortSignal) => Promise<A>) =>+			traced(+				operation,+				text,+				Effect.flatMap(current, (aurora) =>+					Effect.tryPromise({+						try: (signal) => f(aurora, signal),+						catch: (e) => toSqlError(e, operation, aurora),+					})),+			);++		// oxlint-disable-next-line typescript/no-useless-default-assignment -- JavaScript callers can omit both+		const query = ((sql: string, params: unknown[] = [], options: AuroraQueryOptions = {}) =>+			run(+				'query',+				sql,+				(aurora, signal) => aurora.query(sql, params, { ...options, signal } as never),+			)) as AuroraQuery;++		const plainWithTransaction = client.withTransaction;+		const withTransaction = <R, E, A>(self: Effect.Effect<A, E, R>, options?: TransactionOptions) =>+			Effect.suspend(() => {+				const set = options && setTransaction(options);+				if (!set) return plainWithTransaction(self);+				return Effect.flatMap(Effect.serviceOption(client.transactionService), (outer) =>+					Option.isSome(outer)+						? plainWithTransaction(self)+						: plainWithTransaction(Effect.andThen(client.unsafe(set), self)));+			});++		const batch = <A, E, R>(effects: Iterable<Effect.Effect<A, E, R>>) => withTransaction(Effect.all(effects));+		const pipeline = <A, E, R>(effects: Iterable<Effect.Effect<A, E, R>>) =>+			Effect.flatMap(Effect.serviceOption(client.transactionService), (tx) =>+				Effect.flatMap(+					Effect.all(Array.from(effects, (effect) => Effect.exit(effect)), {+						concurrency: Option.isSome(tx) ? 1 : 'unbounded',+					}),+					(exits) => Effect.all(exits),+				));+		const batchExecute = (sql: string, paramSets: unknown[][]) =>+			run('batchExecute', sql, (aurora, signal) => aurora.batch(sql, paramSets, { signal }));++		return Object.assign(client, {+			[TypeId]: TypeId,+			config,+			client: base,+			withTransaction,+			query,+			batch,+			pipeline,+			batchExecute,+		}) as DrizzleAuroraClient;+	},+);++const toAuroraConfig = (config: DrizzleAuroraClientConfig): AuroraConfig => ({+	...config,+	credentials: config.credentials && {+		accessKeyId: config.credentials.accessKeyId,+		secretAccessKey: Redacted.value(config.credentials.secretAccessKey),+		sessionToken: config.credentials.sessionToken && Redacted.value(config.credentials.sessionToken),+	},+});++/** Creates a client with its own AuroraClient. The Data API holds no connections, so there is nothing to close. */+export const make = (config: DrizzleAuroraClientConfig) =>+	Effect.flatMap(+		Effect.try({ try: () => new AuroraClient(toAuroraConfig(config)), catch: (e) => toSqlError(e, 'connect') }),+		(base) => fromClient(base, config),+	);++const layerFrom = <E, R>(build: Effect.Effect<DrizzleAuroraClient, E, R>) =>+	Layer.effectContext(+		Effect.map(+			build,+			(client) => Context.make(DrizzleAuroraClient, client).pipe(Context.add(Client.SqlClient, client)),+		),+	).pipe(Layer.provide(Reactivity.layer));++/** A layer with its own AuroraClient. */+export const layer = (config: DrizzleAuroraClientConfig) => layerFrom(make(config));++/** Like `layer`, with the settings read from Effect Config. */+export const layerConfig = (config: Config.Wrap<DrizzleAuroraClientConfig>) =>+	layerFrom(Effect.flatMap(Config.unwrap(config), make));++/** A layer over an AuroraClient that the caller created. */+export const layerFromClient = (client: AuroraClient, options?: FromClientOptions) =>+	layerFrom(fromClient(client, options));
drizzle-orm/tests/relational-query-values.test.ts+721 −0
drizzle-orm/type-tests/pg/result-parity.ts+401 −0

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Data ConsistencyThe await on cache.get(…) was removed, making the cache operation fire-and-forget. Errors are unobservable and data may be lost on process exit.

    Principle · Keep Shared State Consistent Under Concurrency

    Recorded file drizzle-orm/src/pg-core/async/session.ts · no line recorded

  • Observation · Failure HandlingRemoved await on cache.get() creates fire-and-forget operation with unobserved errors and potential data loss on process exit

    Principle · Set Timeout and Retry Budgets

    Recorded file drizzle-orm/src/pg-core/async/session.ts · no line recorded

Supporting evidence

Reviewed 29 Nov 2026Revision 4fcbd668c28a30 changed files+5107 −889Judge score 4/5
Approved · 0 retained findingsgithub/github-mcp-server#3838Review permalink

add optional secret hiding to secret scanning alert tools

Input

PR author’s description

<!-- Copilot: Fill all sections. Prefer short, concrete answers. If a checkbox is selected, add a brief explanation. -->

PR diff

Current GitHub diff ↗
pkg/github/security_outputs.go · patch excerpt
+type GetSecretScanningAlertInput struct {+	Owner       string `json:"owner"`+	Repo        string `json:"repo"`+	AlertNumber int    `json:"alertNumber"`
Browse 6 changed files
pkg/github/security_outputs.go+8 −0
@@ -24,6 +24,13 @@ type GetSecurityAlertInput struct { 	AlertNumber int    `json:"alertNumber"` } +type GetSecretScanningAlertInput struct {+	Owner       string `json:"owner"`+	Repo        string `json:"repo"`+	AlertNumber int    `json:"alertNumber"`+	HideSecret  *bool  `json:"hide_secret,omitempty"`+}+ type ListCodeScanningAlertsInput struct { 	Owner    string `json:"owner"` 	Repo     string `json:"repo"`@@ -41,6 +48,7 @@ type ListSecretScanningAlertsInput struct { 	State      string `json:"state,omitempty"` 	SecretType string `json:"secret_type,omitempty"` 	Resolution string `json:"resolution,omitempty"`+	HideSecret *bool  `json:"hide_secret,omitempty"` 	Page       *int   `json:"page,omitempty"` 	PerPage    *int   `json:"perPage,omitempty"` }
pkg/github/secret_scanning_test.go+113 −0
@@ -3,16 +3,117 @@ package github import ( 	"context" 	"encoding/json"+	"maps" 	"net/http" 	"testing" +	"github.com/github/github-mcp-server/v2/pkg/ifc"+	"github.com/github/github-mcp-server/v2/pkg/inventory" 	"github.com/github/github-mcp-server/v2/pkg/translations" 	"github.com/google/go-github/v92/github" 	"github.com/google/jsonschema-go/jsonschema"+	"github.com/modelcontextprotocol/go-sdk/mcp" 	"github.com/stretchr/testify/assert" 	"github.com/stretchr/testify/require" ) +func Test_GetSecretScanningAlertHideSecret(t *testing.T) {+	testSecretScanningHideSecret(t, GetSecretScanningAlert(translations.NullTranslationHelper),+		GetReposSecretScanningAlertsByOwnerByRepoByAlertNumber,+		map[string]any{"owner": "owner", "repo": "repo", "alertNumber": 42},+		map[string]string{},+		func(alert string) string { return alert })+}++func Test_ListSecretScanningAlertsHideSecret(t *testing.T) {+	testSecretScanningHideSecret(t, ListSecretScanningAlerts(translations.NullTranslationHelper),+		GetReposSecretScanningAlertsByOwnerByRepo,+		map[string]any{+			"owner": "owner", "repo": "repo", "page": 2, "perPage": 50,+			"state": "resolved", "secret_type": "test_secret", "resolution": "revoked",+		},+		map[string]string{+			"page": "2", "per_page": "50", "state": "resolved",+			"secret_type": "test_secret", "resolution": "revoked",+		},+		func(alert string) string { return "[" + alert + "]" })+}++func testSecretScanningHideSecret(t *testing.T, tool inventory.ServerTool, endpoint string, args map[string]any, query map[string]string, wrap func(string) string) {+	t.Helper()+	const visible = `{"number":42,"state":"resolved","secret_type":"test_secret","secret":"synthetic-test-secret"}`+	const hidden = `{"number":42,"state":"resolved","secret_type":"test_secret"}`+	for _, tc := range []struct {+		name     string+		option   *bool+		response string+	}{+		{name: "absent", response: visible},+		{name: "false", option: new(false), response: visible},+		{name: "true", option: new(true), response: hidden},+	} {+		t.Run(tc.name, func(t *testing.T) {+			for _, protocol := range []string{"direct", "2025-11-25", inventory.ProtocolVersionMultiRoundTrip} {+				t.Run(protocol, func(t *testing.T) {+					requestArgs := make(map[string]any, len(args)+1)+					maps.Copy(requestArgs, args)+					expectedQuery := make(map[string][]string, len(query)+1)+					for key, value := range query {+						expectedQuery[key] = []string{value}+					}+					if tc.option != nil {+						requestArgs["hide_secret"] = *tc.option+						expectedQuery["hide_secret"] = []string{tc.name}+					}+					response := wrap(tc.response)+					calls := 0+					deps := BaseDeps{+						Client: mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{+							endpoint: func(w http.ResponseWriter, r *http.Request) {+								calls+++								assert.Equal(t, http.MethodGet, r.Method)+								assert.EqualValues(t, expectedQuery, r.URL.Query())+								mockResponse(t, http.StatusOK, json.RawMessage(response))(w, r)+							},+						})),+						featureChecker: featureCheckerFor(FeatureFlagIFCLabels),+					}+					ctx := ContextWithDeps(context.Background(), deps)+					var result *mcp.CallToolResult+					var err error+					if protocol == "direct" {+						request := createMCPRequest(requestArgs)+						result, err = tool.Handler(deps)(ctx, &request)+					} else {+						server := mcp.NewServer(&mcp.Implementation{Name: "secret-hiding-test", Version: "v1"}, nil)+						server.AddReceivingMiddleware(InjectDepsMiddleware(deps))+						tool.RegisterFunc(server, deps)+						session := connectCommentVisibilityClient(t, server, protocol)+						result, err = session.CallTool(ctx, &mcp.CallToolParams{Name: tool.Tool.Name, Arguments: requestArgs})+					}+					require.NoError(t, err)+					require.False(t, result.IsError)+					assert.Equal(t, 1, calls, "must make only the requested REST call")+					assert.JSONEq(t, mustMarshalJSON(t, ifc.LabelSecurityAlert()), mustMarshalJSON(t, result.Meta["ifc"]))+					assert.JSONEq(t, response, getTextResult(t, result).Text)+					if protocol != inventory.ProtocolVersionMultiRoundTrip {+						assert.Nil(t, result.StructuredContent)+						return+					}+					require.NotNil(t, result.StructuredContent)+					structuredJSON := mustMarshalJSON(t, result.StructuredContent)+					assert.JSONEq(t, response, structuredJSON)+					var structured any+					require.NoError(t, json.Unmarshal([]byte(structuredJSON), &structured))+					resolved, err := securityOutputSchema(t, tool.Tool.Name).Resolve(nil)+					require.NoError(t, err)+					require.NoError(t, resolved.Validate(structured))+				})+			}+		})+	}+}+ func Test_GetSecretScanningAlert(t *testing.T) { 	toolDef := GetSecretScanningAlert(translations.NullTranslationHelper) @@ -215,6 +316,18 @@ func Test_ListSecretScanningAlerts(t *testing.T) { 			expectError:    false, 			expectedAlerts: []*github.SecretScanningAlert{&openAlert}, 		},+		{+			name: "direct caller zero pagination uses defaults",+			mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{+				GetReposSecretScanningAlertsByOwnerByRepo: expectQueryParams(t, map[string]string{"page": "1", "per_page": "30"}).andThen(+					mockResponse(t, http.StatusOK, []*github.SecretScanningAlert{&openAlert}),+				),+			}),+			requestArgs: map[string]any{+				"owner": "owner", "repo": "repo", "page": 0, "perPage": 0,+			},+			expectedAlerts: []*github.SecretScanningAlert{&openAlert},+		}, 		{ 			name: "alerts listing fails", 			mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
pkg/github/secret_scanning.go+51 −16
@@ -6,6 +6,8 @@ import ( 	"fmt" 	"io" 	"net/http"+	"net/url"+	"strconv"  	ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" 	"github.com/github/github-mcp-server/v2/pkg/ifc"@@ -19,7 +21,7 @@ import ( )  func GetSecretScanningAlert(t translations.TranslationHelperFunc) inventory.ServerTool {-	return NewTool[GetSecurityAlertInput, *SecretScanningAlertOutput](+	return NewTool[GetSecretScanningAlertInput, *SecretScanningAlertOutput]( 		ToolsetMetadataSecretProtection, 		mcp.Tool{ 			Name:        "get_secret_scanning_alert",@@ -43,12 +45,16 @@ func GetSecretScanningAlert(t translations.TranslationHelperFunc) inventory.Serv 						Type:        "number", 						Description: "The number of the alert.", 					},+					"hide_secret": {+						Type:        "boolean",+						Description: "Whether to exclude the secret value from the response. Defaults to false.",+					}, 				}, 				Required: []string{"owner", "repo", "alertNumber"}, 			}, 		}, 		scopes.RequireAll(scopes.SecurityEvents),-		func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GetSecurityAlertInput) (*mcp.CallToolResult, *SecretScanningAlertOutput, error) {+		func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GetSecretScanningAlertInput) (*mcp.CallToolResult, *SecretScanningAlertOutput, error) { 			if args.Owner == "" { 				return utils.NewToolResultError("missing required parameter: owner"), nil, nil 			}@@ -64,16 +70,26 @@ func GetSecretScanningAlert(t translations.TranslationHelperFunc) inventory.Serv 				return nil, nil, fmt.Errorf("failed to get GitHub client: %w", err) 			} -			alert, resp, err := client.SecretScanning.GetAlert(ctx, args.Owner, args.Repo, int64(args.AlertNumber))+			apiURL := fmt.Sprintf("repos/%s/%s/secret-scanning/alerts/%d", url.PathEscape(args.Owner), url.PathEscape(args.Repo), args.AlertNumber)+			if args.HideSecret != nil {+				apiURL += "?hide_secret=" + strconv.FormatBool(*args.HideSecret)+			}+			req, err := client.NewRequest(ctx, http.MethodGet, apiURL, nil)+			if err != nil {+				return utils.NewToolResultErrorFromErr("failed to create request", err), nil, nil+			}+			var alert *github.SecretScanningAlert+			resp, err := client.Do(req, &alert)+			if resp != nil {+				defer func() { _ = resp.Body.Close() }()+			} 			if err != nil { 				return ghErrors.NewGitHubAPIErrorResponse(ctx, 					fmt.Sprintf("failed to get alert with number '%d'", args.AlertNumber), 					resp, 					err, 				), nil, nil 			}-			defer func() { _ = resp.Body.Close() }()- 			if resp.StatusCode != http.StatusOK { 				body, err := io.ReadAll(resp.Body) 				if err != nil {@@ -124,6 +140,10 @@ func ListSecretScanningAlerts(t translations.TranslationHelperFunc) inventory.Se 				Description: "Filter by resolution", 				Enum:        []any{"false_positive", "wont_fix", "revoked", "pattern_edited", "pattern_deleted", "used_in_tests"}, 			},+			"hide_secret": {+				Type:        "boolean",+				Description: "Whether to exclude secret values from the response. Defaults to false.",+			}, 		}, 		Required: []string{"owner", "repo"}, 	}@@ -154,24 +174,39 @@ func ListSecretScanningAlerts(t translations.TranslationHelperFunc) inventory.Se 			if err != nil { 				return nil, nil, fmt.Errorf("failed to get GitHub client: %w", err) 			}-			alerts, resp, err := client.SecretScanning.ListAlertsForRepo(ctx, args.Owner, args.Repo, &github.SecretScanningAlertListOptions{-				State:      args.State,-				SecretType: args.SecretType,-				Resolution: args.Resolution,-				ListOptions: github.ListOptions{-					Page:    pagination.Page,-					PerPage: pagination.PerPage,-				},-			})+			query := url.Values{+				"page":     {strconv.Itoa(pagination.Page)},+				"per_page": {strconv.Itoa(pagination.PerPage)},+			}+			if args.State != "" {+				query.Set("state", args.State)+			}+			if args.SecretType != "" {+				query.Set("secret_type", args.SecretType)+			}+			if args.Resolution != "" {+				query.Set("resolution", args.Resolution)+			}+			if args.HideSecret != nil {+				query.Set("hide_secret", strconv.FormatBool(*args.HideSecret))+			}+			apiURL := fmt.Sprintf("repos/%s/%s/secret-scanning/alerts?%s", url.PathEscape(args.Owner), url.PathEscape(args.Repo), query.Encode())+			req, err := client.NewRequest(ctx, http.MethodGet, apiURL, nil)+			if err != nil {+				return utils.NewToolResultErrorFromErr("failed to create request", err), nil, nil+			}+			var alerts []*github.SecretScanningAlert+			resp, err := client.Do(req, &alerts)+			if resp != nil {+				defer func() { _ = resp.Body.Close() }()+			} 			if err != nil { 				return ghErrors.NewGitHubAPIErrorResponse(ctx, 					fmt.Sprintf("failed to list alerts for repository '%s/%s'", args.Owner, args.Repo), 					resp, 					err, 				), nil, nil 			}-			defer func() { _ = resp.Body.Close() }()- 			if resp.StatusCode != http.StatusOK { 				body, err := io.ReadAll(resp.Body) 				if err != nil {

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens advisories (not part of the checked findings):

  • change_quality: The PR modifies README.md to add hide_secret documentation plus updates to two snapshots, in addition to adding two tests confirming the feature exists. A single hide_secret optional parameter is being added to two existing functionality groups, and its tests are present in the diff, so only one objective is present.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Change qualityThe PR modifies README.md to add `hide_secret` documentation plus updates to two snapshots, in addition to adding two tests confirming the feature exists. A single `hide_secret` optional parameter is being added to two existing functionality groups, and its tests are present in the diff, so only one objective is present.

    Recorded location pkg/github/security_outputs.go:26

  • Observation · Architectural coherenceThe added `hideSecret` parameter in `GetSecretScanningAlertInput` and `ListSecretScanningAlertsInput` follows the README documentation pattern used elsewhere (boolean, optional) without deviation from existing security alert input conventions.

    Recorded location pkg/github/security_outputs.go:26

Supporting evidence

Reviewed 29 Nov 2026Revision 9d30218c10096 changed files+182 −16Judge score 4/5
Approved · 0 retained findingsclap-rs/clap#6456Review permalink

docs: add configurable command alias example

Input

PR author’s description

Closes #3679.

Adds configurable aliases to both git cookbook examples. They recursively reparse expanded aliases, preserve trailing arguments, support alias chains, and keep built-in commands ahead of configured…

PR diff

Current GitHub diff ↗
examples/git-derive.rs · patch excerpt
+use std::collections::HashMap;
Browse 5 changed files
examples/git-derive.rs+42 −1
@@ -1,3 +1,4 @@+use std::collections::HashMap; use std::ffi::OsStr; use std::ffi::OsString; use std::path::PathBuf;@@ -98,8 +99,48 @@ struct StashPushArgs {     message: Option<String>, } +fn aliases() -> HashMap<&'static str, Vec<&'static str>> {+    HashMap::from([+        ("last", vec!["diff", "HEAD~", "HEAD", "--"]),+        ("stage", vec!["add"]),+    ])+}++fn parse_aliases() -> Result<Cli, clap::Error> {+    let args = Cli::try_parse()?;+    expand_aliases(args, Vec::new())+}++fn expand_aliases(args: Cli, mut expanded: Vec<String>) -> Result<Cli, clap::Error> {+    let Commands::External(external_args) = &args.command else {+        return Ok(args);+    };+    let Some(name) = external_args.first().and_then(|name| name.to_str()) else {+        return Ok(args);+    };++    let aliases = aliases();+    let Some(alias) = aliases.get(name) else {+        return Ok(args);+    };+    if expanded.iter().any(|expanded| expanded == name) {+        return Err(clap::Error::raw(+            clap::error::ErrorKind::InvalidSubcommand,+            format!("recursive alias `{}`", expanded[0]),+        ));+    }+    expanded.push(name.to_owned());++    let mut alias_args = vec![OsString::from("git")];+    alias_args.extend(alias.iter().map(OsString::from));+    alias_args.extend(external_args.iter().skip(1).cloned());+    let args = Cli::try_parse_from(alias_args)?;++    expand_aliases(args, expanded)+}+ fn main() {-    let args = Cli::parse();+    let args = parse_aliases().unwrap_or_else(|error| error.exit());      match args.command {         Commands::Clone { remote } => {
examples/git.rs+51 −2
@@ -1,7 +1,8 @@+use std::collections::HashMap; use std::ffi::OsString; use std::path::PathBuf; -use clap::{Command, arg};+use clap::{ArgMatches, Command, arg};  fn cli() -> Command {     Command::new("git")@@ -57,8 +58,56 @@ fn push_args() -> Vec<clap::Arg> {     vec![arg!(-m --message <MESSAGE>)] } +fn aliases() -> HashMap<&'static str, Vec<&'static str>> {+    HashMap::from([+        ("last", vec!["diff", "HEAD~", "HEAD", "--"]),+        ("stage", vec!["add"]),+    ])+}++fn parse_aliases() -> Result<ArgMatches, clap::Error> {+    let matches = cli().try_get_matches()?;+    expand_aliases(matches, Vec::new())+}++fn expand_aliases(+    matches: ArgMatches,+    mut expanded: Vec<String>,+) -> Result<ArgMatches, clap::Error> {+    let Some((name, sub_matches)) = matches.subcommand() else {+        return Ok(matches);+    };+    if cli().find_subcommand(name).is_some() {+        return Ok(matches);+    }++    let aliases = aliases();+    let Some(alias) = aliases.get(name) else {+        return Ok(matches);+    };+    let mut args = alias.iter().map(OsString::from).collect::<Vec<_>>();+    args.extend(+        sub_matches+            .get_many::<OsString>("")+            .into_iter()+            .flatten()+            .cloned(),+    );+    let matches = cli().no_binary_name(true).try_get_matches_from(args)?;+    let new_name = matches.subcommand_name().expect("subcommand required");+    expanded.push(name.to_owned());+    if expanded.iter().any(|name| name == new_name) {+        return Err(clap::Error::raw(+            clap::error::ErrorKind::InvalidSubcommand,+            format!("recursive alias `{}`", expanded[0]),+        ));+    }++    expand_aliases(matches, expanded)+}+ fn main() {-    let matches = cli().get_matches();+    let matches = parse_aliases().unwrap_or_else(|error| error.exit());      match matches.subcommand() {         Some(("clone", sub_matches)) => {
examples/git-derive.md+13 −0
@@ -135,6 +135,19 @@ Calling out to "custom-tool" with ["arg1", "--foo", "bar"]  ``` +Configurable aliases:+Aliases loaded from application configuration can expand into built-in commands+and arguments. Built-in commands take precedence over configured aliases.++```console+$ git-derive last ./src+Diffing HEAD~..HEAD ./src (color=auto)++$ git-derive stage Cargo.toml Cargo.lock+Adding ["Cargo.toml", "Cargo.lock"]++```+ Last argument: ```console $ git-derive diff --help

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Test strategyThe diff introduces an alias expansion feature defined in `aliases()` (lines 102-107) and `expand_aliases()` (lines 114-140) in examples/git-derive.rs, but the diff evidence does not show any tests added to cover this behaviour, creating a gap in regression protection for new alias functionality.

    Recorded location examples/git-derive.rs:101

  • Observation · Historical riskThe expanded alias expansion logic (`parse_aliases`, `expand_aliases`, `aliases`) introduces a new pattern of argument processing that wraps the base command parsing, potentially increasing maintenance surface. The existing example `examples/git.rs` also uses an identical alias pattern. This shared pattern increases the code architecture's complexity with limited separation of concerns.

    Recorded location examples/git-derive.rs:108

Supporting evidence

Reviewed 29 Nov 2026Revision 9a1ec1f2be385 changed files+120 −3Judge score 4/5
Approved · 0 retained findingswikimedia/apps-android-wikipedia#7095Review permalink

[SemanticSearch]: Semantic search team draft merge

Input

PR author’s description

What does this do?

  1. Adds SearchResultsInterleaver.merge, a Team-Draft merge of lexical (prefix + full-text) and semantic search results. For each result, it records which search type placed it, its rank in that…

PR diff

Current GitHub diff ↗
app/src/main/java/org/wikipedia/search/interleave/SplitMix64.kt · patch excerpt
+package org.wikipedia.search.interleave++class SplitMix64(seed: ULong) {+    private var state = seed
Browse 15 changed files
app/src/main/java/org/wikipedia/search/interleave/SplitMix64.kt+23 −0
@@ -0,0 +1,23 @@+package org.wikipedia.search.interleave++class SplitMix64(seed: ULong) {+    private var state = seed++    fun nextULong(): ULong {+        state += GOLDEN_GAMMA+        var z = state+        z = (z xor (z shr 30)) * MIX_MULTIPLIER_1+        z = (z xor (z shr 27)) * MIX_MULTIPLIER_2+        return z xor (z shr 31)+    }++    fun nextCoin(): Int {+        return (nextULong() shr 63).toInt()+    }++    companion object {+        private const val GOLDEN_GAMMA = 0x9E3779B97F4A7C15uL+        private const val MIX_MULTIPLIER_1 = 0xBF58476D1CE4E5B9uL+        private const val MIX_MULTIPLIER_2 = 0x94D049BB133111EBuL+    }+}
app/src/test/res/raw/team_draft_merge_vectors.json+1391 −0
app/src/test/res/raw/fr_napoleon_bonaparte_full_text_search_results.json+264 −0
@@ -0,0 +1,264 @@+{+  "batchcomplete": true,+  "continue": {+    "gsroffset": 10,+    "continue": "gsroffset||"+  },+  "query": {+    "pages": [+      {+        "pageid": 23171,+        "ns": 0,+        "title": "Napoléon III",+        "snippet": "Louis-<span class=\"searchmatch\">Napoléon</span> <span class=\"searchmatch\">Bonaparte</span> (homonymie), <span class=\"searchmatch\">Napoléon</span> (homonymie) et <span class=\"searchmatch\">Bonaparte</span> (homonymie). Vous lisez un « article de qualité » labellisé en 2011. Louis-<span class=\"searchmatch\">Napoléon</span>",+        "sectiontitle": "Personnalité de Napoléon III",+        "index": 2,+        "description": "homme d'État français et dernier monarque de France",+        "descriptionsource": "central",+        "thumbnail": {+          "source": "https://thumb.wikimedia.org/wikipedia/commons/thumb/c/cf/Napol%C3%A9on_III_par_Jean_Hippolyte_Flandrin.jpg/330px-Napol%C3%A9on_III_par_Jean_Hippolyte_Flandrin.jpg?utm_source=fr.wikipedia.org&utm_campaign=api&utm_content=thumbnail",+          "width": 330,+          "height": 479+        },+        "contentmodel": "wikitext",+        "pagelanguage": "fr",+        "pagelanguagehtmlcode": "fr",+        "pagelanguagedir": "ltr",+        "touched": "2026-11-02T16:01:43Z",+        "lastrevid": 240809055,+        "length": 360672,+        "displaytitle": "Napoléon&#160;<abbr class=\"abbr\" title=\"3\"><span class=\"romain\" style=\"text-transform:uppercase\">III</span></abbr>",+        "varianttitles": {+          "fr": "Napoléon&#160;<abbr class=\"abbr\" title=\"3\"><span class=\"romain\" style=\"text-transform:uppercase\">III</span></abbr>"+        }+      },+      {+        "pageid": 57261,+        "ns": 0,+        "title": "Pierre-Napoléon Bonaparte",+        "snippet": "Pour les articles homonymes, voir <span class=\"searchmatch\">Bonaparte</span>. Pierre-<span class=\"searchmatch\">Napoléon</span> <span class=\"searchmatch\">Bonaparte</span> Portrait en pied de Pierre-<span class=\"searchmatch\">Napoléon</span> <span class=\"searchmatch\">Bonaparte</span>, photographie d&#039;Eugène Disdéri, musée",+        "index": 10,+        "description": "prince d'Empire français",+        "descriptionsource": "central",+        "thumbnail": {+          "source": "https://thumb.wikimedia.org/wikipedia/commons/thumb/e/e9/Pierre-Napol%C3%A9on_Bonaparte.jpg/330px-Pierre-Napol%C3%A9on_Bonaparte.jpg?utm_source=fr.wikipedia.org&utm_campaign=api&utm_content=thumbnail",+          "width": 330,+          "height": 542+        },+        "contentmodel": "wikitext",+        "pagelanguage": "fr",+        "pagelanguagehtmlcode": "fr",+        "pagelanguagedir": "ltr",+        "touched": "2026-11-02T16:01:48Z",+        "lastrevid": 240780250,+        "length": 22024,+        "displaytitle": "Pierre-Napoléon Bonaparte",+        "varianttitles": {+          "fr": "Pierre-Napoléon Bonaparte"+        }+      },+      {+        "pageid": 79106,+        "ns": 0,+        "title": "Maison Bonaparte",+        "snippet": "<span class=\"searchmatch\">Bonaparte</span> (1746-1785) <span class=\"searchmatch\">Napoléon</span> Ier (1769-1821) <span class=\"searchmatch\">Napoléon</span> II (1811-1832) Louis <span class=\"searchmatch\">Bonaparte</span> (1778-1846) <span class=\"searchmatch\">Napoléon</span> III (1808-1873) Louis-<span class=\"searchmatch\">Napoléon</span> <span class=\"searchmatch\">Bonaparte</span>,",+        "sectiontitle": "La famille Bonaparte en Corse",+        "index": 4,+        "description": "famille de petite noblesse corse puis dynastie impériale française",+        "descriptionsource": "central",+        "thumbnail": {+          "source": "https://thumb.wikimedia.org/wikipedia/commons/thumb/f/f3/Grandes_Armes_Imp%C3%A9riales_%281804-1815%292.svg/330px-Grandes_Armes_Imp%C3%A9riales_%281804-1815%292.svg.png?utm_source=fr.wikipedia.org&utm_campaign=api&utm_content=thumbnail",+          "width": 330,+          "height": 365+        },+        "contentmodel": "wikitext",+        "pagelanguage": "fr",+        "pagelanguagehtmlcode": "fr",+        "pagelanguagedir": "ltr",+        "touched": "2026-11-02T16:01:51Z",+        "lastrevid": 240329998,+        "length": 154106,+        "displaytitle": "Maison Bonaparte",+        "varianttitles": {+          "fr": "Maison Bonaparte"+        }+      },+      {+        "pageid": 91552,+        "ns": 0,+        "title": "Napoléon II",+        "snippet": "Pour les articles homonymes, voir <span class=\"searchmatch\">Napoléon</span> (homonymie) et Aiglon. <span class=\"searchmatch\">Napoléon</span> François Joseph Charles <span class=\"searchmatch\">Bonaparte</span>, né le 20 mars 1811 à Paris et mort le 22",+        "index": 7,+        "description": "empereur des Français du 22 juin au 7 juillet 1815 et Grand Aigle de la Légion d'honneur",+        "descriptionsource": "central",+        "thumbnail": {+          "source": "https://thumb.wikimedia.org/wikipedia/commons/thumb/4/4a/Le_duc_de_Reichstadt.jpg/330px-Le_duc_de_Reichstadt.jpg?utm_source=fr.wikipedia.org&utm_campaign=api&utm_content=thumbnail",+          "width": 330,+          "height": 490+        },+        "contentmodel": "wikitext",+        "pagelanguage": "fr",+        "pagelanguagehtmlcode": "fr",+        "pagelanguagedir": "ltr",+        "touched": "2026-11-02T16:01:53Z",+        "lastrevid": 240675442,+        "length": 62107,+        "displaytitle": "Napoléon&#160;<abbr class=\"abbr\" title=\"2\"><span class=\"romain\" style=\"text-transform:uppercase\">II</span></abbr>",+        "varianttitles": {+          "fr": "Napoléon&#160;<abbr class=\"abbr\" title=\"2\"><span class=\"romain\" style=\"text-transform:uppercase\">II</span></abbr>"+        }+      },+      {+        "pageid": 145658,+        "ns": 0,+        "title": "Napoléon-Jérôme Bonaparte",+        "snippet": "voir <span class=\"searchmatch\">Napoléon</span> (homonymie). <span class=\"searchmatch\">Napoléon</span> Joseph Charles Paul <span class=\"searchmatch\">Bonaparte</span>, dit <span class=\"searchmatch\">Napoléon</span>-Jérôme, surnommé « Plon-Plon », prince français, dit le prince <span class=\"searchmatch\">Napoléon</span>, prince",+        "index": 5,+        "description": "prince Napoléon, général, prince et comte français, membre de la famille Bonaparte",+        "descriptionsource": "central",+        "thumbnail": {+          "source": "https://thumb.wikimedia.org/wikipedia/commons/thumb/d/d6/Napol%C3%A9on_Joseph_Charles_Paul_Bonaparte_painting.jpg/330px-Napol%C3%A9on_Joseph_Charles_Paul_Bonaparte_painting.jpg?utm_source=fr.wikipedia.org&utm_campaign=api&utm_content=thumbnail",+          "width": 330,+          "height": 434+        },+        "contentmodel": "wikitext",+        "pagelanguage": "fr",+        "pagelanguagehtmlcode": "fr",+        "pagelanguagedir": "ltr",+        "touched": "2026-11-02T16:02:02Z",+        "lastrevid": 240840969,+        "length": 38937,+        "displaytitle": "Napoléon-Jérôme Bonaparte",+        "varianttitles": {+          "fr": "Napoléon-Jérôme Bonaparte"+        }+      },+      {+        "pageid": 330031,+        "ns": 0,+        "title": "Charles Bonaparte (1950)",+        "snippet": "Charles <span class=\"searchmatch\">Bonaparte</span> (homonymie), <span class=\"searchmatch\">Bonaparte</span> (homonymie), Maison <span class=\"searchmatch\">Bonaparte</span> et <span class=\"searchmatch\">Napoléon</span> (homonymie). Charles <span class=\"searchmatch\">Bonaparte</span> (Charles Marie Jérôme Victor <span class=\"searchmatch\">Napoléon</span> Bonaparte)",+        "index": 9,+        "description": "politicien français, membre de la dynastie Bonaparte",+        "descriptionsource": "central",+        "thumbnail": {+          "source": "https://thumb.wikimedia.org/wikipedia/commons/thumb/5/5e/Charles-bonaparte.jpg/330px-Charles-bonaparte.jpg?utm_source=fr.wikipedia.org&utm_campaign=api&utm_content=thumbnail",+          "width": 330,+          "height": 415+        },+        "contentmodel": "wikitext",+        "pagelanguage": "fr",+        "pagelanguagehtmlcode": "fr",+        "pagelanguagedir": "ltr",+        "touched": "2026-11-02T16:02:35Z",+        "lastrevid": 239207513,+        "length": 20439,+        "displaytitle": "Charles Bonaparte (1950)",+        "varianttitles": {+          "fr": "Charles Bonaparte (1950)"+        }+      },+      {+        "pageid": 540618,+        "ns": 0,+        "title": "Louis Napoléon",+        "snippet": "Maison <span class=\"searchmatch\">Bonaparte</span>, Louis-<span class=\"searchmatch\">Napoléon</span> <span class=\"searchmatch\">Bonaparte</span> (homonymie), <span class=\"searchmatch\">Napoléon</span> (homonymie) et <span class=\"searchmatch\">Bonaparte</span> (homonymie). Ne doit pas être confondu avec Louis-<span class=\"searchmatch\">Napoléon</span> Bonaparte",+        "index": 8,+        "description": "militaire français",+        "descriptionsource": "central",+        "thumbnail": {+          "source": "https://thumb.wikimedia.org/wikipedia/commons/thumb/1/15/Louis_Bonaparte.jpg/330px-Louis_Bonaparte.jpg?utm_source=fr.wikipedia.org&utm_campaign=api&utm_content=thumbnail",+          "width": 330,+          "height": 403+        },+        "contentmodel": "wikitext",+        "pagelanguage": "fr",+        "pagelanguagehtmlcode": "fr",+        "pagelanguagedir": "ltr",+        "touched": "2026-11-02T16:03:11Z",+        "lastrevid": 240790634,+        "length": 22136,+        "displaytitle": "Louis Napoléon",+        "varianttitles": {+          "fr": "Louis Napoléon"+        }+      },+      {+        "pageid": 676806,+        "ns": 0,+        "title": "Napoléon Ier",+        "snippet": "« <span class=\"searchmatch\">Napoléon</span> » redirige ici. Pour les autres significations, voir <span class=\"searchmatch\">Napoléon</span> (homonymie) et <span class=\"searchmatch\">Bonaparte</span> (homonymie). <span class=\"searchmatch\">Napoléon</span> <span class=\"searchmatch\">Bonaparte</span>Écouter, né le 15 août",+        "sectiontitle": "Réalisations de Napoléon Bonaparte",+        "index": 1,+        "description": "militaire, homme d'État et monarque français",+        "descriptionsource": "central",+        "thumbnail": {+          "source": "https://thumb.wikimedia.org/wikipedia/commons/thumb/b/b5/Jacques-Louis_David_-_The_Emperor_Napoleon_in_His_Study_at_the_Tuileries_-_Google_Art_Project_2.jpg/330px-Jacques-Louis_David_-_The_Emperor_Napoleon_in_His_Study_at_the_Tuileries_-_Google_Art_Project_2.jpg?utm_source=fr.wikipedia.org&utm_campaign=api&utm_content=thumbnail",+          "width": 330,+          "height": 549+        },+        "contentmodel": "wikitext",+        "pagelanguage": "fr",+        "pagelanguagehtmlcode": "fr",+        "pagelanguagedir": "ltr",+        "touched": "2026-11-02T16:03:33Z",+        "lastrevid": 240611359,+        "length": 260796,+        "displaytitle": "<span class=\"nowrap\">Napoléon <abbr class=\"abbr\" title=\"premier\"><span class=\"romain\" style=\"text-transform:uppercase\">I</span><sup>er</sup></abbr></span>",+        "varianttitles": {+          "fr": "<span class=\"nowrap\">Napoléon <abbr class=\"abbr\" title=\"premier\"><span class=\"romain\" style=\"text-transform:uppercase\">I</span><sup>er</sup></abbr></span>"+        }+      },+      {+        "pageid": 5358353,+        "ns": 0,+        "title": "Jean-Christophe Napoléon",+        "snippet": "Jean-Christophe <span class=\"searchmatch\">Napoléon</span> <span class=\"searchmatch\">Bonaparte</span>, dit Jean-Christophe <span class=\"searchmatch\">Napoléon</span>, né le 11 juillet 1986 à Saint-Raphaël (France), est un membre de la famille <span class=\"searchmatch\">Bonaparte</span>. Il est",+        "index": 6,+        "description": "banquier d'affaires français, descendant de la dynastie Bonaparte et Prince Napoléon",+        "descriptionsource": "central",+        "thumbnail": {+          "source": "https://upload.wikimedia.org/wikipedia/commons/f/f8/Prince_Napol%C3%A9on.JPG?utm_source=fr.wikipedia.org&utm_campaign=api&utm_content=thumbnail_unscaled",+          "width": 165,+          "height": 262+        },+        "contentmodel": "wikitext",+        "pagelanguage": "fr",+        "pagelanguagehtmlcode": "fr",+        "pagelanguagedir": "ltr",+        "touched": "2026-11-02T16:11:20Z",+        "lastrevid": 240790502,+        "length": 28909,+        "displaytitle": "Jean-Christophe Napoléon",+        "varianttitles": {+          "fr": "Jean-Christophe Napoléon"+        }+      },+      {+        "pageid": 17678531,+        "ns": 0,+        "title": "Napoléon Bonaparte (policier)",+        "snippet": "Ne doit pas être confondu avec <span class=\"searchmatch\">Napoléon</span> Ier. Pour les articles homonymes, voir <span class=\"searchmatch\">Bonaparte</span>. <span class=\"searchmatch\">Napoléon</span> <span class=\"searchmatch\">Bonaparte</span>, né le 26 octobre 1965 et mort le 18 octobre",+        "index": 3,+        "description": "policier indonésien",+        "descriptionsource": "central",+        "thumbnail": {+          "source": "https://thumb.wikimedia.org/wikipedia/commons/thumb/5/58/Irjen_Napoleon_Bonaparte.jpg/330px-Irjen_Napoleon_Bonaparte.jpg?utm_source=fr.wikipedia.org&utm_campaign=api&utm_content=thumbnail",+          "width": 330,+          "height": 440+        },+        "contentmodel": "wikitext",+        "pagelanguage": "fr",+        "pagelanguagehtmlcode": "fr",+        "pagelanguagedir": "ltr",+        "touched": "2026-11-02T16:28:21Z",+        "lastrevid": 240906373,+        "length": 2675,+        "displaytitle": "Napoléon Bonaparte (policier)",+        "varianttitles": {+          "fr": "Napoléon Bonaparte (policier)"+        }+      }+    ]+  }+}

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

The recorded Data Consistency observation did not become a verified finding.

Evidence and perspectives

  • Observation · Data ConsistencyAdded a new required field `pageId: Int = 0` to the `SearchResult` data class. While the field has a Kotlin default, kotlinx.serialization does not treat it as optional during deserialization; missing JSON fields will not use the Kotlin default unless explicitly marked with `@Serializable(default = true)` or similar. Existing serialized `SearchResult` objects will deserialize with the field present (value 0), which may not match the expected value if the field was previously absent.

    Principle · Keep Serialized Contracts Compatible

    Recorded location app/src/main/java/org/wikipedia/search/SearchResult.kt:20

Supporting evidence

Reviewed 29 Nov 2026Revision 748a0274f5fe15 changed files+3256 −2Judge score 5/5
Approved · 0 retained findingsthreeport/threeport#746Review permalink

feat: make a GKE cluster's Kubernetes API private

Input

PR author’s description

Part of #729. This is the fourth PR, stacked on #745. It makes a GKE cluster's Kubernetes API private. EKS and OKE keep refusing PrivateApi for now. Their private endpoint needs a network path from the control plane…

PR diff

Current GitHub diff ↗
pkg/cli/v0/k8s_api_access.go · patch excerpt
-// ValidateK8sApiAllowedCidrsFlag checks --k8s-api-allowed-cidrs: the blocks-// must be valid and within the provider's limit, and the flag applies only-// to a cluster tptctl creates on a cloud provider.-func ValidateK8sApiAllowedCidrsFlag(cidrs []string, infraProvider string, controlPlaneOnly bool) error {
Browse 28 changed files
pkg/cli/v0/k8s_api_access.go+46 −16
@@ -15,25 +15,43 @@ import ( 	threeport "github.com/threeport/threeport/pkg/threeport-installer/v0" ) -// ValidateK8sApiAllowedCidrsFlag checks --k8s-api-allowed-cidrs: the blocks-// must be valid and within the provider's limit, and the flag applies only-// to a cluster tptctl creates on a cloud provider.-func ValidateK8sApiAllowedCidrsFlag(cidrs []string, infraProvider string, controlPlaneOnly bool) error {-	if len(cidrs) == 0 {-		return nil+// ValidateK8sApiAccessFlags checks --private-k8s-api and+// --k8s-api-allowed-cidrs: they apply only to a cluster tptctl creates on a+// cloud provider, a private Kubernetes API only to GKE for now, and the+// blocks must be valid and within the provider's limit.+func ValidateK8sApiAccessFlags(privateApi bool, cidrs []string, infraProvider string, controlPlaneOnly bool) error {+	for _, flag := range []struct {+		name string+		set  bool+	}{+		{"--private-k8s-api", privateApi},+		{"--k8s-api-allowed-cidrs", len(cidrs) > 0},+	} {+		if !flag.set {+			continue+		}+		if infraProvider == v0.KubernetesRuntimeInfraProviderKind {+			return fmt.Errorf("%s is not supported with infrastructure provider 'kind'", flag.name)+		}+		if controlPlaneOnly {+			return fmt.Errorf("%s is not supported with --control-plane-only, since tptctl does not create the cluster", flag.name)+		} 	} -	if infraProvider == v0.KubernetesRuntimeInfraProviderKind {-		return errors.New("--k8s-api-allowed-cidrs is not supported with infrastructure provider 'kind'")-	}-	if controlPlaneOnly {-		return errors.New("--k8s-api-allowed-cidrs is not supported with --control-plane-only, since tptctl does not create the cluster")+	if privateApi && infraProvider != v0.KubernetesRuntimeInfraProviderGKE {+		return fmt.Errorf(+			"--private-k8s-api is supported only with infrastructure provider 'gke' for now, not %q - restrict the Kubernetes API with --k8s-api-allowed-cidrs instead",+			infraProvider,+		) 	} +	if len(cidrs) == 0 {+		return nil+	} 	if _, err := v0.ParseCidrs("--k8s-api-allowed-cidrs", allowedCidrsJSON(cidrs)); err != nil { 		return err 	}-	limit, _ := v0.AllowedCidrsLimit(infraProvider, false)+	limit, _ := v0.AllowedCidrsLimit(infraProvider, privateApi) 	if len(cidrs) > limit { 		return fmt.Errorf( 			"--k8s-api-allowed-cidrs has %d entries and %s admits at most %d",@@ -44,6 +62,17 @@ func ValidateK8sApiAllowedCidrsFlag(cidrs []string, infraProvider string, contro 	return nil } +// privateApiField returns a definition's PrivateApi for --private-k8s-api:+// set only when the flag is, so that a public cluster's definition is sent+// as it was before the flag existed.+func privateApiField(privateApi bool) *bool {+	if !privateApi {+		return nil+	}++	return &privateApi+}+ // allowedCidrsJSON returns cidrs as the JSON array the API stores, or nil // when there are none. func allowedCidrsJSON(cidrs []string) *datatypes.JSON {@@ -121,16 +150,17 @@ func withUnreachableClusterCleanup(err error, controlPlaneName string, teardownO // install uses: the one a prior run saved under the control plane's name, or // a new one when the cluster was provisioned outside of tptctl. //-// The cluster keeps the Kubernetes API allowlist it was created with, which-// --k8s-api-allowed-cidrs can't name on this path.  The saved list is put back-// in opts, so that the config entry keeps it and the kubernetes runtime-// definition records it.+// The cluster keeps the Kubernetes API access it was created with, which+// --private-k8s-api and --k8s-api-allowed-cidrs can't name on this path.  The+// saved access is put back in opts, so that the config entry keeps it and the+// kubernetes runtime definition records it. func reusedControlPlaneConfig(threeportConfig *ThreeportConfig, opts *threeport.Options) *ControlPlane { 	existingConfig, err := threeportConfig.GetControlPlaneConfig(opts.ControlPlaneName) 	if err != nil { 		return &ControlPlane{} 	} 	opts.K8sApiAllowedCidrs = existingConfig.K8sApiAllowedCidrs+	opts.PrivateK8sApi = existingConfig.PrivateK8sApi  	return existingConfig }
internal/provider/gke_cluster_connect.go+269 −0
@@ -0,0 +1,269 @@+package provider++import (+	"context"+	"fmt"++	container "cloud.google.com/go/container/apiv1"+	"cloud.google.com/go/container/apiv1/containerpb"+	cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v1"+	"google.golang.org/api/option"++	installer "github.com/threeport/threeport/pkg/threeport-installer/v0"+)++// The controllers of a control plane on GKE reach the GKE clusters it manages+// in the same project as their own Workload Identity principals, which+// Kubernetes RBAC on each cluster authorizes.  A private cluster is reached+// through its DNS endpoint, which also requires container.clusters.connect in+// IAM, so while the project holds a private cluster Threeport provisioned,+// the control plane's namespace holds a role with it on the project.  The+// role lets a caller see clusters and connect to them; what it may do inside+// a cluster is still RBAC's to decide.+//+// The grant is on the project because it cannot be narrowed to one cluster:+// GKE has no IAM policy of its own on a cluster, and a project binding whose+// IAM condition names the cluster by resource type and name did not let a+// caller connect to it, 17 minutes after it was made.+const (+	// gkeClusterConnectRole is the narrowest predefined role with+	// container.clusters.connect: that, container.clusters.get and list, and+	// reading the project.+	gkeClusterConnectRole = "roles/container.clusterViewer"++	// workloadIdentityNamespaceFormat is the Workload Identity Federation+	// principal set of every Kubernetes service account in one namespace, by+	// project number, project ID and namespace.  The pool is the project's,+	// so it holds that namespace on every cluster in the project.+	workloadIdentityNamespaceFormat = "principalSet://iam.googleapis.com/projects/%d/locations/global/workloadIdentityPools/%s.svc.id.goog/namespace/%s"+)++// controlPlaneConnectMember is the IAM member of the control plane's+// controllers in a project.+func controlPlaneConnectMember(projectNumber int64, projectID string) string {+	return fmt.Sprintf(workloadIdentityNamespaceFormat, projectNumber, projectID, installer.ControlPlaneNamespace)+}++// clusterConnectClientOptions authenticates as the runtime's own credentials+// when it has them, and as the process's otherwise.+func (i *KubernetesRuntimeInfraGKE) clusterConnectClientOptions(scope string) []option.ClientOption {+	clientOpts := []option.ClientOption{option.WithScopes(scope)}+	if i.ServiceAccountCredentials != "" {+		clientOpts = append(clientOpts, option.WithCredentialsJSON([]byte(i.ServiceAccountCredentials)))+	}++	return clientOpts+}++// clusterConnectPolicies returns the project policy store and the member the+// role is granted to.+func (i *KubernetesRuntimeInfraGKE) clusterConnectPolicies() (projectPolicies, string, error) {+	crmService, err := cloudresourcemanager.NewService(+		context.Background(),+		i.clusterConnectClientOptions(cloudresourcemanager.CloudPlatformScope)...,+	)+	if err != nil {+		return nil, "", fmt.Errorf("failed to create Cloud Resource Manager service client: %w", err)+	}+	projectNumber, err := i.projectNumber(crmService)+	if err != nil {+		return nil, "", err+	}++	return crmProjectPolicies{service: crmService}, controlPlaneConnectMember(projectNumber, i.ProjectID), nil+}++// grantControlPlaneClusterConnect lets the control plane's controllers reach+// a private cluster through its DNS endpoint.  A cluster with a public IP+// endpoint is reached there, without the IAM check, and grants nothing.  It+// is granted once the cluster, and with it the project's Workload Identity+// pool, exists.+func (i *KubernetesRuntimeInfraGKE) grantControlPlaneClusterConnect() error {+	if !i.PrivateApi {+		return nil+	}+	policies, member, err := i.clusterConnectPolicies()+	if err != nil {+		return err+	}++	return grantClusterConnect(policies, i.ProjectID, member)+}++// controlPlaneClusterConnectGranted reports whether the control plane's+// controllers hold the connect role a private cluster's create grants.  A+// cluster with a public IP endpoint needs none.+func (i *KubernetesRuntimeInfraGKE) controlPlaneClusterConnectGranted() (bool, error) {+	if !i.PrivateApi {+		return true, nil+	}+	policies, member, err := i.clusterConnectPolicies()+	if err != nil {+		return false, err+	}++	return clusterConnectGranted(policies, i.ProjectID, member)+}++// clusterConnectGranted reports whether member holds gkeClusterConnectRole on+// a project, as grantClusterConnect binds it: unconditionally.+func clusterConnectGranted(policies projectPolicies, projectID, member string) (bool, error) {+	policy, err := policies.get(projectID)+	if err != nil {+		return false, fmt.Errorf("failed to get the IAM policy of project %s: %w", projectID, err)+	}+	for _, binding := range policy.Bindings {+		if binding.Role != gkeClusterConnectRole || binding.Condition != nil {+			continue+		}+		for _, m := range binding.Members {+			if m == member {+				return true, nil+			}+		}+	}++	return false, nil+}++// revokeControlPlaneClusterConnect removes the control plane's connect role+// once the project holds no private cluster Threeport provisioned other than+// this one.  The member is the namespace on every cluster in the project, so+// it is shared by every control plane there that uses the same namespace.+func (i *KubernetesRuntimeInfraGKE) revokeControlPlaneClusterConnect() error {+	policies, member, err := i.clusterConnectPolicies()+	if err != nil {+		return err+	}+	listClusters := func() ([]*containerpb.Cluster, error) {+		ctx := context.Background()+		clusterManagerClient, err := container.NewClusterManagerClient(+			ctx,+			i.clusterConnectClientOptions(cloudresourcemanager.CloudPlatformScope)...,+		)+		if err != nil {+			return nil, fmt.Errorf("failed to create cluster manager client: %w", err)+		}+		defer clusterManagerClient.Close()++		response, err := clusterManagerClient.ListClusters(ctx, &containerpb.ListClustersRequest{+			Parent: fmt.Sprintf("projects/%s/locations/-", i.ProjectID),+		})+		if err != nil {+			return nil, fmt.Errorf("failed to list the project's GKE clusters: %w", err)+		}++		return completeClusterList(response)+	}++	return revokeClusterConnect(policies, i.ProjectID, member, listClusters, i.RuntimeInstanceName, i.Region)+}++// completeClusterList returns the clusters a listing found, or an error when+// GKE could not reach some of the project's locations: a cluster there would+// be missing from the list, and the role revoked from under it.+func completeClusterList(response *containerpb.ListClustersResponse) ([]*containerpb.Cluster, error) {+	if missing := response.GetMissingZones(); len(missing) > 0 {+		return nil, fmt.Errorf("GKE could not list the clusters in %v, so the control plane's connect role is kept until it can", missing)+	}++	return response.GetClusters(), nil+}++// grantClusterConnect binds member to gkeClusterConnectRole on a project.+//+// The policy is written even when member already holds the role.  A+// concurrent revoke decides from the clusters it lists after reading the+// policy, and the write changes the policy's etag, so a revoke that listed+// before this cluster existed fails on its stale etag and decides again, and+// one that lists after sees it.+func grantClusterConnect(policies projectPolicies, projectID, member string) error {+	if _, err := updateProjectPolicy(policies, projectID, isTransientIAMError, func(p *cloudresourcemanager.Policy) bool {+		addMemberToPolicy(p, member, []string{gkeClusterConnectRole})+		return true+	}); err != nil {+		return fmt.Errorf("failed to let the control plane connect to the project's private GKE clusters: %w", err)+	}++	return nil+}++// revokeClusterConnect removes member from gkeClusterConnectRole on a+// project, leaving any other role it holds, unless the project holds a+// private cluster Threeport provisioned other than the one named name in+// location.  The clusters are listed after each read of the policy, so the+// decision is made against the policy it is written to; see+// grantClusterConnect.+func revokeClusterConnect(+	policies projectPolicies,+	projectID, member string,+	listClusters func() ([]*containerpb.Cluster, error),+	name, location string,+) error {+	var listErr error+	if _, err := updateProjectPolicy(policies, projectID, isTransientIAMError, func(p *cloudresourcemanager.Policy) bool {+		if !removeMemberFromRole(p, member, gkeClusterConnectRole) {+			return false+		}+		clusters, err := listClusters()+		if err != nil {+			listErr = err+			return false+		}++		return !privateThreeportClusterOtherThan(clusters, name, location)+	}); err != nil {+		return fmt.Errorf("failed to remove the control plane's connect role from project %s: %w", projectID, err)+	}++	return listErr+}++// removeMemberFromRole drops member from role's unconditional binding, and+// the binding when no member is left, reporting whether the policy changed.+func removeMemberFromRole(policy *cloudresourcemanager.Policy, member, role string) bool {+	changed := false+	kept := make([]*cloudresourcemanager.Binding, 0, len(policy.Bindings))+	for _, binding := range policy.Bindings {+		if binding.Role == role && binding.Condition == nil {+			members := make([]string, 0, len(binding.Members))+			for _, m := range binding.Members {+				if m != member {+					members = append(members, m)+				}+			}+			if len(members) != len(binding.Members) {+				changed = true+				binding.Members = members+			}+			if len(binding.Members) == 0 {+				continue+			}+		}+		kept = append(kept, binding)+	}+	policy.Bindings = kept++	return changed+}++// privateThreeportClusterOtherThan reports whether clusters holds a private+// one Threeport provisioned other than the one named name in location.+// Clusters in different locations may share a name, so the location tells+// them apart.  A cluster still being created counts, as it may already be+// one whose create granted the role.+func privateThreeportClusterOtherThan(clusters []*containerpb.Cluster, name, location string) bool {+	for _, cluster := range clusters {+		if cluster.GetResourceLabels()[GcpLabelProvisionedBy] != GcpLabelProvisionedByValue {+			continue+		}+		if cluster.GetName() == name && cluster.GetLocation() == location {+			continue+		}+		if !gkeHasPublicIpEndpoint(cluster) {+			return true+		}+	}++	return false+}
internal/provider/gke_cluster_connect_test.go+253 −0
@@ -0,0 +1,253 @@+package provider++import (+	"context"+	"encoding/json"+	"errors"+	"net/http"+	"net/http/httptest"+	"testing"++	"cloud.google.com/go/container/apiv1/containerpb"+	"github.com/stretchr/testify/assert"+	"github.com/stretchr/testify/require"+	cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v1"+	"google.golang.org/api/option"+)++// gkeCluster is a cluster as GKE lists it: labelled as Threeport's or not,+// with a public IP endpoint or private.+func gkeCluster(name, location string, threeport, private bool) *containerpb.Cluster {+	labels := map[string]string{}+	if threeport {+		labels = GcpResourceLabels(name)+	}+	public := !private++	return &containerpb.Cluster{+		Name:           name,+		Location:       location,+		ResourceLabels: labels,+		ControlPlaneEndpointsConfig: &containerpb.ControlPlaneEndpointsConfig{+			IpEndpointsConfig: &containerpb.ControlPlaneEndpointsConfig_IPEndpointsConfig{EnablePublicEndpoint: &public},+		},+	}+}++// listing returns a cluster lister that answers with each of lists in turn,+// the last one from then on, and counts its calls.+func listing(calls *int, lists ...[]*containerpb.Cluster) func() ([]*containerpb.Cluster, error) {+	return func() ([]*containerpb.Cluster, error) {+		*calls+++		if *calls <= len(lists) {+			return lists[*calls-1], nil+		}+		return lists[len(lists)-1], nil+	}+}++// TestTheControlPlaneCanConnectToTheProjectsPrivateClusters covers the role+// that lets a control plane's controllers reach a private cluster's DNS+// endpoint: it is granted to every Kubernetes service account in the control+// plane's namespace, and removed from that role alone, leaving the+// namespace's other roles and the role's other members.+func TestTheControlPlaneCanConnectToTheProjectsPrivateClusters(t *testing.T) {+	withNoIAMRetryDelay(t)+	member := controlPlaneConnectMember(123456789, "proj")+	assert.Equal(t,+		"principalSet://iam.googleapis.com/projects/123456789/locations/global/workloadIdentityPools/proj.svc.id.goog/namespace/threeport-control-plane",+		member,+	)++	store := &fakePolicies{policy: policyWith(+		binding(gkeClusterConnectRole, "user:someone@example.com"),+		binding("roles/storage.objectViewer", member),+	)}+	require.NoError(t, grantClusterConnect(store, "proj", member))+	assert.ElementsMatch(t, []string{"user:someone@example.com", member}, store.policy.Bindings[0].Members)+	require.NoError(t, grantClusterConnect(store, "proj", member))+	assert.Equal(t, 2, store.sets, "a grant writes even when the member holds the role, so a concurrent revoke's etag goes stale")+	assert.ElementsMatch(t, []string{"user:someone@example.com", member}, store.policy.Bindings[0].Members, "and adds it once")++	calls := 0+	require.NoError(t, revokeClusterConnect(store, "proj", member, listing(&calls, nil), "going", "us-central1"))+	assert.Equal(t, []string{"user:someone@example.com"}, store.policy.Bindings[0].Members)+	assert.Equal(t, []string{member}, store.policy.Bindings[1].Members, "another role the namespace holds is kept")++	// a role left with no member is dropped+	alone := &fakePolicies{policy: policyWith(binding(gkeClusterConnectRole, member))}+	require.NoError(t, revokeClusterConnect(alone, "proj", member, listing(&calls, nil), "going", "us-central1"))+	assert.Empty(t, alone.policy.Bindings)++	// a binding of the role under a condition someone else made is theirs+	conditional := binding(gkeClusterConnectRole, member)+	conditional.Condition = &cloudresourcemanager.Expr{Expression: "request.time < timestamp('2030-01-01T00:00:00Z')"}+	theirs := &fakePolicies{policy: policyWith(conditional)}+	require.NoError(t, revokeClusterConnect(theirs, "proj", member, listing(&calls, nil), "going", "us-central1"))+	assert.Equal(t, []string{member}, theirs.policy.Bindings[0].Members)++	// with nothing to remove, the clusters are not listed and nothing is written+	calls, sets := 0, alone.sets+	require.NoError(t, revokeClusterConnect(alone, "proj", member, listing(&calls, nil), "going", "us-central1"))+	assert.Zero(t, calls)+	assert.Equal(t, sets, alone.sets)+}++// TestACreateIsCompleteOnceTheConnectRoleIsGranted covers the check that+// tells an interrupted create from a finished one: a private cluster's create+// is complete only once the control plane's namespace holds the role, as+// grantClusterConnect binds it, so a create stopped before the grant is run+// again.  A public cluster needs none.+func TestACreateIsCompleteOnceTheConnectRoleIsGranted(t *testing.T) {+	withNoIAMRetryDelay(t)+	member := controlPlaneConnectMember(1, "proj")+	store := &fakePolicies{policy: policyWith(+		binding("roles/storage.objectViewer", member),+		binding(gkeClusterConnectRole, "user:someone@example.com"),+	)}+	conditional := binding(gkeClusterConnectRole, member)+	conditional.Condition = &cloudresourcemanager.Expr{Expression: "request.time < timestamp('2030-01-01T00:00:00Z')"}+	store.policy.Bindings = append(store.policy.Bindings, conditional)++	granted, err := clusterConnectGranted(store, "proj", member)+	require.NoError(t, err)+	assert.False(t, granted, "another role, another member, or the role under a condition")++	require.NoError(t, grantClusterConnect(store, "proj", member))+	granted, err = clusterConnectGranted(store, "proj", member)+	require.NoError(t, err)+	assert.True(t, granted)++	store.getErrs = []error{errors.New("get failed")}+	_, err = clusterConnectGranted(store, "proj", member)+	require.ErrorContains(t, err, "get failed")++	public := &KubernetesRuntimeInfraGKE{ProjectID: "proj", ServiceAccountCredentials: "not json"}+	granted, err = public.controlPlaneClusterConnectGranted()+	require.NoError(t, err)+	assert.True(t, granted, "a public cluster is complete without it, and makes no client")+	public.PrivateApi = true+	_, err = public.controlPlaneClusterConnectGranted()+	require.Error(t, err, "a private cluster checks")+}++// TestAPublicClusterGrantsNoConnectRole covers which clusters are granted the+// role: a cluster with a public IP endpoint is reached there, so nothing is+// granted for it, nor any client made.+func TestAPublicClusterGrantsNoConnectRole(t *testing.T) {+	infra := &KubernetesRuntimeInfraGKE{+		ProjectID: "proj",+		Region:    "us-central1",+		// unusable credentials: any client made from them fails+		ServiceAccountCredentials: "not json",+	}+	require.NoError(t, infra.grantControlPlaneClusterConnect())++	infra.PrivateApi = true+	require.Error(t, infra.grantControlPlaneClusterConnect(), "a private cluster asks for the grant")+}++// TestTheConnectRoleStaysWhileAnotherPrivateThreeportClusterRemains covers+// when a teardown removes the role: the namespace is shared by every control+// plane in the project that uses it, so the role stays while the project+// holds a private cluster Threeport provisioned other than the one going.+func TestTheConnectRoleStaysWhileAnotherPrivateThreeportClusterRemains(t *testing.T) {+	assert.False(t, privateThreeportClusterOtherThan(nil, "going", "us-central1"))+	assert.False(t, privateThreeportClusterOtherThan([]*containerpb.Cluster{+		gkeCluster("going", "us-central1", true, true),+		gkeCluster("someone-elses", "us-central1", false, true),+		gkeCluster("public", "us-central1", true, false),+	}, "going", "us-central1"), "the one going, someone else's, and a public one")+	assert.True(t, privateThreeportClusterOtherThan([]*containerpb.Cluster{+		gkeCluster("going", "us-central1", true, true), gkeCluster("workload", "us-central1", true, true),+	}, "going", "us-central1"))+	assert.True(t, privateThreeportClusterOtherThan([]*containerpb.Cluster{+		gkeCluster("going", "us-central1", true, true), gkeCluster("going", "us-east1", true, true),+	}, "going", "us-central1"), "a cluster of the same name in another region")+	assert.True(t, privateThreeportClusterOtherThan([]*containerpb.Cluster{+		{Name: "older", Location: "us-central1", ResourceLabels: GcpResourceLabels("older"),+			PrivateClusterConfig: &containerpb.PrivateClusterConfig{EnablePrivateEndpoint: true}},+	}, "going", "us-central1"), "a private cluster from before the endpoints config")++	withNoIAMRetryDelay(t)+	member := controlPlaneConnectMember(1, "proj")+	store := &fakePolicies{policy: policyWith(binding(gkeClusterConnectRole, member))}+	calls := 0+	require.NoError(t, revokeClusterConnect(store, "proj", member, listing(&calls,+		[]*containerpb.Cluster{gkeCluster("workload", "us-central1", true, true)},+	), "going", "us-central1"))+	assert.Equal(t, []string{member}, store.policy.Bindings[0].Members)+	assert.Zero(t, store.sets)++	failing := func() ([]*containerpb.Cluster, error) { return nil, errors.New("list failed") }+	require.ErrorContains(t, revokeClusterConnect(store, "proj", member, failing, "going", "us-central1"), "list failed")+	assert.Equal(t, []string{member}, store.policy.Bindings[0].Members, "a failed listing removes nothing")+}++// TestAPartialClusterListingKeepsTheConnectRole covers a listing GKE could+// not complete: a location it could not reach may hold another private+// cluster, so the listing fails and the role is kept.+func TestAPartialClusterListingKeepsTheConnectRole(t *testing.T) {+	clusters := []*containerpb.Cluster{gkeCluster("public", "us-central1", true, false)}+	listed, err := completeClusterList(&containerpb.ListClustersResponse{Clusters: clusters})+	require.NoError(t, err)+	assert.Equal(t, clusters, listed)++	_, err = completeClusterList(&containerpb.ListClustersResponse{Clusters: clusters, MissingZones: []string{"us-east1"}})+	require.ErrorContains(t, err, "us-east1")+}++// TestARevokeDecidesAgainWhenACreateGrantsMeanwhile covers a teardown that+// overlaps a create in the same project: the create's grant is written after+// the revoke read the policy and listed the clusters, before the revoke wrote+// it.  The revoke's write is refused on its stale etag, and it reads and+// lists again, finding the new private cluster, so it keeps the role.+func TestARevokeDecidesAgainWhenACreateGrantsMeanwhile(t *testing.T) {+	withNoIAMRetryDelay(t)+	member := controlPlaneConnectMember(1, "proj")+	store := &fakePolicies{+		policy:   policyWith(binding(gkeClusterConnectRole, member)),+		conflict: 1,+	}+	calls := 0+	require.NoError(t, revokeClusterConnect(store, "proj", member, listing(&calls,+		nil,+		[]*containerpb.Cluster{gkeCluster("new", "us-central1", true, true)},+	), "going", "us-central1"))+	assert.Equal(t, 2, calls, "the clusters are listed again after the conflict")+	assert.Equal(t, []string{member}, store.policy.Bindings[0].Members)+}++// TestProjectPoliciesAreReadAndWrittenWithTheirConditions covers the version+// a project policy is read and written at: one that carries conditional+// bindings, so a project holding any is written back with its conditions+// rather than refused.+func TestProjectPoliciesAreReadAndWrittenWithTheirConditions(t *testing.T) {+	var requested, written int64+	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+		switch r.URL.Path {+		case "/v1/projects/proj:getIamPolicy":+			var request cloudresourcemanager.GetIamPolicyRequest+			require.NoError(t, json.NewDecoder(r.Body).Decode(&request))+			if request.Options != nil {+				requested = request.Options.RequestedPolicyVersion+			}+			// a policy with no condition is version 1, whatever is asked+			require.NoError(t, json.NewEncoder(w).Encode(&cloudresourcemanager.Policy{Version: 1}))+		case "/v1/projects/proj:setIamPolicy":+			var request cloudresourcemanager.SetIamPolicyRequest+			require.NoError(t, json.NewDecoder(r.Body).Decode(&request))+			written = request.Policy.Version+			require.NoError(t, json.NewEncoder(w).Encode(request.Policy))+		default:+			w.WriteHeader(http.StatusNotImplemented)+		}+	}))+	t.Cleanup(server.Close)+	service, err := cloudresourcemanager.NewService(context.Background(), option.WithEndpoint(server.URL+"/"), option.WithoutAuthentication())+	require.NoError(t, err)++	require.NoError(t, grantClusterConnect(crmProjectPolicies{service: service}, "proj", "principalSet://member"))+	assert.Equal(t, int64(conditionalPolicyVersion), requested)+	assert.Equal(t, int64(conditionalPolicyVersion), written)+}

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Failure HandlingRemoval of direct error check `checkKubeApiAllowlist(...)` in favor of `i.kubeApiAllowlist()` may bypass validation of AllowedCidrs and ControlPlaneEgressCidrs, risking acceptance of invalid configurations in private cluster setups.

    Recorded file internal/provider/gke.go · no line recorded

  • Observation · Dependency blast radiusThe change adds a new field PrivateK8sApi to the KubernetesRuntimeDefinition API with a modified description that raises the minimum supported GKE version and clarifies post-creation immutability, which could break clients that strictly expect the previous immutable behavior and older GKE versions.

    Recorded location pkg/api/v0/kubernetes_runtime.go:9

Supporting evidence

Reviewed 29 Nov 2026Revision d910ef3276fe28 changed files+1386 −105Judge score 5/5
Approved · 0 retained findingswikimedia/apps-android-wikipedia#2031Review permalink

Update list of third-party channels.

Input

PR diff

Current GitHub diff ↗
build-all.sh · patch excerpt
+make-release --channel huawei
Browse 1 changed file
build-all.sh+1 −0
@@ -8,3 +8,4 @@ make-release --beta make-release --prod make-release --channel amazon make-release --channel samsung+make-release --channel huawei

→ Outcome

Why this verdict

The available evidence did not establish a defect introduced by this change.

Supporting evidence

Reviewed 29 Nov 2026Revision 9a18873270a51 changed file+1 −0Judge score 5/5
Approved · 0 retained findingsthreeport/threeport#786Review permalink

feat: upgrade EKS and GKE clusters when their definition's Kubernetes version changes

Input

PR author’s description

Part of #732. This is the third part the issue suggests, the update path, for EKS and GKE. Two follow-ups finish the issue: EKS's vpc-cni, coredns and kube-proxy as managed add-ons upgraded with the cluster, then…

PR diff

Current GitHub diff ↗
cmd/database-migrator/migrations/000006_cluster_upgrades.go · patch excerpt
+package migrations++import (+	"context"
Browse 30 changed files
cmd/database-migrator/migrations/000006_cluster_upgrades.go+66 −0
@@ -0,0 +1,66 @@+package migrations++import (+	"context"+	"database/sql"+	"fmt"++	goose "github.com/pressly/goose/v3"+)++// init registers the migration with goose at startup.+func init() {+	goose.AddMigrationNoTxContext(Up000006, Down000006)+}++// clusterUpgradeTables are the EKS and GKE kubernetes runtime instance tables+// that record a cluster's version and its upgrades.+var clusterUpgradeTables = []string{+	"v0_aws_eks_kubernetes_runtime_instances",+	"v0_gcp_gke_kubernetes_runtime_instances",+}++// clusterUpgradeColumns are the columns of an instance's version and+// upgrades, with their types.+var clusterUpgradeColumns = [][2]string{+	{"kubernetes_version", "STRING"},+	{"upgrade_requested_version", "STRING"},+	{"upgrade_acknowledged", "TIMESTAMPTZ"},+	{"upgrading", "BOOL DEFAULT false"},+	{"upgrade_failed", "BOOL DEFAULT false"},+	{"upgrade_refused", "BOOL DEFAULT false"},+	{"upgrade_status", "STRING"},+}++// Up000006 adds an EKS or GKE instance's version and upgrade state.  An+// instance already there has no version until its controller reads it from+// the provider, and isn't upgrading.  000001 builds its tables from the+// current models, so a database it created after the fields were added has+// them already, and each is added only where it is missing.+func Up000006(ctx context.Context, db *sql.DB) error {+	for _, table := range clusterUpgradeTables {+		for _, column := range clusterUpgradeColumns {+			statement := fmt.Sprintf("ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s", table, column[0], column[1])+			if _, err := db.ExecContext(ctx, statement); err != nil {+				return fmt.Errorf("failed to run %q: %w", statement, err)+			}+		}+	}++	return nil+}++// Down000006 removes each column that is there, so it also cleans up after+// Up000006 failing part way.+func Down000006(ctx context.Context, db *sql.DB) error {+	for _, table := range clusterUpgradeTables {+		for _, column := range clusterUpgradeColumns {+			statement := fmt.Sprintf("ALTER TABLE %s DROP COLUMN IF EXISTS %s", table, column[0])+			if _, err := db.ExecContext(ctx, statement); err != nil {+				return fmt.Errorf("failed to run %q: %w", statement, err)+			}+		}+	}++	return nil+}
internal/provider/upgrade_test.go+534 −0
internal/provider/upgrade.go+494 −0

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · TestingThe `GetUpgrade` method, a new interface method for the EKS provider, is not tested. A unit test is required to verify the state retrieval and error handling.

    Principle · Verify New and Changed Behaviour

    Recorded location internal/aws/eks_lifecycle.go:432

  • Observation · TestingThe `GetUpgrade` method, a new interface method for the GKE provider, is not tested. A unit test is required to verify the state retrieval and error handling.

    Principle · Verify New and Changed Behaviour

    Recorded location internal/gcp/gke_lifecycle.go:566

Supporting evidence

Reviewed 29 Nov 2026Revision 53c5936a15c930 changed files+3131 −77Judge score 5/5
AboutReview principlesSupportPrivacyContact
(C) 2026 Superpositional>
Member of the NVIDIA Inception Program