TencentCloud/TencentDB-Agent-Memory · error · MetadataError

duplicate_user_key

duplicate_user_key

Error message

user_key already exists

What it means

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.

Source

Thrown at MemoryCore/src/metadata/service/metadata-service.ts:447

    return this.createUserWithType(input, "normal");
  }

  /**
   * 仅供 /v3/meta/user/create-with-key 使用:允许 system_admin 在建号时显式指定 user_key。
   *
   * 两层去重:
   *   1. 前置 getUserByKey:正常路径快速失败,不进事务
   *   2. store 层 UNIQUE 约束(DuplicateUserKeyError):TOCTOU / 并发兜底
   *
   * router 层需先调 assertCanManageUsers 做鉴权。
   */
  async createNormalUserWithKey(input: {
    username: string;
    user_key: string;
  }): Promise<CreateUserApiResult> {
    const existing = await this.store.getUserByKey(input.user_key);
    if (existing) {
      throw new MetadataError("duplicate_user_key", "user_key already exists");
    }
    try {
      return await this.createUserWithType(
        { username: input.username, default_key_value: input.user_key },
        "normal",
      );
    } catch (err) {
      if (err instanceof DuplicateUserKeyError) {
        throw new MetadataError("duplicate_user_key", "user_key already exists");
      }
      throw err;
    }
  }

  /** 未传 auth_provider / external_id 时补默认值(local / user_id)。 */
  private resolveCreateUserInput(
    input: CreateUserInput,
  ): CreateUserInput & { auth_provider: string; external_id: string } {

View on GitHub (pinned to 3efcd317b8)

Solutions

  1. Generate a fresh unique user_key and retry
  2. Look up the existing user via the key lookup API and reuse/update that account instead of creating a new one
  3. Add a uniqueness prefix (user id / UUID) to client-supplied keys

Example fix

// before
await svc.createNormalUserWithKey({ username: 'a', user_key: existingKey }); // throws
// after
const key = `user-${crypto.randomUUID()}`;
await svc.createNormalUserWithKey({ username: 'a', user_key: key }); // ok
Defensive patterns

Strategy: validation

Validate before calling

const existing = await store.getUserByKey(userKey);
if (existing) throw new Error(`user_key ${userKey} already taken`);

Prevention

When it happens

Trigger: Calling createNormalUserWithKey with a user_key string already used by an existing user.

Common situations: 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.

Related errors


AI-assisted analysis of TencentCloud/TencentDB-Agent-Memory@3efcd317b8 (2026-09-01). Data as JSON: /api/errors/e1c70516b5ea53e2. Report an issue: GitHub.