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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 61 additions & 11 deletions .github/workflows/randomized-order-nightly.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,26 @@ name: Randomized Order Nightly
# as well as the tests inside each file, verified: seed 3 runs three probe files
# as c, b, a where seeds 1 and 2 keep a, b, c.
#
# **The isolation setting decides which half of that hazard a lane can see**,
# which is why the matrix carries it per entry rather than passing
# `--parallel=1` to everything:
#
# - `--parallel=1` means "one worker, *isolated*" (Bun implies `--isolate`),
# so each file gets a fresh global. Shuffling file order under it can only
# surface order dependence *inside* a file.
# - The `api-integration` lane is the one the merge gate runs with no
# `--parallel` at all (scripts/lib/test-lanes.ts), sharing one module graph
# across all 101 files. Cross-file leakage is only reachable in that mode,
# so it gets its own entry that reproduces it — without one, the class this
# workflow exists for had no detector anywhere in CI.
#
# Deliberately **not** merge-gating. A suite that fails weekly on a different
# seed is a bug report; making it block merges teaches everyone to re-run CI,
# and that habit outlasts the fix. Failures rely on the standard
# failed-scheduled-run notification.
#
# The seed is the run number, so every night is a new order and any failure
# names the exact seed to reproduce with:
# (cd apps/<workspace> && bun test --timeout 15000 --parallel=1 --randomize --seed=<n>)
# The seed is the run number, so every night is a new order, and each job logs
# the exact command to reproduce its own lane.

on:
schedule:
Expand All @@ -39,16 +51,41 @@ concurrency:

jobs:
randomized:
name: Randomized order (${{ matrix.workspace }})
name: Randomized order (${{ matrix.lane }})
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
# One workspace's ordering bug says nothing about another's, and finding
# all of them in one night beats finding the first one four nights
# running.
# One lane's ordering bug says nothing about another's, and finding all of
# them in one night beats finding the first one four nights running. Kept
# `false` now that a lane is red on a known, separately tracked defect:
# otherwise that one failure would cancel every other lane's evidence.
fail-fast: false
matrix:
workspace: [api, shared, runtime]
# `include`-only, so each lane carries its own isolation setting and
# path. `isolation` is the empty string for the lane the merge gate runs
# unisolated; every other lane keeps `--parallel=1` (= one worker,
# isolated). `path` empty means the whole workspace suite.
include:
- lane: api
workspace: api
isolation: "--parallel=1"
path: ""
# The same files the `api` entry above already runs, deliberately
# run a second time without isolation. That is the entire point: at
# `--parallel=1` a fresh global per file hides exactly the leakage
# the merge gate's unisolated lane is exposed to.
- lane: api-integration
workspace: api
isolation: ""
path: tests/integration
- lane: shared
workspace: shared
isolation: "--parallel=1"
path: ""
- lane: runtime
workspace: runtime
isolation: "--parallel=1"
path: ""
env:
DATABASE_PATH: /tmp/mangostudio-test.sqlite
SEED: ${{ inputs.seed || github.run_number }}
Expand Down Expand Up @@ -79,15 +116,28 @@ jobs:
env:
MANGOSTUDIO_DIAGNOSTIC_LOGS: "0"
WORKSPACE: ${{ matrix.workspace }}
ISOLATION: ${{ matrix.isolation }}
LANE_PATH: ${{ matrix.path }}
run: |
# `set -o pipefail` is load-bearing, not boilerplate: a step without an
# explicit `shell:` runs under `bash -e {0}`, which does NOT set it, so
# the pipeline's status would be `tee`'s and a failing suite would
# report success — no notification, and the log upload below (gated on
# `outcome != success`) would never run.
set -o pipefail
echo "::notice::Reproduce with: (cd apps/${WORKSPACE} && bun test --timeout 15000 --parallel=1 --randomize --seed=${SEED})"
bun test --timeout 15000 --parallel=1 --randomize --seed="${SEED}" 2>&1 | tee run.log
# An array, not a string: `isolation` and `path` are empty for at
# least one lane each, and a quoted empty string would reach
# `bun test` as an argument it reads as a path filter matching
# nothing. Appended with `if` rather than `&&` so an empty value does
# not make the list return 1 and trip `bash -e`.
args=(--timeout 15000 --randomize "--seed=${SEED}")
if [ -n "${ISOLATION}" ]; then args+=("${ISOLATION}"); fi
if [ -n "${LANE_PATH}" ]; then args+=("${LANE_PATH}"); fi
# Carries the env the job sets, not just the flags: a paste that
# leaves `MANGOSTUDIO_DIAGNOSTIC_LOGS` or `DATABASE_PATH` behind runs
# a different suite than the one that went red.
echo "::notice::Reproduce with: (cd apps/${WORKSPACE} && DATABASE_PATH=${DATABASE_PATH} MANGOSTUDIO_DIAGNOSTIC_LOGS=${MANGOSTUDIO_DIAGNOSTIC_LOGS} bun test ${args[*]})"
bun test "${args[@]}" 2>&1 | tee run.log

# The order is the finding. Without it a red run names a failing test and
# nothing about what ran before it, which is the half that matters.
Expand All @@ -97,6 +147,6 @@ jobs:
if: ${{ !cancelled() && steps.randomized.outcome != 'success' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: randomized-order-${{ matrix.workspace }}-seed-${{ env.SEED }}
name: randomized-order-${{ matrix.lane }}-seed-${{ env.SEED }}
path: apps/${{ matrix.workspace }}/run.log
retention-days: 14
2 changes: 1 addition & 1 deletion apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"test:integration": "MANGOSTUDIO_DIAGNOSTIC_LOGS=0 bun test --timeout 15000 tests/integration",
"test:coverage": "bun ../../scripts/ci/run-workspace-coverage.ts --workspace=api",
"test:coverage:unit": "MANGOSTUDIO_DIAGNOSTIC_LOGS=0 bun test --timings=../../.mango/artifacts/timings/api-unit.json --update-timings --coverage --coverage-dir=../../.mango/artifacts/coverage/api-unit --timeout 15000 --parallel=1 --reporter=junit --reporter-outfile=../../.mango/artifacts/junit/api-unit.xml $MANGOSTUDIO_BUN_TEST_ARGS tests/unit",
"test:coverage:integration": "MANGOSTUDIO_DIAGNOSTIC_LOGS=0 bun test --timings=../../.mango/artifacts/timings/api-integration.json --update-timings --coverage --coverage-dir=../../.mango/artifacts/coverage/api-integration --timeout 15000 --reporter=junit --reporter-outfile=../../.mango/artifacts/junit/api-integration.xml $MANGOSTUDIO_BUN_TEST_ARGS tests/integration"
"test:coverage:integration": "MANGOSTUDIO_DIAGNOSTIC_LOGS=0 bun test --coverage --coverage-dir=../../.mango/artifacts/coverage/api-integration --timeout 15000 --reporter=junit --reporter-outfile=../../.mango/artifacts/junit/api-integration.xml $MANGOSTUDIO_BUN_TEST_ARGS tests/integration"
},
"dependencies": {
"@ai-sdk/deepseek": "^3.0.24",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { afterEach, beforeAll, describe, expect, it } from 'bun:test';
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { ChatTodosResponseSchema, type TodoList } from '@mangostudio/shared/todos';
import Value from 'typebox/value';
import { getDb } from '../../../src/db/database';
Expand All @@ -18,7 +18,19 @@ import {
let TEST_USER!: UserFixture;
let TEST_CHAT!: ChatFixture;

beforeAll(async () => {
/**
* Fresh user and chat per test rather than once per file: `chat_todos` is
* keyed by chat id and the shared in-memory database is never reset between
* tests. A single `TEST_CHAT` created in `beforeAll` was written by "returns
* the persisted todo list with its updatedAt timestamp" and read by "returns
* an empty list with null updatedAt when the chat has no todos" — order
* dependent under randomization, since both target the same chat. Reproduced
* with `bun test --randomize --seed=1` (also seed=2, 3, 6).
*
* `insertTestUser`/`insertTestChat` already mint random ids per call, so
* moving the calls into `beforeEach` is enough to namespace every test's rows.
*/
beforeEach(async () => {
TEST_USER = await insertTestUser();
TEST_CHAT = await insertTestChat(TEST_USER.id);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,40 @@ import Value from 'typebox/value';
import { getDb } from '../../../src/db/database';
import { loadConfigForTest } from '../../../src/lib/config';
import { settingsRoutes } from '../../../src/routes/settings';
import { makeTestIdentity, type UserFixture } from '../../support/factories';
import { createAuthenticatedApiTestApp } from '../../support/harness/create-api-test-app';

const TEST_USER = {
id: 'agent-settings-user',
name: 'Agent Settings User',
email: 'agent-settings@mangostudio.test',
};

const OTHER_USER = {
id: 'agent-settings-other-user',
name: 'Other Agent Settings User',
email: 'other-agent-settings@mangostudio.test',
};

const TEST_AUTH_SECRET = 'test-secret-at-least-32-characters-long';

/**
* Fresh identities per test, because the rows these tests write are keyed by
* user and nothing truncates them in between.
*
* Every settings route here persists per-user state into the shared in-memory
* database — `user_app_settings`, `user_tool_settings`, and the built-in agent
* overrides a `PUT` saves — and `setupTestEnvironment()` migrates that database
* once per process. Isolation does not help: `--isolate` gives each *file* a
* fresh module graph, not each test. With fixed ids the file was therefore
* order-dependent, and in one direction it failed: run "updates built-in
* default settings per user" first and its persisted `default` override is what
* "synthesizes default from legacy app settings and enabled tools" then reads,
* so the assertion on `Legacy chat prompt` gets `Persisted chat prompt`.
* Reproduced with `bun test --randomize --seed=2` (also 4, 5, 6; 1, 3, 7, 8 are
* clean), and it is what the randomized-order nightly has reported every night
* since that workflow landed.
*
* `makeTestIdentity` (tests/support/factories) mints them, so the namespacing
* rule is one helper rather than a per-file counter.
*/
let testUser: UserFixture;
let otherUser: UserFixture;

let restoreAuth: (() => void) | null = null;
let agentsDir: string;

beforeEach(() => {
testUser = makeTestIdentity('agent-settings-user', 'Agent Settings User');
otherUser = makeTestIdentity('agent-settings-other-user', 'Other Agent Settings User');
agentsDir = mkdtempSync(join(tmpdir(), 'mango-agent-routes-'));
loadConfigForTest({
agents: { dir: agentsDir },
Expand All @@ -49,7 +63,7 @@ afterEach(() => {

describe('settings agents routes', () => {
it('lists built-in default and explore agents for authenticated users', async () => {
const { app, restore } = createAuthenticatedApiTestApp(TEST_USER, settingsRoutes);
const { app, restore } = createAuthenticatedApiTestApp(testUser, settingsRoutes);
restoreAuth = restore;

const response = await app.handle(new Request('http://localhost/settings/agents'));
Expand All @@ -71,8 +85,8 @@ describe('settings agents routes', () => {
await getDb()
.insertInto('user_app_settings')
.values({
id: 'agent-legacy-app-settings',
userId: TEST_USER.id,
id: `agent-legacy-app-settings-${testUser.id}`,
userId: testUser.id,
settingsJson: JSON.stringify({
...DEFAULT_APP_SETTINGS,
promptSettings: {
Expand All @@ -90,16 +104,16 @@ describe('settings agents routes', () => {
await getDb()
.insertInto('user_tool_settings')
.values({
id: 'agent-disabled-tool',
userId: TEST_USER.id,
id: `agent-disabled-tool-${testUser.id}`,
userId: testUser.id,
toolName: 'generate_image',
enabled: 0,
parametersJson: '{}',
createdAt: Date.now(),
updatedAt: Date.now(),
})
.execute();
const { app, restore } = createAuthenticatedApiTestApp(TEST_USER, settingsRoutes);
const { app, restore } = createAuthenticatedApiTestApp(testUser, settingsRoutes);
restoreAuth = restore;

const response = await app.handle(new Request('http://localhost/settings/agents/default'));
Expand All @@ -119,7 +133,7 @@ describe('settings agents routes', () => {
});

it('updates built-in default settings per user', async () => {
const { app, restore } = createAuthenticatedApiTestApp(TEST_USER, settingsRoutes);
const { app, restore } = createAuthenticatedApiTestApp(testUser, settingsRoutes);
restoreAuth = restore;

const update = await app.handle(
Expand Down Expand Up @@ -151,7 +165,7 @@ describe('settings agents routes', () => {
});

restoreAuth?.();
const other = createAuthenticatedApiTestApp(OTHER_USER, settingsRoutes);
const other = createAuthenticatedApiTestApp(otherUser, settingsRoutes);
restoreAuth = other.restore;

const otherResponse = await other.app.handle(
Expand All @@ -164,7 +178,7 @@ describe('settings agents routes', () => {
});

it('updates built-in explore settings per user and returns the saved profile in the list endpoint', async () => {
const { app, restore } = createAuthenticatedApiTestApp(TEST_USER, settingsRoutes);
const { app, restore } = createAuthenticatedApiTestApp(testUser, settingsRoutes);
restoreAuth = restore;

const update = await app.handle(
Expand Down Expand Up @@ -203,7 +217,7 @@ describe('settings agents routes', () => {
);

restoreAuth?.();
const other = createAuthenticatedApiTestApp(OTHER_USER, settingsRoutes);
const other = createAuthenticatedApiTestApp(otherUser, settingsRoutes);
restoreAuth = other.restore;

const otherListResponse = await other.app.handle(
Expand All @@ -218,7 +232,7 @@ describe('settings agents routes', () => {
});

it('creates, reads, updates, and deletes markdown-backed user agents', async () => {
const { app, restore } = createAuthenticatedApiTestApp(TEST_USER, settingsRoutes);
const { app, restore } = createAuthenticatedApiTestApp(testUser, settingsRoutes);
restoreAuth = restore;

const create = await app.handle(
Expand Down Expand Up @@ -277,7 +291,7 @@ describe('settings agents routes', () => {
});

it('previews markdown and returns typed validation errors', async () => {
const { app, restore } = createAuthenticatedApiTestApp(TEST_USER, settingsRoutes);
const { app, restore } = createAuthenticatedApiTestApp(testUser, settingsRoutes);
restoreAuth = restore;

const preview = await app.handle(
Expand Down
Loading