Skip to content

Commit 91332e3

Browse files
author
roberttwang
committed
fix(deploy): apply artifact storage migration before startup
1 parent e2dbb0a commit 91332e3

7 files changed

Lines changed: 72 additions & 16 deletions

File tree

‎compose.yaml‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,25 @@ services:
1717
interval: 2s
1818
timeout: 3s
1919
retries: 60
20+
artifact-migration:
21+
profiles: [platform]
22+
# Upgrade existing volumes before the platform starts. Fresh schemas are created by the platform.
23+
image: mysql:8.4
24+
entrypoint: ["sh", "-ec"]
25+
command:
26+
- exec mysql -h mysql -u loopforge loopforge < /migrations/042_run_artifacts_content_mediumtext.sql
27+
environment:
28+
MYSQL_PWD: ${LOOPFORGE_DB_PASSWORD:?Run scripts/configure.sh first}
29+
volumes:
30+
- type: bind
31+
source: ./migrations/042_run_artifacts_content_mediumtext.sql
32+
target: /migrations/042_run_artifacts_content_mediumtext.sql
33+
read_only: true
34+
bind:
35+
create_host_path: false
36+
depends_on:
37+
mysql:
38+
condition: service_healthy
2039
platform:
2140
profiles: [platform]
2241
# Published release stack: never builds. Bump the pinned tag (here and in
@@ -71,6 +90,8 @@ services:
7190
depends_on:
7291
mysql:
7392
condition: service_healthy
93+
artifact-migration:
94+
condition: service_completed_successfully
7495
healthcheck:
7596
test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/health', timeout=2).close()"]
7697
interval: 3s

‎docs/deployment.md‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -217,10 +217,15 @@ For an external MySQL deployment, review that migration and check column existen
217217
| Required upgrade migrations | `009_bot_interactions_utf8mb4.sql`, `036_git_http_credentials.sql`, `041_native_sandbox_inline_assets.sql` | Follow each migration's timing and prerequisites. [Migrating existing GitHub credentials](#migrating-existing-github-credentials) |
218218
| Optional backfills and rewrites of existing rows | `016_public_optional_repositories.sql`, `021_assistant_session_sources.sql` | Run them if the installation needs the converted rows |
219219

220-
For an existing database with `run_artifacts.content` defined as `TEXT`, apply
221-
`migrations/042_run_artifacts_content_mediumtext.sql` before starting the upgraded
222-
platform. It widens the column for the 1 MiB artifact contract and preserves
223-
existing data, character set, collation and nullability. The script is safe to rerun.
220+
Compose runs `migrations/042_run_artifacts_content_mediumtext.sql` before the
221+
platform starts, including during `./start.sh pull`. The native development
222+
script runs the same migration against its Compose database. It widens an existing
223+
`run_artifacts.content` column from `TEXT` to `MEDIUMTEXT` for the 1 MiB artifact
224+
contract and preserves existing data, character set, collation and nullability.
225+
For a deployment using an external MySQL server and no Compose startup, run this
226+
SQL file in the deployment's database upgrade step before starting the new binary.
227+
If the Compose migration fails, review `docker compose --profile platform logs
228+
artifact-migration`, resolve the database error and rerun the upgrade.
224229

225230
### Migrating existing sandboxes to inline assets
226231

‎internal/engine/node_artifact_commit_test.go‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,8 @@ func TestMySQLNodeArtifactCommit(t *testing.T) {
106106
run := runArtifactSOP(t, store, content, "waiting")
107107
assertArchivedPlan(t, store, run, content)
108108
}
109+
oversized := runArtifactSOP(t, store, strings.Repeat("x", maxArtifactBytes+1), "failed")
110+
assertOversizedPlanRejected(t, oversized)
109111
}
110112

111113
func runArtifactSOP(t *testing.T, store *repo.Store, content, wantStatus string) domain.Run {
@@ -149,7 +151,7 @@ func runArtifactSOP(t *testing.T, store *repo.Store, content, wantStatus string)
149151
if _, err := eng.acquireLease(run); err != nil {
150152
t.Fatal(err)
151153
}
152-
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
154+
ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
153155
runID := run.ID
154156
done := make(chan struct{})
155157
go func() {
@@ -168,19 +170,19 @@ func runArtifactSOP(t *testing.T, store *repo.Store, content, wantStatus string)
168170
t.Logf("%d bytes: run=%s, node=%s, approval=%s, artifacts=%d", len(content), run.Status, run.Nodes["writing-plans"].Status, run.Nodes["approval"].Status, len(run.Artifacts))
169171
return run
170172
}
171-
if (wantStatus == "failed" && artifactPublished(run)) || domain.TerminalRunStatus(run.Status) {
173+
if (wantStatus == "failed" && planPublished(run)) || domain.TerminalRunStatus(run.Status) {
172174
break
173175
}
174176
time.Sleep(20 * time.Millisecond)
175177
}
176178
node := run.Nodes["writing-plans"]
177-
t.Fatalf("%d bytes: run=%s, node=%s, approval=%s, artifacts=%d, published=%t, error=%q, want run=%s", len(content), run.Status, node.Status, run.Nodes["approval"].Status, len(run.Artifacts), artifactPublished(run), node.Error, wantStatus)
179+
t.Fatalf("%d bytes: run=%s, node=%s, approval=%s, artifacts=%d, plan published=%t, error=%q, want run=%s", len(content), run.Status, node.Status, run.Nodes["approval"].Status, len(run.Artifacts), planPublished(run), node.Error, wantStatus)
178180
return domain.Run{}
179181
}
180182

181-
func artifactPublished(run domain.Run) bool {
183+
func planPublished(run domain.Run) bool {
182184
return slices.ContainsFunc(run.Telemetry, func(event domain.TelemetryEvent) bool {
183-
return event.NodeID == "writing-plans" && event.Name == "artifact.published"
185+
return event.NodeID == "writing-plans" && event.Name == "artifact.published" && event.Message == "plan"
184186
})
185187
}
186188

@@ -193,8 +195,8 @@ func assertArtifactCommitFailed(t *testing.T, run domain.Run, cause string) {
193195
if node.GateResult == nil || node.GateResult.Decision != "pass" {
194196
t.Fatal("expected the agent to pass its gate before the artifact write failed")
195197
}
196-
if run.Nodes["approval"].Status != "pending" || len(run.Artifacts) != 0 || artifactPublished(run) {
197-
t.Fatalf("rejected write advanced the run or published an artifact: approval=%s artifacts=%d published=%t", run.Nodes["approval"].Status, len(run.Artifacts), artifactPublished(run))
198+
if run.Nodes["approval"].Status != "pending" || len(run.Artifacts) != 0 || planPublished(run) {
199+
t.Fatalf("rejected write advanced the run or published an artifact: approval=%s artifacts=%d plan published=%t", run.Nodes["approval"].Status, len(run.Artifacts), planPublished(run))
198200
}
199201
if !slices.ContainsFunc(run.Events, func(event domain.RunEvent) bool {
200202
return event.NodeID == "writing-plans" && event.Type == "node.failed" && strings.Contains(event.Message, cause)
@@ -213,3 +215,16 @@ func assertArchivedPlan(t *testing.T, store *repo.Store, run domain.Run, content
213215
t.Fatalf("stored artifact differs from the %d-byte plan", len(content))
214216
}
215217
}
218+
219+
func assertOversizedPlanRejected(t *testing.T, run domain.Run) {
220+
t.Helper()
221+
if got := run.Nodes["writing-plans"].Error; !strings.Contains(got, fmt.Sprintf("plan exceeds %d bytes", maxArtifactBytes)) {
222+
t.Fatalf("oversized plan returned %q", got)
223+
}
224+
archived := slices.ContainsFunc(run.Artifacts, func(artifact domain.Artifact) bool {
225+
return artifact.NodeID == "writing-plans" && artifact.Name == "plan"
226+
})
227+
if archived || planPublished(run) || run.Nodes["approval"].Status != "pending" {
228+
t.Fatal("oversized plan was archived, published, or passed to approval")
229+
}
230+
}

‎migrations/042_run_artifacts_content_mediumtext.sql‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
-- Widen legacy artifact storage to accommodate the 1 MiB artifact contract.
2-
-- Apply to the existing LoopForge database before upgrading. Safe to repeat.
2+
-- The Compose startup runs this automatically. Run before starting the new
3+
-- platform in other deployment pipelines. Safe to repeat.
34
SET @loopforge_artifact_ddl = (
45
SELECT CONCAT(
56
'ALTER TABLE `run_artifacts` MODIFY COLUMN `content` MEDIUMTEXT',

‎scripts/dev.sh‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ source .env
88
set +a
99
mkdir -p .local/bin .local/workspaces
1010
docker compose up -d --wait mysql
11+
docker compose --profile platform run --rm --no-deps artifact-migration
1112
bash scripts/build-binaries.sh
1213
if [[ ! -f .local/admin-password ]]; then
1314
(umask 077; python3 -c 'import secrets; print(secrets.token_urlsafe(18))' > .local/admin-password)

‎scripts/test-install-live.sh‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,10 @@ for actor in "${actors[@]}"; do
2222
fixture="$task_dir/$actor"
2323
mkdir -p "$fixture/scripts" "$fixture/migrations/seed" "$fixture/user-home"
2424
cp scripts/{install.sh,configure.sh,docker-access.sh,ghcr-mirror.sh,install-address.py,install-compose.py,install-observability-schema.sh,install-schema-extensions.sh} "$fixture/scripts/"
25-
cp migrations/001_run_obs_generated_columns.sql migrations/033_generic_sop_mr_node.sql migrations/038_generic_sop_host_credentials.sql "$fixture/migrations/"
25+
cp migrations/001_run_obs_generated_columns.sql \
26+
migrations/033_generic_sop_mr_node.sql \
27+
migrations/038_generic_sop_host_credentials.sql \
28+
migrations/042_run_artifacts_content_mediumtext.sql "$fixture/migrations/"
2629
cp migrations/seed/*.sql "$fixture/migrations/seed/"
2730
cp compose.yaml "$fixture/"
2831
read -r http_port mysql_port < <(python3 - <<'PY'
@@ -48,14 +51,23 @@ PY
4851
"${prefix[@]}" bash -c 'if docker info >/dev/null 2>&1; then exit 1; fi; sudo -n docker info >/dev/null'
4952
fi
5053
started=$SECONDS
51-
for attempt in first repeat; do
54+
for attempt in first legacy-upgrade repeat; do
55+
if [[ "$attempt" == legacy-upgrade ]]; then
56+
docker compose -f "$fixture/compose.yaml" --env-file "$fixture/.env" exec -T mysql \
57+
sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" exec mysql -u loopforge loopforge' \
58+
<<<'ALTER TABLE run_artifacts MODIFY COLUMN content TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL;'
59+
fi
5260
"${prefix[@]}" env HOME="$fixture/user-home" PATH=/usr/local/bin:/usr/bin:/bin LOOPFORGE_YES=1 COMPOSE_PROJECT_NAME="lf-install-${actor}-$$" LOOPFORGE_IMAGE="$image" LOOPFORGE_DATA_DIR="$fixture/data" LOOPFORGE_BIND=0.0.0.0 LOOPFORGE_PUBLIC_URL="http://192.0.2.10:$http_port" LOOPFORGE_DOCKER_SOCKET="$docker_socket" AGENTFLOW_HTTP_PORT="$http_port" LOOPFORGE_MYSQL_PORT="$mysql_port" bash "$fixture/scripts/install.sh" > "$fixture/$attempt.log" 2>&1 || { cat "$fixture/$attempt.log"; exit 1; }
5361
grep -q "Access: http://192.0.2.10:$http_port" "$fixture/$attempt.log"
5462
curl -fsS "http://127.0.0.1:$http_port/api/health" >/dev/null
5563
if [[ "$attempt" == first ]]; then
5664
cp "$fixture/.env" "$fixture/initial.env"
5765
else
5866
cmp "$fixture/initial.env" "$fixture/.env"
67+
column=$(docker compose -f "$fixture/compose.yaml" --env-file "$fixture/.env" exec -T mysql \
68+
sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" exec mysql -NB -u loopforge loopforge' \
69+
<<<'SELECT CONCAT_WS("/", DATA_TYPE, COLLATION_NAME, IS_NULLABLE) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = "run_artifacts" AND COLUMN_NAME = "content";')
70+
[[ "$column" == mediumtext/utf8mb4_bin/NO ]] || { printf 'Unexpected artifact column after %s: %s\n' "$attempt" "$column" >&2; exit 1; }
5971
fi
6072
done
6173
docker compose -f "$fixture/compose.yaml" --env-file "$fixture/.env" --profile platform port platform 8080 | grep -q "0.0.0.0:$http_port"
@@ -108,5 +120,5 @@ api('POST','/api/runs/'+run_id+'/approve',{'nodeId':'approve'})
108120
wait_for('succeeded')
109121
print('Verified access, administrator creation, seeded sandboxes/templates/executors, and a real no-key welcome SOP through approval and completion')
110122
PY
111-
printf '%s install + repeat: %ss (UID %s)\n' "$actor" "$((SECONDS-started))" "$("${prefix[@]}" id -u)"
123+
printf '%s install + legacy upgrade + repeat: %ss (UID %s)\n' "$actor" "$((SECONDS-started))" "$("${prefix[@]}" id -u)"
112124
done

‎scripts/test-install.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ def setUp(self):
3535
for name in ('install.sh', 'configure.sh', 'docker-access.sh', 'ghcr-mirror.sh', 'install-address.py', 'install-compose.py', 'install-observability-schema.sh', 'install-schema-extensions.sh'):
3636
shutil.copyfile(ROOT / 'scripts' / name, self.root / 'scripts' / name)
3737
shutil.copyfile(ROOT / 'start.sh', self.root / 'start.sh')
38-
for name in ('001_run_obs_generated_columns.sql', '033_generic_sop_mr_node.sql', '038_generic_sop_host_credentials.sql', '041_native_sandbox_inline_assets.sql'):
38+
for name in ('001_run_obs_generated_columns.sql', '033_generic_sop_mr_node.sql', '038_generic_sop_host_credentials.sql',
39+
'041_native_sandbox_inline_assets.sql', '042_run_artifacts_content_mediumtext.sql'):
3940
(self.root / 'migrations' / name).write_text((ROOT / 'migrations' / name).read_text())
4041
(self.root / 'migrations/seed/001_test.sql').write_text('INSERT IGNORE INTO agents (id) VALUES (1);\n')
4142
(self.root / 'mock').mkdir()

0 commit comments

Comments
 (0)