{"record":{"id":"e1c70516b5ea53e2","repo":"TencentCloud/TencentDB-Agent-Memory","slug":"duplicate-user-key","errorCode":"duplicate_user_key","errorMessage":"user_key already exists","messagePattern":"user_key already exists","errorType":"error_code","errorClass":"MetadataError","httpStatus":null,"severity":"error","filePath":"MemoryCore/src/metadata/service/metadata-service.ts","lineNumber":447,"sourceCode":"    return this.createUserWithType(input, \"normal\");\n  }\n\n  /**\n   * 仅供 /v3/meta/user/create-with-key 使用：允许 system_admin 在建号时显式指定 user_key。\n   *\n   * 两层去重：\n   *   1. 前置 getUserByKey：正常路径快速失败，不进事务\n   *   2. store 层 UNIQUE 约束（DuplicateUserKeyError）：TOCTOU / 并发兜底\n   *\n   * router 层需先调 assertCanManageUsers 做鉴权。\n   */\n  async createNormalUserWithKey(input: {\n    username: string;\n    user_key: string;\n  }): Promise<CreateUserApiResult> {\n    const existing = await this.store.getUserByKey(input.user_key);\n    if (existing) {\n      throw new MetadataError(\"duplicate_user_key\", \"user_key already exists\");\n    }\n    try {\n      return await this.createUserWithType(\n        { username: input.username, default_key_value: input.user_key },\n        \"normal\",\n      );\n    } catch (err) {\n      if (err instanceof DuplicateUserKeyError) {\n        throw new MetadataError(\"duplicate_user_key\", \"user_key already exists\");\n      }\n      throw err;\n    }\n  }\n\n  /** 未传 auth_provider / external_id 时补默认值（local / user_id）。 */\n  private resolveCreateUserInput(\n    input: CreateUserInput,\n  ): CreateUserInput & { auth_provider: string; external_id: string } {","sourceCodeStart":429,"sourceCodeEnd":465,"githubUrl":"https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/3efcd317b84146d6a08518ac0f7ee7c8a8d200ec/MemoryCore/src/metadata/service/metadata-service.ts#L429-L465","documentation":"MetadataError code 'duplicate_user_key' from createNormalUserWithKey's pre-check: the supplied user_key is already registered (store.getUserByKey returned a hit). The check runs before createUserWithType so the common collision case fails fast without relying on the store-level DuplicateUserKeyError.","triggerScenarios":"Calling createNormalUserWithKey with a user_key string already used by an existing user.","commonSituations":"Client-generated keys colliding across environments (e.g. hard-coded dev keys in prod); retrying a create after a partial failure that actually succeeded; importing users where two rows share a key.","solutions":["Generate a fresh unique user_key and retry","Look up the existing user via the key lookup API and reuse/update that account instead of creating a new one","Add a uniqueness prefix (user id / UUID) to client-supplied keys"],"exampleFix":"// before\nawait svc.createNormalUserWithKey({ username: 'a', user_key: existingKey }); // throws\n// after\nconst key = `user-${crypto.randomUUID()}`;\nawait svc.createNormalUserWithKey({ username: 'a', user_key: key }); // ok","handlingStrategy":"validation","validationCode":"const existing = await store.getUserByKey(userKey);\nif (existing) throw new Error(`user_key ${userKey} already taken`);","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Generate user keys server-side with UUIDs instead of client-supplied values","Check key availability in the UI/API before submit","Treat duplicate_user_key as 'account exists' in signup flows"],"tags":["duplicate","user-key","uniqueness"],"backgroundTag":"duplicate-key","analyzedSha":"3efcd317b84146d6a08518ac0f7ee7c8a8d200ec","analyzedAt":"2026-09-01T05:44:22.276Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T10:18:20.063Z"}