fix(sandbox): keep skill install from clobbering a newer owner
A queued remove or a failed older install could stamp or delete a row a re-upload already claimed, and an empty MCPSelectionMode handed the root installer every tenant MCP tool. Fail closed on those races, pin the installer surface, and refuse a missing bundle or leftover zip files.main
parent
03755f11f7
commit
82ce97ba72
|
|
@ -108,6 +108,30 @@ func TestInstallerAgentConfigTurnsOnInstallMode(t *testing.T) {
|
|||
}, "cfg-1")
|
||||
|
||||
require.True(t, config.SkillInstallMode())
|
||||
require.Equal(t, "none", config.MCPSelectionMode,
|
||||
"empty MCPSelectionMode defaults to all tenant MCP tools on a root shell")
|
||||
require.NotNil(t, config.MemoryEnabled)
|
||||
require.False(t, *config.MemoryEnabled,
|
||||
"nil MemoryEnabled inherits the workspace and would register search_memory")
|
||||
require.False(t, config.WebSearchEnabled)
|
||||
}
|
||||
|
||||
func TestInstallerAgentConfigKeepsMCPOffWhenThePlatformYAMLEnablesIt(t *testing.T) {
|
||||
memoryOn := true
|
||||
config := installerAgentConfig(&types.CustomAgent{
|
||||
ID: types.BuiltinSkillInstallerID,
|
||||
Config: types.CustomAgentConfig{
|
||||
AllowedTools: []string{tools.ToolShellExec},
|
||||
MCPSelectionMode: "all",
|
||||
WebSearchEnabled: true,
|
||||
MemoryEnabled: &memoryOn,
|
||||
},
|
||||
}, "cfg-1")
|
||||
|
||||
require.Equal(t, "none", config.MCPSelectionMode)
|
||||
require.False(t, config.WebSearchEnabled)
|
||||
require.NotNil(t, config.MemoryEnabled)
|
||||
require.False(t, *config.MemoryEnabled)
|
||||
}
|
||||
|
||||
func TestInstallerAgentConfigLeavesInstallModeOffForAnotherAgent(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -217,7 +217,8 @@ func stripSkillRootPrefix(raw map[string][]byte) (map[string][]byte, error) {
|
|||
out := make(map[string][]byte, len(raw))
|
||||
for name, content := range raw {
|
||||
if !strings.HasPrefix(name, prefix+"/") {
|
||||
continue
|
||||
return nil, fmt.Errorf("%w: archive holds files outside the skill directory %q",
|
||||
ErrSkillBundleInvalid, prefix)
|
||||
}
|
||||
out[strings.TrimPrefix(name, prefix+"/")] = content
|
||||
}
|
||||
|
|
|
|||
|
|
@ -208,6 +208,15 @@ Use scripts/extract.py to pull text out of a PDF.
|
|||
"paths must be relative to the skill root, not to the archive root")
|
||||
})
|
||||
|
||||
t.Run("rejects files outside the wrapped skill directory", func(t *testing.T) {
|
||||
_, err := ParseSkillBundle(zipBundle(t, map[string]string{
|
||||
"pdf-tools/SKILL.md": validSkillMD,
|
||||
"README.md": "left over from the zip root",
|
||||
}))
|
||||
require.ErrorIs(t, err, ErrSkillBundleInvalid)
|
||||
require.ErrorContains(t, err, "outside the skill directory")
|
||||
})
|
||||
|
||||
t.Run("rejects an archive without SKILL.md", func(t *testing.T) {
|
||||
_, err := ParseSkillBundle(zipBundle(t, map[string]string{"a.txt": "x"}))
|
||||
require.ErrorIs(t, err, ErrSkillBundleInvalid)
|
||||
|
|
|
|||
|
|
@ -89,14 +89,19 @@ func (s *TenantSkillService) InstallSkill(
|
|||
}
|
||||
|
||||
// Store the archive before the long-running part: read_skill serves file
|
||||
// contents from it, and a re-install after a crash needs it too.
|
||||
if ref, err := s.saveBundle(ctx, tenantID, skillID, archive); err == nil {
|
||||
_ = s.updateSkillFields(ctx, tenantID, configID, skillID, func(e *types.TenantSkillEntity) {
|
||||
e.BundleRef = ref
|
||||
})
|
||||
} else {
|
||||
logger.Warnf(ctx, "[skill] store bundle for %s failed: %v", skillID, err)
|
||||
// contents from it, and a re-install after a crash needs it too. A missing
|
||||
// archive is a failed install, not a warning — otherwise the row says
|
||||
// "installing" and later reads have nothing to serve.
|
||||
ref, err := s.saveBundle(ctx, tenantID, skillID, archive)
|
||||
if err != nil {
|
||||
failCtx, cancelFail := s.cleanupContext(ctx)
|
||||
defer cancelFail()
|
||||
s.failSkill(failCtx, tenantID, configID, skillID, bundle, fmt.Errorf("store bundle: %w", err))
|
||||
return "", fmt.Errorf("store bundle for skill %s: %w", skillID, err)
|
||||
}
|
||||
_ = s.updateSkillFields(ctx, tenantID, configID, skillID, func(e *types.TenantSkillEntity) {
|
||||
e.BundleRef = ref
|
||||
})
|
||||
|
||||
s.publishProgress(ctx, tenantID, configID, skillID, SkillProgress{
|
||||
Percent: 10, Stage: "accepted", Status: types.SkillStatusInstalling,
|
||||
|
|
@ -107,7 +112,7 @@ func (s *TenantSkillService) InstallSkill(
|
|||
// reaper (Task 17) is what closes that gap.
|
||||
go func() {
|
||||
bgCtx := context.WithoutCancel(ctx)
|
||||
if err := s.withConfigLock(bgCtx, configID, func(lockCtx context.Context) error {
|
||||
if err := s.withConfigLock(bgCtx, tenantID, configID, func(lockCtx context.Context) error {
|
||||
return s.runInstall(lockCtx, tenantID, configID, skillID, bundle)
|
||||
}); err != nil {
|
||||
logger.Errorf(bgCtx, "[skill] install %s failed: %v", skillID, err)
|
||||
|
|
@ -155,7 +160,7 @@ func (s *TenantSkillService) runInstall(
|
|||
// snapshot keeps serving every session.
|
||||
failCtx, cancelFail := s.cleanupContext(cleanupBase)
|
||||
defer cancelFail()
|
||||
s.failSkill(failCtx, tenantID, configID, skillID, err)
|
||||
s.failSkill(failCtx, tenantID, configID, skillID, bundle, err)
|
||||
}()
|
||||
|
||||
// InstallSkill queues this run before the per-config lock. A remove that
|
||||
|
|
@ -270,6 +275,16 @@ func (s *TenantSkillService) runInstall(
|
|||
if err := ctx.Err(); err != nil {
|
||||
return fmt.Errorf("install lock lost before snapshot: %w", err)
|
||||
}
|
||||
// Re-check after the minutes-long agent run: InstallSkill writes the row
|
||||
// outside this lock, so a newer upload or a queued remove may already own
|
||||
// it. Snapshotting anyway would bake a tree the ledger no longer names.
|
||||
owned, err = s.installStillOwnsTheRow(ctx, tenantID, configID, skillID, bundle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !owned {
|
||||
return nil
|
||||
}
|
||||
// The generation comes from the config read at the top of this function,
|
||||
// while switchImagePointer deliberately re-reads for everything else it
|
||||
// writes. That asymmetry is sound because the two fields have different
|
||||
|
|
@ -314,7 +329,7 @@ func (s *TenantSkillService) runInstall(
|
|||
// even though the skill is installed and serving.
|
||||
readyCtx, cancelReady := s.cleanupContext(cleanupBase)
|
||||
defer cancelReady()
|
||||
if err := s.writeReadySkillState(readyCtx, tenantID, configID, skillID, ref.ID); err != nil {
|
||||
if err := s.writeReadySkillState(readyCtx, tenantID, configID, skillID, ref.ID, bundle); err != nil {
|
||||
return err
|
||||
}
|
||||
s.markConfigSandboxesStale(ctx, tenantID, configID)
|
||||
|
|
@ -705,10 +720,21 @@ func (s *TenantSkillService) updateSkillFields(
|
|||
// runs after the pointer switch: the skill is installed, snapshotted and being
|
||||
// served, so a transient write failure here is a bookkeeping gap, not a failed
|
||||
// install, and re-running the whole install to fix a row would be absurd.
|
||||
//
|
||||
// The write is skipped when a newer upload or a queued remove already owns
|
||||
// the row: the pointer still moved, but stamping ready (or this run's
|
||||
// snapshot id) on that row would lie about which bundle is serving.
|
||||
func (s *TenantSkillService) writeReadySkillState(
|
||||
ctx context.Context, tenantID uint64, configID, skillID, snapshotID string,
|
||||
ctx context.Context, tenantID uint64, configID, skillID, snapshotID string, bundle *SkillBundle,
|
||||
) error {
|
||||
if err := s.retrySkillBookkeeping(ctx, func() error {
|
||||
owned, err := s.installStillOwnsTheRow(ctx, tenantID, configID, skillID, bundle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !owned {
|
||||
return nil
|
||||
}
|
||||
return s.updateSkillFields(ctx, tenantID, configID, skillID,
|
||||
func(e *types.TenantSkillEntity) {
|
||||
e.Status = types.SkillStatusReady
|
||||
|
|
@ -747,8 +773,12 @@ func (s *TenantSkillService) retrySkillBookkeeping(
|
|||
}
|
||||
|
||||
func (s *TenantSkillService) failSkill(
|
||||
ctx context.Context, tenantID uint64, configID, skillID string, cause error,
|
||||
ctx context.Context, tenantID uint64, configID, skillID string, bundle *SkillBundle, cause error,
|
||||
) {
|
||||
owned, err := s.installStillOwnsTheRow(ctx, tenantID, configID, skillID, bundle)
|
||||
if err != nil || !owned {
|
||||
return
|
||||
}
|
||||
_ = s.updateSkillFields(ctx, tenantID, configID, skillID, func(e *types.TenantSkillEntity) {
|
||||
e.Status = types.SkillStatusFailed
|
||||
e.Error = cause.Error()
|
||||
|
|
@ -1069,11 +1099,14 @@ func installerAgentDefaults(ctx context.Context, tenantID uint64) *types.CustomA
|
|||
// skill". The model is the one choice still taken from the stored record, in
|
||||
// resolveInstallerModel.
|
||||
func installerAgentConfig(defaults *types.CustomAgent, configID string) *types.AgentConfig {
|
||||
memoryOff := false
|
||||
cfg := &types.AgentConfig{
|
||||
MaxIterations: 30,
|
||||
AllowedTools: []string{tools.ToolShellExec},
|
||||
Temperature: 0.2,
|
||||
WebSearchEnabled: false,
|
||||
MCPSelectionMode: "none",
|
||||
MemoryEnabled: &memoryOff,
|
||||
SandboxConfigID: configID,
|
||||
}
|
||||
if defaults == nil {
|
||||
|
|
@ -1095,8 +1128,10 @@ func installerAgentConfig(defaults *types.CustomAgent, configID string) *types.A
|
|||
cfg.Temperature = custom.Temperature
|
||||
cfg.SystemPrompt = custom.SystemPrompt
|
||||
cfg.UseCustomSystemPrompt = custom.SystemPrompt != ""
|
||||
cfg.WebSearchEnabled = custom.WebSearchEnabled
|
||||
cfg.WebSearchMaxResults = custom.WebSearchMaxResults
|
||||
cfg.WebSearchEnabled = false
|
||||
cfg.WebSearchMaxResults = 0
|
||||
cfg.MCPSelectionMode = "none"
|
||||
cfg.MemoryEnabled = &memoryOff
|
||||
cfg.MultiTurnEnabled = custom.MultiTurnEnabled
|
||||
cfg.LLMCallTimeout = custom.LLMCallTimeout
|
||||
return cfg
|
||||
|
|
|
|||
|
|
@ -240,6 +240,60 @@ func TestRunInstallAbortsWhenTheSkillRowWasRemoved(t *testing.T) {
|
|||
require.Nil(t, skill)
|
||||
}
|
||||
|
||||
func TestWriteReadySkillStateDoesNotStampANewerBundle(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
newer := strings.Repeat("b", 64)
|
||||
require.NoError(t, fx.skillRepo.UpdateSkill(context.Background(), &types.TenantSkillEntity{
|
||||
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
|
||||
Name: fx.bundle.Name, BundleSHA256: newer,
|
||||
Status: types.SkillStatusInstalling,
|
||||
}))
|
||||
|
||||
require.NoError(t, fx.svc.writeReadySkillState(
|
||||
context.Background(), 7, "cfg-1", "sk-1", "snap-stale", fx.bundle))
|
||||
|
||||
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.SkillStatusInstalling, skill.Status)
|
||||
require.Equal(t, newer, skill.BundleSHA256)
|
||||
require.Empty(t, skill.InstalledSnapshotID,
|
||||
"this run's snapshot must not be attributed to a newer upload")
|
||||
}
|
||||
|
||||
func TestFailSkillDoesNotStampANewerBundle(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
newer := strings.Repeat("b", 64)
|
||||
require.NoError(t, fx.skillRepo.UpdateSkill(context.Background(), &types.TenantSkillEntity{
|
||||
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
|
||||
Name: fx.bundle.Name, BundleSHA256: newer,
|
||||
Status: types.SkillStatusInstalling,
|
||||
}))
|
||||
|
||||
fx.svc.failSkill(context.Background(), 7, "cfg-1", "sk-1", fx.bundle, errors.New("old run died"))
|
||||
|
||||
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.SkillStatusInstalling, skill.Status)
|
||||
require.Equal(t, newer, skill.BundleSHA256)
|
||||
require.Empty(t, skill.Error)
|
||||
}
|
||||
|
||||
func TestInstallSkillRefusesWhenBundleCannotBeStored(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
fx.saveErr = errors.New("object store down")
|
||||
archive := zipBundle(t, map[string]string{"SKILL.md": validSkillMD})
|
||||
|
||||
_, err := fx.svc.InstallSkill(context.Background(), 7, "cfg-1", archive)
|
||||
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "store bundle")
|
||||
skill, getErr := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
|
||||
require.NoError(t, getErr)
|
||||
require.Equal(t, types.SkillStatusFailed, skill.Status,
|
||||
"a skill whose archive never landed must not sit at installing")
|
||||
require.NotContains(t, fx.events, "create-session")
|
||||
}
|
||||
|
||||
func TestRunInstallAbortsWhenANewerBundleOwnsTheRow(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
newer := strings.Repeat("b", 64)
|
||||
|
|
@ -688,6 +742,9 @@ type installFixture struct {
|
|||
installerRecord *types.CustomAgent
|
||||
engineConfig *types.AgentConfig
|
||||
engineModel chat.Chat
|
||||
// saveErr fails bundle storage so InstallSkill cannot accept a skill
|
||||
// whose archive will later be unreadable.
|
||||
saveErr error
|
||||
}
|
||||
|
||||
func newInstallFixture(t *testing.T) *installFixture {
|
||||
|
|
@ -1510,7 +1567,10 @@ func (installFileService) CheckConnectivity(context.Context) error { return nil
|
|||
func (installFileService) SaveFile(context.Context, *multipart.FileHeader, uint64, string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
func (installFileService) SaveBytes(context.Context, []byte, uint64, string, bool) (string, error) {
|
||||
func (s installFileService) SaveBytes(context.Context, []byte, uint64, string, bool) (string, error) {
|
||||
if s.fx != nil && s.fx.saveErr != nil {
|
||||
return "", s.fx.saveErr
|
||||
}
|
||||
return "file://bundle.zip", nil
|
||||
}
|
||||
func (installFileService) GetFile(context.Context, string) (io.ReadCloser, error) { return nil, nil }
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ func (s *TenantSkillService) RemoveSkill(
|
|||
// that is the stuck-run reaper's job (Task 17).
|
||||
go func() {
|
||||
bgCtx := context.WithoutCancel(ctx)
|
||||
if err := s.withConfigLock(bgCtx, configID, func(lockCtx context.Context) error {
|
||||
if err := s.withConfigLock(bgCtx, tenantID, configID, func(lockCtx context.Context) error {
|
||||
return s.runRemove(lockCtx, tenantID, configID, skillID)
|
||||
}); err != nil {
|
||||
logger.Errorf(bgCtx, "[skill] remove %s failed: %v", skillID, err)
|
||||
|
|
@ -79,6 +79,12 @@ func (s *TenantSkillService) runRemove(
|
|||
if existing == nil {
|
||||
return nil
|
||||
}
|
||||
// RemoveSkill queues this run before the per-config lock. A newer upload
|
||||
// of the same name already flipped the row back to installing; deleting
|
||||
// it (or wiping its directory) would discard that install.
|
||||
if existing.Status != types.SkillStatusRemoving {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The image directory is the skill name, and SkillDirFor is what refuses a
|
||||
// name that would escape the skills root. Resolved before any sandbox work
|
||||
|
|
@ -130,14 +136,6 @@ func (s *TenantSkillService) runRemove(
|
|||
if currentSnapshotID(cfgEntity) == "" {
|
||||
return s.finishRemoval(cleanupBase, tenantID, configID, skillID)
|
||||
}
|
||||
// Shared with the install: a snapshot the live credentials cannot resolve
|
||||
// must not be built on, and here that matters most - the removal would
|
||||
// wipe a directory the booted image never had and then move the pointer
|
||||
// past an image the old credentials still make recoverable.
|
||||
if err := ensureUsableImage(cfgEntity); err != nil {
|
||||
return err
|
||||
}
|
||||
builtFingerprint := skillOwnerFingerprint(cfgEntity.Config)
|
||||
|
||||
// Everything below either creates provider resources or moves the image
|
||||
// pointer, and the fallback moves it without taking a snapshot first. A
|
||||
|
|
@ -168,6 +166,16 @@ func (s *TenantSkillService) runRemove(
|
|||
return s.finishRemoval(cleanupBase, tenantID, configID, skillID)
|
||||
}
|
||||
|
||||
// Remaining skills still live in the current snapshot, so it must be an
|
||||
// image the live credentials can resolve. A last-skill clear above does
|
||||
// not boot that snapshot — it only drops the pointer — and must stay
|
||||
// possible after a credential rotation so the operator can fall back to
|
||||
// the base template.
|
||||
if err := ensureUsableImage(cfgEntity); err != nil {
|
||||
return err
|
||||
}
|
||||
builtFingerprint := skillOwnerFingerprint(cfgEntity.Config)
|
||||
|
||||
// ResolveEffectiveConfig has already turned the current snapshot into the
|
||||
// template, so this sandbox boots from the image the skill is in.
|
||||
sess, mgr, err := s.startMaintenanceSession(ctx, tenantID, configID, "remove")
|
||||
|
|
@ -202,6 +210,13 @@ func (s *TenantSkillService) runRemove(
|
|||
if err := ctx.Err(); err != nil {
|
||||
return fmt.Errorf("remove lock lost before snapshot: %w", err)
|
||||
}
|
||||
owned, err := s.removeStillOwnsTheRow(ctx, tenantID, configID, skillID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !owned {
|
||||
return nil
|
||||
}
|
||||
// The generation comes from the config read at the top of this function
|
||||
// while switchImagePointer re-reads for everything else, for the same
|
||||
// reason it does in an install: SkillImage is written only by an install
|
||||
|
|
@ -373,6 +388,14 @@ func (s *TenantSkillService) finishRemoval(
|
|||
ctx, cancel := s.cleanupContext(cleanupBase)
|
||||
defer cancel()
|
||||
|
||||
owned, err := s.removeStillOwnsTheRow(ctx, tenantID, configID, skillID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !owned {
|
||||
return nil
|
||||
}
|
||||
|
||||
skill, err := s.skills.GetSkill(ctx, tenantID, configID, skillID)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -400,6 +423,10 @@ func (s *TenantSkillService) finishRemoval(
|
|||
func (s *TenantSkillService) restoreSkillAfterFailedRemoval(
|
||||
ctx context.Context, tenantID uint64, configID, skillID string, cause error,
|
||||
) {
|
||||
owned, err := s.removeStillOwnsTheRow(ctx, tenantID, configID, skillID)
|
||||
if err != nil || !owned {
|
||||
return
|
||||
}
|
||||
status := types.SkillStatusFailed
|
||||
_ = s.updateSkillFields(ctx, tenantID, configID, skillID,
|
||||
func(e *types.TenantSkillEntity) {
|
||||
|
|
@ -419,6 +446,23 @@ func (s *TenantSkillService) restoreSkillAfterFailedRemoval(
|
|||
})
|
||||
}
|
||||
|
||||
// removeStillOwnsTheRow is the lock-side counterpart of RemoveSkill's
|
||||
// optimistic status flip. A newer upload of the same name already set the
|
||||
// row back to installing; deleting it (or restoring it to ready/failed)
|
||||
// would discard that install.
|
||||
func (s *TenantSkillService) removeStillOwnsTheRow(
|
||||
ctx context.Context, tenantID uint64, configID, skillID string,
|
||||
) (bool, error) {
|
||||
current, err := s.skills.GetSkill(ctx, tenantID, configID, skillID)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("load skill %s: %w", skillID, err)
|
||||
}
|
||||
if current == nil {
|
||||
return false, nil
|
||||
}
|
||||
return current.Status == types.SkillStatusRemoving, nil
|
||||
}
|
||||
|
||||
func (s *TenantSkillService) deleteBundleBestEffort(
|
||||
ctx context.Context, tenantID uint64, bundleRef string,
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package service
|
|||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
|
|
@ -159,6 +160,41 @@ func TestRunRemoveStopsBeforeClearingThePointerWhenTheLockIsLost(t *testing.T) {
|
|||
// RemoveSkill validates the skill outside the lock, so two submissions queue
|
||||
// two runs. The second one has nothing left to do and must not spend a sandbox,
|
||||
// a snapshot and a generation bump proving it.
|
||||
func TestRunRemoveAbortsWhenANewerInstallOwnsTheRow(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
fx.seedInstalledSkill("sk-1", "snap-old", 2)
|
||||
fx.seedInstalledSkill("sk-2", "snap-old", 2)
|
||||
require.NoError(t, fx.skillRepo.UpdateSkill(context.Background(), &types.TenantSkillEntity{
|
||||
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
|
||||
Name: "skill-sk-1", BundleSHA256: strings.Repeat("c", 64),
|
||||
Status: types.SkillStatusInstalling, InstalledSnapshotID: "snap-old",
|
||||
}))
|
||||
|
||||
require.NoError(t, fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1"))
|
||||
|
||||
require.Empty(t, fx.events, "a queued remove must not wipe a skill a newer upload already claimed")
|
||||
require.Nil(t, fx.configRepo.saved)
|
||||
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, skill)
|
||||
require.Equal(t, types.SkillStatusInstalling, skill.Status)
|
||||
}
|
||||
|
||||
func TestRunRemoveClearsTheLastSkillWhenCredentialsRotated(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
fx.seedInstalledSkill("sk-1", "snap-old", 2)
|
||||
fx.configRepo.entity.Config.E2B.APIKey = "key-2"
|
||||
|
||||
require.NoError(t, fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1"))
|
||||
|
||||
require.Empty(t, fx.configRepo.saved.Config.SkillImage.SnapshotID,
|
||||
"the last skill can fall back to the base template without booting the unreadable snapshot")
|
||||
require.Equal(t, []string{"switch-pointer"}, fx.events)
|
||||
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, skill)
|
||||
}
|
||||
|
||||
func TestRunRemoveDoesNothingWhenTheSkillIsAlreadyGone(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
fx.seedInstalledSkill("sk-1", "snap-old", 2)
|
||||
|
|
|
|||
|
|
@ -86,22 +86,26 @@ func NewTenantSkillService(
|
|||
// installs would each snapshot a base that lacks the other's work, and whoever
|
||||
// wrote the pointer last would silently discard the other install.
|
||||
func (s *TenantSkillService) withConfigLock(
|
||||
ctx context.Context, configID string, fn func(context.Context) error,
|
||||
ctx context.Context, tenantID uint64, configID string, fn func(context.Context) error,
|
||||
) error {
|
||||
key := skillImageLockKey(tenantID, configID)
|
||||
if s.redis == nil {
|
||||
release, err := s.localLocks.lock(ctx, configID)
|
||||
release, err := s.localLocks.lock(ctx, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
return fn(ctx)
|
||||
}
|
||||
key := fmt.Sprintf("weknora-skill-image-lock:%s", configID)
|
||||
return redislock.WithRenewableLock(
|
||||
ctx, s.redis, key, skillImageLockLease, skillImageLockRenew, fn,
|
||||
)
|
||||
}
|
||||
|
||||
func skillImageLockKey(tenantID uint64, configID string) string {
|
||||
return fmt.Sprintf("weknora-skill-image-lock:%d:%s", tenantID, configID)
|
||||
}
|
||||
|
||||
// keyedMutex is the no-Redis fallback for withConfigLock.
|
||||
type keyedMutex struct {
|
||||
mu sync.Mutex
|
||||
|
|
|
|||
|
|
@ -15,6 +15,12 @@ func TestSkillProgressKeyIncludesTheTenant(t *testing.T) {
|
|||
"two workspaces must not share a progress slot because they happened to reuse IDs")
|
||||
}
|
||||
|
||||
func TestSkillImageLockKeyIncludesTheTenant(t *testing.T) {
|
||||
require.Equal(t, "weknora-skill-image-lock:7:cfg-1", skillImageLockKey(7, "cfg-1"))
|
||||
require.NotEqual(t, skillImageLockKey(7, "cfg-1"), skillImageLockKey(8, "cfg-1"),
|
||||
"two workspaces must not share an image lock because they happened to reuse config IDs")
|
||||
}
|
||||
|
||||
func TestTenantSkillServiceWithConfigLockLocalRespectsCanceledContext(t *testing.T) {
|
||||
svc := NewTenantSkillService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
entered := make(chan struct{})
|
||||
|
|
@ -22,7 +28,7 @@ func TestTenantSkillServiceWithConfigLockLocalRespectsCanceledContext(t *testing
|
|||
holderDone := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
holderDone <- svc.withConfigLock(context.Background(), "config-1", func(context.Context) error {
|
||||
holderDone <- svc.withConfigLock(context.Background(), 7, "config-1", func(context.Context) error {
|
||||
close(entered)
|
||||
<-releaseHolder
|
||||
return nil
|
||||
|
|
@ -36,7 +42,7 @@ func TestTenantSkillServiceWithConfigLockLocalRespectsCanceledContext(t *testing
|
|||
|
||||
waiterDone := make(chan error, 1)
|
||||
go func() {
|
||||
waiterDone <- svc.withConfigLock(ctx, "config-1", func(context.Context) error {
|
||||
waiterDone <- svc.withConfigLock(ctx, 7, "config-1", func(context.Context) error {
|
||||
return errors.New("canceled waiter entered lock")
|
||||
})
|
||||
}()
|
||||
|
|
|
|||
Loading…
Reference in New Issue