GeezerVison is showing github.com — fix(core): attribute V1 global sessions during import by rekram1-node · Pull Request #56322 · anomalyco/opencode
fix(core): attribute V1 global sessions during import
#56322
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.ts
(4)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
export * as V1Migration from "./v1-migration.js"
import { Cause, Effect, Layer, Option, Schema, Semaphore } from "effect"
import { Cause, Effect, Fiber, Layer, Option, Schema, Semaphore } from "effect"
import { Database } from "./database.js"
import { storedAbsolutePath } from "./path.js"
import { SessionMessageTable, SessionTable } from "../session/sql.js"
Expand All
@@ -11,11 +11,14 @@ import { KVTable } from "../kv/sql.js"
import { EventSequenceTable } from "../event/sql.js"
import { eq, sql } from "drizzle-orm"
import { Global } from "@opencode/util/global"
import { FSUtil } from "@opencode/util/fs-util"
import { existsSync } from "node:fs"
import path from "node:path"
import type { Database as SQLiteDatabase } from "bun:sqlite"
import { Project } from "@opencode/schema/project"
import { Agent } from "@opencode/schema/agent"
import { Project } from "../project.js"
import { AbsolutePath } from "../schema.js"
import { ProjectTable } from "../project/sql.js"
export type SourceMessage = {
readonly id: string
Expand Down
Expand Up
@@ -535,7 +538,9 @@ function updateProgress(progress: Progress) {
if (runtimeState.status === "running") runtimeState = { status: "running", progress }
}
export function run(options: Options = {}): Effect.Effect<RunResult, never, Database.Service | Global.Service> {
export function run(
options: Options = {},
): Effect.Effect<RunResult, never, Database.Service | Global.Service | Project.Service | FSUtil.Service> {
return lock.withPermit(
Effect.gen(function* () {
const db = (yield* Database.Service).db
Expand Down
Expand Up
@@ -588,15 +593,49 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
project.worktree,
]),
)
const directories = new Map<string, { project: Project.Resolved; path: string } | undefined>()
let lookupTimedOut = false
while (true) {
const state = yield* readState(db)
const cursorValue = state?.phase === "sessions" ? state.cursor : undefined
const nextID = yield* db.get<{ id: string; project_id: string; directory: string }>(
cursorValue === undefined
? sql`SELECT id, project_id, directory FROM session ORDER BY id DESC LIMIT 1`
: sql`SELECT id, project_id, directory FROM session WHERE id < ${cursorValue} ORDER BY id DESC LIMIT 1`,
)
const nextID = yield* db.get<{
id: string
project_id: string
workspace_id: string | null
directory: string
path: string | null
time_updated: number
imported: number
}>(sql`
SELECT id, project_id, workspace_id, directory, path, time_updated,
EXISTS (SELECT 1 FROM session_v2 WHERE session_v2.id = session.id) AS imported
FROM session
${cursorValue === undefined ? sql`` : sql`WHERE id < ${cursorValue}`}
ORDER BY id DESC LIMIT 1
`)
if (!nextID) break
const projectID = projects.has(nextID.project_id) ? nextID.project_id : Project.ID.global
// Legacy ACP sessions can store a cwd relative to an unknown process directory.
// Use the project worktree instead, and leave the original V1 row intact.
const directory =
!nextID.directory || storedAbsolutePath(nextID.directory)
? nextID.directory
: (storedAbsolutePath(projects.get(projectID) ?? path.parse(global.data).root) ?? "")
const unowned =
projectID === Project.ID.global &&
nextID.workspace_id === null &&
!nextID.imported &&
directory === nextID.directory
if (unowned && !lookupTimedOut && !directories.has(directory)) {
const resolved = yield* resolveDirectory(directory)
// One hung directory (e.g. a dead network mount) usually means more; leave the rest under global.
if (Option.isNone(resolved)) {
lookupTimedOut = true
yield* Effect.logWarning("Stopped resolving V1 session directories after a timeout", { directory })
}
directories.set(directory, Option.getOrUndefined(resolved))
}
const owner = unowned ? directories.get(directory) : undefined
yield* db
.transaction((tx) =>
Effect.gen(function* () {
Expand All
@@ -608,24 +647,29 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
set: { value: { phase: "sessions", cursor: nextID.id }, time_updated: Date.now() },
})
.run()
const projectID = projects.has(nextID.project_id) ? nextID.project_id : Project.ID.global
if (projectID !== nextID.project_id)
yield* Effect.logWarning("Reassigned V1 session with missing project", {
sessionID: nextID.id,
projectID: nextID.project_id,
})
// Legacy ACP sessions can store a cwd relative to an unknown process directory.
// Use the project worktree instead, and leave the original V1 row intact.
const directory =
!nextID.directory || storedAbsolutePath(nextID.directory)
? nextID.directory
: (storedAbsolutePath(projects.get(projectID) ?? path.parse(global.data).root) ?? "")
if (directory !== nextID.directory)
yield* Effect.logWarning("Replaced relative V1 session directory", {
sessionID: nextID.id,
directory: nextID.directory,
resolved: directory,
})
if (owner && !projects.has(owner.project.id))
yield* tx
.insert(ProjectTable)
.values({
id: owner.project.id,
worktree: owner.project.canonical,
vcs: owner.project.vcs?.type,
sandboxes: [],
time_active: nextID.time_updated,
})
.onConflictDoNothing()
.run()
yield* tx.run(sql`
INSERT OR IGNORE INTO session_v2 (
id, project_id, workspace_id, parent_id, slug, directory, path, title, version, share_url,
Expand All
@@ -634,7 +678,7 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
revert, permission, agent, model, time_created, time_updated, time_compacting, time_archived
)
SELECT
id, ${projectID}, workspace_id, parent_id, slug, ${directory}, path, title, version, share_url,
id, ${owner?.project.id ?? projectID}, workspace_id, parent_id, slug, ${directory}, ${owner?. path ?? nextID.path} , title, version, share_url,
summary_additions, summary_deletions, summary_files, summary_diffs, metadata, cost,
tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write,
revert, NULL, agent, model, time_created, time_updated, time_compacting, time_archived
Expand Down
Expand Up
@@ -688,6 +732,7 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
}),
)
.pipe(Effect.orDie)
if (owner && !projects.has(owner.project.id)) projects.set(owner.project.id, owner.project.canonical)
if (runtimeState.status === "running")
runtimeState = {
status: "running",
Expand Down
Expand Up
@@ -718,6 +763,39 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
)
}
// V1 grouped non-git sessions under global; V2 resolves an owner for each directory.
// Discovery must not publish adoption events for sessions already stored in V2.
// Any failure keeps the session under global. The lookup runs detached so a filesystem or git call
// that ignores interruption cannot stall the migration; Option.none means it timed out.
function resolveDirectory(directory: string) {
return Effect.gen(function* () {
const fiber = yield* Effect.forkDetach(
Effect.gen(function* () {
if (!directory) return
const fs = yield* FSUtil.Service
const normalized = yield* fs
.realPath(path.resolve(FSUtil.windowsPath(directory)))
.pipe(Effect.orElseSucceed(() => undefined))
if (!normalized || !(yield* fs.isDir(normalized))) return
const projects = yield* Project.Service
const project = yield* projects.resolve(AbsolutePath.make(normalized), { persist: false })
return {
project,
path: path.relative(project.directory, normalized).replaceAll("\\", "/"),
}
}),
)
const result = yield* Fiber.join(fiber).pipe(
Effect.catchDefect((defect) =>
Effect.logWarning("Failed to resolve V1 session directory", { directory, defect }).pipe(Effect.as(undefined)),
),
Effect.timeoutOption("5 seconds"),
)
if (Option.isNone(result)) yield* Effect.forkDetach(Fiber.interrupt(fiber))
return result
})
}
function nextPath(options: Options, data: string) {
if (options.nextDatabasePath) return options.nextDatabasePath
if (process.env.OPENCODE_DB === ":memory:") return undefined
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -65,13 +65,18 @@ export interface ListInput {
readonly archived?: boolean
}
export interface ResolveOptions {
/** Discover ownership without persisting or announcing it. */
readonly persist?: boolean
}
export interface Interface {
readonly list: (input?: ListInput) => Effect.Effect<ReadonlyArray<Info>>
readonly update: (input: UpdateInput) => Effect.Effect<Info, NotFoundError>
/** Records Project activity for recency ordering, at most once per minute per Project. */
readonly activate: (projectID: ID) => Effect.Effect<void>
/** Resolves and persists the owning Project. */
readonly resolve: (input: AbsolutePath) => Effect.Effect<Resolved>
/** Resolves the owning Project, persisting it unless `persist` is false . */
readonly resolve: (input: AbsolutePath, options?: ResolveOptions ) => Effect.Effect<Resolved>
/** Archives Projects whose known directories are all gone; resolving a Project unarchives it. */
readonly sweep: () => Effect.Effect<void>
}
Expand Down
Expand Up
@@ -350,7 +355,8 @@ const layer = Layer.effect(
}
})
const resolve = Effect.fn("Project.resolve")(function* (input: AbsolutePath) {
const resolve = Effect.fn("Project.resolve")(function* (input: AbsolutePath, options?: ResolveOptions) {
const save = (project: Resolved) => (options?.persist === false ? Effect.succeed(project) : persist(project))
const directory = AbsolutePath.make(yield* fs.resolve(input))
const native = yield* fs.up({ targets: [".git", ".hg"], start: directory, mode: "first" }).pipe(
Effect.map((matches) => matches[0]),
Expand All
@@ -370,7 +376,7 @@ const layer = Layer.effect(
Effect.map((items) => items.find((item) => item.kind === "main")?.directory ?? repo.worktree),
Effect.orElseSucceed(() => repo.worktree),
)
return yield* persist ({
return yield* save ({
previous,
id: id ?? ID.global,
directory: repo.worktree,
Expand All
@@ -381,13 +387,13 @@ const layer = Layer.effect(
const hg = native && path.basename(native) === ".hg" ? yield* hgDiscover(AbsolutePath.make(native)) : undefined
if (hg) {
return yield* persist ({
return yield* save ({
...hg,
canonical: hg.directory,
})
}
return yield* persist ({
return yield* save ({
id: ID.make(Hash.fast(`directory:${directory}`)),
directory,
canonical: directory,
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -11,11 +11,16 @@ import { Project } from "@opencode/core/project"
import { Agent } from "@opencode/schema/agent"
import { ProjectTable } from "@opencode/core/project/sql"
import { AbsolutePath } from "@opencode/core/schema"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { LayerNode } from "@opencode/util/effect/layer-node"
import { FSUtil } from "@opencode/util/fs-util"
import { Global } from "@opencode/util/global"
import { Effect, Fiber, Layer, Logger, Schedule, Schema, Scope } from "effect"
import { eq, sql } from "drizzle-orm"
import type { SqlClient } from "effect/sql/SqlClient"
import { tmpdir } from "./fixture/tmpdir"
import { initRepo } from "./fixture/git"
import fs from "fs/promises"
import path from "path"
const makeDb = EffectDrizzleSqlite.makeWithDefaults()
Expand Down
Expand Up
@@ -878,13 +883,21 @@ describe("V1Migration database workflow", () => {
`)
})
const database = <A, E>(effect: Effect.Effect<A, E, Database.Service | Global.Service | Scope.Scope>) =>
const database = <A, E>(
effect: Effect.Effect<A, E, Database.Service | Global.Service | Scope.Scope | Project.Service | FSUtil.Service>,
) =>
run(
Effect.gen(function* () {
const db = yield* makeDb
yield* DatabaseMigration.apply(db)
yield* createLegacyTables(db)
return yield* effect.pipe(Effect.provideService(Database.Service, { db }))
return yield* effect.pipe(
Effect.provide(
AppNodeBuilder.build(LayerNode.group([Project.node, Database.node, FSUtil.node]), [
Database.node.replace(Layer.succeed(Database.Service, { db })),
]),
),
)
}),
)
Expand Down
Expand Up
@@ -1180,6 +1193,66 @@ describe("V1Migration database workflow", () => {
)
})
test("attributes V1 global sessions to the V2 project of their directory", async () => {
await using tmp = await tmpdir()
const plain = path.join(tmp.path, "plain")
const nested = path.join(plain, "nested")
const repo = path.join(tmp.path, "repo")
const missing = path.join(tmp.path, "missing")
await fs.mkdir(nested, { recursive: true })
await fs.mkdir(path.join(repo, "pkg", "a"), { recursive: true })
await initRepo(repo)
await database(
Effect.gen(function* () {
const { db } = yield* Database.Service
const projects = yield* Project.Service
yield* db.run(
sql`INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) VALUES ('global', '/', 1, 2, '[]')`,
)
yield* Effect.forEach(
[
{ id: "ses_plain", project: "global", directory: plain },
{ id: "ses_nested", project: "global", directory: nested },
{ id: "ses_repo", project: "global", directory: path.join(repo, "pkg", "a") },
{ id: "ses_missing", project: "global", directory: missing },
{ id: "ses_orphan", project: "missing-project", directory: plain },
{ id: "ses_imported", project: "global", directory: plain },
],
(input) =>
db.run(sql`
INSERT INTO session (id, project_id, slug, directory, title, version, time_created, time_updated)
VALUES (${input.id}, ${input.project}, ${input.id}, ${input.directory}, 'Test', '1', 1, 2)
`),
)
yield* db.run(sql`
INSERT INTO session_v2 (id, project_id, slug, directory, title, version, time_created, time_updated)
VALUES ('ses_imported', 'global', 'ses_imported', ${plain}, 'Kept', '1', 1, 2)
`)
expect(yield* V1Migration.run()).toEqual({ status: "completed" })
// New owners take their recency from the V1 session instead of the import time.
expect(
yield* db.all(sql`SELECT time_active FROM project WHERE id NOT IN ('global', 'missing-project')`),
).toEqual([{ time_active: 2 }, { time_active: 2 }, { time_active: 2 }])
// Resolve after the import, since runtime resolution persists the projects it finds.
const owners = {
plain: yield* projects.resolve(AbsolutePath.make(plain)),
nested: yield* projects.resolve(AbsolutePath.make(nested)),
repo: yield* projects.resolve(AbsolutePath.make(repo)),
}
expect(owners.repo.vcs?.type).toBe("git")
expect(yield* db.all(sql`SELECT id, project_id, path, title FROM session_v2 ORDER BY id`)).toEqual([
{ id: "ses_imported", project_id: "global", path: null, title: "Kept" },
{ id: "ses_missing", project_id: "global", path: null, title: "Test" },
{ id: "ses_nested", project_id: owners.nested.id, path: "", title: "Test" },
{ id: "ses_orphan", project_id: owners.plain.id, path: "", title: "Test" },
{ id: "ses_plain", project_id: owners.plain.id, path: "", title: "Test" },
{ id: "ses_repo", project_id: owners.repo.id, path: "pkg/a", title: "Test" },
])
}),
)
})
test("replaces projections containing apostrophes and checkpoints completion", async () => {
await database(
Effect.gen(function* () {
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -22,6 +22,7 @@ import { ShellSelect } from "@opencode/core/shell/select"
import { Job } from "@opencode/core/job"
import { Mcp } from "@opencode/core/mcp/index"
import { Global } from "@opencode/util/global"
import { FSUtil } from "@opencode/util/fs-util"
import { InstructionDiscovery } from "@opencode/core/instruction-discovery"
import { LocationServiceMap } from "@opencode/core/location-service-map"
import { LocationActivity } from "@opencode/core/location-activity"
Expand Down
Expand Up
@@ -50,6 +51,7 @@ import type { ServerOptions } from "./options"
const applicationServiceNodes = [
Global.node,
FSUtil.node,
Database.node,
Bus.node,
EventLogger.node,
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.