diff --git a/apps/server/src/fork/processRunnerFork.closedStdin.test.ts b/apps/server/src/fork/processRunnerFork.closedStdin.test.ts index 0b76c52f26452..6dc7f3dc59dbd 100644 --- a/apps/server/src/fork/processRunnerFork.closedStdin.test.ts +++ b/apps/server/src/fork/processRunnerFork.closedStdin.test.ts @@ -11,7 +11,7 @@ import * as Layer from "effect/Layer"; import * as PlatformError from "effect/PlatformError"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import { ChildProcessSpawner } from "effect/process"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as ProcessRunner from "../processRunner.ts"; import { isClosedStdin } from "./processRunnerFork.ts"; @@ -98,8 +98,34 @@ describe("a child that closed its stdin", () => { }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))), ); - it("is told by the broken pipe's code anywhere under the error", () => { + it.effect("ends with its own exit code when Node already closed its stdin", () => + Effect.gen(function* () { + const result = yield* runOn( + exitedChild({ code: 3, stdout: "", stdin: "ERR_STREAM_DESTROYED" }), + { command: "program", args: [], stdin: "input" }, + ); + assert.strictEqual(result.code, 3); + }), + ); + + it.live("a write after a real child has exited counts as a closed stdin", () => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* spawner.spawn( + ChildProcess.make(process.execPath, ["-e", "process.exit(3)"]), + ); + yield* child.exitCode; + const error = yield* Stream.run(Stream.encodeText(Stream.make("late")), child.stdin).pipe( + Effect.flip, + ); + assert.isTrue(isClosedStdin(error)); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it("is told by the closed pipe's code anywhere under the error", () => { assert.isTrue(isClosedStdin(stdinFailure("EPIPE"))); + assert.isTrue(isClosedStdin(stdinFailure("ERR_STREAM_DESTROYED"))); + assert.isTrue(isClosedStdin(stdinFailure("ERR_STREAM_PREMATURE_CLOSE"))); assert.isTrue(isClosedStdin({ code: "EPIPE" })); assert.isFalse(isClosedStdin(stdinFailure("EIO"))); assert.isFalse(isClosedStdin(undefined)); diff --git a/apps/server/src/fork/processRunnerFork.ts b/apps/server/src/fork/processRunnerFork.ts index 261f688ef73c7..83f30d1c15a74 100644 --- a/apps/server/src/fork/processRunnerFork.ts +++ b/apps/server/src/fork/processRunnerFork.ts @@ -40,14 +40,24 @@ export const collectTail = (stream: Stream.Stream, maxBytes: n ); /** - * True when `error` (or a cause under it) is EPIPE: the child closed its stdin before the runner + * Node's codes for a write to a child's stdin that is already closed: EPIPE when the child closed + * it first, the other two when Node saw the child exit and closed it itself. + */ +const CLOSED_STDIN_CODES: ReadonlySet = new Set([ + "EPIPE", + "ERR_STREAM_DESTROYED", + "ERR_STREAM_PREMATURE_CLOSE", +]); + +/** + * True when `error` (or a cause under it) says the child's stdin was closed before the runner * wrote it, e.g. `timeout` exiting 127 at once for a missing program. Not a failure to run it; * its exit code and output say how it ended. */ export function isClosedStdin(error: unknown): boolean { let current: unknown = error; for (let depth = 0; depth < 6 && typeof current === "object" && current !== null; depth += 1) { - if ((current as { readonly code?: unknown }).code === "EPIPE") return true; + if (CLOSED_STDIN_CODES.has((current as { readonly code?: unknown }).code)) return true; const reason = (current as { readonly reason?: unknown }).reason; current = typeof reason === "object" && reason !== null && "cause" in reason diff --git a/apps/server/src/golive/forkReport.test.ts b/apps/server/src/golive/forkReport.test.ts index 2723fa4902fdd..c98312d4ed61e 100644 --- a/apps/server/src/golive/forkReport.test.ts +++ b/apps/server/src/golive/forkReport.test.ts @@ -1081,10 +1081,9 @@ describe("__fork-report settings", () => { expect(cleared.featuresOn).toEqual(featuresOn); expect(Object.values(cleared.featuresWhere).flat()).toEqual(featuresOn.map(() => "server")); } - // Pinned: playtest with a key this build does not know stays on. - expect(settingsReport({ playtest: { ...playtest, laterKey: 1 } }).fork.featuresOn).toEqual([ - "playtest", - ]); + // A playtest value with a key this build does not know reads as off, as the load does: the key + // may be a newer build's limit, so this build must not run playtest without it. + expect(settingsReport({ playtest: { ...playtest, laterKey: 1 } }).fork.featuresOn).toEqual([]); }); it("names the model policy by its mode, and reads an invalid one as enforce, as the load does", () => { diff --git a/docs/fork/README.md b/docs/fork/README.md index 3b100bc4b3ca9..cba194b1135a1 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -262,11 +262,12 @@ In the app: **Settings → Fork**, section Playtest: the switch (it stays off un set), the steps as JSON under **Edit steps** (checked as a save is), and the limits under Advanced. Only the person can change it; agents cannot. A save that is on without all four steps, repeats a -push step's name (or names one `claim`, `renew` or `release`), or names a program by anything but -its full path on the server's OS is refused. A hand-edited -value that is not valid reads as off (with a warning in the server log), and the next save of any -setting writes the default in its place; fields a newer build added are dropped the same way (as for -`waitChecks`). Other fields: how often a claim is renewed (`renewMinutes`), when an idle +push step's name (or names one `claim`, `renew` or `release`), names a program by anything but its +full path on the server's OS, or has a field this build does not know is refused. A hand-edited +value that is not valid, or has a field this build does not know (a newer build's limit, a typo), +reads as off (with a warning in the server log), and the next save of any setting writes the default +in its place. So after moving back to an older build, copy the playtest value first: the older +build's next save replaces a newer build's value. Other fields: how often a claim is renewed (`renewMinutes`), when an idle session ends (`idleMinutes`) and the longest session (`maxHours`). ```json diff --git a/fork-ci/actions/ci-demand/README.md b/fork-ci/actions/ci-demand/README.md index 822bdb3beec44..25f4d4a219913 100644 --- a/fork-ci/actions/ci-demand/README.md +++ b/fork-ci/actions/ci-demand/README.md @@ -91,4 +91,5 @@ Two choices to keep in mind when comparing before and after: ## General vs project General: the command, its counting rules and its cache. Project: only the repository (an argument, or `ciDemand.repo` -in the project's own config file) and where the caller keeps the cache. +in the project's own config file) and where the caller keeps the cache. The examples here, as in +[fleet-route](../fleet-route/README.md), call that file `.github/fleet.json`; the name is the project's choice. diff --git a/fork-ci/actions/docs-scope/README.md b/fork-ci/actions/docs-scope/README.md index e24f79fce6920..0323211b988cf 100644 --- a/fork-ci/actions/docs-scope/README.md +++ b/fork-ci/actions/docs-scope/README.md @@ -35,8 +35,8 @@ jobs: base: ${{ steps.green.outputs.sha }} # empty: a full run - if: steps.scope.outputs.docs_only != 'true' run: ./gradlew build - - if: fromJSON(steps.scope.outputs.jobs).engine != 'false' - run: ./gradlew :engine:test + - if: fromJSON(steps.scope.outputs.jobs).core != 'false' + run: ./gradlew :core:test ``` Always test `!= 'true'` and `!= 'false'`, never `== 'false'` or `== 'true'`: a missing or empty output then means @@ -44,7 +44,7 @@ Always test `!= 'true'` and `!= 'false'`, never `== 'false'` or `== 'true'`: a m Run it as a step of the jobs it gates, as above. If it runs in a job of its own that others `need`, a failure of that job skips them, and GitHub counts a skipped required job as passing: gate them with -`if: ${{ !cancelled() && (needs.scope.result != 'success' || fromJSON(needs.scope.outputs.jobs).engine != 'false') }}`. +`if: ${{ !cancelled() && (needs.scope.result != 'success' || fromJSON(needs.scope.outputs.jobs).core != 'false') }}`. ### Outputs @@ -54,8 +54,8 @@ job skips them, and GitHub counts a skipped required job as passing: gate them w | `jobs` | JSON `{"": "true" \| "false"}`; `{}` when unknown | | `reason` | one line: `docs-only:`, `full run:`, `scoped run:` or `not docs-only:` and why | -The step log also prints one line per job: `job engine: run (engine/A.java matches its paths)` or -`job engine: skip (...)`. Control characters, line separators and bytes that are not UTF-8 in a file name are +The step log also prints one line per job: `job core: run (core/A.java matches its paths)` or +`job core: skip (...)`. Control characters, line separators and bytes that are not UTF-8 in a file name are printed escaped (`\n`, `\udcff`), so a file name can neither start a `::workflow-command::` line nor add an output. ## What "the change" is @@ -93,7 +93,7 @@ the diff to commits a passing push run already tested. "never_docs": [ { "glob": "**/src/**", "why": "inside a source set (packed into jars)" }, { "glob": "**/tests/**", "why": "inside a test folder" }, - { "glob": "tools/CLAIMS.md", "why": "read by the release tool" } + { "glob": "tools/RELEASE-NOTES.md", "why": "read by the release tool" } ], "never_docs_from": [ { @@ -107,13 +107,13 @@ the diff to commits a passing push run already tested. "docs_only_events": ["pull_request"], "no_build": [".github/ISSUE_TEMPLATE/**", "tools/notes/**"], "jobs": { - "engine": { - "paths": ["engine/**", "shared/items/**"], + "core": { + "paths": ["core/**", "shared/common/**"], "paths_from": [ { "file": "tools/modules.json", "list": "modules", - "where": { "kind": "engine-module" }, + "where": { "kind": "core-module" }, "field": ["paths", "inputs"], "label": "id" } diff --git a/fork-ci/actions/docs-scope/docs-scope.test.py b/fork-ci/actions/docs-scope/docs-scope.test.py index 37bb445158eb4..a936b60b9bb73 100644 --- a/fork-ci/actions/docs-scope/docs-scope.test.py +++ b/fork-ci/actions/docs-scope/docs-scope.test.py @@ -21,8 +21,8 @@ REGISTRY_PATH = 'tools/registry.json' REGISTRY = {'modules': [ {'id': 'site', 'kind': 'plugin', 'inputs': ['plugins/site/README.md']}, - {'id': 'content-locale', 'kind': 'engine-module', 'inputs': ['plugins/locale/common/src/main/java/Wire.java']}, - {'id': 'content-travel', 'kind': 'engine-module', 'inputs': ['plugins/travel/common/src/main/java']}, + {'id': 'alpha', 'kind': 'core-module', 'inputs': ['plugins/alpha/common/src/main/java/Api.java']}, + {'id': 'beta', 'kind': 'core-module', 'inputs': ['plugins/beta/common/src/main/java']}, ]} # A project's rules, as a caller would write them (the general half of a docs-only gate). CONFIG = { @@ -36,14 +36,14 @@ {'glob': '**/test/**', 'why': 'inside a test folder'}, {'glob': '**/fixtures/**', 'why': 'inside a fixture folder'}, {'glob': 'skills/review/SKILL.md', 'why': 'read by a tooling test'}, - {'glob': 'plugins/RELEASE-CLAIMS.md', 'why': 'read by the release tool'}, + {'glob': 'plugins/RELEASE-NOTES.md', 'why': 'read by the release tool'}, ], 'never_docs_from': [{'file': REGISTRY_PATH, 'list': 'modules', 'field': 'inputs', 'label': 'id', 'why': 'listed in the registry'}], 'jobs': { 'plugins': {'paths': ['plugins/**']}, - 'engine': {'paths': ['engine/**', 'plugins/items/**'], - 'paths_from': [{'file': REGISTRY_PATH, 'list': 'modules', 'where': {'kind': 'engine-module'}, + 'core': {'paths': ['core/**', 'plugins/shared/**'], + 'paths_from': [{'file': REGISTRY_PATH, 'list': 'modules', 'where': {'kind': 'core-module'}, 'field': 'inputs', 'label': 'id'}]}, }, } @@ -206,7 +206,7 @@ def test_a_named_file_read_by_a_test(self): self.check('skills/review/SKILL.md') def test_a_named_file_read_by_a_tool(self): - self.check('plugins/RELEASE-CLAIMS.md') + self.check('plugins/RELEASE-NOTES.md') def test_an_md_listed_in_the_registry(self): self.check('plugins/site/README.md') @@ -222,7 +222,7 @@ class RegistryAtTheBase(Repo): itself does not decide (it is docs, or a job's own path), so only the registry read can (an entry the PR adds counts too: never_docs_from is read at the head as well).""" config = {'docs': ['**'], 'never_docs_from': CONFIG['never_docs_from'], - 'jobs': {'plugins': {'paths': ['plugins/**', 'tools/**']}, 'engine': CONFIG['jobs']['engine']}} + 'jobs': {'plugins': {'paths': ['plugins/**', 'tools/**']}, 'core': CONFIG['jobs']['core']}} def drop(self, module_id): return json.dumps({'modules': [m for m in REGISTRY['modules'] if m['id'] != module_id]}) @@ -234,15 +234,15 @@ def test_a_pr_that_drops_a_never_docs_entry_does_not_free_the_file(self): self.assertIn('site inputs: plugins/site/README.md', out) def test_a_pr_that_drops_a_jobs_entry_still_runs_the_job(self): - self.pr({REGISTRY_PATH: self.drop('content-locale'), 'plugins/locale/common/src/main/java/Wire.java': 'x'}) - self.assertEqual(self.scope()[1], {'plugins': 'true', 'engine': 'true'}) + self.pr({REGISTRY_PATH: self.drop('alpha'), 'plugins/alpha/common/src/main/java/Api.java': 'x'}) + self.assertEqual(self.scope()[1], {'plugins': 'true', 'core': 'true'}) def test_a_pr_that_adds_a_never_docs_entry_counts_it_at_the_head(self): # never_docs_from read at both sides self.pr({REGISTRY_PATH: json.dumps({'modules': REGISTRY['modules'] + [{'id': 'manual', 'inputs': ['docs/manual.md']}]}), 'docs/manual.md': 'y'}) docs, jobs, out = self.scope() - self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'engine': 'true'}), out) + self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'core': 'true'}), out) self.assertIn('manual inputs: docs/manual.md', out) @@ -251,25 +251,25 @@ class RegistryAtTheHead(Repo): judge a PR come from the base. The registry sits in a job's paths (the common case), so its change alone does not run every job.""" config = {**CONFIG, 'jobs': {'plugins': {'paths': ['plugins/**']}, - 'engine': {**CONFIG['jobs']['engine'], 'paths': ['engine/**', 'tools/**']}}} + 'core': {**CONFIG['jobs']['core'], 'paths': ['core/**', 'tools/**']}}} def add(self, *modules): return json.dumps({'modules': REGISTRY['modules'] + list(modules)}) def test_a_head_only_entry_cannot_claim_a_file_no_job_names(self): # even innocently: a new module lists it - self.pr({REGISTRY_PATH: self.add({'id': 'root', 'kind': 'engine-module', 'inputs': ['build.gradle']}), + self.pr({REGISTRY_PATH: self.add({'id': 'root', 'kind': 'core-module', 'inputs': ['build.gradle']}), 'build.gradle': 'x'}) docs, jobs, out = self.scope() - self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'engine': 'true'}), out) + self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'core': 'true'}), out) self.assertIn('full run: build.gradle is not a docs file', out.splitlines()[0]) self.assertIn('which no job names at the base: every job runs', out.splitlines()[0]) def test_a_head_only_entry_still_adds_its_job(self): - self.pr({REGISTRY_PATH: self.add({'id': 'new', 'kind': 'engine-module', 'inputs': ['plugins/new/X.java']}), + self.pr({REGISTRY_PATH: self.add({'id': 'new', 'kind': 'core-module', 'inputs': ['plugins/new/X.java']}), 'plugins/new/X.java': 'x'}) docs, jobs, out = self.scope() - self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'engine': 'true'}), out) - self.assertIn('job engine: run (plugins/new/X.java matches new inputs', out) + self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'core': 'true'}), out) + self.assertIn('job core: run (plugins/new/X.java matches new inputs', out) class Submodules(Repo): @@ -366,8 +366,8 @@ def test_registry_entries_that_could_never_match_are_a_full_run(self): # never ('no object of the kind a job keeps', None)): with self.subTest(name): self.reset() - engine = [m for m in REGISTRY['modules'] if m['kind'] == 'engine-module'] if modules else [] - modules = [{k: v for k, v in m.items() if v is not None} for m in modules or [site]] + engine + core = [m for m in REGISTRY['modules'] if m['kind'] == 'core-module'] if modules else [] + modules = [{k: v for k, v in m.items() if v is not None} for m in modules or [site]] + core self.base = self.commit('registry', {REGISTRY_PATH: json.dumps({'modules': modules})}) self.pr({'plugins/site/README.md': 'y'}) docs, jobs, out = self.scope() @@ -397,7 +397,7 @@ def setUp(self): def test_the_real_merge_commit_is_a_full_run(self): # the check does not refuse the right checkout self.git('checkout', '-q', '--detach', self.github_sha) - self.assertEqual(self.scope(head_sha=self.pr_head)[:2], (False, {'plugins': 'true', 'engine': 'true'})) + self.assertEqual(self.scope(head_sha=self.pr_head)[:2], (False, {'plugins': 'true', 'core': 'true'})) def test_a_pr_head_checkout_is_a_full_run(self): docs, jobs, out = self.scope(sha=self.github_sha, head_sha=self.pr_head) @@ -473,7 +473,7 @@ def test_a_newline_name_in_a_source_set_is_not_docs(self): def test_a_newline_name_in_a_job_folder_runs_that_job_by_its_paths(self): self.pr({'plugins/x\ny.java': 'x'}) docs, jobs, out = self.scope() - self.assertEqual(jobs, {'plugins': 'true', 'engine': 'false'}, out) + self.assertEqual(jobs, {'plugins': 'true', 'core': 'false'}, out) self.assertIn('matches its paths', out) def test_a_name_cannot_inject_a_workflow_command_or_an_output(self): # scope() checks every line @@ -488,9 +488,9 @@ class ConfigAtTheBase(Repo): loosen what judges it (the general half of a gate that ran the PR's own copy).""" def test_a_pr_that_loosens_its_own_config_still_runs_in_full(self): - self.pr({CONFIG_PATH: json.dumps({'docs': ['**'], 'jobs': {}}), 'engine/A.java': 'class A {}'}) + self.pr({CONFIG_PATH: json.dumps({'docs': ['**'], 'jobs': {}}), 'core/A.java': 'class A {}'}) docs, jobs, out = self.scope() - self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'engine': 'true'}), out) # the base's jobs, all + self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'core': 'true'}), out) # the base's jobs, all def test_no_config_at_the_base(self): # the PR that adds the config runs in full self.git('rm', '-q', CONFIG_PATH) @@ -536,14 +536,14 @@ def test_a_bad_source_entry_names_itself(self): # wrong types and typos in a * self.assertIn(why, out) def test_an_unknown_key_in_a_paths_from_entry(self): # "wehre" would drop the kind filter: the job runs more - engine = CONFIG['jobs']['engine'] - source = {**{k: v for k, v in engine['paths_from'][0].items() if k != 'where'}, 'wehre': {'kind': 'x'}} + core = CONFIG['jobs']['core'] + source = {**{k: v for k, v in core['paths_from'][0].items() if k != 'where'}, 'wehre': {'kind': 'x'}} self.commit('typo', {CONFIG_PATH: json.dumps( - {**CONFIG, 'jobs': {**CONFIG['jobs'], 'engine': {**engine, 'paths_from': [source]}}})}) + {**CONFIG, 'jobs': {**CONFIG['jobs'], 'core': {**core, 'paths_from': [source]}}})}) self.pr({'README.md': 'y'}) docs, jobs, out = self.scope() self.assertEqual((docs, jobs), (False, {}), out) - self.assertIn('jobs.engine.paths_from entry', out) + self.assertIn('jobs.core.paths_from entry', out) class LooseConfig(Repo): @@ -566,12 +566,12 @@ class Jobs(Repo): def test_a_job_runs_for_its_paths_and_skips_otherwise(self): self.pr({'plugins/a/src/main/java/A.java': 'class A {}'}) docs, jobs, out = self.scope() - self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'engine': 'false'}), out) - self.assertIn('job engine: skip', out) + self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'core': 'false'}), out) + self.assertIn('job core: skip', out) - def test_docs_in_a_job_folder_do_not_run_it(self): # code elsewhere makes it a full run, not an engine build - self.pr({'engine/README.md': 'y', 'plugins/a/A.java': 'class A {}'}) - self.assertEqual(self.scope()[1], {'plugins': 'true', 'engine': 'false'}) + def test_docs_in_a_job_folder_do_not_run_it(self): # code elsewhere makes it a full run, not an core build + self.pr({'core/README.md': 'y', 'plugins/a/A.java': 'class A {}'}) + self.assertEqual(self.scope()[1], {'plugins': 'true', 'core': 'false'}) def test_a_file_no_job_names_runs_every_job(self): # unclear which job it reaches: all of them for path in ('app/Main.java', '.github/workflows/ci.yml', CONFIG_PATH): @@ -579,63 +579,63 @@ def test_a_file_no_job_names_runs_every_job(self): # unclear which job it reac self.reset() self.pr({path: json.dumps(CONFIG) + ' '}) docs, jobs, out = self.scope() - self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'engine': 'true'}), out) + self.assertEqual((docs, jobs), (False, {'plugins': 'true', 'core': 'true'}), out) self.assertIn('every job runs', out.splitlines()[0]) def test_a_config_change_runs_every_job_even_if_a_job_names_it(self): cfg = {**CONFIG, 'jobs': {**CONFIG['jobs'], 'plugins': {'paths': ['plugins/**', '.github/**']}}} self.base = self.commit('a job names .github', {CONFIG_PATH: json.dumps(cfg)}) self.pr({CONFIG_PATH: json.dumps(cfg) + ' '}) - self.assertEqual(self.scope()[1], {'plugins': 'true', 'engine': 'true'}) + self.assertEqual(self.scope()[1], {'plugins': 'true', 'core': 'true'}) def test_an_md_input_in_a_job_folder_runs_it(self): - self.pr({'engine/core/src/main/resources/help.md': 'y'}) - self.assertEqual(self.scope()[1]['engine'], 'true') + self.pr({'core/util/src/main/resources/help.md': 'y'}) + self.assertEqual(self.scope()[1]['core'], 'true') def test_a_scoped_run_says_so_and_a_full_run_says_full(self): # the reason matches what the jobs do - self.pr({'engine/A.java': 'class A {}'}) + self.pr({'core/A.java': 'class A {}'}) docs, jobs, out = self.scope() - self.assertEqual(jobs, {'plugins': 'false', 'engine': 'true'}, out) - self.assertTrue(out.startswith('scoped run: engine/A.java is not a docs file; only the jobs'), out) + self.assertEqual(jobs, {'plugins': 'false', 'core': 'true'}, out) + self.assertTrue(out.startswith('scoped run: core/A.java is not a docs file; only the jobs'), out) self.reset() - self.pr({'engine/A.java': 'class A {}', 'app/Main.java': 'x'}) + self.pr({'core/A.java': 'class A {}', 'app/Main.java': 'x'}) docs, jobs, out = self.scope() - self.assertEqual(jobs, {'plugins': 'true', 'engine': 'true'}, out) + self.assertEqual(jobs, {'plugins': 'true', 'core': 'true'}, out) self.assertTrue(out.startswith('full run: app/Main.java is not a docs file and 1 more, which no job'), out) def test_docs_only_skips_every_job(self): self.pr({'README.md': 'y'}) - self.assertEqual(self.scope()[:2], (True, {'plugins': 'false', 'engine': 'false'})) + self.assertEqual(self.scope()[:2], (True, {'plugins': 'false', 'core': 'false'})) def test_a_folder_added_to_a_jobs_paths_runs_it(self): # a shared folder another job builds against - self.pr({'plugins/items/common/Item.java': 'class Item {}'}) - self.assertEqual(self.scope()[1]['engine'], 'true') + self.pr({'plugins/shared/common/Shared.java': 'class Shared {}'}) + self.assertEqual(self.scope()[1]['core'], 'true') def test_a_jobs_paths_from_a_registry_filtered_by_kind(self): # the registry names what a module compiles - for path, runs in (('plugins/locale/common/src/main/java/Wire.java', 'true'), - ('plugins/locale/common/src/main/java/Other.java', 'false'), - ('plugins/travel/common/src/main/java/a/Leg.java', 'true')): + for path, runs in (('plugins/alpha/common/src/main/java/Api.java', 'true'), + ('plugins/alpha/common/src/main/java/Other.java', 'false'), + ('plugins/beta/common/src/main/java/a/Step.java', 'true')): with self.subTest(path=path): self.reset() self.pr({path: 'class X {}'}) docs, jobs, out = self.scope() - self.assertEqual(jobs['engine'], runs, out) + self.assertEqual(jobs['core'], runs, out) def test_a_registry_entry_of_another_kind_does_not_run_the_job(self): - self.pr({'plugins/site/README.md': 'y'}) # an input of a "plugin", not of an "engine-module" - self.assertEqual(self.scope()[1]['engine'], 'false') + self.pr({'plugins/site/README.md': 'y'}) # an input of a "plugin", not of a "core-module" + self.assertEqual(self.scope()[1]['core'], 'false') class OtherEvents(Repo): def test_a_push_with_a_base_reads_its_jobs_and_is_never_docs_only(self): - self.commit('code', {'engine/A.java': 'class A {}'}) + self.commit('code', {'core/A.java': 'class A {}'}) docs, jobs, out = self.scope('push', self.base) - self.assertEqual((docs, jobs), (False, {'plugins': 'false', 'engine': 'true'}), out) + self.assertEqual((docs, jobs), (False, {'plugins': 'false', 'core': 'true'}), out) def test_a_docs_push_skips_every_job_but_is_not_docs_only(self): self.commit('docs', {'plugins/README.md': 'y'}) docs, jobs, out = self.scope('push', self.base) - self.assertEqual((docs, jobs), (False, {'plugins': 'false', 'engine': 'false'}), out) + self.assertEqual((docs, jobs), (False, {'plugins': 'false', 'core': 'false'}), out) self.assertIn('not in docs_only_events', out) def test_docs_only_events_can_name_push(self): @@ -645,7 +645,7 @@ def test_docs_only_events_can_name_push(self): self.assertTrue(self.scope('push', self.base)[0]) def test_a_base_off_the_first_parent_line_is_a_full_run(self): # a merged fork PR's head was never tested - self.commit('code A (its run went red)', {'engine/A.java': 'class A {}'}) + self.commit('code A (its run went red)', {'core/A.java': 'class A {}'}) self.git('checkout', '-q', '-b', 'fork-main') fork_pr_head = self.commit('docs (its pull_request run passed)', {'README.md': 'y'}) self.git('checkout', '-q', 'main') @@ -654,7 +654,7 @@ def test_a_base_off_the_first_parent_line_is_a_full_run(self): # a merged fork docs, jobs, out = self.scope('push', fork_pr_head) self.assertEqual((docs, jobs), (False, {}), out) self.assertIn('not on the first-parent line', out) - self.assertEqual(self.scope('push', self.base)[1], {'plugins': 'false', 'engine': 'true'}) # main's green + self.assertEqual(self.scope('push', self.base)[1], {'plugins': 'false', 'core': 'true'}) # main's green def test_a_base_that_is_not_a_commit(self): self.commit('docs', {'README.md': 'y'}) @@ -671,7 +671,7 @@ class NoBuild(Repo): def test_a_no_build_path_runs_no_job_and_is_logged(self): self.pr({'tools/lint.py': 'x', 'scratch.txt': 'y'}) docs, jobs, out = self.scope() - self.assertEqual((docs, jobs), (False, {'plugins': 'false', 'engine': 'false'}), out) + self.assertEqual((docs, jobs), (False, {'plugins': 'false', 'core': 'false'}), out) self.assertTrue(out.startswith('scoped run: scratch.txt is not a docs file and 1 more'), out) self.assertIn('no_build: scratch.txt builds nothing (matches scratch.txt) and 1 more', out) self.assertNotIn('every job', out) @@ -679,22 +679,22 @@ def test_a_no_build_path_runs_no_job_and_is_logged(self): def test_it_is_never_a_job_output(self): self.pr({'tools/lint.py': 'x', 'app/Main.java': 'y'}) docs, jobs, out = self.scope() - self.assertEqual(set(jobs), {'plugins', 'engine'}, out) - self.assertEqual(jobs, {'plugins': 'true', 'engine': 'true'}, out) # app/ is named by nothing: every job + self.assertEqual(set(jobs), {'plugins', 'core'}, out) + self.assertEqual(jobs, {'plugins': 'true', 'core': 'true'}, out) # app/ is named by nothing: every job def test_a_path_a_job_also_names_runs_that_job_and_is_not_logged_as_nothing(self): - cfg = {**self.config, 'no_build': ['tools/**', 'engine/docs/**']} - self.base = self.commit('engine/docs is no-build', {CONFIG_PATH: json.dumps(cfg)}) - self.pr({'engine/docs/gen.py': 'x'}) + cfg = {**self.config, 'no_build': ['tools/**', 'core/docs/**']} + self.base = self.commit('core/docs is no-build', {CONFIG_PATH: json.dumps(cfg)}) + self.pr({'core/docs/gen.py': 'x'}) docs, jobs, out = self.scope() - self.assertEqual(jobs, {'plugins': 'false', 'engine': 'true'}, out) + self.assertEqual(jobs, {'plugins': 'false', 'core': 'true'}, out) self.assertNotIn('no_build:', out) def test_a_registry_entry_beats_no_build(self): # paths_from names it: the job runs self.pr({REGISTRY_PATH: json.dumps({'modules': REGISTRY['modules'] + [ - {'id': 't', 'kind': 'engine-module', 'inputs': ['tools/gen']}]}), 'tools/gen/A.java': 'x'}) + {'id': 't', 'kind': 'core-module', 'inputs': ['tools/gen']}]}), 'tools/gen/A.java': 'x'}) docs, jobs, out = self.scope() - self.assertEqual(jobs['engine'], 'true', out) + self.assertEqual(jobs['core'], 'true', out) def test_docs_stay_docs(self): # no_build never makes a docs file anything else self.pr({'tools/README.md': 'y'}) @@ -703,19 +703,19 @@ def test_docs_stay_docs(self): # no_build never makes a docs file anything els def test_a_never_docs_md_in_a_no_build_folder_builds_nothing(self): self.pr({'tools/tests/case.md': 'y'}) docs, jobs, out = self.scope() - self.assertEqual((docs, jobs), (False, {'plugins': 'false', 'engine': 'false'}), out) + self.assertEqual((docs, jobs), (False, {'plugins': 'false', 'core': 'false'}), out) self.assertIn('no_build: tools/tests/case.md builds nothing', out) def test_the_config_runs_every_job_even_inside_no_build(self): self.pr({CONFIG_PATH: json.dumps(self.config) + ' '}) docs, jobs, out = self.scope() - self.assertEqual(jobs, {'plugins': 'true', 'engine': 'true'}, out) + self.assertEqual(jobs, {'plugins': 'true', 'core': 'true'}, out) self.assertNotIn('no_build:', out) def test_it_is_judged_at_the_base(self): # a PR cannot add itself a no_build glob cfg = {**self.config, 'no_build': self.config['no_build'] + ['app/**']} self.pr({CONFIG_PATH: json.dumps(cfg), 'app/Main.java': 'y'}) - self.assertEqual(self.scope()[1], {'plugins': 'true', 'engine': 'true'}) + self.assertEqual(self.scope()[1], {'plugins': 'true', 'core': 'true'}) def test_a_wrong_type_is_a_full_run_that_names_it(self): for bad in ('tools/**', [''], [1], {'paths': ['tools/**']}): @@ -734,7 +734,7 @@ def test_an_unnamed_path_still_runs_every_job(self): self.assertNotIn('no_build', CONFIG) self.pr({'tools/lint.py': 'x'}) docs, jobs, out = self.scope() - self.assertEqual(jobs, {'plugins': 'true', 'engine': 'true'}, out) + self.assertEqual(jobs, {'plugins': 'true', 'core': 'true'}, out) self.assertNotIn('no_build:', out) @@ -746,7 +746,7 @@ class NoBuildBesideAFakeJob(Repo): def test_both_stop_the_full_run(self): self.pr({'docs/gen.py': 'x', 'tools/lint.py': 'y'}) docs, jobs, out = self.scope() - self.assertEqual(jobs, {'plugins': 'false', 'engine': 'false', 'no-build': 'true'}, out) + self.assertEqual(jobs, {'plugins': 'false', 'core': 'false', 'no-build': 'true'}, out) self.assertIn('job no-build: run (docs/gen.py matches its paths)', out) self.assertIn('no_build: tools/lint.py builds nothing (matches tools/**)', out) self.assertNotIn('docs/gen.py builds nothing', out) @@ -756,11 +756,11 @@ class PythonApi(Repo): """docs_rule, job_rule and rules (#1508): the action's own rule about one path, for tools outside a workflow. The agreement tests run the action on a PR of each sample path and ask the helpers the same question.""" config = {**CONFIG, 'no_build': ['tools/**']} - SAMPLE = ('README.md', 'plugins/a/README.md', 'engine/README.md', 'plugins/a/src/main/resources/x.md', - 'skills/review/SKILL.md', 'plugins/RELEASE-CLAIMS.md', 'plugins/site/README.md', 'engine/A.java', - 'plugins/a/A.java', 'plugins/items/common/Item.java', 'app/Main.java', 'tools/lint.py', - 'tools/tests/x.md', CONFIG_PATH, 'plugins/locale/common/src/main/java/Wire.java', - 'plugins/locale/common/src/main/java/Other.java', 'plugins/travel/common/src/main/java/a/Leg.java', + SAMPLE = ('README.md', 'plugins/a/README.md', 'core/README.md', 'plugins/a/src/main/resources/x.md', + 'skills/review/SKILL.md', 'plugins/RELEASE-NOTES.md', 'plugins/site/README.md', 'core/A.java', + 'plugins/a/A.java', 'plugins/shared/common/Shared.java', 'app/Main.java', 'tools/lint.py', + 'tools/tests/x.md', CONFIG_PATH, 'plugins/alpha/common/src/main/java/Api.java', + 'plugins/alpha/common/src/main/java/Other.java', 'plugins/beta/common/src/main/java/a/Step.java', 'notes/line\nbreak.md', 'notes/plain.md') def show(self, ref): @@ -800,7 +800,7 @@ def test_they_agree_on_a_head_only_registry_entry(self): # an entry at the hea mods = REGISTRY['modules'] for path, entry in (('build.gradle', 'build.gradle'), ('plugins/new/X.java', 'plugins/new/X.java')): with self.subTest(path=path): - added = {'modules': mods + [{'id': 'n', 'kind': 'engine-module', 'inputs': [entry]}]} + added = {'modules': mods + [{'id': 'n', 'kind': 'core-module', 'inputs': [entry]}]} self.agree(path, {REGISTRY_PATH: json.dumps(added), path: 'x'}) def test_they_agree_on_a_never_docs_entry_at_the_head(self): @@ -814,15 +814,15 @@ def test_one_reader_and_a_dict_config(self): # a tool asking about one tree, e self.assertTrue(is_docs('README.md')) self.assertFalse(is_docs('plugins/site/README.md')) self.assertFalse(is_docs('.github/docs-scope.json'), 'the default config path is never docs') - engine = DS.job_rule(self.config, 'engine', read) - self.assertTrue(engine('plugins/locale/common/src/main/java/Wire.java')) - self.assertFalse(engine('tools/lint.py')) - self.assertTrue(engine('app/Main.java'), 'a path no job names runs every job') + core = DS.job_rule(self.config, 'core', read) + self.assertTrue(core('plugins/alpha/common/src/main/java/Api.java')) + self.assertFalse(core('tools/lint.py')) + self.assertTrue(core('app/Main.java'), 'a path no job names runs every job') self.assertTrue(DS.job_rule(self.config, 'renamed', read)('README.md'), 'a job the config does not have runs, even for docs (the action leaves it out of jobs)') r = DS.rules(self.config, read) self.assertEqual(r.builds_nothing('tools/lint.py'), 'tools/**') - self.assertIsNone(r.builds_nothing('engine/A.java')) + self.assertIsNone(r.builds_nothing('core/A.java')) self.assertEqual(r.not_docs('README.md', plain=False), 'a symlink or submodule, not a plain file') self.assertEqual(self.config, {**CONFIG, 'no_build': ['tools/**']}, "the caller's dict is not changed") self.assertNotIn('docs_only_events', CONFIG, "nor the caller's nested values") @@ -837,7 +837,7 @@ def test_unreadable_rules_fail_closed(self): # the action runs in full: nothin self.assertTrue(DS.job_rule(config, 'plugins', read)('README.md')) with self.assertRaises(DS.Unclear): DS.rules(config, read) - self.assertTrue(DS.job_rule(self.config, 'nope', lambda name: reg)('engine/A.java'), + self.assertTrue(DS.job_rule(self.config, 'nope', lambda name: reg)('core/A.java'), 'a job the config does not have reads as "run", as a missing job output does') with self.assertRaisesRegex(DS.Unclear, 'tools/registry.json is not in the tree'): DS.rules(self.config, lambda name: None) @@ -847,9 +847,9 @@ def test_read_entries_keeps_its_signature(self): # older callers pass refs and src = CONFIG['never_docs_from'][0] per = DS.read_entries(src, (self.base,), run) self.assertEqual(DS.union(per), {'plugins/site/README.md': 'site inputs', - 'plugins/locale/common/src/main/java/Wire.java': 'content-locale inputs', - 'plugins/travel/common/src/main/java': 'content-travel inputs'}) - self.assertTrue(DS.entry_match('plugins/travel/common/src/main/java/a/B.java', DS.union(per))) + 'plugins/alpha/common/src/main/java/Api.java': 'alpha inputs', + 'plugins/beta/common/src/main/java': 'beta inputs'}) + self.assertTrue(DS.entry_match('plugins/beta/common/src/main/java/a/B.java', DS.union(per))) class Globs(CleanEnv): diff --git a/fork-ci/actions/gradle-cache/README.md b/fork-ci/actions/gradle-cache/README.md index 05feb01e50f50..293b66a5782d6 100644 --- a/fork-ci/actions/gradle-cache/README.md +++ b/fork-ci/actions/gradle-cache/README.md @@ -19,7 +19,7 @@ Pin a release commit by its full SHA, never a commit of main ([why](../../README - id: m2 uses: scuttletoby/t3code/fork-ci/actions/gradle-cache@ # ci/vN with: - lock: engine/m2-lock.json # project fact + lock: core/m2-lock.json # project fact cache-dir: ~/.cache/my-ci-m2 # optional: keep an existing warm cache - run: ./gradlew --offline -Dmaven.repo.local="${{ steps.m2.outputs.maven-repo-local }}" build ``` @@ -41,7 +41,7 @@ Output `maven-repo-local`: the staged folder. { "release": "m2-jars", "files": [ - { "path": "org/example/engine/1.0/engine-1.0.jar", "sha256": "<64 hex>", "release": "m2-jars" } + { "path": "org/example/core/1.0/core-1.0.jar", "sha256": "<64 hex>", "release": "m2-jars" } ] } ``` @@ -56,9 +56,9 @@ Run these on a machine whose `~/.m2` has the version, with `gh` logged in: ```bash S=fork-ci/actions/gradle-cache/gradle_cache.py # from a checkout of the pinned commit -python3 -I $S publish --lock engine/m2-lock.json --repo OWNER/REPO org.example:engine:1.1 # then commit the lock -python3 -I $S check --lock engine/m2-lock.json --repo OWNER/REPO # needs GH_TOKEN -python3 -I $S prune-lock --lock engine/m2-lock.json --keep org.example:engine:1.1 org.example:engine:1.0 +python3 -I $S publish --lock core/m2-lock.json --repo OWNER/REPO org.example:core:1.1 # then commit the lock +python3 -I $S check --lock core/m2-lock.json --repo OWNER/REPO # needs GH_TOKEN +python3 -I $S prune-lock --lock core/m2-lock.json --keep org.example:core:1.1 org.example:core:1.0 ``` - `publish` uploads the version's jar, pom, module and `maven-metadata-local.xml` (no sources or diff --git a/fork-ci/actions/gradle-cache/gradle_cache.test.py b/fork-ci/actions/gradle-cache/gradle_cache.test.py index 979f704feaed1..c5caaa7ae4e44 100644 --- a/fork-ci/actions/gradle-cache/gradle_cache.test.py +++ b/fork-ci/actions/gradle-cache/gradle_cache.test.py @@ -20,7 +20,7 @@ spec.loader.exec_module(M) JAR, POM = b'jar bytes', b'' -V = 'org/example/engine/1.0' +V = 'org/example/core/1.0' DAY = 86400 @@ -69,10 +69,10 @@ def stage(self, gh, out=None): M.stage(self.lock_file, out or self.out, gh, cache=self.cache, say=self.lines.append) def rows(self): - return [{'path': f'{V}/engine-1.0.jar', 'sha256': sha(JAR)}, {'path': f'{V}/engine-1.0.pom', 'sha256': sha(POM)}] + return [{'path': f'{V}/core-1.0.jar', 'sha256': sha(JAR)}, {'path': f'{V}/core-1.0.pom', 'sha256': sha(POM)}] def remote(self): - return FakeGitHub({f'{sha(JAR)}-engine-1.0.jar': JAR, f'{sha(POM)}-engine-1.0.pom': POM}) + return FakeGitHub({f'{sha(JAR)}-core-1.0.jar': JAR, f'{sha(POM)}-core-1.0.pom': POM}) def staged(self, out=None): out = out or self.out @@ -83,8 +83,8 @@ class Stage(Base): def test_a_fresh_runner_gets_exactly_the_locked_files(self): self.lock(self.rows()) self.stage(self.remote()) - self.assertEqual(self.staged(), [f'{V}/engine-1.0.jar', f'{V}/engine-1.0.pom']) - with open(os.path.join(self.out, V, 'engine-1.0.jar'), 'rb') as f: + self.assertEqual(self.staged(), [f'{V}/core-1.0.jar', f'{V}/core-1.0.pom']) + with open(os.path.join(self.out, V, 'core-1.0.jar'), 'rb') as f: self.assertEqual(f.read(), JAR) def test_a_second_run_takes_the_cache_and_still_asks_github(self): @@ -94,22 +94,22 @@ def test_a_second_run_takes_the_cache_and_still_asks_github(self): gh = self.remote() self.stage(gh) self.assertEqual(gh.downloads, []) - gone = self.remote(); del gone.files[f'{sha(POM)}-engine-1.0.pom'] + gone = self.remote(); del gone.files[f'{sha(POM)}-core-1.0.pom'] shutil.rmtree(self.out) # a warm cache never hides an asset that is gone: the fresh runner would be red - with self.assertRaisesRegex(M.Refused, 'engine-1.0.pom: the release jars has no asset'): + with self.assertRaisesRegex(M.Refused, 'core-1.0.pom: the release jars has no asset'): self.stage(gone) def test_a_missing_asset_is_red_by_name_and_nothing_is_staged(self): self.lock(self.rows()) - gh = self.remote(); del gh.files[f'{sha(JAR)}-engine-1.0.jar'] - with self.assertRaisesRegex(M.Refused, r'engine-1\.0\.jar: the release jars has no asset'): + gh = self.remote(); del gh.files[f'{sha(JAR)}-core-1.0.jar'] + with self.assertRaisesRegex(M.Refused, r'core-1\.0\.jar: the release jars has no asset'): self.stage(gh) self.assertFalse(os.path.exists(self.out)) def test_other_bytes_under_the_asset_name_are_red_and_never_cached(self): self.lock(self.rows()) gh = self.remote() - gh.files[f'{sha(JAR)}-engine-1.0.jar'] = b'an older jar' + gh.files[f'{sha(JAR)}-core-1.0.jar'] = b'an older jar' real = gh.assets gh.assets = lambda tag: {n: {k: v for k, v in a.items() if k != 'digest'} for n, a in real(tag).items()} with self.assertRaisesRegex(M.Refused, 'the download has sha256'): @@ -133,7 +133,7 @@ def test_a_damaged_cache_file_is_named_and_downloaded_again(self): f.write(b'cut off') gh = self.remote() self.stage(gh) - self.assertEqual(sorted(gh.downloads), sorted([f'{sha(JAR)}-engine-1.0.jar', f'{sha(POM)}-engine-1.0.pom'])) + self.assertEqual(sorted(gh.downloads), sorted([f'{sha(JAR)}-core-1.0.jar', f'{sha(POM)}-core-1.0.pom'])) self.assertTrue(any(line.startswith('WARN:') and sha(JAR) in line for line in self.lines)) with open(os.path.join(self.cache, sha(JAR)), 'rb') as f: self.assertEqual(f.read(), JAR) @@ -141,7 +141,7 @@ def test_a_damaged_cache_file_is_named_and_downloaded_again(self): def test_a_folder_with_files_is_refused(self): self.lock(self.rows()) os.makedirs(os.path.join(self.out, V)) - open(os.path.join(self.out, V, 'engine-0.9.jar'), 'w').close() + open(os.path.join(self.out, V, 'core-0.9.jar'), 'w').close() with self.assertRaisesRegex(M.Refused, 'is not empty'): self.stage(self.remote()) @@ -175,7 +175,7 @@ def one(out): t.join() self.assertEqual(errors, []) for i in range(4): - self.assertEqual(self.staged(os.path.join(self.root, f'out{i}')), [f'{V}/engine-1.0.jar', f'{V}/engine-1.0.pom']) + self.assertEqual(self.staged(os.path.join(self.root, f'out{i}')), [f'{V}/core-1.0.jar', f'{V}/core-1.0.pom']) self.assertEqual(sorted(os.listdir(self.cache)), sorted([sha(JAR), sha(POM)])) @@ -184,8 +184,8 @@ def setUp(self): super().setUp() folder = os.path.join(self.m2, *V.split('/')) os.makedirs(folder) - for name, data in (('engine-1.0.jar', JAR), ('engine-1.0.pom', POM), ('engine-1.0-sources.jar', b's'), - ('engine-1.0-javadoc.jar', b'j'), ('_remote.repositories', b'r')): + for name, data in (('core-1.0.jar', JAR), ('core-1.0.pom', POM), ('core-1.0-sources.jar', b's'), + ('core-1.0-javadoc.jar', b'j'), ('_remote.repositories', b'r')): with open(os.path.join(folder, name), 'wb') as f: f.write(data) self.uploaded, self.release, self.calls = [], {}, [] @@ -231,7 +231,7 @@ def gh(self, cmd): def assets_of(self, tag): return self.release if tag == 'jars' else self.others[tag] - def publish(self, run=None, coords=('org.example:engine:1.0',), **kw): + def publish(self, run=None, coords=('org.example:core:1.0',), **kw): M.publish(self.lock_file, list(coords), 'example/repo', m2=self.m2, run=run or self.gh, say=self.lines.append, **kw) def paths(self): @@ -244,7 +244,7 @@ def test_publish_uploads_the_build_files_and_a_second_run_changes_nothing(self): self.lock([]) self.exists = False self.publish() - self.assertEqual(sorted(self.uploaded), sorted([f'{sha(JAR)}-engine-1.0.jar', f'{sha(POM)}-engine-1.0.pom'])) + self.assertEqual(sorted(self.uploaded), sorted([f'{sha(JAR)}-core-1.0.jar', f'{sha(POM)}-core-1.0.pom'])) self.assertEqual(self.paths(), [(r['path'], r['sha256']) for r in self.rows()]) self.uploaded.clear() self.publish() @@ -268,7 +268,7 @@ def dies_after_first_upload(cmd): self.assertEqual(len(self.release), 2) def test_other_bytes_under_a_locked_path_are_refused_and_the_lock_stays(self): - self.lock([{'path': f'{V}/engine-1.0.jar', 'sha256': sha(b'the first build')}]) + self.lock([{'path': f'{V}/core-1.0.jar', 'sha256': sha(b'the first build')}]) with self.assertRaisesRegex(M.Refused, 'never reused'): self.publish() self.assertEqual(self.uploaded, []) @@ -277,18 +277,18 @@ def test_other_bytes_under_a_locked_path_are_refused_and_the_lock_stays(self): def test_a_version_not_in_m2_is_refused(self): self.lock([]) with self.assertRaisesRegex(M.Refused, 'has no jar and pom'): - self.publish(coords=['org.example:engine:2.0']) + self.publish(coords=['org.example:core:2.0']) def test_a_path_the_lock_could_not_read_is_refused_before_any_upload(self): # source #1257 r1: Maven's 1.0+b1 was uploaded and written, then the lock refused itself (every stage red) self.lock([]) - folder = os.path.join(self.m2, 'org', 'example', 'engine', '1.0+b1') + folder = os.path.join(self.m2, 'org', 'example', 'core', '1.0+b1') os.makedirs(folder) - for name in ('engine-1.0+b1.jar', 'engine-1.0+b1.pom'): + for name in ('core-1.0+b1.jar', 'core-1.0+b1.pom'): with open(os.path.join(folder, name), 'wb') as f: f.write(name.encode()) - with self.assertRaisesRegex(M.Refused, r"bad path 'org/example/engine/1\.0\+b1/engine-1\.0\+b1\.jar'"): - self.publish(coords=['org.example:engine:1.0+b1']) + with self.assertRaisesRegex(M.Refused, r"bad path 'org/example/core/1\.0\+b1/core-1\.0\+b1\.jar'"): + self.publish(coords=['org.example:core:1.0+b1']) self.assertEqual(self.uploaded, []) self.assertEqual(self.read_lock()['files'], []) M.read_lock(self.lock_file) # the lock is still readable: every other stage stays green @@ -326,7 +326,7 @@ def check_then_another_runner_removes_it(data): self.stage(self.remote()) finally: M.sha256 = real - self.assertEqual(self.staged(), [f'{V}/engine-1.0.jar', f'{V}/engine-1.0.pom']) + self.assertEqual(self.staged(), [f'{V}/core-1.0.jar', f'{V}/core-1.0.pom']) def test_a_stage_that_fails_half_way_leaves_no_out_and_the_rerun_is_green(self): self.lock(self.rows()) @@ -338,7 +338,7 @@ def test_a_stage_that_fails_half_way_leaves_no_out_and_the_rerun_is_green(self): self.assertFalse(os.path.exists(self.out)) self.assertEqual([n for n in os.listdir(self.root) if '.part-' in n], []) # the half-built folder went too self.stage(self.remote()) - self.assertEqual(self.staged(), [f'{V}/engine-1.0.jar', f'{V}/engine-1.0.pom']) + self.assertEqual(self.staged(), [f'{V}/core-1.0.jar', f'{V}/core-1.0.pom']) class Issue1330CachePrune(Base): @@ -347,17 +347,17 @@ def test_unused_old_entries_go_used_ones_stay_and_unknown_files_are_named(self): self.lock(self.rows()) os.makedirs(self.cache) long_ago, recent = time.time() - 40 * DAY, time.time() - DAY - files = {sha(b'old engine'): long_ago, sha(b'branch engine'): recent, sha(JAR): long_ago, 'notes.txt': long_ago} + files = {sha(b'old core'): long_ago, sha(b'branch core'): recent, sha(JAR): long_ago, 'notes.txt': long_ago} for name, t in files.items(): with open(os.path.join(self.cache, name), 'wb') as f: f.write(JAR if name == sha(JAR) else b'x') os.utime(os.path.join(self.cache, name), (t, t)) gh = self.remote() self.stage(gh) - self.assertNotIn(f'{sha(JAR)}-engine-1.0.jar', gh.downloads) # 40 days old but used: kept, not fetched again + self.assertNotIn(f'{sha(JAR)}-core-1.0.jar', gh.downloads) # 40 days old but used: kept, not fetched again left = set(os.listdir(self.cache)) - self.assertNotIn(sha(b'old engine'), left) # no lock row, unused for 40 days - self.assertIn(sha(b'branch engine'), left) # another branch's lock may still use it + self.assertNotIn(sha(b'old core'), left) # no lock row, unused for 40 days + self.assertIn(sha(b'branch core'), left) # another branch's lock may still use it self.assertIn('notes.txt', left) # never removes a file it did not write self.assertGreater(os.stat(os.path.join(self.cache, sha(JAR))).st_mtime, recent) # used: its age restarts self.assertTrue(any('notes.txt' in line for line in self.lines)) @@ -385,17 +385,17 @@ def test_rows_keep_their_release_when_the_lock_moves_to_a_new_one(self): gh.releases['jars-2'] = {} self.stage(gh) self.assertEqual(gh.listed, ['jars']) - self.assertEqual(self.staged(), [f'{V}/engine-1.0.jar', f'{V}/engine-1.0.pom']) + self.assertEqual(self.staged(), [f'{V}/core-1.0.jar', f'{V}/core-1.0.pom']) def test_prune_lock_keeps_only_the_named_versions(self): - other = 'org/example/engine/0.9' - self.lock(self.rows() + [{'path': f'{other}/engine-0.9.jar', 'sha256': sha(b'0.9')}]) - M.prune_lock(self.lock_file, ['org.example:engine:1.0'], say=self.lines.append) + other = 'org/example/core/0.9' + self.lock(self.rows() + [{'path': f'{other}/core-0.9.jar', 'sha256': sha(b'0.9')}]) + M.prune_lock(self.lock_file, ['org.example:core:1.0'], say=self.lines.append) self.assertEqual(self.paths(), [(r['path'], r['sha256']) for r in self.rows()]) - M.prune_lock(self.lock_file, ['org.example:engine:1.0'], say=self.lines.append) # a rerun changes nothing + M.prune_lock(self.lock_file, ['org.example:core:1.0'], say=self.lines.append) # a rerun changes nothing self.assertEqual(len(self.read_lock()['files']), 2) - with self.assertRaisesRegex(M.Refused, 'org.example:engine:3.0.*no rows'): # a typo never empties the lock - M.prune_lock(self.lock_file, ['org.example:engine:1.0', 'org.example:engine:3.0'], say=self.lines.append) + with self.assertRaisesRegex(M.Refused, 'org.example:core:3.0.*no rows'): # a typo never empties the lock + M.prune_lock(self.lock_file, ['org.example:core:1.0', 'org.example:core:3.0'], say=self.lines.append) self.assertEqual(len(self.read_lock()['files']), 2) @@ -405,31 +405,31 @@ class Issue1329ReleaseMistakes(PublishBase): def test_check_names_every_missing_or_unfinished_asset_without_downloading(self): self.lock(self.rows()) gh = self.remote() - del gh.files[f'{sha(POM)}-engine-1.0.pom'] + del gh.files[f'{sha(POM)}-core-1.0.pom'] real = gh.assets gh.assets = lambda tag: {n: dict(a, state='starter') for n, a in real(tag).items()} with self.assertRaises(M.Refused) as e: M.check(self.lock_file, gh, say=self.lines.append) - self.assertIn('engine-1.0.pom: the release jars has no asset', str(e.exception)) - self.assertIn('engine-1.0.jar: the upload of', str(e.exception)) + self.assertIn('core-1.0.pom: the release jars has no asset', str(e.exception)) + self.assertIn('core-1.0.jar: the upload of', str(e.exception)) self.assertEqual(gh.downloads, []) M.check(self.lock_file, self.remote(), say=self.lines.append) def test_publish_puts_back_a_deleted_asset_of_a_locked_version(self): self.lock([]) self.publish() - del self.release[f'{sha(JAR)}-engine-1.0.jar'] + del self.release[f'{sha(JAR)}-core-1.0.jar'] self.uploaded.clear() self.publish() - self.assertEqual(self.uploaded, [f'{sha(JAR)}-engine-1.0.jar']) + self.assertEqual(self.uploaded, [f'{sha(JAR)}-core-1.0.jar']) self.stage(FakeGitHub(self.release)) def test_an_unfinished_upload_is_replaced(self): self.lock([]) - self.release = {f'{sha(JAR)}-engine-1.0.jar': b'cut'} - self.states = {f'{sha(JAR)}-engine-1.0.jar': 'starter'} + self.release = {f'{sha(JAR)}-core-1.0.jar': b'cut'} + self.states = {f'{sha(JAR)}-core-1.0.jar': 'starter'} self.publish() - self.assertEqual(self.release[f'{sha(JAR)}-engine-1.0.jar'], JAR) + self.assertEqual(self.release[f'{sha(JAR)}-core-1.0.jar'], JAR) def test_every_error_stage_and_check_print_has_a_troubleshooting_row(self): with open(os.path.join(HERE, 'README.md')) as f: @@ -529,10 +529,10 @@ def test_a_deleted_asset_is_put_back_after_the_move(self): self.lock([]) self.publish() self.move_to('jars-2') - del self.release[f'{sha(JAR)}-engine-1.0.jar'] + del self.release[f'{sha(JAR)}-core-1.0.jar'] self.uploaded.clear() self.publish() - self.assertEqual(self.uploaded, [f'{sha(JAR)}-engine-1.0.jar']) # back into the row's own release + self.assertEqual(self.uploaded, [f'{sha(JAR)}-core-1.0.jar']) # back into the row's own release self.assertEqual(self.created, []) # no empty jars-2 for it self.assertEqual({r['release'] for r in self.read_lock()['files']}, {'jars'}) self.stage(FakeGitHub(self.release)) @@ -544,15 +544,15 @@ def test_a_rerun_after_the_move_changes_nothing_and_a_new_version_goes_to_the_ne self.uploaded.clear() self.publish() self.assertEqual((self.uploaded, self.created), ([], [])) - folder = os.path.join(self.m2, 'org', 'example', 'engine', '1.1') + folder = os.path.join(self.m2, 'org', 'example', 'core', '1.1') os.makedirs(folder) - for name in ('engine-1.1.jar', 'engine-1.1.pom'): + for name in ('core-1.1.jar', 'core-1.1.pom'): with open(os.path.join(folder, name), 'wb') as f: f.write(name.encode()) - self.publish(coords=['org.example:engine:1.0', 'org.example:engine:1.1']) + self.publish(coords=['org.example:core:1.0', 'org.example:core:1.1']) self.assertEqual(self.created, ['jars-2']) self.assertEqual(sorted(self.uploaded), - sorted(f'jars-2/{sha(n.encode())}-{n}' for n in ('engine-1.1.jar', 'engine-1.1.pom'))) + sorted(f'jars-2/{sha(n.encode())}-{n}' for n in ('core-1.1.jar', 'core-1.1.pom'))) self.assertEqual({r['path'].split('/')[3]: r['release'] for r in self.read_lock()['files']}, {'1.0': 'jars', '1.1': 'jars-2'}) @@ -560,7 +560,7 @@ def test_a_rerun_after_the_move_changes_nothing_and_a_new_version_goes_to_the_ne class LensSameVersionTwice(PublishBase): """Lens S1+S2 (minor): one version named twice wrote every row twice, and the lock then refused itself.""" def test_one_version_named_twice_or_spelled_two_ways_writes_each_row_once(self): - for coords in (['org.example:engine:1.0'] * 2, ['org.example:engine:1.0', 'org/example:engine:1.0']): + for coords in (['org.example:core:1.0'] * 2, ['org.example:core:1.0', 'org/example:core:1.0']): with self.subTest(coords=coords): self.lock([]) self.release.clear() @@ -579,10 +579,10 @@ class LensLegacyLockRollover(PublishBase): def setUp(self): super().setUp() self.lock(self.rows()) # no "release" in any row - self.release = {f'{sha(JAR)}-engine-1.0.jar': JAR, f'{sha(POM)}-engine-1.0.pom': POM} - folder = os.path.join(self.m2, 'org', 'example', 'engine', '1.1') + self.release = {f'{sha(JAR)}-core-1.0.jar': JAR, f'{sha(POM)}-core-1.0.pom': POM} + folder = os.path.join(self.m2, 'org', 'example', 'core', '1.1') os.makedirs(folder) - for name in ('engine-1.1.jar', 'engine-1.1.pom'): + for name in ('core-1.1.jar', 'core-1.1.pom'): with open(os.path.join(folder, name), 'wb') as f: f.write(name.encode()) @@ -599,10 +599,10 @@ def lock_bytes(self): def test_a_move_before_every_row_names_its_release_is_refused_before_any_upload(self): self.move_to('jars-2') before = self.lock_bytes() - for coords in (['org.example:engine:1.1'], ['org.example:engine:1.0'], ['org.example:engine:1.0'] * 2): + for coords in (['org.example:core:1.1'], ['org.example:core:1.0'], ['org.example:core:1.0'] * 2): with self.subTest(coords=coords): # the new version, the repair of an old one, and a rerun of it - with self.assertRaisesRegex(M.Refused, r'(?s)no "release" of their own.*engine-1\.0\.jar.*' - r'engine-1\.0\.pom.*Nothing was uploaded'): + with self.assertRaisesRegex(M.Refused, r'(?s)no "release" of their own.*core-1\.0\.jar.*' + r'core-1\.0\.pom.*Nothing was uploaded'): self.publish(coords=coords) self.assertEqual((self.uploaded, self.created), ([], [])) self.assertEqual(self.lock_bytes(), before) @@ -610,17 +610,17 @@ def test_a_move_before_every_row_names_its_release_is_refused_before_any_upload( self.move_to('jars') # undone by hand: stage still finds every old file gh = FakeGitHub(self.release) self.stage(gh) - self.assertEqual(self.staged(), [f'{V}/engine-1.0.jar', f'{V}/engine-1.0.pom']) + self.assertEqual(self.staged(), [f'{V}/core-1.0.jar', f'{V}/core-1.0.pom']) def test_the_readme_rollover_writes_every_rows_release_first_and_a_rerun_changes_nothing(self): self.publish() # step 1: publish a version the lock already has; it uploads nothing, only writes the releases self.assertEqual((self.uploaded, self.created), ([], [])) self.assertEqual({r['release'] for r in self.read_lock()['files']}, {'jars'}) self.move_to('jars-2') # step 2 - self.publish(coords=['org.example:engine:1.1']) # step 3 + self.publish(coords=['org.example:core:1.1']) # step 3 self.assertEqual(self.created, ['jars-2']) self.assertEqual(sorted(self.uploaded), - sorted(f'jars-2/{sha(n.encode())}-{n}' for n in ('engine-1.1.jar', 'engine-1.1.pom'))) + sorted(f'jars-2/{sha(n.encode())}-{n}' for n in ('core-1.1.jar', 'core-1.1.pom'))) self.assertEqual({r['path'].split('/')[3]: r['release'] for r in self.read_lock()['files']}, {'1.0': 'jars', '1.1': 'jars-2'}) gh = FakeGitHub(self.release) @@ -628,14 +628,14 @@ def test_the_readme_rollover_writes_every_rows_release_first_and_a_rerun_changes self.stage(gh) self.assertEqual(len(self.staged()), 4) before, self.uploaded = self.lock_bytes(), [] - self.publish(coords=['org.example:engine:1.0', 'org.example:engine:1.1']) + self.publish(coords=['org.example:core:1.0', 'org.example:core:1.1']) self.assertEqual((self.uploaded, self.created, self.lock_bytes()), ([], ['jars-2'], before)) def test_a_deleted_asset_of_a_row_that_names_no_release_is_never_guessed(self): """The lock's release may have moved, so publish cannot tell 'deleted here' from 'lives in an older release'.""" - del self.release[f'{sha(JAR)}-engine-1.0.jar'] + del self.release[f'{sha(JAR)}-core-1.0.jar'] before = self.lock_bytes() - with self.assertRaisesRegex(M.Refused, r'no "release" of their own.*engine-1\.0\.jar'): + with self.assertRaisesRegex(M.Refused, r'no "release" of their own.*core-1\.0\.jar'): self.publish() self.assertEqual((self.uploaded, self.lock_bytes()), ([], before)) lock = self.read_lock() # the README's repair: write the tag that held it, then publish @@ -644,7 +644,7 @@ def test_a_deleted_asset_of_a_row_that_names_no_release_is_never_guessed(self): with open(self.lock_file, 'w') as f: json.dump(lock, f) self.publish() - self.assertEqual(self.uploaded, [f'{sha(JAR)}-engine-1.0.jar']) + self.assertEqual(self.uploaded, [f'{sha(JAR)}-core-1.0.jar']) self.stage(FakeGitHub(self.release)) @@ -655,7 +655,7 @@ def test_a_cache_dir_that_cannot_be_made_only_warns(self): open(os.path.join(self.root, 'a-file'), 'w').close() self.cache = os.path.join(self.root, 'a-file', 'cache') self.stage(self.remote()) - self.assertEqual(self.staged(), [f'{V}/engine-1.0.jar', f'{V}/engine-1.0.pom']) + self.assertEqual(self.staged(), [f'{V}/core-1.0.jar', f'{V}/core-1.0.pom']) self.assertTrue(any(line.startswith('WARN:') and 'cache' in line for line in self.lines), self.lines) def test_a_full_disk_on_a_cache_write_only_warns(self): @@ -665,7 +665,7 @@ def full(*_): raise OSError(errno.ENOSPC, 'No space left on device') with mock.patch.object(M, 'write_atomic', full): self.stage(self.remote()) - self.assertEqual(self.staged(), [f'{V}/engine-1.0.jar', f'{V}/engine-1.0.pom']) + self.assertEqual(self.staged(), [f'{V}/core-1.0.jar', f'{V}/core-1.0.pom']) self.assertTrue(any(line.startswith('WARN:') and 'No space' in line for line in self.lines), self.lines) def test_a_cache_file_that_cannot_be_read_only_warns(self): @@ -676,7 +676,7 @@ def unreadable(*_): gh = self.remote() with mock.patch.object(M, 'cached', unreadable): self.stage(gh) - self.assertEqual(self.staged(), [f'{V}/engine-1.0.jar', f'{V}/engine-1.0.pom']) + self.assertEqual(self.staged(), [f'{V}/core-1.0.jar', f'{V}/core-1.0.pom']) self.assertEqual(len(gh.downloads), 2) self.assertTrue(any(line.startswith('WARN:') and 'cannot be read' in line for line in self.lines), self.lines) @@ -692,7 +692,7 @@ def test_a_cache_owned_by_another_user_only_warns(self): self.addCleanup(os.chmod, self.cache, 0o755) gh = self.remote() self.stage(gh) - self.assertEqual(self.staged(), [f'{V}/engine-1.0.jar', f'{V}/engine-1.0.pom']) + self.assertEqual(self.staged(), [f'{V}/core-1.0.jar', f'{V}/core-1.0.pom']) self.assertEqual(len(gh.downloads), 2) self.assertTrue(any(line.startswith('WARN:') for line in self.lines), self.lines) diff --git a/fork-kit/cleaner/README.md b/fork-kit/cleaner/README.md index a1dd50b50a1a6..476fd9a28152e 100644 --- a/fork-kit/cleaner/README.md +++ b/fork-kit/cleaner/README.md @@ -609,7 +609,8 @@ stays, each reads the same bytes as before, and the disk holds them once. Withou "folders": [ { "path": "~/mirrors", "days": 30 }, { "path": "/srv/build-output/releases", "days": 14 } - ] + ], + "writtenInPlace": [] } ``` @@ -618,6 +619,7 @@ stays, each reads the same bytes as before, and the disk holds them once. Withou | `dedupe.folders[].path` | required | a folder; files at any depth in it are looked at | | `dedupe.folders[].days` | required | days without a change (7 or more): newer files are not looked at | | `dedupe.folders[].layered` | false | the folder may be on a filesystem that is not local (as compress-cold) | +| `dedupe.writtenInPlace` | required | more name patterns (no `/`) never linked: one program's own kinds | **The risk it takes: read this before you name a folder.** Names of one hard-linked file are one file, so any write **into** one name changes every name, and the other names' old bytes are gone. Most ways of writing a file do @@ -629,11 +631,12 @@ So name **only folders of copies written once and then only read** (mirrors, rel never a folder where anything writes into files: no build caches, no game or server worlds, no virtual machine images, no working copies. The rule refuses the kinds it knows are written in place (databases `*.db`, `*.db3`, `*.sqlite*`, `*.mdb`, `*.ldb`, `*.ibd`, `*.wal`, and every file with a `-wal`, `-shm` or `-journal` beside it; logs -`*.log`, `*.log.*`, `*.jsonl`, `*.ndjson`, `*.journal`, `*.pid`; Minecraft region files `*.mca`, `*.mcr`, `*.mcc`; -disk images `*.qcow2`, `*.img`, `*.raw`, `*.vmdk`, `*.vdi`, `*.vhd`, `*.vhdx`; swap `*.swp`, `*.swap`; mail boxes -`mbox`, `*.mbox`; partial downloads a client resumes in place `*.part`, `*.crdownload`, `*.partial`, `*.!qb`), but -such a list can never be complete. Every plan and run that links says it again in one line (`dedupe: names of one file -share every later write ...`). On btrfs or XFS a tool that shares blocks with a reflink (`FIDEDUPERANGE`) is the +`*.log`, `*.log.*`, `*.jsonl`, `*.ndjson`, `*.journal`, `*.pid`; disk images `*.qcow2`, `*.img`, `*.raw`, `*.vmdk`, +`*.vdi`, `*.vhd`, `*.vhdx`; swap `*.swp`, `*.swap`; mail boxes `mbox`, `*.mbox`; partial downloads a client resumes +in place `*.part`, `*.crdownload`, `*.partial`, `*.!qb`), plus the name patterns in `dedupe.writtenInPlace` (one +program's own kinds, such as a game's save files; `[]` when the folders hold none), but such a list can never be +complete. Every plan and run that links says it again in one line (`dedupe: names of one file share every later +write ...`). On btrfs or XFS a tool that shares blocks with a reflink (`FIDEDUPERANGE`) is the safer choice: later writes do not reach the other copies. This rule makes hard links because the hosts it was made for are ext4, which has no reflinks. @@ -722,8 +725,18 @@ the rename)`. The report has a class - **the cache is missing, broken or cannot be written:** files are read again; a cache that cannot be written is named in one line and the run goes on. - **the machine file is older and has no `dedupe`:** the rule does nothing. +- **the machine file is older and has no `dedupe.writtenInPlace`:** older cleaners refused some kinds themselves + (game region files) that the built-in list no longer has, so with folders named and this key missing the rule + links nothing. Each folder is kept with `could not read: dedupe.writtenInPlace is missing ...` and every run + exits 1 until the key is there; the other rules run as usual. `[]` is the owner's word that no program writes + its own kinds in place in these folders. - **the cleaner is older than the machine file:** an older cleaner refuses the unknown `dedupe` key and every daily run exits 2. Install this cleaner on a machine first, then add the key. +- **upgrading a machine whose `dedupe` section has no `writtenInPlace`:** add the key first (the kinds a program + there writes in place, or `[]`), then install this cleaner. Until the new cleaner is in, the older one refuses + the machine file (`unknown key 'writtenInPlace'`) and every rule stops, every daily run exits 2, nothing is + touched. The other order is safe too, only noisier: the new cleaner links nothing and exits 1 until the key is + added. ## The machine file diff --git a/fork-kit/cleaner/lib/cleaner/config.py b/fork-kit/cleaner/lib/cleaner/config.py index 7426efd5cd130..80bdb8cc9a81d 100644 --- a/fork-kit/cleaner/lib/cleaner/config.py +++ b/fork-kit/cleaner/lib/cleaner/config.py @@ -118,6 +118,11 @@ def _names(value): return f'every entry must be a plain name, without / or a wildcard (not {bad[0]!r})' if bad else None +def _name_globs(value): + bad = [v for v in value if not _name_glob(v)] + return f'every entry must be a name pattern without / (not {bad[0]!r})' if bad else None + + def _patterns(value): for pattern, days in value.items(): if not _name_glob(pattern): @@ -240,6 +245,10 @@ def _github(value): # become hard links of one of them. Each folder is a FOLDER_SPEC. Without folders the rule does nothing. DEDUPE_SPEC = { 'folders': (list, (), None), + # More name patterns never linked, on top of dedupe.IN_PLACE. Missing (an older machine file) is not `[]`: with + # folders named, the rule then links nothing (dedupe.plan_dedupe), so an upgrade never links a kind an older + # cleaner refused. + 'writtenInPlace': (list, None, _name_globs), } COMPARE_SPEC = { 'name': (str, machine_file.REQUIRED, None), @@ -271,7 +280,7 @@ def _github(value): 'folders.path': 'picks', 'folders.days': 'floor', 'folders.layered': 'loosens', # dedupe deletes no content either (every name keeps its bytes and metadata); its folders never are or hold a # must-keep path, and every refusal holds in them (dedupe.py). - 'dedupe': 'picks', 'dedupe.folders': 'picks', + 'dedupe': 'picks', 'dedupe.folders': 'picks', 'dedupe.writtenInPlace': 'keeps more', # agentScratch: on, its folder and its days pick what it looks at. keepFirst only adds a copy before a delete: # more patterns copy more; maxFileBytes has a floor; a session with more than maxSessionBytes to copy stays # whole, so the cap picks which sessions the rule may take at all (every refusal still holds for them). The @@ -499,6 +508,8 @@ def _dedupe(self, section, where, log_text, out_text, archive=()): to a must-keep path or name (the same guard as every rule: dedupe changes how files are stored), never in or above the cleaner's own files, a folder another rule deletes from or compresses in, or another of its own.""" values = machine_file.fields(section, DEDUPE_SPEC, where) + listed = values['writtenInPlace'] + self.dedupe_in_place = None if listed is None else tuple(v.lower() for v in listed) folders = [] for i, entry in enumerate(values['folders']): at = f'{where}.folders[{i}]' diff --git a/fork-kit/cleaner/lib/cleaner/dedupe.py b/fork-kit/cleaner/lib/cleaner/dedupe.py index 3b718e3bda05c..20e9b09452c57 100644 --- a/fork-kit/cleaner/lib/cleaner/dedupe.py +++ b/fork-kit/cleaner/lib/cleaner/dedupe.py @@ -22,7 +22,8 @@ What it never takes: links (never followed), other filesystems and mount points (a hard link cannot cross one either), other owners' files, credential and lock names, must-keep names, folders with a KEEP file and git folders, in or above a configured folder up to `/` (git needs its files as they are), kinds written in place (IN_PLACE: -databases and their journals, logs, game region files, disk images, mail boxes, partial downloads), files changed in the last `days`, files in use (open, locked, named by a process or a +databases and their journals, logs, disk images, mail boxes, partial downloads; and the machine file's +`dedupe.writtenInPlace`), files changed in the last `days`, files in use (open, locked, named by a process or a systemd unit), immutable or append-only files, files with more than one name already (linking one of their names frees nothing), and files under MIN_BYTES. A file that changes while it is read or compared is kept as it is. config.py refuses folders in or holding a must-keep path and folders another rule takes. @@ -55,12 +56,13 @@ PART = '.cleaner-link' PART_NAME = re.compile(r'^\.(.+)\.[0-9a-f]{8}' + re.escape(PART) + '$') NAME_MAX = 255 -# Names programs write in place: databases and their journals, logs, append-only records, Minecraft region and -# chunk files, virtual machine and disk images, swap files, mail boxes, partial downloads a client resumes. Never complete: the README says to name only folders of +# Names programs write in place: databases and their journals, logs, append-only records, virtual machine and disk +# images, swap files, mail boxes, partial downloads a client resumes. One program's own kinds (a game's save files) +# go in the machine file (`dedupe.writtenInPlace`). Never complete: the README says to name only folders of # write-once copies. IN_PLACE = ('*.db', '*.db-*', '*.db3', '*.sqlite', '*.sqlite3', '*.sqlite-*', '*.sqlite3-*', '*-wal', '*-shm', '*-journal', '*.journal', '*.wal', '*.mdb', '*.ldb', '*.ibd', '*.log', '*.log.*', '*.jsonl', '*.ndjson', - '*.pid', '*.mca', '*.mcr', '*.mcc', '*.qcow2', '*.img', '*.raw', '*.vmdk', '*.vdi', '*.vhd', '*.vhdx', + '*.pid', '*.qcow2', '*.img', '*.raw', '*.vmdk', '*.vdi', '*.vhd', '*.vhdx', '*.swp', '*.swap', 'mbox', '*.mbox', '*.part', '*.crdownload', '*.partial', '*.!qb') SIDECARS = ('-wal', '-shm', '-journal') # chattr flags a person can set (linux/fs.h FS_FL_USER_MODIFIABLE) plus data journalling, no-copy-on-write, verity @@ -68,6 +70,10 @@ # other's). FS_VERITY_FL, FS_DAX_FL = 0x00100000, 0x02000000 FLAGS_MASK = 0x000380FF | 0x00004000 | 0x00800000 | FS_VERITY_FL | FS_DAX_FL +# A machine file older than `dedupe.writtenInPlace`: kinds that an older cleaner refused (and that are not in IN_PLACE +# any more) may be in the folders, so nothing is linked until the owner names them, or `[]`. +MISSING_KINDS = ('dedupe.writtenInPlace is missing from the machine file: nothing here is linked until it lists the ' + 'kinds a program writes in place in these folders, or is [] when there are none') WARNING = ('dedupe: names of one file share every later write into any of them (cp onto an existing file, shell >, ' 'downloads, most programs): name only folders of copies written once and then only read') @@ -318,9 +324,9 @@ def _name_refusal(cfg, facts, folder, path, st, names): return Refusal('credential name', name) if matches(name, LOCK_NAMES): return Refusal('lock file', name) - if matches(name, IN_PLACE) or any(name + s in names for s in SIDECARS): - return Refusal('written in place', 'a kind written in place (a database, journal, log, region file or ' - 'disk image): a hard link would share its next write') + if matches(name, IN_PLACE + cfg.dedupe_in_place) or any(name + s in names for s in SIDECARS): + return Refusal('written in place', 'a kind written in place (a database, journal, log, disk image or a ' + 'kind the machine file names): a hard link would share its next write') if guard.owner(st) != os.getuid(): return Refusal('another owner', f'uid {guard.owner(st)}') if not st.st_mode & stat.S_IRUSR: @@ -459,6 +465,10 @@ def plan_dedupe(cfg, facts, plan, measure): from .rules import Item, Kept if not cfg.dedupe_folders: return + if cfg.dedupe_in_place is None: + for folder in cfg.dedupe_folders: + plan.kept.append(Kept(folder.path, RULE, 'could not read', MISSING_KINDS)) + return run = Run(Cache.load(cfg)) plan.after.append(lambda: run.cache.save(run.seen)) files, parts = [], [] diff --git a/fork-kit/cleaner/tests/dedupe.test.py b/fork-kit/cleaner/tests/dedupe.test.py index 15d878d1792b3..520d2f2f90c37 100644 --- a/fork-kit/cleaner/tests/dedupe.test.py +++ b/fork-kit/cleaner/tests/dedupe.test.py @@ -65,8 +65,12 @@ def facts(self, cfg, **over): self.settle() return super().facts(cfg, **over) - def dd_cfg(self, days=30, folders=None, **section): - return self.cfg(dedupe={'folders': folders or [{'path': self.dd, 'days': days}]}, **section) + def dd_cfg(self, days=30, folders=None, in_place=(), **section): + """A dedupe section for the test's folder; `in_place` is `dedupe.writtenInPlace` (None leaves it out).""" + dedupe = {'folders': folders or [{'path': self.dd, 'days': days}]} + if in_place is not None: + dedupe['writtenInPlace'] = list(in_place) + return self.cfg(dedupe=dedupe, **section) def put(self, *parts, data=None, days=40, mode=0o644): path = os.path.join(self.dd, *parts) @@ -464,7 +468,7 @@ def test_a_folder_reached_through_a_link_is_kept(self): f.write(body()) self.age(os.path.join(real, name), 40) os.symlink(self.path('real'), self.path('via')) - cfg = self.cfg(dedupe={'folders': [{'path': self.path('via', 'dd'), 'days': 30}]}) + cfg = self.dd_cfg(folders=[{'path': self.path('via', 'dd'), 'days': 30}]) self.assertKept(self.plan(cfg), self.path('via', 'dd'), 'symbolic link') self.run_cleaner(cfg) self.assertNotEqual(self.ino(os.path.join(real, 'a.bin')), self.ino(os.path.join(real, 'b.bin'))) @@ -709,13 +713,57 @@ def test_the_readme_and_the_plan_say_so(self): self.assertIn('cp onto an existing file', self.c.dedupe.WARNING) def test_more_kinds_written_in_place(self): - names = ('r.0.0.mca', 'disk.qcow2', 'disk.img', 'disk.vmdk', 'disk.vdi', 'disk.raw', 'x.wal', 'x.ldb') + names = ('disk.qcow2', 'disk.img', 'disk.vmdk', 'disk.vdi', 'disk.raw', 'x.wal', 'x.ldb') for name in names: self.put(name) plan = self.plan(self.dd_cfg()) for name in names: self.assertKept(plan, os.path.join(self.dd, name), 'written in place') + def test_the_machine_file_adds_kinds_written_in_place(self): + """A program's own kinds (a game's save files) are named in the machine file, not in the code.""" + a, b = self.put('r.0.0.MCA', days=50), self.put('r.0.1.mca') + c, d = self.put('x.bin', days=50), self.put('y.bin') + kinds = lambda value: self.dd_cfg(in_place=value) + plan = self.plan(kinds(['*.mca', 'world.dat'])) + for path in (a, b): + self.assertKept(plan, path, 'written in place') + self.assertEqual(self.items(plan), [d]) + for bad in (['saves/*.mca'], [''], ['..'], [5], '*.mca'): + with self.subTest(bad=bad), self.assertRaises(machine_file.MachineFileError): + kinds(bad) + + def test_an_older_machine_file_without_written_in_place_links_nothing(self): + """An older machine file has no `dedupe.writtenInPlace`, and an older cleaner refused kinds the built-in list + no longer has: with the key missing the rule links nothing and says why, every run, until the owner adds it + (an explicit [] links as before). The other rules still run.""" + a, b = self.put('one.sav', days=50), self.put('two.sav') + c, d = self.put('x.bin', days=50), self.put('y.bin') + gone = self.old_dir('job-1', 3) + older = self.dd_cfg(in_place=None, tmp={'root': self.tmp, 'patterns': {'job-*': 1}}) + for again in (False, True): + with self.subTest(again=again): + code, lines = self.run_cleaner(older) + self.assertEqual(code, 1, lines) + said = [line for line in lines if 'dedupe.writtenInPlace is missing' in line] + self.assertEqual(len(said), 1, lines) + self.assertTrue(said[0].startswith(f'kept {self.dd} (dedupe: could not read: '), said) + self.assertEqual(len({self.ino(p) for p in (a, b, c, d)}), 4) + self.assertFalse(os.path.exists(gone)) + plan = self.plan(older) + self.assertEqual((self.items(plan), [(k.path, k.code) for k in plan.kept]), ([], [(self.dd, 'could not read')])) + # The owner names the kinds: those stay, the rest is linked, and a second run has nothing to do. + for again in (False, True): + code, lines = self.run_cleaner(self.dd_cfg(in_place=['*.sav'])) + self.assertEqual(code, 0, lines) + self.assertNotEqual(self.ino(a), self.ino(b)) + self.assertEqual(self.ino(c), self.ino(d)) + self.assertEqual(len([line for line in lines if line.startswith('linked ')]), 0 if again else 1, lines) + # [] is the owner's word that no program here writes in place: every copy is linked. + code, lines = self.run_cleaner(self.dd_cfg(in_place=[])) + self.assertEqual(code, 0, lines) + self.assertEqual(self.ino(a), self.ino(b)) + def test_files_with_other_chattr_flags_are_not_linked(self): a, b = self.put('a.bin', days=50), self.put('b.bin') if not set_flag(b, NODUMP): @@ -1350,7 +1398,7 @@ def test_files_in_two_folders_are_linked_to_each_other_and_the_readme_says_so(se InUse, 'test_a_file_opened_while_it_is_compared_stays'), 'credential names': ('dedupe', "if matches(name, CREDENTIAL_NAMES):\n return Refusal('credential name', name)", "if False:\n return Refusal('credential name', name)", Refused, 'test_what_it_never_takes'), - 'written in place': ('dedupe', 'if matches(name, IN_PLACE) or any(name + s in names for s in SIDECARS):', 'if False:', + 'written in place': ('dedupe', 'if matches(name, IN_PLACE + cfg.dedupe_in_place) or any(name + s in names for s in SIDECARS):', 'if False:', Refused, 'test_what_it_never_takes'), 'must-keep names': ('dedupe', "if guard.kept_name(cfg, name):\n return Refusal('must keep', name)", "if False:\n return Refusal('must keep', name)", Refused, 'test_what_it_never_takes'), @@ -1372,7 +1420,15 @@ def test_files_in_two_folders_are_linked_to_each_other_and_the_readme_says_so(se Writes, 'test_a_file_open_at_the_link_stays'), 'chattr flags count': ('dedupe', 'return (stat.S_IMODE(st.st_mode), st.st_uid, st.st_gid, attrs, _flags(fd))', 'return (stat.S_IMODE(st.st_mode), st.st_uid, st.st_gid, attrs, 0)', Writes, 'test_files_with_other_chattr_flags_are_not_linked'), - 'more kinds written in place': ('dedupe', "'*.pid', '*.mca',", "'*.pid',", Writes, 'test_more_kinds_written_in_place'), + 'more kinds written in place': ('dedupe', "'*.pid', '*.qcow2',", "'*.pid',", Writes, 'test_more_kinds_written_in_place'), + 'kinds the machine file names': ('dedupe', 'matches(name, IN_PLACE + cfg.dedupe_in_place)', 'matches(name, IN_PLACE)', + Writes, 'test_the_machine_file_adds_kinds_written_in_place'), + 'an older machine file links nothing': ('dedupe', ' if cfg.dedupe_in_place is None:\n for folder in cfg.dedupe_folders:', + ' if False:\n for folder in cfg.dedupe_folders:', + Writes, 'test_an_older_machine_file_without_written_in_place_links_nothing'), + 'a missing writtenInPlace is not []': ('config', 'None if listed is None else tuple(v.lower() for v in listed)', + 'tuple(v.lower() for v in listed or ())', + Writes, 'test_an_older_machine_file_without_written_in_place_links_nothing'), 'the plan warns': ('dedupe', ' plan.notes.append(WARNING)', ' pass', Writes, 'test_the_readme_and_the_plan_say_so'), 'the cache needs an unchanged stamp': ('dedupe', 'if cached is not None and tuple(cached[:3]) == stamp:', 'if cached is not None:', Cached, 'test_a_changed_file_is_read_again'), diff --git a/fork-kit/common/machine.example.json b/fork-kit/common/machine.example.json index 5faeea73ef478..05ece018177ef 100644 --- a/fork-kit/common/machine.example.json +++ b/fork-kit/common/machine.example.json @@ -93,7 +93,7 @@ "docker": { "enabled": true, "days": 7 }, "agentScratch": { "enabled": true, "days": 3 }, "compressCold": { "folders": [{ "path": "~/.codex/sessions", "days": 30 }] }, - "dedupe": { "folders": [{ "path": "~/mirrors", "days": 30 }] }, + "dedupe": { "folders": [{ "path": "~/mirrors", "days": 30 }], "writtenInPlace": [] }, "daily": { "mode": "compare", "oldTimers": ["example-retention.timer"], diff --git a/packages/contracts/src/forkSettings.ts b/packages/contracts/src/forkSettings.ts index ee1d4b6338ca5..1e228209c4a16 100644 --- a/packages/contracts/src/forkSettings.ts +++ b/packages/contracts/src/forkSettings.ts @@ -35,7 +35,7 @@ import { PlacementSettingsFromSettingsFile, PlacementSettingsPatch, } from "./placement.ts"; -import { PlaytestSettings, PlaytestSettingsFromSettingsFile } from "./playtest.ts"; +import { PlaytestSettingsFromSettingsFile, PlaytestSettingsPatch } from "./playtest.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; import { ReviewRulesFromSettingsFile, @@ -166,8 +166,8 @@ export const ForkServerSettingsPatchFields = { mcpThreadProfiles: Schema.optionalKey(McpThreadProfilesPatch), /** Strict: `apply` or `refuse`. */ mcpCarriedProfiles: Schema.optionalKey(McpCarriedProfiles), - /** Strict: a save refuses a bad step, or `enabled` without all four steps. */ - playtest: Schema.optionalKey(PlaytestSettings), + /** Strict: a save refuses a bad step, an unknown field, or `enabled` without all four steps. */ + playtest: Schema.optionalKey(PlaytestSettingsPatch), /** Strict: a save refuses a bad value, an unknown field, or `source: command` without a command. */ handoff: Schema.optionalKey(HandoffSettingsPatch), /** Strict: a save refuses a bad field, an unknown key, or a value without `preset`. */ @@ -330,10 +330,10 @@ export const ForkProjectOverridePatchFields = { mcpProfile: Schema.optionalKey(McpProjectProfileRefPatch), mcpSubagentProfile: Schema.optionalKey(McpProjectProfileRefPatch), /** - * A save refuses a bad step, or `enabled` without all four steps. Left out keeps the stored value; - * `null` clears it (the project then uses the server's). + * A save refuses a bad step, an unknown field, or `enabled` without all four steps. Left out keeps + * the stored value; `null` clears it (the project then uses the server's). */ - playtest: Schema.optionalKey(Schema.NullOr(PlaytestSettings)), + playtest: Schema.optionalKey(Schema.NullOr(PlaytestSettingsPatch)), /** As `playtest`: left out keeps the stored value; `null` clears it. */ handoff: Schema.optionalKey(Schema.NullOr(HandoffSettingsPatch)), /** diff --git a/packages/contracts/src/playtest.test.ts b/packages/contracts/src/playtest.test.ts index f56857f666f1d..5efa9d82df3d3 100644 --- a/packages/contracts/src/playtest.test.ts +++ b/packages/contracts/src/playtest.test.ts @@ -168,6 +168,9 @@ describe("playtest settings in the settings file", () => { { ...ADAPTER, claim: step(["game"]) }, { ...ADAPTER, push: [ADAPTER.push[0], ADAPTER.push[0]] }, { ...ADAPTER, enabled: "yes" }, + // A newer build's field (a limit this build would not apply), at the top or in a step. + { ...ADAPTER, onlyBranches: ["playtest/*"] }, + { ...ADAPTER, claim: { ...ADAPTER.claim, maxRuns: 1 } }, "on", null, [], @@ -227,6 +230,17 @@ describe("playtest settings in a save", () => { expect(() => project(without("release"))).toThrow(); expect(() => project({ ...ADAPTER, push: [{ name: "x", argv: ["guard"] }] })).toThrow(); }); + + it.each([ + ["a field from a newer build", { ...ADAPTER, onlyBranches: ["playtest/*"] }], + ["a typo", { ...ADAPTER, timeoutSecond: 30 }], + ["a newer field in a step", { ...ADAPTER, claim: { ...ADAPTER.claim, maxRuns: 1 } }], + ])("refuses %s, never drops it and saves the rest as on", (_name, value) => { + expect(() => decodePatch({ playtest: value })).toThrow(); + expect(() => + decodePatch({ projectSettingsOverrides: { [PROJECT]: { playtest: value } } }), + ).toThrow(); + }); }); describe("playtest adapter contract", () => { diff --git a/packages/contracts/src/playtest.ts b/packages/contracts/src/playtest.ts index 1b38ced2c257b..d4208e68ec018 100644 --- a/packages/contracts/src/playtest.ts +++ b/packages/contracts/src/playtest.ts @@ -140,11 +140,31 @@ export type PlaytestSettings = typeof PlaytestSettings.Type; export const DEFAULT_PLAYTEST_SETTINGS: PlaytestSettings = Schema.decodeSync(PlaytestSettings)({}); const decodePlaytestSettingsOption = Schema.decodeUnknownOption(PlaytestSettings); +/** Also refuses an unknown field, nested ones too: it may be a newer build's limit. */ +const isStrictPlaytestSettings = (raw: unknown) => + decodePlaytestSettingsOption(raw, { onExcessProperty: "error" })._tag === "Some"; + +/** A save's value: refused when bad, also for a field this build does not know (never dropped). */ +export const PlaytestSettingsPatch = Schema.Unknown.check( + Schema.makeFilter(isStrictPlaytestSettings, { + expected: "playtest settings with only the fields this build knows", + }), +).pipe( + Schema.decodeTo( + PlaytestSettings, + // The value is already checked; the settings writer saves it sparse. + SchemaTransformation.transformEffect({ + decode: (raw: unknown) => Effect.succeed(raw as typeof PlaytestSettings.Encoded), + encode: (settings: typeof PlaytestSettings.Encoded) => Effect.succeed(settings as unknown), + }), + ), +); /** * The settings file's value. A bad one reads as off with a warning (fail closed; the rest of the - * file still loads), and the next save writes the default in its place. In a project's overrides - * it reads as off too, never as the server's adapter. + * file still loads), and the next save writes the default in its place. So does a field this build + * does not know: it may be a newer build's limit that this build would not apply. In a project's + * overrides it reads as off too, never as the server's adapter. */ export const PlaytestSettingsFromSettingsFile = Schema.Unknown.pipe( Schema.decodeTo( @@ -153,7 +173,7 @@ export const PlaytestSettingsFromSettingsFile = Schema.Unknown.pipe( PlaytestSettings, SchemaTransformation.transformEffect({ decode: Effect.fn("PlaytestSettingsFromSettingsFile.decode")(function* (raw: unknown) { - if (decodePlaytestSettingsOption(raw)._tag === "Some") { + if (isStrictPlaytestSettings(raw)) { return raw as typeof PlaytestSettings.Encoded; } yield* Effect.logWarning(