PrimeIntellect/SWE-rebench-V2 huggingface dataset:
Repository: nats-io/nats.go (go)

Issue:
Add error value for when a KV key already exists

Pull request:
Add ErrKeyExists on kv.Create
Fix #1134


Patch:
diff --git a/kv.go b/kv.go
index f127e61..defe68c 100644
--- a/kv.go
+++ b/kv.go
@@ -297,6 +297,7 @@ var (
 	ErrKeyDeleted             = errors.New("nats: key was deleted")
 	ErrHistoryToLarge         = errors.New("nats: history limited to a max of 64")
 	ErrNoKeysFound            = errors.New("nats: no keys found")
+	ErrKeyExists              = errors.New("nats: key exists")
 )
 
 const (
@@ -629,6 +630,14 @@ func (kv *kvs) Create(key string, value []byte) (revision uint64, err error) {
 		return kv.Update(key, value, e.Revision())
 	}
 
+	// Check if the expected last subject sequence is not zero which implies
+	// the key already exists.
+	if aerr, ok := err.(*APIError); ok {
+		if aerr.ErrorCode == 10071 {
+			return 0, ErrKeyExists
+		}
+	}
+
 	return 0, err
 }
 


Test patch:
diff --git a/kv_test.go b/kv_test.go
index dd16d84..d2c3863 100644
--- a/kv_test.go
+++ b/kv_test.go
@@ -203,3 +203,26 @@ func TestKeyValueMirrorDirectGet(t *testing.T) {
 		}
 	}
 }
+
+func TestKeyValueCreate(t *testing.T) {
+	s := RunBasicJetStreamServer()
+	defer shutdownJSServerAndRemoveStorage(t, s)
+
+	nc, js := jsClient(t, s)
+	defer nc.Close()
+
+	kv, err := js.CreateKeyValue(&KeyValueConfig{Bucket: "TEST"})
+	if err != nil {
+		t.Fatalf("Error creating kv: %v", err)
+	}
+
+	_, err = kv.Create("key", []byte("1"))
+	if err != nil {
+		t.Fatalf("Error creating key: %v", err)
+	}
+
+	_, err = kv.Create("key", []byte("1"))
+	if err != ErrKeyExists {
+		t.Fatalf("Expected ErrKeyExists, got: %v", err)
+	}
+}