Superpositional
AboutReview principlesPricingBlogGalleryAsk a RepoFAQ…

Real reviews of open-source pull requests

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

1 of 13, clap-rs/clap#6492
Ask this repo
Approved · 0 retained findingsclap-rs/clap#6492

docs: Scrape the git example

Input

PR author’s description

What does this PR try to solve?

examples/git.rs is the only example without an [[example]] entry in Cargo.toml. Cargo still auto-discovers it, so it builds and examples/git.md still runs under trycmd, which…

PR diff

Current GitHub diff ↗
Cargo.toml · patch excerpt
+[[example]]+name = "git"+doc-scrape-examples = true+
Browse 1 changed file
Cargo.toml+4 −0
@@ -230,6 +230,10 @@ name = "find" required-features = ["cargo"] doc-scrape-examples = true +[[example]]+name = "git"+doc-scrape-examples = true+ [[example]] name = "git-derive" required-features = ["derive"]

→ Outcome

Why this verdict

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

Supporting evidence

Reviewed 27 Nov 2026Revision f1ac0115624f1 changed file+4 −0Judge score 5/5
Approved · 0 retained findingsdrizzle-team/drizzle-orm#6595

Cancel queries only on pooled connections in Drizzle Postgres

Input

PR author’s description

The protocol accepts a CancelRequest only as the first packet of a new connection. A pool already owns its connections, so only a pooled connection cancels queries. A single connection from connect() offers no cancel…

PR diff

Current GitHub diff ↗
postgres/test/unit/cancellation.test.ts · patch excerpt
-import { connect } from '../../src/index.ts';+import net from 'node:net';+import os from 'node:os';+import { Duplex } from 'node:stream';
Browse 26 changed files
postgres/test/unit/cancellation.test.ts+207 −6
@@ -1,7 +1,13 @@ // Query cancellation (timeout + AbortSignal -> out-of-band CancelRequest), driven // against the MockPgServer — deterministic, no real PostgreSQL. import { describe, expect, test } from 'bun:test';-import { connect } from '../../src/index.ts';+import net from 'node:net';+import os from 'node:os';+import { Duplex } from 'node:stream';+import { connect, createPool, type Transport } from '../../src/index.ts';+import { nodeCancel, nodeTransport } from '../../src/transport-node.ts';+import { sendCancelRequest } from '../../src/webstream.ts';+import { acquireFromOwnPool } from '../helpers/db.ts'; import { MockPgServer } from '../mock/server.ts';  const OK = () => ({ fields: [{ name: 'n', oid: 23 }], rows: [['1']] as string[][], command: 'SELECT' });@@ -14,11 +20,13 @@ async function withMock<T>(fn: (m: MockPgServer) => Promise<T>): Promise<T> { 		await m.close(); 	} }+const pooledConnection = (m: MockPgServer) => acquireFromOwnPool(createPool(m.connectConfig({ max: 1 })));+const hasIpv6Loopback = Object.values(os.networkInterfaces()).flat().some((i) => i?.address === '::1');  describe('per-query timeout', () => { 	test('a hung query times out, sends ONE CancelRequest, and the connection recovers', async () => { 		await withMock(async (m) => {-			const c = await connect(m.connectConfig());+			const c = await pooledConnection(m); 			m.setMode('hang'); 			const err = await c.query('select 1', [], { timeout: 80 }).catch((e) => e); 			expect((err as { code?: string }).code).toBe('QUERY_TIMEOUT');@@ -32,7 +40,7 @@ describe('per-query timeout', () => {  	test('a fast query under the timeout is never cancelled', async () => { 		await withMock(async (m) => {-			const c = await connect(m.connectConfig());+			const c = await pooledConnection(m); 			expect((await c.query('select 1', [], { timeout: 1000 })).rows.length).toBe(1); 			await tick(30); 			expect(m.cancelRequests).toBe(0);@@ -44,7 +52,7 @@ describe('per-query timeout', () => { describe('AbortSignal', () => { 	test('aborting an in-flight query rejects it and sends a CancelRequest', async () => { 		await withMock(async (m) => {-			const c = await connect(m.connectConfig());+			const c = await pooledConnection(m); 			m.setMode('hang'); 			const ac = new AbortController(); 			const p = c.query('select 1', [], { signal: ac.signal }).catch((e) => e);@@ -61,7 +69,7 @@ describe('AbortSignal', () => {  	test('an already-aborted signal rejects immediately and never hits the wire', async () => { 		await withMock(async (m) => {-			const c = await connect(m.connectConfig());+			const c = await pooledConnection(m); 			const ac = new AbortController(); 			ac.abort(); 			expect(await c.query('select 1', [], { signal: ac.signal }).catch((e) => e)).toBeInstanceOf(Error);@@ -72,7 +80,7 @@ describe('AbortSignal', () => {  	test('aborting a QUEUED query drops it without a CancelRequest', async () => { 		await withMock(async (m) => {-			const c = await connect(m.connectConfig());+			const c = await pooledConnection(m); 			m.setMode('hang'); 			const first = c.query('select 1').catch((e) => e); // occupies the connection 			await tick(20);@@ -87,6 +95,199 @@ describe('AbortSignal', () => { 	}, 10000); }); +describe('the cancel connection', () => {+	// The host name does not resolve, so the cancel reaches the mock only through the IP address of the session.+	test('dials the IP address of the session, not the host name', async () => {+		await withMock(async (m) => {+			const transport: Transport = {+				connect: (target, signal) => nodeTransport({ ...target, host: '127.0.0.1' }, signal),+				cancel: nodeCancel,+			};+			const pool = createPool(m.connectConfig({ max: 1, host: 'db.invalid', transport }));+			try {+				m.setMode('hang');+				const err = await pool.query('select 1', [], { timeout: 50 }).then(() => null, (e) => e);+				expect((err as { code?: string }).code).toBe('QUERY_TIMEOUT');+				await tick(100);+				expect(m.cancelRequests).toBe(1);+			} finally {+				await pool.end();+			}+		});+	});++	// The proxy listens on ::1 and the mock on 127.0.0.1 only, so a cancel that dials the peer of the+	// socket finds no server.+	test.skipIf(!hasIpv6Loopback)('dials the host when a socket factory opened the session', async () => {+		await withMock(async (m) => {+			const proxy = net.createServer((client) => {+				const server = net.connect(m.port, '127.0.0.1');+				client.on('error', () => server.destroy());+				server.on('error', () => client.destroy());+				client.pipe(server).pipe(client);+			});+			await new Promise<void>((resolve) => proxy.listen(0, '::1', resolve));+			const proxyPort = (proxy.address() as net.AddressInfo).port;+			const pool = createPool(m.connectConfig({ max: 1, socket: () => net.connect(proxyPort, '::1') }));+			try {+				m.setMode('hang');+				const err = await pool.query('select 1', [], { timeout: 50 }).then(() => null, (e) => e);+				expect((err as { code?: string }).code).toBe('QUERY_TIMEOUT');+				await tick(100);+				expect(m.cancelRequests).toBe(1);+			} finally {+				await pool.end();+				proxy.close();+			}+		});+	});+});++describe('a query that has ended', () => {+	test('gets no CancelRequest, and the connection stays in use', async () => {+		await withMock(async (m) => {+			let openCancel!: () => void;+			const isCancelHeld = new Promise<void>((resolve) => {+				openCancel = resolve;+			});+			// The real cancel waits until the query has ended. A real network cannot be timed that precisely.+			const transport: Transport = {+				connect: nodeTransport,+				cancel: async (target, key, isQueryRunning) => {+					await isCancelHeld;+					await nodeCancel(target, key, isQueryRunning);+				},+			};+			// Behind a pooler, a cancel that was sent retires the connection. Reuse shows that nothing was sent.+			const c = await acquireFromOwnPool(createPool(m.connectConfig({ max: 1, pooler: true, transport })));+			try {+				m.setMode('hang');+				const err = await c.query('select 1', [], { timeout: 50 }).then(() => null, (e) => e);+				expect((err as { code?: string }).code).toBe('QUERY_TIMEOUT');+				m.setMode('normal');+				m.finishHung();+				await tick();+				openCancel();+				await tick(50);+				expect(m.cancelRequests).toBe(0);+				expect(c.cancelSettled).toBeUndefined();+				expect((await c.query('select 1')).rows).toEqual([[1]] as never);+			} finally {+				await c.end();+			}+		});+	});++	test('nodeCancel writes a CancelRequest only while the query runs', async () => {+		await withMock(async (m) => {+			const target = {+				...m.connectConfig(),+				host: '127.0.0.1',+				port: m.port,+				ssl: false as const,+				connectTimeout: 1000,+			};+			await nodeCancel(target, { pid: 1, secret: 1 }, () => false);+			await nodeCancel(target, { pid: 1, secret: 1 }, () => true);+			await tick();+			expect(m.cancelRequests).toBe(1);+			expect(m.connectAttempts).toBe(2);+		});+	});++	test('sendCancelRequest writes a CancelRequest only while the query runs', async () => {+		await withMock(async (m) => {+			const send = async (isQueryRunning: () => boolean) => {+				const socket = net.connect(m.port, '127.0.0.1');+				await new Promise((resolve) => socket.once('connect', resolve));+				const { readable, writable } = Duplex.toWeb(socket);+				try {+					await sendCancelRequest(readable, writable, { pid: 1, secret: 1 }, isQueryRunning);+				} finally {+					socket.destroy();+				}+			};+			await send(() => false);+			await send(() => true);+			await tick();+			expect(m.cancelRequests).toBe(1);+			expect(m.connectAttempts).toBe(2);+		});+	});+});++describe('a single connection', () => {+	test('rejects a query with timeout or signal before anything is sent', async () => {+		let queries = 0;+		const m = await MockPgServer.start({+			onQuery: () => {+				queries++;+				return OK();+			},+		});+		try {+			const c = await connect(m.connectConfig());+			const signal = new AbortController().signal;+			const columns = { id: 'int4', n: 'int4' } as const;+			const rows = [[1, 1], [2, 2]];+			const results = await Promise.all([+				c.query('select 1', [], { timeout: 1000 } as never).catch((e) => e),+				c.query('select 1', [], { signal } as never).catch((e) => e),+				c.query('select 1', [], { snapshot: '00000003-1', timeout: 1000 } as never).catch((e) => e),+				c.queryTyped('select 1', [], [], { signal } as never).catch((e) => e),+				c.bulkInsert('t', columns, rows, { chunk: 1, timeout: 1000 } as never).catch((e) => e),+				c.bulkUpdate('t', columns, rows, { by: 'id', chunk: 1, signal } as never).catch((e) => e),+				c.copyFrom('copy t from stdin', [], { timeout: 1000 } as never).catch((e) => e),+				c.copyMany('t', columns, rows, { chunk: 1, signal } as never).catch((e) => e),+				c.stream('select 1', [], { timeout: 1000 } as never).next().catch((e) => e),+				c.copyTo('copy t to stdout', { signal } as never).next().catch((e) => e),+			]);+			for (const err of results as Error[]) {+				expect((err as { code?: string }).code).toBe('CANCEL_NEEDS_POOL');+				expect(err.message).toBe(+					'Canceling a query needs a pooled connection. Create the connection with createPool, or remove timeout and signal.',+				);+			}+			expect(queries).toBe(0);+			await c.end();+		} finally {+			await m.close();+		}+	});++	test('an early close of stream() reads and drops the rest of the result', async () => {+		await withMock(async (m) => {+			const c = await connect(m.connectConfig());+			m.setMode('hang');+			const it = c.stream('select 1');+			await tick();+			await it.return!();+			await tick();+			expect(m.cancelRequests).toBe(0);+			m.setMode('normal');+			m.finishHung();+			expect((await c.query('select 1')).rows).toEqual([[1]] as never);+			await c.end();+		});+	});++	test('an early close of copyTo() reads and drops the rest of the result', async () => {+		await withMock(async (m) => {+			const c = await connect(m.connectConfig());+			m.setMode('hang');+			const it = c.copyTo('copy t to stdout');+			await tick();+			await it.return!();+			await tick();+			expect(m.cancelRequests).toBe(0);+			m.setMode('normal');+			m.finishHung();+			expect((await c.query('select 1')).rows).toEqual([[1]] as never);+			await c.end();+		});+	});+});+ describe('stream early close', () => { 	// A real server ignores a cancel that reaches an idle backend, so only the mock can see a needless one. 	test('a stream that is read to the end sends no CancelRequest', async () => {
postgres/src/connection.ts+99 −59
postgres/test/types/cancel-options.ts+62 −0
@@ -0,0 +1,62 @@+// Type checks for timeout and signal. `bun run typecheck` fails when an expectation breaks.+// Nothing here runs.+import { connect, type Connection, createPool } from '../../src/index.ts';++const signal = new AbortController().signal;+const columns = { id: 'int4' } as const;++export async function singleConnectionRejectsCancelOptions() {+	const single = await connect();+	// @ts-expect-error canceling needs a pooled connection+	await single.query('select 1', [], { timeout: 1 });+	// @ts-expect-error canceling needs a pooled connection+	await single.query('select 1', [], { signal });+	// @ts-expect-error canceling needs a pooled connection+	await single.query('select 1', [], { mode: 'object', timeout: 1 });+	// @ts-expect-error canceling needs a pooled connection+	await single.queryTyped('select 1', [], [], { signal });+	// @ts-expect-error canceling needs a pooled connection+	await single.bulkInsert('t', columns, [[1]], { timeout: 1 });+	// @ts-expect-error canceling needs a pooled connection+	await single.bulkUpdate('t', columns, [[1]], { by: 'id', signal });+	// @ts-expect-error canceling needs a pooled connection+	await single.copyFrom('copy t from stdin', [], { timeout: 1 });+	// @ts-expect-error canceling needs a pooled connection+	await single.copyMany('t', columns, [[1]], { signal });+	// @ts-expect-error canceling needs a pooled connection+	single.stream('select 1', [], { timeout: 1 });+	// @ts-expect-error canceling needs a pooled connection+	single.copyTo('copy t to stdout', { signal });+	await single.transaction(async (tx) => {+		// @ts-expect-error a transaction on a single connection cannot cancel either+		await tx.query('select 1', [], { timeout: 1 });+	});+	await single.query('select 1', [], { mode: 'object' });+}++export async function pooledConnectionAcceptsCancelOptions() {+	const pool = createPool();+	const pooled = await pool.acquire();+	await pooled.query('select 1', [], { timeout: 1, signal });+	await pooled.query('select 1', [], { mode: 'object', timeout: 1 });+	await pooled.queryTyped('select 1', [], [], { signal });+	await pooled.bulkInsert('t', columns, [[1]], { timeout: 1 });+	await pooled.bulkUpdate('t', columns, [[1]], { by: 'id', signal });+	await pooled.copyFrom('copy t from stdin', [], { timeout: 1 });+	await pooled.copyMany('t', columns, [[1]], { signal });+	pooled.stream('select 1', [], { timeout: 1 });+	pooled.copyTo('copy t to stdout', { signal });+	const { client } = await pool.connect();+	await client.query('select 1', [], { timeout: 1 });+	await pool.transaction(async (tx) => {+		await tx.query('select 1', [], { signal });+		await tx.transaction(async (nested) => nested.query('select 1', [], { timeout: 1 }));+	});+	await pool.query('select 1', [], { timeout: 1 });+}++export async function plainConnectionAcceptsBoth() {+	const pool = createPool();+	const connections: Connection[] = [await connect(), await pool.acquire()];+	await connections[0]!.query('select 1', [], { timeout: 1, signal });+}

→ Outcome

Why this verdict

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

Supporting evidence

Reviewed 27 Nov 2026Revision f59ef8e8ff8326 changed files+642 −117Judge score 5/5
Approved · 0 retained findingsmicrosoft/markitdown#1510

Perf: Optimize non-seekable stream buffering using shutil.copyfileobj

Input

PR author’s description

Objective

Optimize buffering of non-seekable streams by replacing the manual chunk reading loop with shutil.copyfileobj(). The proposed method is more memory efficient with fewer buffer reallocations, all while…

PR diff

Current GitHub diff ↗
packages/markitdown/src/markitdown/_markitdown.py · patch excerpt
-            while True:-                chunk = stream.read(4096)-                if not chunk:-                    break
Browse 1 changed file
packages/markitdown/src/markitdown/_markitdown.py+1 −5
@@ -435,11 +435,7 @@ def convert_stream(         # Check if we have a seekable stream. If not, load the entire stream into memory.         if not stream.seekable():             buffer = io.BytesIO()-            while True:-                chunk = stream.read(4096)-                if not chunk:-                    break-                buffer.write(chunk)+            shutil.copyfileobj(stream, buffer)             buffer.seek(0)             stream = buffer 

→ Outcome

Why this verdict

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

The recorded observation did not become a verified finding.

Evidence and perspectives

  • Observation · Historical riskThe executed code at lines 438-442 before this change reads data in a byte-by-byte loop using 'if not chunk: break' and writes each chunk to buffer, which is effectively a broken read pattern that can exhaust input stream file descriptors. This mirrors a known defect pattern where reading until EOF without advancing seeks can block indefinitely; the replacement 'shutil.copyfileobj(stream, buffer)' in the new code correctly transfers chunks without reading until EOF, addressing a historical hazard that can cause hangs with seekable streams.

    Recorded location packages/markitdown/src/markitdown/_markitdown.py:447

Supporting evidence

Reviewed 27 Nov 2026Revision 10832de75fef1 changed file+1 −5Judge score 5/5
Approved · 0 retained findingsgithub/github-mcp-server#1652

Add aliases for new actions tools

Input

PR author’s description

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

Summary

<!-- In 1–2 sentences: what does this PR do? -->

PR diff

Current GitHub diff ↗
docs/tool-renaming.md · patch excerpt
-| *(none currently)* | |+| `cancel_workflow_run` | `actions_run_trigger` |+| `delete_workflow_run_logs` | `actions_run_trigger` |+| `download_workflow_run_artifact` | `actions_get` |
Browse 2 changed files
docs/tool-renaming.md+16 −1
@@ -46,5 +46,20 @@ Will get `issue_read` and `get_file_contents` tools registered, with no errors. <!-- START AUTOMATED ALIASES --> | Old Name | New Name | |----------|----------|-| *(none currently)* | |+| `cancel_workflow_run` | `actions_run_trigger` |+| `delete_workflow_run_logs` | `actions_run_trigger` |+| `download_workflow_run_artifact` | `actions_get` |+| `get_workflow` | `actions_get` |+| `get_workflow_job` | `actions_get` |+| `get_workflow_job_logs` | `actions_get` |+| `get_workflow_run` | `actions_get` |+| `get_workflow_run_logs` | `actions_get` |+| `get_workflow_run_usage` | `actions_get` |+| `list_workflow_jobs` | `actions_list` |+| `list_workflow_run_artifacts` | `actions_list` |+| `list_workflow_runs` | `actions_list` |+| `list_workflows` | `actions_list` |+| `rerun_failed_jobs` | `actions_run_trigger` |+| `rerun_workflow_run` | `actions_run_trigger` |+| `run_workflow` | `actions_run_trigger` | <!-- END AUTOMATED ALIASES -->
pkg/github/deprecated_tool_aliases.go+17 −0
@@ -11,4 +11,21 @@ package github //	"create_pr": "pull_request_create", var DeprecatedToolAliases = map[string]string{ 	// Add entries as tools are renamed+	// Actions tools consolidated+	"list_workflows":                 "actions_list",+	"list_workflow_runs":             "actions_list",+	"list_workflow_jobs":             "actions_list",+	"list_workflow_run_artifacts":    "actions_list",+	"get_workflow":                   "actions_get",+	"get_workflow_run":               "actions_get",+	"get_workflow_job":               "actions_get",+	"get_workflow_run_usage":         "actions_get",+	"get_workflow_run_logs":          "actions_get",+	"get_workflow_job_logs":          "actions_get",+	"download_workflow_run_artifact": "actions_get",+	"run_workflow":                   "actions_run_trigger",+	"rerun_workflow_run":             "actions_run_trigger",+	"rerun_failed_jobs":              "actions_run_trigger",+	"cancel_workflow_run":            "actions_run_trigger",+	"delete_workflow_run_logs":       "actions_run_trigger", }

→ Outcome

Why this verdict

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

The recorded observation did not become a verified finding.

Evidence and perspectives

  • Observation · Historical riskThe deprecated_tool_aliases.go file has not previously changed, indicating it is a new addition to support this tool renaming effort.

    Recorded location docs/tool-renaming.md:25

Supporting evidence

Reviewed 27 Nov 2026Revision d8333517295d2 changed files+33 −1Judge score 5/5
Approved · 0 retained findingsclap-rs/clap#6498

chore(deps): Update Rust Stable to v1.98

Input

PR author’s description

This PR contains the following updates:

PackageUpdateChange
STABLEminor1.97 → 1.98

Release Notes

PR diff

Current GitHub diff ↗
.github/workflows/ci.yml · patch excerpt
-        toolchain: "1.97"  # STABLE+        toolchain: "1.98"  # STABLE
Browse 3 changed files
.github/workflows/ci.yml+4 −4
@@ -167,7 +167,7 @@ jobs:     - name: Install Rust       uses: dtolnay/rust-toolchain@stable       with:-        toolchain: "1.97"  # STABLE+        toolchain: "1.98"  # STABLE     - uses: Swatinem/rust-cache@v2     - name: UI Tests       run: make test-ui-${{ matrix.features }}@@ -213,7 +213,7 @@ jobs:     - name: Install Rust       uses: dtolnay/rust-toolchain@stable       with:-        toolchain: "1.97"  # STABLE+        toolchain: "1.98"  # STABLE     - uses: Swatinem/rust-cache@v2     - name: Check documentation       env:@@ -228,7 +228,7 @@ jobs:     - name: Install Rust       uses: dtolnay/rust-toolchain@stable       with:-        toolchain: "1.97"  # STABLE+        toolchain: "1.98"  # STABLE         components: rustfmt     - uses: Swatinem/rust-cache@v2     - name: Check formatting@@ -242,7 +242,7 @@ jobs:     - name: Install Rust       uses: dtolnay/rust-toolchain@stable       with:-        toolchain: "1.97"  # STABLE+        toolchain: "1.98"  # STABLE         components: clippy     - uses: Swatinem/rust-cache@v2     - name: Lint (ultra-minimal)
Makefile+1 −1
@@ -10,7 +10,7 @@ ifneq (${TOOLCHAIN_TARGET},)   ARGS+=--target ${TOOLCHAIN_TARGET} endif -STABLE?=1.97+STABLE?=1.98  _FEATURES = minimal default wasm full debug release _FEATURES_minimal = --no-default-features --features "std"
tests/derive_ui.rs+1 −1
@@ -8,7 +8,7 @@ #![cfg(feature = "unstable-derive-ui-tests")]  #[cfg(feature = "derive")]-#[rustversion::attr(not(stable(1.97)), ignore)] // STABLE+#[rustversion::attr(not(stable(1.98)), ignore)] // STABLE #[test] fn ui() {     let t = trybuild::TestCases::new();

→ Outcome

Why this verdict

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

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Test strategyThe UI test `ui` in `tests/derive_ui.rs` now requires Rust 1.98 via `#[rustversion::attr(not(stable(1.98)), ignore)]`, but the CI workflow still configures each job with `toolchain: '1.98'` via `rust-toolchain@stable`, which can disable the test if any of the jobs default to a different version. No explicit test is written to verify that the UI test framework or command line responds correctly to the updated toolchain and feature configurations, leaving the UI change under-verified.

    Recorded location tests/derive_ui.rs:12

  • Observation · Architectural coherenceThe change updates the Rust stable toolchain version from 1.97 to 1.98 in three workflow jobs and the Makefile default, and simultaneously updates the #[rustversion::attr] gate in tests/derive_ui.rs to exclude version 1.98, causing the UI tests to skip on 1.98 because the gate evaluates to true (not(stable(1.98))) when the condition is not stably supported at 1.98.

    Recorded file .github/workflows/ci.yml · no line recorded

Supporting evidence

Reviewed 27 Nov 2026Revision 86f8be7bcd883 changed files+6 −6Judge score 5/5
Approved · 0 retained findingsserde-rs/serde#2950

Fix temporary value lifetime in `serialize_struct`

Input

PR author’s description

In the 2024 edition of Rust, serde's macros for serialize_with can lead to a temporary lifetime error such as:

PR diff

Current GitHub diff ↗
serde_derive/src/ser.rs · patch excerpt
-    quote!({+    quote!(&{
Browse 1 changed file
serde_derive/src/ser.rs+2 −2
@@ -1235,7 +1235,7 @@ fn wrap_serialize_with(         #serialize_with(#(#self_var.values.#field_access, )* #serializer_var)     }; -    quote!({+    quote!(&{         #[doc(hidden)]         struct __SerializeWith #wrapper_impl_generics #where_clause {             values: (#(&'__a #field_tys, )*),@@ -1252,7 +1252,7 @@ fn wrap_serialize_with(             }         } -        &__SerializeWith {+        __SerializeWith {             values: (#(#field_exprs, )*),             phantom: _serde::__private::PhantomData::<#this_type #ty_generics>,         }

→ Outcome

Why this verdict

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

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Historical riskThe changed code in the wrap_serialize_with function removes a reference binding that was used by a newly generated struct instance, potentially increasing dereference operations and risk of complexity bugs in generated serialization code.

    Recorded location serde_derive/src/ser.rs:1203

  • Observation · Change qualityThe change removes a const reference prefix from two generated struct definitions within the same function, which simultaneously affects the serialization implementation and the generated code's semantics.

    Recorded location serde_derive/src/ser.rs:1203

Supporting evidence

Reviewed 27 Nov 2026Revision 106da4905fe41 changed file+2 −2Judge score 5/5
Approved · 0 retained findingsdrizzle-team/drizzle-orm#6631

Run the import checks in a pool with one process per CPU

Input

PR author’s description

int:imports failed on #6629 because two runs of "dynamic imports check for CommonJS chunk" hit the 5s limit per process. The CommonJS chunks ran as it.concurrent tests, so up to 5 chunks of 10 processes ran at once…

PR diff

Current GitHub diff ↗
integration-tests/tests/imports/index.test.ts · patch excerpt
-import { afterAll, expect, it } from 'vitest';-import 'zx/globals';-import * as fs from 'fs';+import { execFile } from 'child_process';
Browse 1 changed file
integration-tests/tests/imports/index.test.ts+45 −61
@@ -1,11 +1,8 @@-import { afterAll, expect, it } from 'vitest';-import 'zx/globals';-import * as fs from 'fs';+import { execFile } from 'child_process'; import { globSync } from 'glob';+import os from 'os'; import path from 'path';-$.verbose = true;--const IMPORTS_FOLDER = 'tests/imports/files';+import { expect, it } from 'vitest';  // The published `exports` map collapsed to a `"./*"` wildcard, so the importable public subpaths // are no longer enumerable from it — re-derive them from the same source globs the build keys off.@@ -17,22 +14,36 @@ const exportSubpaths = [ 	), ]; -fs.mkdirSync(IMPORTS_FOLDER, { recursive: true });+type ImportCheck = { name: string; args: string[] }; -afterAll(() => {-	fs.rmSync(IMPORTS_FOLDER, { recursive: true });-});+// Resolves with an error message, or with undefined when the process exits with code 0.+// The 5s limit catches an import that hangs, for example one that keeps the event loop open.+function runNode(args: string[]): Promise<string | undefined> {+	return new Promise((resolve) => {+		execFile('node', args, { timeout: 5000 }, (error, _stdout, stderr) => {+			resolve(error ? `${error.message}\n${stderr}` : undefined);+		});+	});+} -function chunk<T>(arr: T[], size: number): T[][] {-	const chunks: T[][] = [];-	for (let i = 0; i < arr.length; i += size) {-		chunks.push(arr.slice(i, i + size));-	}-	return chunks;+// Runs one process per CPU at a time. More processes than CPUs slow each other down until+// healthy imports hit the 5s limit.+async function findFailedImports(checks: ImportCheck[]): Promise<string[]> {+	const failures: string[] = [];+	let next = 0;+	const worker = async () => {+		while (next < checks.length) {+			const { name, args } = checks[next++]!;+			const error = await runNode(args);+			if (error) failures.push(`${name}: ${error}`);+		}+	};+	await Promise.all(new Array(os.availableParallelism()).fill(undefined).map(worker));+	return failures; } -const promisesCJS: (() => ProcessPromise)[] = [];-for (const [i, key] of exportSubpaths.entries()) {+const checksCJS: ImportCheck[] = [];+for (const key of exportSubpaths) { 	const o1 = path.join('drizzle-orm', key); 	if ( 		o1.startsWith('drizzle-orm/bun-sqlite') || o1.startsWith('drizzle-orm/pglite')@@ -44,32 +55,15 @@ for (const [i, key] of exportSubpaths.entries()) { 	) { 		continue; 	}-	fs.writeFileSync(`${IMPORTS_FOLDER}/imports_${i}.cjs`, 'requ');-	fs.appendFileSync(`${IMPORTS_FOLDER}/imports_${i}.cjs`, 'ire("' + o1 + '");\n', {});--	// fs.writeFileSync(`${IMPORTS_FOLDER}/imports_${i}.mjs`, 'imp');-	// fs.appendFileSync(`${IMPORTS_FOLDER}/imports_${i}.mjs`, 'ort "' + o1 + '"\n', {});--	promisesCJS.push(-		() => $`node ${IMPORTS_FOLDER}/imports_${i}.cjs`.nothrow().timeout('5s', 'SIGTERM'),-		// () => $`node ${IMPORTS_FOLDER}/imports_${i}.mjs`.nothrow().timeout('5s', 'SIGTERM'),-	);+	checksCJS.push({ name: o1, args: ['--input-type=commonjs', '-e', `require(${JSON.stringify(o1)})`] }); } -const chunksCJS = chunk(promisesCJS, 10);--for (const c of chunksCJS) {-	it.concurrent('dynamic imports check for CommonJS chunk', async () => {-		const results = await Promise.all(c.map((c) => c()));--		for (const result of results) {-			expect(result.exitCode, result.message).toBe(0);-		}-	});-}+it('every entry point loads with require()', async () => {+	expect(await findFailedImports(checksCJS)).toEqual([]);+}); -const promises: (() => ProcessPromise)[] = [];-for (const [i, key] of exportSubpaths.entries()) {+const checksESM: ImportCheck[] = [];+for (const key of exportSubpaths) { 	const o1 = path.join('drizzle-orm', key); 	if ( 		o1.startsWith('drizzle-orm/bun-sqlite') || o1.startsWith('drizzle-orm/expo-sqlite')@@ -80,26 +74,16 @@ for (const [i, key] of exportSubpaths.entries()) { 	) { 		continue; 	}-	fs.writeFileSync(`${IMPORTS_FOLDER}/imports_${i}.mjs`, 'imp');-	fs.appendFileSync(`${IMPORTS_FOLDER}/imports_${i}.mjs`, 'ort "' + o1 + '"\n', {});-	promises.push(-		() => $`node ${IMPORTS_FOLDER}/imports_${i}.mjs`.nothrow().timeout('5s', 'SIGTERM'),-		() =>-			$`node --import import-in-the-middle/hook.mjs ${IMPORTS_FOLDER}/imports_${i}.mjs`.nothrow().timeout(-				'5s',-				'SIGTERM',-			),+	const source = `import ${JSON.stringify(o1)}`;+	checksESM.push(+		{ name: o1, args: ['--input-type=module', '-e', source] },+		{+			name: `${o1} with import-in-the-middle`,+			args: ['--import', 'import-in-the-middle/hook.mjs', '--input-type=module', '-e', source],+		}, 	); } -const chunksESM = chunk(promises, 10);--for (const c of chunksESM) {-	it('dynamic imports check for ESM chunk', async () => {-		const results = await Promise.all(c.map((c) => c()));--		for (const result of results) {-			expect(result.exitCode, result.message).toBe(0);-		}-	});-}+it('every entry point loads with import', async () => {+	expect(await findFailedImports(checksESM)).toEqual([]);+});

→ Outcome

Why this verdict

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

Supporting evidence

Reviewed 27 Nov 2026Revision db1b5b966cfa1 changed file+45 −61Judge score 5/5
Approved · 0 retained findingsmicrosoft/markitdown#1919

Use frozenset for OMML direct tag lookup

Input

PR author’s description

Summary

Replaces __direct_tags from tuple to frozenset in the DOCX OMML math converter (oMath2Latex) to improve membership lookup efficiency in a hot code path.

Motivation

PR diff

Current GitHub diff ↗
packages/markitdown/src/markitdown/converter_utils/docx/math/omml.py · patch excerpt
-    __direct_tags = ("box", "sSub", "sSup", "sSubSup", "num", "den", "deg", "e")+    __direct_tags = frozenset(+        ("box", "sSub", "sSup", "sSubSup", "num", "den", "deg", "e")+    )
Browse 1 changed file
packages/markitdown/src/markitdown/converter_utils/docx/math/omml.py+3 −1
@@ -179,7 +179,9 @@ class oMath2Latex(Tag2Method):      _t_dict = T -    __direct_tags = ("box", "sSub", "sSup", "sSubSup", "num", "den", "deg", "e")+    __direct_tags = frozenset(+        ("box", "sSub", "sSup", "sSubSup", "num", "den", "deg", "e")+    )      def __init__(self, element):         self._latex = self.process_children(element)

→ Outcome

Why this verdict

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

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Historical riskThe changed file added a frozenset(...) literal to __direct_tags, marking a structural change to tag dispatching that appears to be an alternating pattern of using a tuple vs frozenset. This signals increased surface-level maintenance burden and complexity in the tag dispatching endpoint.
  • Observation · Architectural coherenceConverting a tuple literal to a frozenset in the __direct_tags class attribute of oMath2Latex introduces a deviation from the pattern established by other classes, such as Pr, which uses a regular tuple unconditionally.

    Recorded location packages/markitdown/src/markitdown/converter_utils/docx/math/omml.py:131

Supporting evidence

Reviewed 27 Nov 2026Revision 4ea4f30739971 changed file+3 −1Judge score 5/5
Approved · 0 retained findingsgithub/github-mcp-server#3407

perf: cache encoded tools/list schemas

Input

PR author’s description

Summary

Cache encoded tool schemas once per process and reuse them in tools/list responses without changing their wire representation.

PR diff

Current GitHub diff ↗
pkg/inventory/registry.go · patch excerpt
+//+// Schema definitions must remain immutable and be reused across registrations.+// Their encodings are retained process-wide, keyed by source schema identity.
Browse 6 changed files
pkg/inventory/registry.go+10 −1
@@ -240,12 +240,21 @@ func shouldStripMCPAppsMetadata(ctx context.Context) bool { // the client did not advertise the io.modelcontextprotocol/ui extension. The // strip happens here (rather than at Build() time) so the per-request // context, which carries the client capability, is in scope.+//+// Schema definitions must remain immutable and be reused across registrations.+// Their encodings are retained process-wide, keyed by source schema identity. func (r *Inventory) RegisterTools(ctx context.Context, s *mcp.Server, deps any, middleware ...ToolHandlerMiddleware) { 	tools := r.ToolsForRegistration(ctx) 	addToolAvailabilityMiddleware(s, tools)+	schemas := make(map[string]listedToolSchemas, len(tools)) 	for _, tool := range tools {-		tool.RegisterFunc(s, deps, middleware...)+		registered := tool.register(s, deps, middleware...)+		schemas[registered.Name] = listedToolSchemas{+			source:     tool.Tool.InputSchema,+			registered: registered,+		} 	}+	s.AddReceivingMiddleware(encodedToolSchemasMiddleware(schemas)) }  // RegisterResourceTemplates registers all available resource templates with the server.
pkg/inventory/encoded_schemas_test.go+300 −0
@@ -0,0 +1,300 @@+package inventory++import (+	"context"+	"encoding/json"+	"errors"+	"sync"+	"sync/atomic"+	"testing"++	"github.com/google/jsonschema-go/jsonschema"+	"github.com/modelcontextprotocol/go-sdk/mcp"+	"github.com/stretchr/testify/assert"+	"github.com/stretchr/testify/require"+)++func listThroughEncoder(t *testing.T, definitions map[string]listedToolSchemas, list *mcp.ListToolsResult) *mcp.ListToolsResult {+	t.Helper()+	handler := encodedToolSchemasMiddleware(definitions)(func(context.Context, string, mcp.Request) (mcp.Result, error) {+		return list, nil+	})+	result, err := handler(context.Background(), MCPMethodToolsList, nil)+	require.NoError(t, err)+	return result.(*mcp.ListToolsResult)+}++func TestEncodedSchemasVariantIsolation(t *testing.T) {+	t.Parallel()+	for _, property := range []string{"dotcom", "enterprise", "feature_enabled"} {+		t.Run(property, func(t *testing.T) {+			t.Parallel()+			schema := &jsonschema.Schema{+				Type:       "object",+				Properties: map[string]*jsonschema.Schema{property: {Type: "string"}, "owner": {Type: "string"}},+			}+			tool := &mcp.Tool{Name: "same_name", InputSchema: schema, OutputSchema: schema}+			AnnotateHeaderParams(tool)+			before := &mcp.ListToolsResult{Tools: []*mcp.Tool{tool}, NextCursor: "unchanged"}+			want, err := json.Marshal(before)+			require.NoError(t, err)+			after := listThroughEncoder(t, map[string]listedToolSchemas{+				tool.Name: {source: schema, registered: tool},+			}, before)+			got, err := json.Marshal(after)+			require.NoError(t, err)+			assert.Equal(t, string(want), string(got))+			assert.IsType(t, json.RawMessage{}, after.Tools[0].InputSchema)+			assert.IsType(t, json.RawMessage{}, after.Tools[0].OutputSchema)+			assert.NotSame(t, before, after)+			assert.NotSame(t, tool, after.Tools[0])+			assert.Same(t, schema, tool.OutputSchema)+			assert.IsType(t, &jsonschema.Schema{}, tool.InputSchema)+			assert.Contains(t, string(got), property)+			assert.NotContains(t, string(after.Tools[0].OutputSchema.(json.RawMessage)), "x-mcp-header")+			assert.Contains(t, string(after.Tools[0].InputSchema.(json.RawMessage)), "x-mcp-header")+		})+	}+}++type encodingProbe struct {+	calls atomic.Int64+	err   error+}++func (p *encodingProbe) MarshalJSON() ([]byte, error) {+	p.calls.Add(1)+	return []byte(`true`), p.err+}++func TestEncodedSchemasConcurrentRegistration(t *testing.T) {+	t.Parallel()+	probe := &encodingProbe{}+	schema := &jsonschema.Schema{+		Type:       "object",+		Properties: map[string]*jsonschema.Schema{"owner": {Type: "string"}},+		Extra:      map[string]any{"x-probe": probe},+	}+	original, err := json.Marshal(schema)+	require.NoError(t, err)+	initialCalls := probe.calls.Load()+	const workers = 32+	results := make(chan json.RawMessage, workers)+	var wg sync.WaitGroup+	for range workers {+		wg.Go(func() {+			tool := &mcp.Tool{Name: "concurrent", InputSchema: schema}+			AnnotateHeaderParams(tool)+			before := &mcp.ListToolsResult{Tools: []*mcp.Tool{tool}}+			handler := encodedToolSchemasMiddleware(map[string]listedToolSchemas{+				tool.Name: {source: schema, registered: tool},+			})(func(context.Context, string, mcp.Request) (mcp.Result, error) {+				return before, nil+			})+			for range 10 {+				result, err := handler(context.Background(), MCPMethodToolsList, nil)+				if !assert.NoError(t, err) {+					return+				}+				after := result.(*mcp.ListToolsResult)+				assert.Same(t, tool, before.Tools[0])+				assert.IsType(t, &jsonschema.Schema{}, tool.InputSchema)+				data := after.Tools[0].InputSchema.(json.RawMessage)+				assert.True(t, json.Valid(data))+			}+			result, err := handler(context.Background(), MCPMethodToolsList, nil)+			if assert.NoError(t, err) {+				results <- result.(*mcp.ListToolsResult).Tools[0].InputSchema.(json.RawMessage)+			}+		})+	}+	wg.Wait()+	close(results)+	assert.Equal(t, int64(1), probe.calls.Load()-initialCalls, "all registration clones share one encoding")+	var first json.RawMessage+	for data := range results {+		if first == nil {+			first = data+		}+		assert.Equal(t, first, data)+	}+	after, err := json.Marshal(schema)+	require.NoError(t, err)+	assert.Equal(t, original, after, "source schema must remain unchanged")+}++func TestEncodedSchemasRepeatedInventoryRegistration(t *testing.T) {+	t.Parallel()+	schema := &jsonschema.Schema{+		Type:       "object",+		Properties: map[string]*jsonschema.Schema{"owner": {Type: "string"}},+	}+	definition := ServerTool{+		Tool: mcp.Tool{Name: "repeated", InputSchema: schema, OutputSchema: schema},+		HandlerFunc: func(any) mcp.ToolHandler {+			return func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) {+				return &mcp.CallToolResult{}, nil+			}+		},+	}+	original, err := json.Marshal(schema)+	require.NoError(t, err)+	var first []byte+	for range 20 {+		inv, err := NewBuilder().SetTools([]ServerTool{definition}).WithToolsets([]string{"all"}).Build()+		require.NoError(t, err)+		server := mcp.NewServer(&mcp.Implementation{Name: "repeated"}, nil)+		inv.ForMCPRequest(MCPMethodToolsList, "").RegisterTools(context.Background(), server, nil)+		st, ct := mcp.NewInMemoryTransports()+		ss, err := server.Connect(context.Background(), st, nil)+		require.NoError(t, err)+		cs, err := mcp.NewClient(&mcp.Implementation{Name: "test"}, nil).Connect(context.Background(), ct, nil)+		require.NoError(t, err)+		list, err := cs.ListTools(context.Background(), nil)+		_ = cs.Close()+		_ = ss.Close()+		require.NoError(t, err)+		data, err := json.Marshal(list)+		require.NoError(t, err)+		if first == nil {+			first = data+		}+		assert.Equal(t, first, data)+	}+	var entries int+	encodedSchemas.Range(func(key, _ any) bool {+		if key.(encodedSchemaKey).schema == schema {+			entries+++		}+		return true+	})+	assert.Equal(t, 2, entries, "new inventories and annotation clones must reuse the two source-schema keys")+	after, err := json.Marshal(schema)+	require.NoError(t, err)+	assert.Equal(t, original, after)+}++func TestEncodedSchemasPreserveReplacementsAndErrors(t *testing.T) {+	t.Parallel()+	source := &jsonschema.Schema{Type: "object"}+	registered := &mcp.Tool{Name: "tool", InputSchema: source}+	replacement := &mcp.Tool{Name: "tool", InputSchema: &jsonschema.Schema{Type: "object", Description: "replacement"}}+	raw := &mcp.Tool{Name: "raw", InputSchema: json.RawMessage(`{"type":"object","properties":{}}`)}+	before := &mcp.ListToolsResult{Tools: []*mcp.Tool{replacement, raw}}+	after := listThroughEncoder(t, map[string]listedToolSchemas{+		"tool": {source: source, registered: registered},+		"raw":  {source: raw.InputSchema, registered: raw},+	}, before)+	assert.Same(t, replacement.InputSchema, after.Tools[0].InputSchema)+	assert.Equal(t, raw.InputSchema, after.Tools[1].InputSchema)++	broken := &jsonschema.Schema{Type: "object", Extra: map[string]any{+		"x-probe": &encodingProbe{err: errors.New("encoding failed")},+	}}+	tool := &mcp.Tool{Name: "broken", InputSchema: broken}+	handler := encodedToolSchemasMiddleware(map[string]listedToolSchemas{+		"broken": {source: broken, registered: tool},+	})(func(context.Context, string, mcp.Request) (mcp.Result, error) {+		return &mcp.ListToolsResult{Tools: []*mcp.Tool{tool}}, nil+	})+	result, err := handler(context.Background(), MCPMethodToolsList, nil)+	assert.Nil(t, result)+	require.ErrorContains(t, err, `encode input schema for "broken"`)++	wantErr := errors.New("downstream error")+	handler = encodedToolSchemasMiddleware(nil)(func(context.Context, string, mcp.Request) (mcp.Result, error) {+		return nil, wantErr+	})+	_, err = handler(context.Background(), MCPMethodToolsList, nil)+	assert.ErrorIs(t, err, wantErr)+}++func TestEncodedSchemasSharedResultIsImmutable(t *testing.T) {+	t.Parallel()+	schema := &jsonschema.Schema{Type: "object", Description: "shared"}+	tool := &mcp.Tool{Name: "shared", InputSchema: schema}+	list := &mcp.ListToolsResult{Tools: []*mcp.Tool{tool}, NextCursor: "cursor"}+	handler := encodedToolSchemasMiddleware(map[string]listedToolSchemas{+		tool.Name: {source: schema, registered: tool},+	})(func(context.Context, string, mcp.Request) (mcp.Result, error) {+		return list, nil+	})+	var wg sync.WaitGroup+	for range 32 {+		wg.Go(func() {+			for range 10 {+				result, err := handler(context.Background(), MCPMethodToolsList, nil)+				if !assert.NoError(t, err) {+					return+				}+				patched := result.(*mcp.ListToolsResult)+				assert.Equal(t, "cursor", patched.NextCursor)+				assert.Equal(t, "shared", patched.Tools[0].Name)+				assert.Equal(t, json.RawMessage(`{"type":"object","description":"shared"}`), patched.Tools[0].InputSchema)+				patched.NextCursor = "caller cursor"+				patched.Tools[0].Name = "caller tool"+				patched.Tools[0].InputSchema = json.RawMessage(`{}`)+				patched.Tools[0] = nil+			}+		})+	}+	wg.Wait()+	assert.Same(t, tool, list.Tools[0])+	assert.Same(t, schema, tool.InputSchema)+	assert.Equal(t, "shared", tool.Name)+	assert.Equal(t, "cursor", list.NextCursor)+}++func TestEncodedSchemasLeaveSDKValidationIntact(t *testing.T) {+	t.Parallel()+	type values struct {+		Count int `json:"count"`+	}+	input := &jsonschema.Schema{+		Type:       "object",+		Properties: map[string]*jsonschema.Schema{"count": {Type: "integer"}},+		Required:   []string{"count"},+	}+	output := &jsonschema.Schema{+		Type:       "object",+		Properties: map[string]*jsonschema.Schema{"count": {Type: "integer", Minimum: new(float64)}},+		Required:   []string{"count"},+	}+	for _, optimized := range []bool{false, true} {+		t.Run(map[bool]string{false: "baseline", true: "encoded"}[optimized], func(t *testing.T) {+			var calls int+			server := mcp.NewServer(&mcp.Implementation{Name: "validation"}, &mcp.ServerOptions{SchemaCache: mcp.NewSchemaCache()})+			tool := &mcp.Tool{Name: "validate", InputSchema: input, OutputSchema: output}+			mcp.AddTool(server, tool, func(_ context.Context, _ *mcp.CallToolRequest, args values) (*mcp.CallToolResult, values, error) {+				calls+++				return nil, args, nil+			})+			if optimized {+				server.AddReceivingMiddleware(encodedToolSchemasMiddleware(map[string]listedToolSchemas{+					tool.Name: {source: input, registered: tool},+				}))+			}+			st, ct := mcp.NewInMemoryTransports()+			ss, err := server.Connect(context.Background(), st, nil)+			require.NoError(t, err)+			defer func() { _ = ss.Close() }()+			cs, err := mcp.NewClient(&mcp.Implementation{Name: "test"}, nil).Connect(context.Background(), ct, nil)+			require.NoError(t, err)+			defer func() { _ = cs.Close() }()+			_, err = cs.ListTools(context.Background(), nil)+			require.NoError(t, err)+			invalid, err := cs.CallTool(context.Background(), &mcp.CallToolParams{Name: tool.Name, Arguments: map[string]any{"count": "wrong"}})+			require.NoError(t, err)+			assert.True(t, invalid.IsError)+			assert.Zero(t, calls, "input validation rejects before calling the handler")+			_, err = cs.CallTool(context.Background(), &mcp.CallToolParams{Name: tool.Name, Arguments: values{Count: -1}})+			require.Error(t, err, "output validation must still reject a negative result")+			result, err := cs.CallTool(context.Background(), &mcp.CallToolParams{Name: tool.Name, Arguments: values{Count: 1}})+			require.NoError(t, err)+			assert.False(t, result.IsError)+			assert.Equal(t, 2, calls)+			assert.Same(t, input, tool.InputSchema)+			assert.Same(t, output, tool.OutputSchema)+		})+	}+}
pkg/github/encoded_schemas_test.go+269 −0
@@ -0,0 +1,269 @@+package github++import (+	"bufio"+	"bytes"+	"context"+	"encoding/json"+	"fmt"+	"io"+	"net"+	"net/http"+	"net/http/httptest"+	"slices"+	"testing"++	ghcontext "github.com/github/github-mcp-server/pkg/context"+	"github.com/github/github-mcp-server/pkg/inventory"+	"github.com/github/github-mcp-server/pkg/translations"+	"github.com/github/github-mcp-server/pkg/utils"+	"github.com/modelcontextprotocol/go-sdk/mcp"+	"github.com/stretchr/testify/assert"+	"github.com/stretchr/testify/require"+)++// The baseline uses the public single-tool registration path, which does not+// install the tools/list encoder. Both paths select the same inventory first.+func schemaListServer(ctx context.Context, inv *inventory.Inventory, optimized bool, pageSize int) *mcp.Server {+	server := mcp.NewServer(&mcp.Implementation{Name: "schema-list"}, &mcp.ServerOptions{PageSize: pageSize})+	if optimized {+		inv.RegisterTools(ctx, server, nil)+	} else {+		for _, tool := range inv.ToolsForRegistration(ctx) {+			tool.RegisterFunc(server, nil)+		}+	}+	return server+}++func schemaListContext(protocol string, ui bool) context.Context {+	return ghcontext.WithUISupport(ghcontext.WithMCPMethodInfo(context.Background(), &ghcontext.MCPMethodInfo{+		Method:             inventory.MCPMethodToolsList,+		ProtocolVersion:    protocol,+		ClientCapabilities: &mcp.ClientCapabilities{},+	}), ui)+}++type schemaListWire struct {+	Result *mcp.ListToolsResult `json:"result"`+	Error  json.RawMessage      `json:"error"`+}++func schemaListPages(ctx context.Context, t *testing.T, inv *inventory.Inventory, optimized bool, transport, protocol string, pageSize int) ([][]byte, []string) {+	t.Helper()+	var request func(string) []byte+	switch transport {+	case "stdio":+		server := schemaListServer(ctx, inv, optimized, pageSize)+		serverConn, clientConn := net.Pipe()+		ss, err := server.Connect(ctx, &mcp.IOTransport{Reader: serverConn, Writer: serverConn}, nil)+		require.NoError(t, err)+		defer func() { _ = ss.Close() }()+		defer func() { _ = clientConn.Close() }()+		reader := bufio.NewReader(clientConn)+		exchange := func(body string) []byte {+			_, err := io.WriteString(clientConn, body+"\n")+			require.NoError(t, err)+			response, err := reader.ReadBytes('\n')+			require.NoError(t, err)+			return response+		}+		init := exchange(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":%q,"capabilities":{},"clientInfo":{"name":"test","version":"1"}}}`, protocol))+		require.NotContains(t, string(init), `"error"`)+		_, err = io.WriteString(clientConn, `{"jsonrpc":"2.0","method":"notifications/initialized"}`+"\n")+		require.NoError(t, err)+		request = exchange+	case "http":+		handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server {+			return schemaListServer(ctx, inv, optimized, pageSize)+		}, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true})+		request = func(body string) []byte {+			req := httptest.NewRequest(http.MethodPost, "/", bytes.NewBufferString(body))+			req.Header.Set("Content-Type", "application/json")+			req.Header.Set("Accept", "application/json, text/event-stream")+			req.Header.Set("Mcp-Protocol-Version", protocol)+			req.Header.Set("Mcp-Method", "tools/list")+			rec := httptest.NewRecorder()+			handler.ServeHTTP(rec, req)+			require.Contains(t, []int{http.StatusOK, http.StatusBadRequest}, rec.Code, rec.Body.String())+			return rec.Body.Bytes()+		}+	default:+		t.Fatalf("unknown transport: %s", transport)+	}+	var pages [][]byte+	names := make([]string, 0)+	listRequest := func(id int, cursor string) string {+		return fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,"method":"tools/list","params":{"cursor":%q,"_meta":{"io.modelcontextprotocol/protocolVersion":%q,"io.modelcontextprotocol/clientInfo":{"name":"test","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}}}`, id, cursor, protocol)+	}+	cursor := ""+	for {+		response := request(listRequest(2, cursor))+		pages = append(pages, response)+		var wire schemaListWire+		require.NoError(t, json.Unmarshal(response, &wire))+		require.Empty(t, wire.Error)+		require.NotNil(t, wire.Result)+		for _, tool := range wire.Result.Tools {+			names = append(names, tool.Name)+		}+		if wire.Result.NextCursor == "" {+			break+		}+		require.NotEqual(t, cursor, wire.Result.NextCursor)+		cursor = wire.Result.NextCursor+	}+	bad := request(listRequest(3, "not-a-valid-cursor"))+	var wire schemaListWire+	require.NoError(t, json.Unmarshal(bad, &wire))+	require.NotEmpty(t, wire.Error)+	pages = append(pages, bad)+	return pages, names+}++func TestEncodedSchemasWireParity(t *testing.T) {+	type selection struct {+		name     string+		toolsets []string+		features []string+		exclude  []string+		explicit []string+		scopes   []string+		protocol string+		ui       bool+	}+	prototype, err := NewInventory(translations.NullTranslationHelper).WithToolsets([]string{"all"}).Build()+	require.NoError(t, err)+	var selections []selection+	for _, toolset := range append([]inventory.ToolsetID{"all", "default"}, prototype.ToolsetIDs()...) {+		for _, enabled := range []bool{false, true} {+			features := []string(nil)+			if enabled {+				features = AllowedFeatureFlags+			}+			selections = append(selections, selection{+				name: fmt.Sprintf("%s/all-flags=%v", toolset, enabled), toolsets: []string{string(toolset)}, features: features,+			})+		}+	}+	for _, feature := range AllowedFeatureFlags {+		selections = append(selections, selection{name: "flag/" + feature, toolsets: []string{"all"}, features: []string{feature}})+	}+	selections = append(selections,+		selection{name: "insiders", toolsets: []string{"all"}, features: InsidersFeatureFlags},+		selection{name: "none", toolsets: []string{}},+		selection{name: "explicit-and-excluded", toolsets: []string{"repos"}, explicit: []string{"get_me"}, exclude: []string{"get_commit"}},+		selection{name: "scopes", toolsets: []string{"all"}, scopes: []string{"read:user"}},+		selection{name: "legacy-no-ui", toolsets: []string{"all"}, features: AllowedFeatureFlags, protocol: "2025-11-25"},+		selection{name: "apps", toolsets: []string{"all"}, features: AllowedFeatureFlags, ui: true},+	)+	for _, host := range []utils.HostType{utils.HostTypeDotcom, utils.HostTypeGHEC, utils.HostTypeGHES} {+		// Reuse the same static definitions across request-time variants, just as+		// both the local HTTP and remote inventory factories do.+		definitions := AllTools(translations.NullTranslationHelper, WithHost(host))+		for _, readOnly := range []bool{false, true} {+			for _, sel := range selections {+				t.Run(fmt.Sprintf("host=%d/readonly=%v/%s", host, readOnly, sel.name), func(t *testing.T) {+					protocol := sel.protocol+					if protocol == "" {+						protocol = inventory.ProtocolVersionMultiRoundTrip+					}+					ctx := schemaListContext(protocol, sel.ui)+					flags := ResolveFeatureFlags(sel.features, false)+					builder := inventory.NewBuilder().SetTools(definitions).+						WithToolsets(sel.toolsets).WithReadOnly(readOnly).+						WithTools(sel.explicit).WithExcludeTools(sel.exclude).+						WithFeatureChecker(func(_ context.Context, stringFlag string) (bool, error) {+							return flags[stringFlag], nil+						})+					if sel.scopes != nil {+						builder.WithFilter(CreateToolScopeFilter(sel.scopes))+					}+					inv, err := builder.Build()+					require.NoError(t, err)+					wantNames := make([]string, 0)+					for _, tool := range inv.ToolsForRegistration(ctx) {+						wantNames = append(wantNames, tool.Tool.Name)+					}+					slices.Sort(wantNames)+					wantNames = slices.Compact(wantNames)+					for _, transport := range []string{"stdio", "http"} {+						t.Run(transport, func(t *testing.T) {+							before, baselineNames := schemaListPages(ctx, t, inv, false, transport, protocol, 7)+							after, encodedNames := schemaListPages(ctx, t, inv, true, transport, protocol, 7)+							assert.Equal(t, before, after, "complete JSON-RPC wire responses, including cursors and errors")+							assert.Equal(t, wantNames, baselineNames)+							assert.Equal(t, wantNames, encodedNames)+						})+					}+				})+			}+		}+	}+}++func schemaListClient(tb testing.TB, server *mcp.Server) *mcp.ClientSession {+	tb.Helper()+	st, ct := mcp.NewInMemoryTransports()+	ss, err := server.Connect(context.Background(), st, nil)+	require.NoError(tb, err)+	client := mcp.NewClient(&mcp.Implementation{Name: "benchmark"}, nil)+	cs, err := client.Connect(context.Background(), ct, nil)+	require.NoError(tb, err)+	tb.Cleanup(func() {+		_ = cs.Close()+		_ = ss.Close()+	})+	return cs+}++func BenchmarkEncodedSchemas(b *testing.B) {+	ctx := schemaListContext(inventory.ProtocolVersionMultiRoundTrip, false)+	inv, err := NewInventory(translations.NullTranslationHelper).+		WithToolsets([]string{"all"}).+		WithFeatureChecker(func(context.Context, string) (bool, error) { return true, nil }).+		Build()+	require.NoError(b, err)+	for _, optimized := range []bool{false, true} {+		name := map[bool]string{false: "baseline", true: "encoded"}[optimized]+		b.Run(name, func(b *testing.B) {+			b.Run("ListTools", func(b *testing.B) {+				cs := schemaListClient(b, schemaListServer(ctx, inv, optimized, 1000))+				result, err := cs.ListTools(ctx, nil)+				require.NoError(b, err)+				payload, err := json.Marshal(result)+				require.NoError(b, err)+				b.ReportAllocs()+				b.ResetTimer()+				for b.Loop() {+					if _, err := cs.ListTools(ctx, nil); err != nil {+						b.Fatal(err)+					}+				}+				b.ReportMetric(float64(len(payload)), "payload-B")+				b.ReportMetric(float64(len(result.Tools)), "tools")+			})+			b.Run("ConstructionAndList", func(b *testing.B) {+				b.ReportAllocs()+				for b.Loop() {+					st, ct := mcp.NewInMemoryTransports()+					server := schemaListServer(ctx, inv, optimized, 1000)+					ss, err := server.Connect(ctx, st, nil)+					if err != nil {+						b.Fatal(err)+					}+					cs, err := mcp.NewClient(&mcp.Implementation{Name: "benchmark"}, nil).Connect(ctx, ct, nil)+					if err != nil {+						b.Fatal(err)+					}+					_, err = cs.ListTools(ctx, nil)+					_ = cs.Close()+					_ = ss.Close()+					if err != nil {+						b.Fatal(err)+					}+				}+			})+		})+	}+}

→ Outcome

Why this verdict

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

Supporting evidence

Reviewed 27 Nov 2026Revision 2aa8fac2ee2b6 changed files+708 −1Judge score 5/5
Approved · 0 retained findingsclap-rs/clap#6519

fix(complete): Make it easier to debug

Input

PR author’s description

<!-- Thanks for helping out! -->

What does this PR try to solve?

Found this helpful when debugging #6517

Notes to reviewers

PR diff

Current GitHub diff ↗
clap_complete/src/engine/complete.rs · patch excerpt
+    debug!("complete_option: arg={arg:?}, current_dir={current_dir:?}");
Browse 1 changed file
clap_complete/src/engine/complete.rs+3 −0
@@ -248,6 +248,7 @@ fn complete_option(     cmd: &clap::Command,     current_dir: Option<&std::path::Path>, ) -> Vec<CompletionCandidate> {+    debug!("complete_option: arg={arg:?}, current_dir={current_dir:?}");     let mut completions = Vec::<CompletionCandidate>::new();     if arg.is_empty() {         completions.extend(longs_and_visible_aliases(cmd));@@ -338,6 +339,7 @@ fn complete_option(             }         }     }+    debug!("complete_option: completions={completions:?}");     completions } @@ -425,6 +427,7 @@ fn complete_arg_value(         })         .collect(); +    debug!("complete_arg_value: values={values:?}");     values } 

→ Outcome

Why this verdict

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

Supporting evidence

Reviewed 27 Nov 2026Revision 9a0248c837b81 changed file+3 −0Judge score 5/5
Approved · 0 retained findingsdrizzle-team/drizzle-orm#6629

Fix wrong instants and `Invalid Date` when decoding temporal values

Input

PR author’s description

This ports drizzle-team/minipg#14 (released there as @drizzle-team/minipg 0.4.4) into postgres/. The monorepo copy did not have it. Decoding of date, timestamp and timestamptz now goes through one parser in…

PR diff

Current GitHub diff ↗
postgres/src/decode.ts · patch excerpt
-function parseInstantMs(s: string): number {…+const parseInstantMs = (s: string): number => instantFromString(s) ?? NaN;
Browse 5 changed files
postgres/src/decode.ts+20 −181
@@ -16,6 +16,14 @@ import { extAt, extLeafFor } from './geo.ts'; import { buildJsonWalk, genJsonParsers, type JsonMarker, type JsonPlan, type JsTarget, specNeedsWalk } from './json.ts'; import { parseJsonBuffer } from './jsonparse.ts'; import { customAt, customDelimFor, customLeafFor } from './registry.ts';+import {+	BIN_TS_MS_EXPR,+	binTimestampMs,+	instantFromBytes,+	instantFromString,+	instantSnippet,+	PG_EPOCH_MS,+} from './temporal.ts'; import type { Decoder } from './types.ts';  // ---------------------------------------------------------------------------------------------@@ -171,84 +179,9 @@ const byteaLeaf: Leaf = ( 	s, ) => (s.charCodeAt(0) === 92 && s.charCodeAt(1) === 120 ? Buffer.from(s.slice(2), 'hex') : Buffer.from(s, 'utf8')); // '\x' hex -/** ms-since-epoch from a PG temporal text element — a STRING port of the interpreted tsParse (same field parse,- *  bare +00 offset, year<=99 fixup) so array Date values are bit-identical to the scalar timestamp path. */-function parseInstantMs(s: string): number {-	if (s === 'infinity' || s === '-infinity') return NaN; // PG ±infinity has no JS Date -> Invalid Date (matches the binary scalar)-	let e = s.length, bc = false;-	if (e >= 3 && s.charCodeAt(e - 1) === 67 && s.charCodeAt(e - 2) === 66 && s.charCodeAt(e - 3) === 32) {-		bc = true;-		e -= 3;-	} // strip a trailing ' BC'-	let p = 0;-	let Y = 0;-	for (; p < e; p++) {-		const c = s.charCodeAt(p);-		if (c < 48 || c > 57) break;-		Y = Y * 10 + (c - 48);-	}-	p++;-	const Mo = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);-	p += 3;-	const D = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);-	p += 2;-	let H = 0, Mi = 0, S = 0, ms = 0, off = 0;-	if (p < e && s.charCodeAt(p) === 32) {-		p++;-		H = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);-		p += 3;-		Mi = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);-		p += 3;-		S = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);-		p += 2;-		if (p < e && s.charCodeAt(p) === 46) {-			p++;-			let f = 0, k = 0;-			for (; p < e && k < 3; p++) {-				const c = s.charCodeAt(p);-				if (c < 48 || c > 57) break;-				f = f * 10 + (c - 48);-				k++;-			}-			while (k < 3) {-				f *= 10;-				k++;-			}-			ms = f;-			while (p < e) {-				const c = s.charCodeAt(p);-				if (c < 48 || c > 57) break;-				p++;-			}-		}-		if (p < e && (s.charCodeAt(p) === 43 || s.charCodeAt(p) === 45)) {-			const sg = s.charCodeAt(p) === 45 ? -1 : 1;-			p++;-			const th = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);-			p += 2;-			let tm = 0, tsc = 0;-			if (p < e && s.charCodeAt(p) === 58) {-				p++;-				tm = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);-				p += 2;-				if (p < e && s.charCodeAt(p) === 58) {-					p++;-					tsc = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);-					p += 2;-				}-			}-			off = sg * ((th * 60 + tm) * 60 + tsc) * 1000;-		} // LMT offsets carry SECONDS (named tz, pre-standard/BC dates)-	}-	const year = bc ? 1 - Y : Y; // PG 'N BC' -> proleptic/astronomical year 1-N (44 BC -> -43, 1 BC -> 0)-	let ems = Date.UTC(year, Mo - 1, D, H, Mi, S, ms);-	if (year >= 0 && year <= 99) {-		const d = new Date(ems);-		d.setUTCFullYear(year);-		ems = d.getTime();-	} // Date.UTC remaps 0-99 to 1900+-	return ems - off;-}+/** ms-since-epoch from a PG temporal text element (src/temporal.ts) so array Date values are bit-identical+ *  to the scalar timestamp path. ±infinity and non-ISO text -> NaN (Invalid Date). */+const parseInstantMs = (s: string): number => instantFromString(s) ?? NaN;  /** Element OID (+ optional element :target) -> leaf decoder, mirroring the scalar pickText/defaultJs defaults. */ function elemLeafFor(elemOid: number, js?: string): Leaf {@@ -526,29 +459,12 @@ const f64FromBytes = (v: string) => // (fastest + lossless). date/timestamp/timestamptz can map to a JS Date or epoch-ms number; naive // (no-offset) values are treated as UTC, timestamptz applies its offset. Direct field parse from // bytes -> Date.UTC (2-4x faster than new Date(text) AND correct — new Date parses no-tz as LOCAL).-// ms = first 3 fractional digits (micros truncated; Date is ms-only). Years < 100 / BC: use string.+// ms = first 3 fractional digits (micros truncated; Date is ms-only). Parser: src/temporal.ts. export const INSTANT_OIDS = new Set([1082, 1114, 1184]); // date, timestamp, timestamptz const tsFromBytes = (v: string, kind: 'date' | 'ms') =>-	`{ let p = o, e = o + l;-      if (b[p] === 105 || (b[p] === 45 && b[p + 1] === 105)) { ${-		kind === 'date' ? `${v} = new Date(NaN)` : `${v} = NaN`-	} } else {-      let bc = false; if (l >= 3 && b[e - 1] === 67 && b[e - 2] === 66 && b[e - 3] === 32) { bc = true; e -= 3 }-      let Y = 0; for (; p < e; p++) { const c = b[p]; if (c < 48 || c > 57) break; Y = Y * 10 + (c - 48) } p++;-      const Mo = (b[p] - 48) * 10 + (b[p + 1] - 48); p += 3;-      const D = (b[p] - 48) * 10 + (b[p + 1] - 48); p += 2;-      let H = 0, Mi = 0, S = 0, ms = 0, off = 0;-      if (p < e && b[p] === 32) { p++;-        H = (b[p] - 48) * 10 + (b[p + 1] - 48); p += 3;-        Mi = (b[p] - 48) * 10 + (b[p + 1] - 48); p += 3;-        S = (b[p] - 48) * 10 + (b[p + 1] - 48); p += 2;-        if (p < e && b[p] === 46) { p++; let f = 0, k = 0; for (; p < e && k < 3; p++) { const c = b[p]; if (c < 48 || c > 57) break; f = f * 10 + (c - 48); k++ } while (k < 3) { f *= 10; k++ } ms = f; while (p < e) { const c = b[p]; if (c < 48 || c > 57) break; p++ } }-        if (p < e && (b[p] === 43 || b[p] === 45)) { const sg = b[p] === 45 ? -1 : 1; p++; const th = (b[p] - 48) * 10 + (b[p + 1] - 48); p += 2; let tm = 0, tsc = 0; if (p < e && b[p] === 58) { p++; tm = (b[p] - 48) * 10 + (b[p + 1] - 48); p += 2; if (p < e && b[p] === 58) { p++; tsc = (b[p] - 48) * 10 + (b[p + 1] - 48); p += 2 } } off = sg * ((th * 60 + tm) * 60 + tsc) * 1000 }-      }-      const yy = bc ? 1 - Y : Y;-      let ems = Date.UTC(yy, Mo - 1, D, H, Mi, S, ms); if (yy >= 0 && yy <= 99) { const dd = new Date(ems); dd.setUTCFullYear(yy); ems = dd.getTime() } ems -= off; ${+	`{ let ems, ok; ${instantSnippet('b', 'o', 'o + l', 'ems', 'ok')} if (!ok) ems = NaN; ${ 		kind === 'date' ? `${v} = new Date(ems)` : `${v} = ems`-	} } }`;+	} }`;  // The natural JS target for a wire OID (before any per-column override). export function defaultJs(oid: number): 'number' | 'string' | 'bool' | 'json' | 'bytea' | 'helper' {@@ -639,9 +555,8 @@ function inlineSnippet(oid: number, v: string, js?: Target): [string, string] | // int8, timestamp (int64 µs since 2000 -> the integer directly), bytea. numeric/arrays/json/jsonb are // NOT supported in binary (complex format, or no benefit) — request text. uuid works but text is faster // (PG ships it pre-formatted), so prefer text there too. `js` still picks date/epoch/number.-const PG_EPOCH_MS = 946684800000; // 2000-01-01 UTC in unix ms // int64 read, NO BigInt: signed hi from a manual shift, unsigned lo (>>> 0), value = hi*2^32 + lo.-// Exact for |value| < 2^53 (int8 magnitudes below that, timestamp µs until ~year 2255).+// Exact for |value| < 2^53 (int8 magnitudes below that). Timestamps use BIN_TS_MS_EXPR instead (exact to the ms everywhere). const RD64 = 	'const hi = (b[o] << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3], lo = ((b[o + 4] << 24) | (b[o + 5] << 16) | (b[o + 6] << 8) | b[o + 7]) >>> 0'; function binarySnippet(oid: number, v: string, js?: Target): [string, string] | null {@@ -670,7 +585,7 @@ function binarySnippet(oid: number, v: string, js?: Target): [string, string] | 			return [`${v} = b.readDoubleBE(o)`, 'float8 bin (exact)']; 		case 1114: 		case 1184: { // timestamp/timestamptz: int64 µs since 2000-01-01 (no BigInt). Default -> Date.-			const ms = `Math.floor((hi * 4294967296 + lo) / 1000) + ${PG_EPOCH_MS}`;+			const ms = BIN_TS_MS_EXPR; 			return js === 'ms' 				? [`{ ${RD64}; ${v} = ${ms} }`, 'timestamp bin :ms'] 				: [`{ ${RD64}; ${v} = new Date(${ms}) }`, 'timestamp bin :date'];@@ -1066,84 +981,8 @@ const txtF64: CellDecoder = (b, o, l) => { const txtF4Precise: CellDecoder = (b, o, l) => Math.fround(txtF64(b, o, l) as number); // float4:precise -> exact stored f32  // temporal :date/:ms (direct field parse -> Date.UTC; naive = UTC, tz applies offset; micros -> ms).-// Mirrors parseInstantMs exactly: ±infinity -> NaN, trailing ' BC' -> astronomical year 1-N.-function tsParse(b: Buffer, o: number, l: number): number {-	if (b[o] === 105 || (b[o] === 45 && b[o + 1] === 105)) return NaN; // 'infinity' / '-infinity'-	let p = o;-	let e = o + l;-	let bc = false;-	if (l >= 3 && b[e - 1] === 67 && b[e - 2] === 66 && b[e - 3] === 32) {-		bc = true;-		e -= 3;-	} // strip ' BC'-	let Y = 0;-	for (; p < e; p++) {-		const c = b[p]!;-		if (c < 48 || c > 57) break;-		Y = Y * 10 + (c - 48);-	}-	p++;-	const Mo = (b[p]! - 48) * 10 + (b[p + 1]! - 48);-	p += 3;-	const D = (b[p]! - 48) * 10 + (b[p + 1]! - 48);-	p += 2;-	let H = 0, Mi = 0, S = 0, ms = 0, off = 0;-	if (p < e && b[p] === 32) {-		p++;-		H = (b[p]! - 48) * 10 + (b[p + 1]! - 48);-		p += 3;-		Mi = (b[p]! - 48) * 10 + (b[p + 1]! - 48);-		p += 3;-		S = (b[p]! - 48) * 10 + (b[p + 1]! - 48);-		p += 2;-		if (p < e && b[p] === 46) {-			p++;-			let f = 0, k = 0;-			for (; p < e && k < 3; p++) {-				const c = b[p]!;-				if (c < 48 || c > 57) break;-				f = f * 10 + (c - 48);-				k++;-			}-			while (k < 3) {-				f *= 10;-				k++;-			}-			ms = f;-			while (p < e) {-				const c = b[p]!;-				if (c < 48 || c > 57) break;-				p++;-			}-		}-		if (p < e && (b[p] === 43 || b[p] === 45)) {-			const sg = b[p] === 45 ? -1 : 1;-			p++;-			const th = (b[p]! - 48) * 10 + (b[p + 1]! - 48);-			p += 2;-			let tm = 0, tsc = 0;-			if (p < e && b[p] === 58) {-				p++;-				tm = (b[p]! - 48) * 10 + (b[p + 1]! - 48);-				p += 2;-				if (p < e && b[p] === 58) {-					p++;-					tsc = (b[p]! - 48) * 10 + (b[p + 1]! - 48);-					p += 2;-				}-			}-			off = sg * ((th * 60 + tm) * 60 + tsc) * 1000;-		}-	}-	const year = bc ? 1 - Y : Y; // PG 'N BC' -> astronomical year 1-N (44 BC -> -43, 1 BC -> 0)-	let ems = Date.UTC(year, Mo - 1, D, H, Mi, S, ms);-	if (year >= 0 && year <= 99) {-		const d = new Date(ems);-		d.setUTCFullYear(year);-		ems = d.getTime();-	} // Date.UTC remaps years 0-99 to 1900+Y; undo it BEFORE applying the tz offset-	return ems - off;-}+// Same parser as the JIT snippet and parseInstantMs (src/temporal.ts): ±infinity / non-ISO -> NaN.+const tsParse = (b: Buffer, o: number, l: number): number => instantFromBytes(b, o, l) ?? NaN; const tsDate: CellDecoder = (b, o, l) => new Date(tsParse(b, o, l)); const tsEpoch: CellDecoder = (b, o, l) => tsParse(b, o, l); @@ -1165,8 +1004,8 @@ const binInt8Str: CellDecoder = (b, o) => { 	return n >= -9007199254740991 && n <= 9007199254740991 ? '' + n : b.readBigInt64BE(o).toString(); }; const binInt8BigInt: CellDecoder = (b, o) => b.readBigInt64BE(o);-const binTsEpoch: CellDecoder = (b, o) => Math.floor(rd64(b, o) / 1000) + PG_EPOCH_MS;-const binTsDate: CellDecoder = (b, o) => new Date(Math.floor(rd64(b, o) / 1000) + PG_EPOCH_MS);+const binTsEpoch: CellDecoder = (b, o) => binTimestampMs(b, o);+const binTsDate: CellDecoder = (b, o) => new Date(binTimestampMs(b, o)); const binDateEpoch: CellDecoder = (b, o) => b.readInt32BE(o) * 86400000 + PG_EPOCH_MS; const binDateDate: CellDecoder = (b, o) => new Date(b.readInt32BE(o) * 86400000 + PG_EPOCH_MS); const binBytea: CellDecoder = (b, o, l) => {
postgres/src/temporal.ts+227 −0
@@ -0,0 +1,227 @@+// PG temporal text -> epoch ms, shared by every text-side temporal decoder: array elements (string),+// interpreted scalars (Buffer), JIT scalars and the JIT json scanner (inline code). All three parse the+// same grammar and must stay bit-identical:+//+//   'infinity' | '-infinity'                                  -> NaN (no JS Date; matches binary)+//   Y+-MM-DD[( |T)HH:MM:SS[.f+][(+|-)HH[:MM[:SS]] | Z]][ BC]+//+// Years have 4+ digits (PG prints 5-6 digit years as-is); ' BC' maps N BC to the astronomical year 1-N.+// Naive values are UTC; the offset may carry seconds (LMT). Fraction digits past ms are truncated.+// Input that doesn't match yields `undefined` from the parsers (`ok = false` in the snippet) so the caller+// can pick NaN (wire text, always ISO) or a Date.parse fallback (json strings, which may be anything).+//+// Two Date.UTC pitfalls are avoided:+//  - it remaps years 0-99 to 1900-1999 — undoing that with setUTCFullYear after the fact breaks Feb 29+//    of year 0 (1900 isn't leap, so it already rolled to Mar 1); instead compute 400 years later (same+//    calendar) and subtract exactly 400 Gregorian years.+//  - it returns NaN as soon as the LOCAL fields fall outside ±8.64e15 ms — the offset is folded into the+//    seconds field so the instant, not the wall clock, is what gets range-checked.++export const PG_EPOCH_MS = 946684800000; // 2000-01-01 UTC in unix ms+export const Y400_MS = 12622780800000; // 146097 days: 400 Gregorian years, always exact++/** Inline-code version. Reads bytes `buf[start..end)` and assigns `out` (number, NaN for ±infinity) and+ *  `ok` (false when the text isn't the grammar above); `out`/`ok` must be declared by the caller. Locals+ *  live in a block, so the snippet can be spliced anywhere (generated mappers, json scanner). */+export function instantSnippet(buf: string, start: string, end: string, out: string, ok: string): string {+	const args: Record<string, string> = { '@buf': buf, '@start': start, '@end': end, '@out': out, '@ok': ok };+	return INSTANT_TEMPLATE.replace(/@(buf|start|end|out|ok)\b/g, (m) => args[m]!);+}+// Locals are $-prefixed so they can never shadow the caller's buf/start/end/out/ok expressions.+const INSTANT_TEMPLATE = instantTemplate('@buf', '@start', '@end', '@out', '@ok').replace(+	/\b(p|e|bc|Y|n|Mo|D|H|Mi|S|ms|off|sg|th|tm|tsc|f|k|c|yy|sh)\b/g,+	'$$$1',+);+function instantTemplate(B: string, start: string, end: string, out: string, ok: string): string {+	return `{ let p = ${start}, e = ${end}; ${ok} = true;+      if (${B}[p] === 105 || (${B}[p] === 45 && ${B}[p + 1] === 105)) { ${out} = NaN; ${ok} = e - p === (${B}[p] === 45 ? 9 : 8) } else {+      let bc = false; if (e - p >= 3 && ${B}[e - 1] === 67 && ${B}[e - 2] === 66 && ${B}[e - 3] === 32) { bc = true; e -= 3 }+      let Y = 0, n = 0; for (; p < e; p++) { const c = ${B}[p]; if (c < 48 || c > 57) break; Y = Y * 10 + (c - 48); n++ }+      if (n < 4 || ${B}[p] !== 45 || ${B}[p + 3] !== 45 || e - p < 6) ${ok} = false; p++;+      const Mo = (${B}[p] - 48) * 10 + (${B}[p + 1] - 48); p += 3;+      const D = (${B}[p] - 48) * 10 + (${B}[p + 1] - 48); p += 2;+      let H = 0, Mi = 0, S = 0, ms = 0, off = 0;+      if (p < e && (${B}[p] === 32 || ${B}[p] === 84)) { p++;+        if (e - p < 8 || ${B}[p + 2] !== 58 || ${B}[p + 5] !== 58) ${ok} = false;+        H = (${B}[p] - 48) * 10 + (${B}[p + 1] - 48); p += 3;+        Mi = (${B}[p] - 48) * 10 + (${B}[p + 1] - 48); p += 3;+        S = (${B}[p] - 48) * 10 + (${B}[p + 1] - 48); p += 2;+        if (p < e && ${B}[p] === 46) { p++; let f = 0, k = 0; for (; p < e && k < 3; p++) { const c = ${B}[p]; if (c < 48 || c > 57) break; f = f * 10 + (c - 48); k++ } while (k < 3) { f *= 10; k++ } ms = f; while (p < e) { const c = ${B}[p]; if (c < 48 || c > 57) break; p++ } }+        if (p < e && (${B}[p] === 43 || ${B}[p] === 45)) { const sg = ${B}[p] === 45 ? -1 : 1; p++; const th = (${B}[p] - 48) * 10 + (${B}[p + 1] - 48); p += 2; let tm = 0, tsc = 0; if (p < e && ${B}[p] === 58) { p++; tm = (${B}[p] - 48) * 10 + (${B}[p + 1] - 48); p += 2; if (p < e && ${B}[p] === 58) { p++; tsc = (${B}[p] - 48) * 10 + (${B}[p + 1] - 48); p += 2 } } off = sg * ((th * 60 + tm) * 60 + tsc) }+        else if (p < e && ${B}[p] === 90) p++;+      }+      if (p !== e) ${ok} = false;+      const yy = bc ? 1 - Y : Y, sh = yy >= 0 && yy <= 99 ? 400 : 0;+      ${out} = Date.UTC(yy + sh, Mo - 1, D, H, Mi, S - off, ms); if (sh !== 0) ${out} -= ${Y400_MS} } }`;+}++// Hand-written mirrors of instantSnippet for the no-eval paths (interpreted decoders, array leaves, the+// json walk). Keep the three in lockstep — test/unit/temporal.test.ts checks them against each other.++/** Buffer version: epoch ms, NaN for ±infinity, undefined when `b[o..o+l)` isn't PG ISO temporal text. */+export function instantFromBytes(b: Uint8Array, o: number, l: number): number | undefined {+	let p = o, e = o + l;+	if (b[p] === 105 || (b[p] === 45 && b[p + 1] === 105)) return l === (b[p] === 45 ? 9 : 8) ? NaN : undefined;+	let bc = false;+	if (e - p >= 3 && b[e - 1] === 67 && b[e - 2] === 66 && b[e - 3] === 32) {+		bc = true;+		e -= 3;+	}+	let Y = 0, n = 0;+	for (; p < e; p++) {+		const c = b[p]!;+		if (c < 48 || c > 57) break;+		Y = Y * 10 + (c - 48);+		n++;+	}+	if (n < 4 || b[p] !== 45 || b[p + 3] !== 45 || e - p < 6) return undefined;+	p++;+	const Mo = (b[p]! - 48) * 10 + (b[p + 1]! - 48);+	p += 3;+	const D = (b[p]! - 48) * 10 + (b[p + 1]! - 48);+	p += 2;+	let H = 0, Mi = 0, S = 0, ms = 0, off = 0;+	if (p < e && (b[p] === 32 || b[p] === 84)) {+		p++;+		if (e - p < 8 || b[p + 2] !== 58 || b[p + 5] !== 58) return undefined;+		H = (b[p]! - 48) * 10 + (b[p + 1]! - 48);+		p += 3;+		Mi = (b[p]! - 48) * 10 + (b[p + 1]! - 48);+		p += 3;+		S = (b[p]! - 48) * 10 + (b[p + 1]! - 48);+		p += 2;+		if (p < e && b[p] === 46) {+			p++;+			let f = 0, k = 0;+			for (; p < e && k < 3; p++) {+				const c = b[p]!;+				if (c < 48 || c > 57) break;+				f = f * 10 + (c - 48);+				k++;+			}+			while (k < 3) {+				f *= 10;+				k++;+			}+			ms = f;+			while (p < e) {+				const c = b[p]!;+				if (c < 48 || c > 57) break;+				p++;+			}+		}+		if (p < e && (b[p] === 43 || b[p] === 45)) {+			const sg = b[p] === 45 ? -1 : 1;+			p++;+			const th = (b[p]! - 48) * 10 + (b[p + 1]! - 48);+			p += 2;+			let tm = 0, tsc = 0;+			if (p < e && b[p] === 58) {+				p++;+				tm = (b[p]! - 48) * 10 + (b[p + 1]! - 48);+				p += 2;+				if (p < e && b[p] === 58) {+					p++;+					tsc = (b[p]! - 48) * 10 + (b[p + 1]! - 48);+					p += 2;+				}+			}+			off = sg * ((th * 60 + tm) * 60 + tsc);+		} else if (p < e && b[p] === 90) p++;+	}+	if (p !== e) return undefined;+	const yy = bc ? 1 - Y : Y, sh = yy >= 0 && yy <= 99 ? 400 : 0;+	const ems = Date.UTC(yy + sh, Mo - 1, D, H, Mi, S - off, ms);+	return sh !== 0 ? ems - Y400_MS : ems;+}++/** String version of instantFromBytes. */+export function instantFromString(s: string): number | undefined {+	let p = 0, e = s.length;+	if (s.charCodeAt(0) === 105 || (s.charCodeAt(0) === 45 && s.charCodeAt(1) === 105)) {+		return s === 'infinity' || s === '-infinity' ? NaN : undefined;+	}+	let bc = false;+	if (e >= 3 && s.charCodeAt(e - 1) === 67 && s.charCodeAt(e - 2) === 66 && s.charCodeAt(e - 3) === 32) {+		bc = true;+		e -= 3;+	}+	let Y = 0, n = 0;+	for (; p < e; p++) {+		const c = s.charCodeAt(p);+		if (c < 48 || c > 57) break;+		Y = Y * 10 + (c - 48);+		n++;+	}+	if (n < 4 || s.charCodeAt(p) !== 45 || s.charCodeAt(p + 3) !== 45 || e - p < 6) return undefined;+	p++;+	const Mo = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);+	p += 3;+	const D = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);+	p += 2;+	let H = 0, Mi = 0, S = 0, ms = 0, off = 0;+	if (p < e && (s.charCodeAt(p) === 32 || s.charCodeAt(p) === 84)) {+		p++;+		if (e - p < 8 || s.charCodeAt(p + 2) !== 58 || s.charCodeAt(p + 5) !== 58) return undefined;+		H = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);+		p += 3;+		Mi = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);+		p += 3;+		S = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);+		p += 2;+		if (p < e && s.charCodeAt(p) === 46) {+			p++;+			let f = 0, k = 0;+			for (; p < e && k < 3; p++) {+				const c = s.charCodeAt(p);+				if (c < 48 || c > 57) break;+				f = f * 10 + (c - 48);+				k++;+			}+			while (k < 3) {+				f *= 10;+				k++;+			}+			ms = f;+			while (p < e) {+				const c = s.charCodeAt(p);+				if (c < 48 || c > 57) break;+				p++;+			}+		}+		if (p < e && (s.charCodeAt(p) === 43 || s.charCodeAt(p) === 45)) {+			const sg = s.charCodeAt(p) === 45 ? -1 : 1;+			p++;+			const th = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);+			p += 2;+			let tm = 0, tsc = 0;+			if (p < e && s.charCodeAt(p) === 58) {+				p++;+				tm = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);+				p += 2;+				if (p < e && s.charCodeAt(p) === 58) {+					p++;+					tsc = (s.charCodeAt(p) - 48) * 10 + (s.charCodeAt(p + 1) - 48);+					p += 2;+				}+			}+			off = sg * ((th * 60 + tm) * 60 + tsc);+		} else if (p < e && s.charCodeAt(p) === 90) p++;+	}+	if (p !== e) return undefined;+	const yy = bc ? 1 - Y : Y, sh = yy >= 0 && yy <= 99 ? 400 : 0;+	const ems = Date.UTC(yy + sh, Mo - 1, D, H, Mi, S - off, ms);+	return sh !== 0 ? ems - Y400_MS : ems;+}++/** int64 µs since 2000-01-01 (big-endian at b[o]) -> epoch ms, floored, exact over the whole Date range+ *  without BigInt: hi*2^32 = 1000*(hi*4294967) + hi*296, so the division only touches the small part.+ *  (hi*2^32 + lo as one double loses µs past 2^53 ≈ year 2285 and can round across a ms/second.)+ *  ±infinity (int64 max/min) and anything else past ±8.64e15 ms lands out of Date range. */+export function binTimestampMs(b: Uint8Array, o: number): number {+	const hi = (b[o]! << 24) | (b[o + 1]! << 16) | (b[o + 2]! << 8) | b[o + 3]!;+	const lo = ((b[o + 4]! << 24) | (b[o + 5]! << 16) | (b[o + 6]! << 8) | b[o + 7]!) >>> 0;+	return hi * 4294967 + Math.floor((hi * 296 + lo) / 1000) + PG_EPOCH_MS;+}+/** Inline-code version of binTimestampMs — an expression over the `hi`/`lo` locals declared by RD64. */+export const BIN_TS_MS_EXPR = `hi * 4294967 + Math.floor((hi * 296 + lo) / 1000) + ${PG_EPOCH_MS}`;
postgres/test/unit/temporal.test.ts+155 −0
@@ -0,0 +1,155 @@+// src/temporal.ts: the three copies of the PG temporal text parser (inline snippet, Buffer, string) must agree+// with each other and with an independent reference; binTimestampMs must equal the exact BigInt division.+import { describe, expect, test } from 'bun:test';+import {+	binTimestampMs,+	instantFromBytes,+	instantFromString,+	instantSnippet,+	PG_EPOCH_MS,+} from '../../src/temporal.ts';++const snippetFn = new Function(+	'b',+	'o',+	'l',+	`let ms, ok; ${instantSnippet('b', 'o', 'o + l', 'ms', 'ok')} return ok ? ms : undefined`,+) as (b: Uint8Array, o: number, l: number) => number | undefined;++/** All three parsers on `s` (bytes at a non-zero offset to catch o-relative bugs); throws if they disagree. */+const parse = (s: string): number | undefined => {+	const pad = Buffer.from('xx' + s + 'yy');+	const a = instantFromString(s), b = instantFromBytes(pad, 2, s.length), c = snippetFn(pad, 2, s.length);+	expect(Object.is(b, a)).toBe(true);+	expect(Object.is(c, a)).toBe(true);+	return a;+};+const iso = (+	ms: number | undefined,+) => (ms === undefined ? 'undefined' : Number.isNaN(ms) ? 'NaN' : new Date(ms).toISOString());++// Reference: setUTCFullYear/setUTCHours take the year verbatim (no 0-99 remap) and normalize overflow.+const ref = (y: number, mo: number, d: number, h: number, mi: number, s: number, ms: number, offSec: number) => {+	const dt = new Date(0);+	dt.setUTCFullYear(y, mo - 1, d);+	dt.setUTCHours(h, mi, s - offSec, ms);+	return dt.getTime();+};++describe('instant text parser', () => {+	test.each([+		// [text, expected ISO]+		['2020-06-01 13:45:00', '2020-06-01T13:45:00.000Z'],+		['2020-06-01 13:45:00.123456+02', '2020-06-01T11:45:00.123Z'],+		['2020-06-01T13:45:00.1+05:45', '2020-06-01T08:00:00.100Z'],+		['1880-01-01 02:02:04+02:02:04', '1880-01-01T00:00:00.000Z'],+		['2020-06-01T13:45:00Z', '2020-06-01T13:45:00.000Z'],+		['2020-06-01', '2020-06-01T00:00:00.000Z'],+		// years 0-99 (Date.UTC remaps them to 19xx) incl. Feb 29 of 1 BC (year 0 is leap, 1900 isn't)+		['0001-02-29 12:00:00+00 BC', '0000-02-29T12:00:00.000Z'],+		['0001-02-29T12:00:00 BC', '0000-02-29T12:00:00.000Z'],+		['0001-02-29 BC', '0000-02-29T00:00:00.000Z'],+		['0004-02-29', '0004-02-29T00:00:00.000Z'],+		['0099-12-31 23:00:00-01', '0100-01-01T00:00:00.000Z'],+		['0001-01-01 01:00:00+02', '0000-12-31T23:00:00.000Z'],+		['0100-01-01 00:00:00+01', '0099-12-31T23:00:00.000Z'],+		['0002-12-31T23:59:59.999+00:00 BC', '-000001-12-31T23:59:59.999Z'],+		['0002-12-31 BC', '-000001-12-31T00:00:00.000Z'],+		['4714-11-24 00:00:00+00 BC', '-004713-11-24T00:00:00.000Z'],+		// 5+ digit years; the instant (not the wall clock) is range-checked+		['10000-01-01T00:00:00+00:00', '+010000-01-01T00:00:00.000Z'],+		['10000-01-01T01:59:59.999+02:00', '9999-12-31T23:59:59.999Z'],+		['10000-01-01', '+010000-01-01T00:00:00.000Z'],+		['275760-09-13 03:00:00+03', '+275760-09-13T00:00:00.000Z'],+		['275760-09-13 00:00:00.000567+00', '+275760-09-13T00:00:00.000Z'],+		['275760-09-13 00:00:00.001+00', 'NaN'],+		['271822-04-19 21:00:00-03 BC', '-271821-04-20T00:00:00.000Z'],+		['infinity', 'NaN'],+		['-infinity', 'NaN'],+	])('%s', (s, want) => {+		expect(iso(parse(s))).toBe(want);+	});++	test.each([+		'',+		'infinityx',+		'-inf',+		'20-01-01',+		'2020/01/01',+		'2020-01-01 1:00:00',+		'2020-01-01 12:00',+		'2020-01-01 12:00:00 junk',+		'-000001-01-01',+		'Jan 1 2020',+	])('rejects %p', (s) => {+		expect(parse(s)).toBeUndefined();+	});++	test('random dates, times, offsets agree with the reference', () => {+		let seed = 12345;+		const rnd = (n: number) => {+			seed = (seed * 1103515245 + 12345) % 2147483648;+			return seed % n;+		};+		const p2 = (n: number) => String(n).padStart(2, '0');+		for (let i = 0; i < 20000; i++) {+			const y = rnd(5) === 0 ? rnd(200) - 99 : rnd(250000) - 4000; // astronomical; dense around 0-99+			const mo = rnd(12) + 1, d = rnd(new Date(Date.UTC(2000 + (((y % 400) + 400) % 400), mo, 0)).getUTCDate()) + 1;+			const h = rnd(24), mi = rnd(60), s = rnd(60), us = rnd(1000000);+			const oh = rnd(16), om = rnd(4) * 15, os = rnd(10) === 0 ? rnd(60) : 0, sg = rnd(2) ? 1 : -1;+			const off = sg * ((oh * 60 + om) * 60 + os);+			const Y = y <= 0 ? 1 - y : y;+			const txt = `${String(Y).padStart(4, '0')}-${p2(mo)}-${p2(d)} ${p2(h)}:${p2(mi)}:${p2(s)}.${+				String(us).padStart(6, '0')+			}${sg < 0 ? '-' : '+'}${p2(oh)}:${p2(om)}${os ? ':' + p2(os) : ''}${y <= 0 ? ' BC' : ''}`;+			const got = parse(txt);+			const want = ref(y, mo, d, h, mi, s, Math.floor(us / 1000), off);+			if (got !== want) throw new Error(`${txt}: got ${iso(got)}, want ${iso(want)}`);+		}+	});+});++describe('binTimestampMs', () => {+	const enc = (us: bigint) => {+		const b = Buffer.alloc(10);+		b.writeBigInt64BE(us, 1);+		return b;+	};+	const exact = (us: bigint) => {+		let q = us / 1000n;+		if (us % 1000n < 0n) q -= 1n;+		return Number(q) + PG_EPOCH_MS;+	}; // floor++	test.each([+		0n,+		1n,+		-1n,+		999n,+		-999n,+		1000n,+		-1001n,+		8639053315200000567n, // 275760-09-13 00:00:00.000567 — as one double it rounded past 8.64e15+		8639053315200000000n,+		253402300799999999n - 946684800000000n, // 9999-12-31 23:59:59.999999 — rounded up to year 10000+		95649120000999999n, // 5000-01-01 00:00:00.999999+		-8640000000000000000n - 946684800000000n, // -271821-04-20, start of Date range+		9223372036854775807n,+		-9223372036854775808n, // PG ±infinity+	])('%p', (us) => {+		const got = binTimestampMs(enc(us), 1);+		const want = exact(us);+		if (Math.abs(want) <= 8.64e15) expect(got).toBe(want);+		else expect(Number.isNaN(new Date(got).getTime())).toBe(true);+	});++	test('random int64 µs in Date range match the exact BigInt division', () => {+		let s = 987654321n;+		for (let i = 0; i < 20000; i++) {+			s = (s * 6364136223846793005n + 1442695040888963407n) & 0xffffffffffffffffn;+			const us = (s % 17280000000000000000n) - 8640000000000000000n - 946684800000000n;+			const got = binTimestampMs(enc(us), 1), want = exact(us);+			if (got !== want) throw new Error(`${us}: got ${got}, want ${want}`);+		}+	});+});

→ Outcome

Why this verdict

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

The recorded Failure Handling observation did not become a verified finding.

Evidence and perspectives

  • Observation · Failure HandlingReplaces manual parseInstantMs with instantFromString(s) ?? NaN, converting parse failures to NaN success values that silently propagate invalid temporal data.

    Principle · Keep Failure Visible to the Caller

    Recorded file postgres/src/decode.ts · no line recorded

Supporting evidence

Reviewed 27 Nov 2026Revision 9e43331e26175 changed files+524 −193Judge score 5/5
Approved · 0 retained findingsmicrosoft/markitdown#2458

fix(wikipedia): drop the site suffix from italicised titles

Input

PR author’s description

Summary

WikipediaConverter looks for the article title in a span.mw-page-title-main. Wikipedia only emits that span when the title is plain text — titles rendered with markup (italicised species, film,…

PR diff

Current GitHub diff ↗
packages/markitdown/src/markitdown/converters/_wikipedia_converter.py · patch excerpt
-        title_elm = soup.find("span", {"class": "mw-page-title-main"})+        # Wikipedia only wraps the title in mw-page-title-main when it is plain+        # text. Titles that carry markup -- italicised species, film, album and+        # journal names -- are written straight into the first heading instead.
Browse 2 changed files
packages/markitdown/src/markitdown/converters/_wikipedia_converter.py+10 −2
@@ -64,15 +64,23 @@ def convert(          # Print only the main content         body_elm = soup.find("div", {"id": "mw-content-text"})-        title_elm = soup.find("span", {"class": "mw-page-title-main"})+        # Wikipedia only wraps the title in mw-page-title-main when it is plain+        # text. Titles that carry markup -- italicised species, film, album and+        # journal names -- are written straight into the first heading instead.+        title_elm = soup.find("span", {"class": "mw-page-title-main"}) or soup.find(+            "h1", {"id": "firstHeading"}+        )          webpage_text = ""         main_title = None if soup.title is None else soup.title.string          if body_elm:             # What's the title             if title_elm and isinstance(title_elm, bs4.Tag):-                main_title = title_elm.string+                # .string is None as soon as the element holds more than one+                # child, which is what a title mixing markup with plain text+                # looks like, so gather the descendant text instead.+                main_title = title_elm.get_text()              # Treat whitespace-only titles as if they were absent             if main_title:
packages/markitdown/tests/test_wikipedia_titles.py+57 −0
@@ -0,0 +1,57 @@+#!/usr/bin/env python3 -m pytest+"""Article titles that carry markup must survive conversion."""++import io++from markitdown import StreamInfo+from markitdown.converters import WikipediaConverter++STREAM_INFO = StreamInfo(+    url="https://en.wikipedia.org/wiki/Example",+    mimetype="text/html",+    extension=".html",+)+++def _page(heading: str, document_title: str) -> io.BytesIO:+    """Build a page shaped like the article HTML Wikipedia actually serves."""+    return io.BytesIO(+        f"""<html><head><title>{document_title} - Wikipedia</title></head><body>+<h1 id="firstHeading" class="firstHeading mw-first-heading">{heading}</h1>+<div id="mw-content-text"><p>Body text.</p></div>+</body></html>""".encode()+    )+++def test_plain_title_is_read_from_the_title_span() -> None:+    """A plain title keeps being read from mw-page-title-main."""+    page = _page(+        '<span lang="en" dir="ltr"><span class="mw-page-title-main">Paris</span></span>',+        "Paris",+    )++    result = WikipediaConverter().convert(page, STREAM_INFO)++    assert result.title == "Paris"+    assert result.markdown.lstrip().startswith("# Paris")+++def test_fully_italicised_title_keeps_its_text() -> None:+    """Wikipedia drops the title span for italicised titles, e.g. species names."""+    page = _page("<i>Escherichia coli</i>", "Escherichia coli")++    result = WikipediaConverter().convert(page, STREAM_INFO)++    # Without the first-heading fallback this became "Escherichia coli - Wikipedia".+    assert result.title == "Escherichia coli"+    assert result.markdown.lstrip().startswith("# Escherichia coli")+++def test_title_mixing_markup_and_plain_text_keeps_both_parts() -> None:+    """A disambiguated italic title spans several children, so .string is None."""+    page = _page("<i>Titanic</i> (1997 film)", "Titanic (1997 film)")++    result = WikipediaConverter().convert(page, STREAM_INFO)++    assert result.title == "Titanic (1997 film)"+    assert result.markdown.lstrip().startswith("# Titanic (1997 film)")

→ Outcome

Why this verdict

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

Supporting evidence

Reviewed 27 Nov 2026Revision f75aa5e652e02 changed files+67 −2Judge score 5/5
Approved · 0 retained findingsgithub/github-mcp-server#3419

fix(repos): return a resource link for files over 1 MB in get_file_contents

Input

PR author’s description

Summary

get_file_contents errors on every file of 1 MB or more since v1.10.0. This treats the Contents API's encoding: "none" response as "content not returned", so the existing large-file resource link is…

PR diff

Current GitHub diff ↗
pkg/github/repositories_helper.go · patch excerpt
-	if file.Content == nil {+	// Files over 1 MB come back with encoding "none" and no content.+	if file.Content == nil || file.GetEncoding() == "none" {
Browse 2 changed files
pkg/github/repositories_helper.go+2 −1
@@ -214,7 +214,8 @@ func inspectRepositoryFile(ctx context.Context, client *github.Client, owner, re }  func repositoryContentBytes(file *github.RepositoryContent) ([]byte, bool, error) {-	if file.Content == nil {+	// Files over 1 MB come back with encoding "none" and no content.+	if file.Content == nil || file.GetEncoding() == "none" { 		return []byte{}, file.GetType() != "symlink" && file.GetSize() == 0, nil 	} 	content, err := file.GetContent()
pkg/github/repositories_test.go+16 −0
@@ -795,6 +795,22 @@ func Test_GetFileContents_ContentlessRequestCounts(t *testing.T) { 		require.True(t, ok) 	}) +	t.Run("large file with encoding none", func(t *testing.T) {+		result, requests := runRepositoryReadFixture(t, repositoryReadFixture{+			contents: &github.RepositoryContent{+				Type: new("file"), Path: new("large.bin"), SHA: new(fileSHA), Size: new(largeSize),+				Content: new(""), Encoding: new("none"),+			},+			trees: map[string]*github.Tree{commitSHA: {Entries: []*github.TreeEntry{+				{Path: new("large.bin"), Mode: new("100644"), Type: new("blob"), SHA: new(fileSHA)},+			}}},+		}, args("large.bin"))+		require.False(t, result.IsError)+		assert.Equal(t, 2, requests)+		_, ok := result.Content[1].(*mcp.ResourceLink)+		require.True(t, ok)+	})+ 	t.Run("internal large link uses exact-path tree descent", func(t *testing.T) { 		target := "../target.bin" 		linkSHA := gitBlobSHA([]byte(target))

→ Outcome

Why this verdict

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

Supporting evidence

Reviewed 27 Nov 2026Revision 6b09a70d2f762 changed files+18 −1Judge score 5/5
AboutReview principlesSupportPrivacyContact
(C) 2026 Superpositional>
Member of the NVIDIA Inception Program