{"record":{"id":"b2131730a960b7cd","repo":"TencentCloud/TencentDB-Agent-Memory","slug":"last-system-admin","errorCode":"last_system_admin","errorMessage":"cannot delete the last system_admin user","messagePattern":"cannot delete the last system_admin user","errorType":"error_code","errorClass":"MetadataError","httpStatus":null,"severity":"error","filePath":"MemoryCore/src/metadata/service/metadata-service.ts","lineNumber":526,"sourceCode":"    return this.store.getUserByKey(userKey);\n  }\n\n  async getUserByExternalId(authProvider: string, externalId: string): Promise<UserEntity | null> {\n    return this.store.getUserByExternalId(authProvider, externalId);\n  }\n\n  async deleteUsersForCaller(userIds: string[], ctx: V3AuthContext): Promise<BatchDeleteResult> {\n    if (!canManageUsers(ctx)) {\n      throw new MetadataError(\"permission_denied\", \"user management requires system admin\");\n    }\n    let deletingSystemAdmins = 0;\n    for (const id of userIds) {\n      const u = await this.getUserById(id);\n      if (u && isSystemAdminUser(u)) deletingSystemAdmins++;\n    }\n    const totalAdmins = await this.store.countSystemAdmins();\n    if (totalAdmins > 0 && totalAdmins - deletingSystemAdmins < 1) {\n      throw new MetadataError(\"last_system_admin\", \"cannot delete the last system_admin user\");\n    }\n    return this.deleteUsers(userIds);\n  }\n\n  async deleteUsers(userIds: string[]): Promise<BatchDeleteResult> {\n    return this.store.deleteUsers(userIds);\n  }\n\n  async listUsersForCaller(\n    input: { team_id?: string } & UserListFilter,\n    ctx: V3AuthContext,\n    pagination: PaginationParams,\n  ): Promise<PaginatedResult<UserPublic>> {\n    const filtersPresent = !!(input.user_ids?.length || input.username);\n    const storeFilter = this.buildUserListStoreFilter(input);\n\n    if (!input.team_id) {\n      if (!ctx.isSystemAdmin) {","sourceCodeStart":508,"sourceCodeEnd":544,"githubUrl":"https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/3efcd317b84146d6a08518ac0f7ee7c8a8d200ec/MemoryCore/src/metadata/service/metadata-service.ts#L508-L544","documentation":"MetadataError 'last_system_admin' from deleteUsersForCaller: the batch would delete every remaining system_admin, leaving the system without admin governance. The service counts admins (countSystemAdmins) and refuses when totalAdmins - deletingSystemAdmins < 1.","triggerScenarios":"Calling deleteUsersForCaller with a batch that includes the only existing system_admin (e.g. ['admin-id']), or a batch whose admin deletions exhaust the admin pool.","commonSituations":"Cleanup scripts bulk-deleting stale accounts that include the bootstrap admin; deleting 'test' users where the bootstrap admin was actually in use; multi-tenant scripts iterating all user ids.","solutions":["Remove the system_admin id(s) from the deletion batch and keep at least one admin","Promote another user to system_admin first, then delete the original","Filter the batch: skip ids where isSystemAdminUser(u) is true when totalAdmins === 1"],"exampleFix":"// before\nawait svc.deleteUsersForCaller([adminId, u1, u2], ctx); // throws last_system_admin\n// after\nconst deletable = [u1, u2]; // exclude the last system_admin\nawait svc.deleteUsersForCaller(deletable, ctx);","handlingStrategy":"validation","validationCode":"const totalAdmins = await store.countSystemAdmins();\nconst adminDeletes = 0;\nfor (const id of userIds) {\n  const u = await svc.getUserById(id);\n  if (u && isSystemAdminUser(u)) adminDeletes++;\n}\nif (totalAdmins > 0 && totalAdmins - adminDeletes < 1) {\n  throw new Error('batch would remove the last system_admin');\n}","typeGuard":"function isDeletable(u: UserEntity | null, remainingAdmins: number): boolean {\n  return !(u && isSystemAdminUser(u) && remainingAdmins - 1 < 1);\n}","tryCatchPattern":"try {\n  await svc.deleteUsersForCaller(ids, ctx);\n} catch (e) {\n  if (e instanceof MetadataError && e.code === 'last_system_admin') {\n    // retry excluding admin ids\n  } else throw e;\n}","preventionTips":["Always exclude the last system_admin from bulk delete batches","Promote a replacement admin before removing an admin account","Audit cleanup scripts so bootstrap admin ids are never included"],"tags":["system-admin","guard","deletion"],"backgroundTag":"last-admin-delete-blocked","analyzedSha":"3efcd317b84146d6a08518ac0f7ee7c8a8d200ec","analyzedAt":"2026-09-01T05:44:22.276Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T15:18:49.778Z"}