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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion v2-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,7 @@ not execute these kinds: `crates/application/src/workflow_run/engine/node_type.r
用户删除普通对话时,它的工作目录在成果能从回合交付恢复、或用户选了 `discard` 时才删除。判定、状态与运维见 [`internal/workspacereclaim`](internal/workspacereclaim):

- **能恢复**(按登记的 session 直接查 `v2_execution_turns` / `v2_turn_deliveries` / `v2_turn_delivery_work`,对话行删了也能判):有交付记录(否则 `legacy`);没有未结束的回合和交付义务(否则 `delivering`);最后一轮的交付是 `delivered`/`empty`(否则 `last_turn_undelivered`);Agent 仓库没有 `refs/stash`、`refs/remotes/` 之外的 ref 都剥成提交且不超出起点与 `HEAD` 的祖先(伪 ref 如 `ORIG_HEAD` 不算)、快照里没有与起点不同的 gitlink、顶层以下没有任何名为 `.git` 的条目(目录、gitfile、链接都算,被忽略的目录也扫)、`.git/modules/` 下没有已初始化的子模块、HEAD 是起点或其祖先或它跟踪的每个路径都与交付树或起点树一致、index 没有冲突且每个条目都与交付树、起点树或(未暂存时)HEAD 一致(否则 `git_state`,预览的 `git` 列出 stash 条数、各 ref 超出的提交数、嵌套仓库路径、`headDiffers`/`headCommits`、`indexDiffers`);`.git` 解析不出来、HEAD 无法解析成可读的提交(只有直接目标分支不存在的 unborn HEAD 可跳过,符号引用不递归)、磁盘上记录的 ref(loose 与 packed-refs,只看 Git 会当作 ref 的名字,过期的 `.lock` 等跳过)格式不对或 Git 读不出来、Git 明确报对象缺失或损坏,都判 `unverifiable`;I/O、权限、超时等其他 Git 失败按 `check_failed` 重试;持交付的目录锁按交付快照规则重新生成树(只写临时目录),与最后一轮交付的树(`empty` 时起点的树)相同(否则 `changed_after_delivery`,生成不了为 `unverifiable`)。
- **预览**:`workspace`(`none` 附 `no_workspace` / `workspace_missing`;`recoverable`;`undelivered` 附上面的原因)、`ignored`、`undeliveredChanges`(相对最近一次 `delivered` 交付,没有时相对起点,至多 200 条)与 `undeliveredTotal`、`latestDelivery`(页面经 `…/workspace/deliveries/{id}/patch` 下载)、`revision`(最后一轮、交付、判定、快照树、Git 统计,以及 discard 会删掉、交付又带不走的全部 Git 相关内容的字节摘要:顶层仓库的 ref/HEAD/stash OID 与 index 内容,每个嵌套仓库整棵子树(工作树与 `.git`,含对象)的内容,gitfile、链接或 `.git` 目录里的 `commondir` 指向 checkout 内的 Git 目录时连同目标整棵(同一目录只算一次);任何字节变化都会改变它)、`discardable`(只有未交付且内容摘要完整时为 true;字节或条目超限、特殊文件、读取失败、指针指向 checkout 外或解析不了都为 false,没有检查就为 false;此时 discard 返回 409 `discard_unverifiable`,界面不给丢弃选项)。
- **预览**:`workspace`(`none` 附 `no_workspace` / `workspace_missing`;`recoverable`;`undelivered` 附上面的原因)、`ignored`、`undeliveredChanges`(相对最近一次 `delivered` 交付,没有时相对起点,至多 200 条)与 `undeliveredTotal`、`latestDelivery`(页面经 `…/workspace/deliveries/{id}/patch` 下载)、`revision`(最后一轮、交付、判定、快照树、Git 统计,以及 discard 会删掉、交付又带不走的全部 Git 相关内容的字节摘要:顶层仓库的 ref/HEAD/stash OID 与 index 内容,每个嵌套仓库整棵子树(工作树与 `.git`,含对象)的内容,gitfile、链接或 `.git` 目录里的 `commondir` 指向 checkout 内的 Git 目录时连同目标整棵(同一目录只算一次);任何字节变化都会改变它)、`discardable`(只有未交付且内容摘要完整时为 true;字节或条目超限、特殊文件、读取失败、嵌套 Git 目录内含符号链接或 `alternates`、指针指向 checkout 外或解析不了都为 false,没有检查就为 false;此时 discard 返回 409 `discard_unverifiable`,界面不给丢弃选项)。
- **删除**:删除请求在删除事务提交后用服务生命周期的上下文(不随请求取消)启动回收,5 秒内删完返回 `reclaimed`,否则返回 `pending`/`in_progress`、后台继续删完(关机时取消,记录留 `deleting` 给启动);事务提交后的任何错误都只体现在结果里,不报成删除失败。`reclaim` 不需要 `revision`,删除时重新判定,结果只会更保守。`discard` 必须带回预览的 `revision`,在结束会话之前重新计算,不一致或还在交付返回 409 `deletion_preview_stale`,对话和目录都不动。返回 `workspace`:`reclaimed`(附 `releasedBytes`、`releasedFiles`)、`kept`(附原因)、`pending`(`in_progress` 后台继续;`delivering`、`removal_failed`、`check_failed` 下次启动再做;`reclaim_unavailable` 等带运行时的启动)、`none`。
- **先登记再删**:`store.DeleteChatConversationReclaiming`(只有用户删除走它;首轮被拒回滚对话用的 `DeleteChatConversation` 不登记)在删除对话的同一事务里写一行 `v2_workspace_reclaims`:目录 ID、项目、session、路径、`clone_execution`、模式(不可变)。状态 `pending → deleting → reclaimed | kept`;`deleting` 之后只重查身份与路径,不再判定。启动时在 `boot.Recover` 里 `RecoverTurnDeliveries` 之后、恢复工作流之前,把 `pending` / `deleting` 的再执行一遍;运行中不另外触发,不加定时任务。同一条回收在进程内按目录 ID 互斥。
- **保留与重试**:`reclaim` 下不能恢复、身份不符(`identity_mismatch`:路径或 `clone_execution` 与 `v2_workspaces` 不一致或路径被别的行记录)、别的 session 用过(`shared`)、仍有活 session(`session_live`)、路径不安全(`unsafe_path`)记 `kept`;检查时(读工作目录、镜像、Git 失败,`check_failed`)或删除时(`removal_failed`)的基础设施错误保持原状态,`attempts` 加一、记 `last_error` 与日志,下次启动重试;只有目录内容本身无法验证(Git 元数据不能安全读取、改动过大、分不清物化技能)才判 `unverifiable`。
Expand Down
2 changes: 1 addition & 1 deletion v2-server/internal/workspacefs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@

## 删除对话时的检查与删除

`InspectReclaim` 持目录锁按交付的快照规则在临时目录生成树(不写镜像、不写 ref),与给定交付提交(空时起点)的树比对,列出差异(至多 `MaxReclaimChanges` 条,另给总数),并查交付带不走的 Git 状态(`refs/stash`、`refs/remotes/` 之外超出起点与 `HEAD` 的本地 ref、与起点不同的 gitlink、嵌套 `.git`)和有无被忽略规则排除的文件(不算物化的技能),并带出快照树 OID 和 Git 身份摘要供预览的 `revision` 绑定内容。身份摘要绑定 discard 会删掉、交付带不走的全部 Git 相关字节:顶层仓库的 ref/HEAD/stash OID 与 index 内容,每个嵌套仓库整棵子树(含 `.git` 与对象)的内容,gitfile、链接或 `.git` 目录里的 `commondir` 指向 checkout 内的 Git 目录时连同目标整棵(同一目录只算一次)。读取不调用 Git、不跟随链接:先 `Lstat` 只接受普通文件,再以 `O_NOFOLLOW|O_NONBLOCK` 打开并 `fstat` 复核。内容字节共用交付的对象上限、条目至多 10 万;任何超限、特殊文件、读取失败、指向 checkout 外或解析不了的指针都让摘要不完整(`GitIdentityComplete` 为 false),且不会再恢复。整个检查受 2 分钟上限约束。目录内容无法验证时返回 `ErrUnverifiable`,其余错误(磁盘、镜像、Git)可重试。
`InspectReclaim` 持目录锁按交付的快照规则在临时目录生成树(不写镜像、不写 ref),与给定交付提交(空时起点)的树比对,列出差异(至多 `MaxReclaimChanges` 条,另给总数),并查交付带不走的 Git 状态(`refs/stash`、`refs/remotes/` 之外超出起点与 `HEAD` 的本地 ref、与起点不同的 gitlink、嵌套 `.git`)和有无被忽略规则排除的文件(不算物化的技能),并带出快照树 OID 和 Git 身份摘要供预览的 `revision` 绑定内容。身份摘要绑定 discard 会删掉、交付带不走的全部 Git 相关字节:顶层仓库的 ref/HEAD/stash OID 与 index 内容,每个嵌套仓库整棵子树(含 `.git` 与对象)的内容,gitfile、链接或 `.git` 目录里的 `commondir` 指向 checkout 内的 Git 目录时连同目标整棵(同一目录只算一次)。读取不调用 Git、不跟随链接:先 `Lstat` 只接受普通文件,再以 `O_NOFOLLOW|O_NONBLOCK` 打开并 `fstat` 复核;嵌套 Git 目录(含 `.git/modules/` 与解析后的 Git 目录)内出现符号链接或 `objects/info/alternates` 时同样不跟随,直接将摘要标记为不完整。内容字节共用交付的对象上限、条目至多 10 万;任何超限、特殊文件、读取失败、嵌套 Git 目录内的符号链接或 `alternates`、指向 checkout 外或解析不了的指针都让摘要不完整(`GitIdentityComplete` 为 false),且不会再恢复。整个检查受 2 分钟上限约束。目录内容无法验证时返回 `ErrUnverifiable`,其余错误(磁盘、镜像、Git)可重试。

`RemoveCheckout(root, path)` 只删除位于 checkout 根 `root`(`<项目目录>/w/r`)之下的 `path`:从 `root` 起经目录句柄逐级打开,每级先 `Lstat` 确认是目录而非链接、打开后比对 dev/inode;统计、补属主写权限、删内容(链接只删本身)经 checkout 句柄,最后经父目录句柄删掉 checkout 本身,检查之后不再按路径重开。读不到的条目返回带路径的错误,列出后消失的不计。不安全时返回 `ErrUnsafeCheckout`;路径或根已不存在视为已删除。
139 changes: 123 additions & 16 deletions v2-server/internal/workspacefs/reclaim_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,10 +256,12 @@ const maxNestedEntries = 100000
//
// complete reports that every such byte was bound. It is false, and stays false, when anything
// could not be: a byte or entry limit, a special file, a read that failed, a pointer leading out
// of the checkout or not resolving. A discard is then refused, since the revision cannot prove the
// person saw what would be deleted. Files are read without Git and without following links: an
// Lstat must show a regular file, the open is O_NOFOLLOW|O_NONBLOCK and an fstat must confirm the
// same file, so nothing can block on a FIFO or a device.
// of the checkout or not resolving, or any symlink or objects/info/alternates inside a nested Git
// directory (including .git/modules entries and resolved Git directories). A discard is then
// refused, since the revision cannot prove the person saw what would be deleted. Files are read
// without Git and without following links: an Lstat must show a regular file, the open is
// O_NOFOLLOW|O_NONBLOCK and an fstat must confirm the same file, so nothing can block on a FIFO
// or a device.
func (s *DeliveryFS) gitIdentity(ctx context.Context, st *staged, g GitFindings) (identity string, complete bool, err error) {
h := sha256.New()
d := &digester{ctx: ctx, h: h, bytes: s.maxObjects, complete: true}
Expand Down Expand Up @@ -299,8 +301,10 @@ func (s *DeliveryFS) gitIdentity(ctx context.Context, st *staged, g GitFindings)
return "", false, err
}
// digested lists the subtrees already bound, so a Git directory several repositories share
// (or one inside a repository's own subtree) is read once.
// (or one inside a repository's own subtree) is read once. checkedGitDirs tracks the Git
// directories already verified to contain no symlinks, special files, or alternates.
var digested []string
var checkedGitDirs []string
for _, repo := range g.Repositories {
if err := ctx.Err(); err != nil {
return "", false, err
Expand All @@ -317,11 +321,16 @@ func (s *DeliveryFS) gitIdentity(ctx context.Context, st *staged, g GitFindings)
d.incomplete("open modules", err)
continue
}
d.tree(modules, name)
if _, err := modules.Lstat(path.Join(name, "commondir")); err == nil || !errors.Is(err, fs.ErrNotExist) {
d.incomplete("commondir inside nested module", err)
}
d.gitTree(modules, name)
Comment on lines +324 to +327

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2-1(建议) git submodule deinit 后,名为 group/lib 的子模块仍会在 .git/modules/group/lib 保留 Git 元数据,工作树里已经没有 .git 供后续解析。gitState 只枚举 modules 的直接子项,所以这里检查的是 group 根下的 commondir 和 objects/info/alternates,漏掉了真正的子模块目录。若它引用了 checkout 内被忽略的共享 Git 状态,该状态变动后 revision 仍可能保持不变,旧确认可以删掉未预览的数据。建议按实际的子模块 Git 目录执行检查,并补一条 deinit 后仍应拒绝丢弃的回归测试。

改动较大,建议另开 PR 处理,不影响这次合并。

modules.Close()
if real, err := filepath.EvalSymlinks(filepath.Join(layout.CommonDir(), "modules", name)); err == nil {
if rel, err := filepath.Rel(realRoot, real); err == nil && filepath.IsLocal(rel) {
digested = append(digested, filepath.ToSlash(rel))
if rel, err := filepath.Rel(realRoot, real); err == nil && filepath.IsLocal(rel) && rel != "." {
rel = filepath.ToSlash(rel)
digested = append(digested, rel)
checkedGitDirs = append(checkedGitDirs, rel)
}
}
continue
Expand All @@ -331,7 +340,9 @@ func (s *DeliveryFS) gitIdentity(ctx context.Context, st *staged, g GitFindings)
// The repository's Git directories may lie elsewhere: a gitfile or a link points at them,
// and a .git directory may name a shared one in commondir. Bound only when they are inside
// the checkout (and so deleted with it), each once; outside, or not resolving, a discard
// could not show what it drops.
// could not show what it drops. Symlinks and alternates inside nested Git directories are
// rejected instead of followed, so shared Git state outside .git cannot be hidden behind
// an ignored link.
if _, err := root.Lstat(path.Join(repo, ".git")); err != nil {
continue
}
Expand All @@ -347,17 +358,24 @@ func (s *DeliveryFS) gitIdentity(ctx context.Context, st *staged, g GitFindings)
continue
}
rel, err := filepath.Rel(realRoot, real)
if err != nil || !filepath.IsLocal(rel) {
if err != nil || !filepath.IsLocal(rel) || rel == "." {
d.incomplete("nested Git directory outside the checkout", nil)
continue
}
rel = filepath.ToSlash(rel)
if within(rel, digested) {
if !within(rel, digested) {
fmt.Fprintf(h, "points at %s\x00", rel)
d.gitTree(root, rel)
digested = append(digested, rel)
checkedGitDirs = append(checkedGitDirs, rel)
continue
}
if !within(rel, checkedGitDirs) {
d.checkGitDir(root, rel)
checkedGitDirs = append(checkedGitDirs, rel)
continue
}
fmt.Fprintf(h, "points at %s\x00", rel)
d.tree(root, rel)
digested = append(digested, rel)
d.rejectAlternates(root, rel)
}
}
if err := ctx.Err(); err != nil {
Expand Down Expand Up @@ -438,9 +456,33 @@ func (d *digester) file(r *os.Root, name string) {
// tree writes every entry below dir (dir itself included, .git directories included): regular
// files by content, links by target, directories by name. Any other kind of entry cannot be bound.
func (d *digester) tree(r *os.Root, dir string) {
d.walkTree(r, dir, true, "")
}

// gitTree writes every entry below a nested Git directory by content and fails closed when any
// symlink, special file, or objects/info/alternates is encountered inside it.
func (d *digester) gitTree(r *os.Root, dir string) {
dir = path.Clean(dir)
info, err := r.Lstat(dir)
if err != nil {
d.incomplete(dir, err)
return
}
if !info.IsDir() {
d.incomplete(dir+" is not a directory", nil)
return
}
d.walkTree(r, dir, false, path.Join(dir, "objects/info/alternates"))
}

func (d *digester) walkTree(r *os.Root, dir string, allowSymlinks bool, alternates string) {
if _, err := r.Lstat(dir); errors.Is(err, fs.ErrNotExist) {
fmt.Fprintf(d.h, "missing %s\x00", dir)
return // a gitlink with no working tree here
if allowSymlinks {
fmt.Fprintf(d.h, "missing %s\x00", dir)
return // a gitlink with no working tree here
}
d.incomplete(dir, err)
return
}
err := fs.WalkDir(r.FS(), dir, func(p string, e fs.DirEntry, err error) error {
if err != nil {
Expand All @@ -453,10 +495,18 @@ func (d *digester) tree(r *os.Root, dir string) {
d.incomplete("too many entries", nil)
return fs.SkipAll
}
if alternates != "" && p == alternates {
d.incomplete(p+" uses alternates in a nested Git directory", nil)
return fs.SkipAll
}
switch t := e.Type(); {
case t.IsDir():
fmt.Fprintf(d.h, "dir %s\x00", p)
case t&fs.ModeSymlink != 0:
if !allowSymlinks {
d.incomplete(p+" is a symlink in a nested Git directory", nil)
return fs.SkipAll
}
target, err := r.Readlink(p)
if err != nil {
return err
Expand All @@ -477,6 +527,63 @@ func (d *digester) tree(r *os.Root, dir string) {
}
}

// checkGitDir verifies that an already-digested nested Git directory (for example a .git
// subdirectory walked via tree(root, repo)) contains no symlinks, special files, or
// objects/info/alternates.
func (d *digester) checkGitDir(r *os.Root, dir string) {
if !d.complete {
return
}
dir = path.Clean(dir)
info, err := r.Lstat(dir)
if err != nil {
d.incomplete(dir, err)
return
}
if !info.IsDir() {
d.incomplete(dir+" is not a directory", nil)
return
}
alternates := path.Join(dir, "objects/info/alternates")
checked := 0
err = fs.WalkDir(r.FS(), dir, func(p string, e fs.DirEntry, err error) error {
if err != nil {
return err
}
if err := d.ctx.Err(); err != nil {
return err
}
if checked++; checked > maxNestedEntries {
d.incomplete("too many entries", nil)
return fs.SkipAll
}
if p == alternates {
d.incomplete(p+" uses alternates in a nested Git directory", nil)
return fs.SkipAll
}
t := e.Type()
switch {
case t&fs.ModeSymlink != 0:
d.incomplete(p+" is a symlink in a nested Git directory", nil)
return fs.SkipAll
case !t.IsDir() && !t.IsRegular():
d.incomplete(p+" is a special file", nil)
return fs.SkipAll
}
return nil
})
if err != nil {
d.incomplete(dir, err)
}
}

func (d *digester) rejectAlternates(r *os.Root, dir string) {
p := path.Join(path.Clean(dir), "objects/info/alternates")
if _, err := r.Lstat(p); err == nil || !errors.Is(err, fs.ErrNotExist) {
d.incomplete(p+" uses alternates in a nested Git directory", err)
}
}

// maxTreeListing bounds a listing of the HEAD tree, the index or the delivery's tree.
const maxTreeListing = 64 << 20

Expand Down
Loading
Loading