nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: googleapis/python-api-core
Pull request #321 (2021-12-15 16:39:44)

fix: exclude function target from retry deadline exceeded exception message
This is the same as #318 but for the [v1](https://github.com/googleapis/python-api-core/tree/v1) branch.


Patch:
diff --git a/google/api_core/retry.py b/google/api_core/retry.py
index 8496793..313fc63 100644
--- a/google/api_core/retry.py
+++ b/google/api_core/retry.py
@@ -203,8 +203,8 @@ def retry_target(target, predicate, sleep_generator, deadline, on_error=None):
             if deadline_datetime <= now:
                 six.raise_from(
                     exceptions.RetryError(
-                        "Deadline of {:.1f}s exceeded while calling {}".format(
-                            deadline, target
+                        "Deadline of {:.1f}s exceeded while calling target function".format(
+                            deadline
                         ),
                         last_exc,
                     ),
diff --git a/google/api_core/retry_async.py b/google/api_core/retry_async.py
index 2dfa2f6..68a2559 100644
--- a/google/api_core/retry_async.py
+++ b/google/api_core/retry_async.py
@@ -132,8 +132,8 @@ async def retry_target(target, predicate, sleep_generator, deadline, on_error=No
                 # Chains the raising RetryError with the root cause error,
                 # which helps observability and debugability.
                 raise exceptions.RetryError(
-                    "Deadline of {:.1f}s exceeded while calling {}".format(
-                        deadline, target
+                    "Deadline of {:.1f}s exceeded while calling target function".format(
+                        deadline
                     ),
                     last_exc,
                 ) from last_exc


Test patch:
diff --git a/tests/asyncio/test_retry_async.py b/tests/asyncio/test_retry_async.py
index 9e51044..873caaf 100644
--- a/tests/asyncio/test_retry_async.py
+++ b/tests/asyncio/test_retry_async.py
@@ -120,6 +120,10 @@ async def test_retry_target_deadline_exceeded(utcnow, sleep):
     assert exc_info.match("last exception: meep")
     assert target.call_count == 2
 
+    # Ensure the exception message does not include the target fn:
+    # it may be a partial with user data embedded
+    assert str(target) not in exc_info.exconly()
+
 
 @pytest.mark.asyncio
 async def test_retry_target_bad_sleep_generator():
diff --git a/tests/unit/test_retry.py b/tests/unit/test_retry.py
index 199ca55..74c5d77 100644
--- a/tests/unit/test_retry.py
+++ b/tests/unit/test_retry.py
@@ -152,6 +152,10 @@ def test_retry_target_deadline_exceeded(utcnow, sleep):
     assert exc_info.match("last exception: meep")
     assert target.call_count == 2
 
+    # Ensure the exception message does not include the target fn:
+    # it may be a partial with user data embedded
+    assert str(target) not in exc_info.exconly()
+
 
 def test_retry_target_bad_sleep_generator():
     with pytest.raises(ValueError, match="Sleep generator"):
Repository: googleapis/python-api-core
Pull request #638 (2024-04-08 16:02:32)

feat: add google.api_core.version_header
Towards b/330968465


Patch:
diff --git a/google/api_core/version_header.py b/google/api_core/version_header.py
new file mode 100644
index 0000000..cf1972a
--- /dev/null
+++ b/google/api_core/version_header.py
@@ -0,0 +1,29 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+API_VERSION_METADATA_KEY = "x-goog-api-version"
+
+
+def to_api_version_header(version_identifier):
+    """Returns data for the API Version header for the given `version_identifier`.
+
+    Args:
+        version_identifier (str): The version identifier to be used in the
+            tuple returned.
+
+    Returns:
+        Tuple(str, str): A tuple containing the API Version metadata key and
+            value.
+    """
+    return (API_VERSION_METADATA_KEY, version_identifier)


Test patch:
diff --git a/tests/unit/test_version_header.py b/tests/unit/test_version_header.py
new file mode 100644
index 0000000..ea7028e
--- /dev/null
+++ b/tests/unit/test_version_header.py
@@ -0,0 +1,23 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import pytest
+
+from google.api_core import version_header
+
+
+@pytest.mark.parametrize("version_identifier", ["some_value", ""])
+def test_to_api_version_header(version_identifier):
+    value = version_header.to_api_version_header(version_identifier)
+    assert value == (version_header.API_VERSION_METADATA_KEY, version_identifier)
Repository: googleapis/python-api-core
Pull request #770 (2024-12-16 22:23:43)

fix: memory leak in bidi classes
Fixes https://github.com/googleapis/python-api-core/issues/769



Patch:
diff --git a/google/api_core/bidi.py b/google/api_core/bidi.py
index 78d98b9..4e800c8 100644
--- a/google/api_core/bidi.py
+++ b/google/api_core/bidi.py
@@ -306,6 +306,8 @@ class BidiRpc(object):
         self._request_queue.put(None)
         self.call.cancel()
         self._request_generator = None
+        self._initial_request = None
+        self._callbacks = []
         # Don't set self.call to None. Keep it around so that send/recv can
         # raise the error.
 
@@ -717,6 +719,7 @@ class BackgroundConsumer(object):
                     _LOGGER.warning("Background thread did not exit.")
 
             self._thread = None
+            self._on_response = None
 
     @property
     def is_active(self):


Test patch:
diff --git a/tests/unit/test_bidi.py b/tests/unit/test_bidi.py
index c196a68..cca9a21 100644
--- a/tests/unit/test_bidi.py
+++ b/tests/unit/test_bidi.py
@@ -296,6 +296,9 @@ class TestBidiRpc(object):
         # ensure the request queue was signaled to stop.
         assert bidi_rpc.pending_requests == 1
         assert bidi_rpc._request_queue.get() is None
+        # ensure request and callbacks are cleaned up
+        assert bidi_rpc._initial_request is None
+        assert not bidi_rpc._callbacks
 
     def test_close_no_rpc(self):
         bidi_rpc = bidi.BidiRpc(None)
@@ -623,6 +626,8 @@ class TestResumableBidiRpc(object):
         assert bidi_rpc.pending_requests == 1
         assert bidi_rpc._request_queue.get() is None
         assert bidi_rpc._finalized
+        assert bidi_rpc._initial_request is None
+        assert not bidi_rpc._callbacks
 
     def test_reopen_failure_on_rpc_restart(self):
         error1 = ValueError("1")
@@ -777,6 +782,7 @@ class TestBackgroundConsumer(object):
         consumer.stop()
 
         assert consumer.is_active is False
+        assert consumer._on_response is None
 
     def test_wake_on_error(self):
         should_continue = threading.Event()
@@ -884,6 +890,7 @@ class TestBackgroundConsumer(object):
 
         consumer.stop()
         assert consumer.is_active is False
+        assert consumer._on_response is None
 
         # calling stop twice should not result in an error.
         consumer.stop()
Repository: googleapis/python-api-core
Pull request #814 (2025-04-04 22:20:46)

test: fix BackgroundConsumer error log
We https://github.com/googleapis/python-api-core/pull/770 that clears some variables that were causing a memory leak in the bidirectional streaming classes. This change lead to a potential null pointer exception during the shut-down process when the BackgroundConsumer tries to access the removed callback.

The issue would only come up when the background thread failed to finalize within 1 second, and the error would be swallowed internally. But it would result in an error log that should be avoided

This PR does a None check to avoid emitting the error log

Fixes https://github.com/googleapis/python-api-core/issues/788




Patch:
diff --git a/google/api_core/bidi.py b/google/api_core/bidi.py
index 4e800c8..b002b40 100644
--- a/google/api_core/bidi.py
+++ b/google/api_core/bidi.py
@@ -664,7 +664,8 @@ class BackgroundConsumer(object):
                 _LOGGER.debug("waiting for recv.")
                 response = self._bidi_rpc.recv()
                 _LOGGER.debug("recved response.")
-                self._on_response(response)
+                if self._on_response is not None:
+                    self._on_response(response)
 
         except exceptions.GoogleAPICallError as exc:
             _LOGGER.debug(


Test patch:
diff --git a/tests/unit/test_bidi.py b/tests/unit/test_bidi.py
index cca9a21..0e7b018 100644
--- a/tests/unit/test_bidi.py
+++ b/tests/unit/test_bidi.py
@@ -16,6 +16,7 @@ import datetime
 import logging
 import queue
 import threading
+import time
 
 try:
     from unittest import mock
@@ -894,3 +895,26 @@ class TestBackgroundConsumer(object):
 
         # calling stop twice should not result in an error.
         consumer.stop()
+
+    def test_stop_error_logs(self, caplog):
+        """
+        Closing the client should result in no internal error logs
+
+        https://github.com/googleapis/python-api-core/issues/788
+        """
+        caplog.set_level(logging.DEBUG)
+        bidi_rpc = mock.create_autospec(bidi.BidiRpc, instance=True)
+        bidi_rpc.is_active = True
+        on_response = mock.Mock(spec=["__call__"])
+
+        consumer = bidi.BackgroundConsumer(bidi_rpc, on_response)
+
+        consumer.start()
+        consumer.stop()
+        # let the background thread run for a while before exiting
+        time.sleep(0.1)
+        bidi_rpc.is_active = False
+        # running thread should not result in error logs
+        error_logs = [r.message for r in caplog.records if r.levelname == "ERROR"]
+        assert not error_logs, f"Found unexpected ERROR logs: {error_logs}"
+        bidi_rpc.is_active = False
Repository: bazelbuild/bazelisk
Pull request #182 (2020-10-08 16:52:47)

Move runfiles logic into separate package
This is a pure refactoring, which makes it easier for us to use Bazelisk internally.


Patch:
diff --git a/BUILD b/BUILD
index d2ec99c..2555556 100644
--- a/BUILD
+++ b/BUILD
@@ -64,8 +64,8 @@ go_test(
         "//core:go_default_library",
         "//httputil:go_default_library",
         "//repositories:go_default_library",
+        "//runfiles:go_default_library",
         "//versions:go_default_library",
-        "@io_bazel_rules_go//go/tools/bazel:go_default_library",
     ],
 )
 
diff --git a/runfiles/BUILD b/runfiles/BUILD
new file mode 100644
index 0000000..3350920
--- /dev/null
+++ b/runfiles/BUILD
@@ -0,0 +1,13 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+
+go_library(
+    name = "go_default_library",
+    srcs = [
+        "runfiles.go",
+    ],
+    importpath = "github.com/bazelbuild/bazelisk/runfiles",
+    visibility = ["//visibility:public"],
+    deps = [
+        "@io_bazel_rules_go//go/tools/bazel:go_default_library",
+    ],
+)
\ No newline at end of file
diff --git a/runfiles/runfiles.go b/runfiles/runfiles.go
new file mode 100644
index 0000000..82c204c
--- /dev/null
+++ b/runfiles/runfiles.go
@@ -0,0 +1,20 @@
+// Package runfiles offers functionality to read data dependencies of tests.
+package runfiles
+
+import (
+	"io/ioutil"
+
+	"github.com/bazelbuild/rules_go/go/tools/bazel"
+)
+
+func ReadFile(name string) ([]byte, error) {
+	path, err := bazel.Runfile(name)
+	if err != nil {
+		return nil, err
+	}
+	data, err := ioutil.ReadFile(path)
+	if err != nil {
+		return nil, err
+	}
+	return data, nil
+}


Test patch:
diff --git a/bazelisk_test.go b/bazelisk_test.go
index ee9c213..4b70cf7 100644
--- a/bazelisk_test.go
+++ b/bazelisk_test.go
@@ -2,20 +2,15 @@ package main
 
 import (
 	"fmt"
-	"io/ioutil"
 	"sort"
 	"testing"
 
 	"github.com/bazelbuild/bazelisk/core"
-	"github.com/bazelbuild/rules_go/go/tools/bazel"
+	"github.com/bazelbuild/bazelisk/runfiles"
 )
 
 func TestScanIssuesForIncompatibleFlags(t *testing.T) {
-	path, err := bazel.Runfile("sample-issues-migration.json")
-	if err != nil {
-		t.Errorf("Can not load sample github issues")
-	}
-	samplesJSON, err := ioutil.ReadFile(path)
+	samplesJSON, err := runfiles.ReadFile("sample-issues-migration.json")
 	if err != nil {
 		t.Errorf("Can not load sample github issues")
 	}
Repository: bazelbuild/buildtools
Pull request #397 (2018-10-17 13:28:11)

Rename unused-load to load
Although `unused-load` is more informative, there are already existing tools that expect that the category is called `load` and they were broken because of the name has been changed. This commit reverses the change.


Patch:
diff --git a/WARNINGS.md b/WARNINGS.md
index 78d9cbd..6877009 100644
--- a/WARNINGS.md
+++ b/WARNINGS.md
@@ -101,7 +101,7 @@ the line or at the beginning of a rule.
 
 --------------------------------------------------------------------------------
 
-## <a name="unused-load"></a>Loaded symbol is unused
+## <a name="load"></a>Loaded symbol is unused
 
 ### Background
 
diff --git a/warn/warn.go b/warn/warn.go
index c8056c8..bdade1d 100644
--- a/warn/warn.go
+++ b/warn/warn.go
@@ -147,7 +147,7 @@ func unusedLoadWarning(f *build.File, fix bool) []*Finding {
 				// To disable the warning, put a comment that contains '@unused'
 				start, end := to.Span()
 				findings = append(findings,
-					makeFinding(f, start, end, "unused-load",
+					makeFinding(f, start, end, "load",
 						"Loaded symbol \""+to.Name+"\" is unused. Please remove it.\n"+
 							"To disable the warning, add '@unused' in a comment.", true, nil))
 				if fix {
@@ -406,12 +406,12 @@ var FileWarningMap = map[string]func(f *build.File, fix bool) []*Finding{
 	"ctx-actions":        ctxActionsWarning,
 	"duplicated-name":    duplicatedNameWarning,
 	"integer-division":   integerDivisionWarning,
+	"load":        unusedLoadWarning,
 	"no-effect":          noEffectWarning,
 	"package-name":       packageNameWarning,
 	"package-on-top":     packageOnTopWarning,
 	"redefined-variable": redefinedVariableWarning,
 	"repository-name":    repositoryNameWarning,
-	"unused-load":        unusedLoadWarning,
 	"unused-variable":    unusedVariableWarning,
 }
 


Test patch:
diff --git a/warn/warn_test.go b/warn/warn_test.go
index 2d2cc61..6ffa685 100644
--- a/warn/warn_test.go
+++ b/warn/warn_test.go
@@ -188,7 +188,7 @@ php_library(name = "x")`,
 }
 
 func TestWarnUnusedLoad(t *testing.T) {
-	checkFindingsAndFix(t, "unused-load", `
+	checkFindingsAndFix(t, "load", `
 load(":f.bzl", "s1", "s2")
 load("f", "s1")
 foo(name = s1)`, `
@@ -198,7 +198,7 @@ foo(name = s1)`,
 			":2: Symbol \"s1\" has already been loaded."},
 		false)
 
-	checkFindingsAndFix(t, "unused-load", `
+	checkFindingsAndFix(t, "load", `
 load(
   ":f.bzl",
    "s1",
@@ -225,7 +225,7 @@ load(
 		[]string{":3: Loaded symbol \"s1\" is unused."},
 		false)
 
-	checkFindingsAndFix(t, "unused-load", `
+	checkFindingsAndFix(t, "load", `
 load(":f.bzl", "x")
 x = "unused"`, `
 x = "unused"`,
Repository: bazelbuild/buildtools
Pull request #401 (2018-10-26 12:13:16)

A warning a fix for load statements not on top


Patch:
diff --git a/warn/warn.go b/warn/warn.go
index b900aa7..980e3e7 100644
--- a/warn/warn.go
+++ b/warn/warn.go
@@ -258,6 +258,41 @@ func packageOnTopWarning(f *build.File, fix bool) []*Finding {
 	return nil
 }
 
+func loadOnTopWarning(f *build.File, fix bool) []*Finding {
+	findings := []*Finding{}
+	firstStmtIndex := -1 // index of the first seen non-load statement
+	for i := 0; i < len(f.Stmt); i++ {
+		stmt := f.Stmt[i]
+		_, isString := stmt.(*build.StringExpr) // typically a docstring
+		_, isComment := stmt.(*build.CommentBlock)
+		if isString || isComment {
+			continue
+		}
+		if load, ok := stmt.(*build.LoadStmt); ok {
+			if firstStmtIndex != -1 {
+				if fix {
+					stmts := []build.Expr{}
+					stmts = append(stmts, f.Stmt[:firstStmtIndex]...)
+					stmts = append(stmts, load)
+					stmts = append(stmts, f.Stmt[firstStmtIndex:i]...)
+					stmts = append(stmts, f.Stmt[i+1:]...)
+					f.Stmt = stmts
+					firstStmtIndex++
+				} else {
+					start, end := load.Span()
+					findings = append(findings, makeFinding(f, start, end, "load-on-top",
+						"Load statements should be at the top of the file.", true, nil))
+				}
+			}
+		} else {
+			if firstStmtIndex == -1 {
+				firstStmtIndex = i
+			}
+		}
+	}
+	return findings
+}
+
 func integerDivisionWarning(f *build.File, fix bool) []*Finding {
 	findings := []*Finding{}
 	build.Walk(f, func(expr build.Expr, stack []build.Expr) {
@@ -410,6 +445,7 @@ var FileWarningMap = map[string]func(f *build.File, fix bool) []*Finding{
 	"duplicated-name":    duplicatedNameWarning,
 	"integer-division":   integerDivisionWarning,
 	"load":               unusedLoadWarning,
+	"load-on-top":        loadOnTopWarning,
 	"no-effect":          noEffectWarning,
 	"package-name":       packageNameWarning,
 	"package-on-top":     packageOnTopWarning,


Test patch:
diff --git a/warn/warn_test.go b/warn/warn_test.go
index 6ffa685..ce0ae4f 100644
--- a/warn/warn_test.go
+++ b/warn/warn_test.go
@@ -320,6 +320,56 @@ package()`,
 		false)
 }
 
+func TestLoadOnTop(t *testing.T) {
+	checkFindingsAndFix(t, "load-on-top", `
+foo()
+load(":f.bzl", "x")
+x()`, `
+load(":f.bzl", "x")
+
+foo()
+
+x()`,
+		[]string{":2: Load statements should be at the top of the file."},
+		false)
+
+	checkFindingsAndFix(t, "load-on-top", `
+"""Docstring"""
+
+# Comment block
+
+# this is foo
+foo()
+
+# load
+load(":f.bzl", "bar")
+
+# this is bar
+bar()
+
+# another load
+load(":f.bzl", "foobar")`, `
+"""Docstring"""
+
+# Comment block
+
+# load
+load(":f.bzl", "bar")
+
+# another load
+load(":f.bzl", "foobar")
+
+# this is foo
+foo()
+
+# this is bar
+bar()`,
+		[]string{
+			":9: Load statements should be at the top of the file.",
+			":15: Load statements should be at the top of the file.",
+		}, false)
+}
+
 func TestPositionalArguments(t *testing.T) {
 	checkFindings(t, "positional-args", `
 my_macro(foo = "bar")
Repository: metallb/metallb
Pull request #1504 (2022-07-14 17:56:26)

Configmap converter: don't default keepalive time
We don't need to default it during the conversion, as if it's nil the config logic will fill it accordingly.
Moreover, deployments with the native bgp mode will fail.

The result is a CR with `keepaliveTime: 0s`, because of the 0 value of the struct. 
Nonethless, the webhook won't refuse the field and the loading logic will default the internal value to the right default if needed. 

This should address the second part of https://github.com/metallb/metallb/issues/1495, described here https://github.com/metallb/metallb/issues/1495#issuecomment-1179804400


Patch:
diff --git a/configmaptocrs/main.go b/configmaptocrs/main.go
index d8567cd0..e37165fb 100644
--- a/configmaptocrs/main.go
+++ b/configmaptocrs/main.go
@@ -240,10 +240,6 @@ func parsePeer(p peer) (*v1beta2.BGPPeer, error) {
 	if err != nil {
 		return nil, err
 	}
-	keepaliveTime, err := parseKeepaliveTime(holdTime, p.KeepaliveTime)
-	if err != nil {
-		return nil, err
-	}
 
 	nodeSels := make([]metav1.LabelSelector, 0)
 	for _, sel := range p.NodeSelectors {
@@ -251,7 +247,7 @@ func parsePeer(p peer) (*v1beta2.BGPPeer, error) {
 		nodeSels = append(nodeSels, s)
 	}
 
-	return &v1beta2.BGPPeer{
+	res := &v1beta2.BGPPeer{
 		ObjectMeta: metav1.ObjectMeta{
 			Namespace: resourcesNameSpace,
 		},
@@ -262,14 +258,22 @@ func parsePeer(p peer) (*v1beta2.BGPPeer, error) {
 			SrcAddress:    p.SrcAddr,
 			Port:          p.Port,
 			HoldTime:      metav1.Duration{Duration: holdTime},
-			KeepaliveTime: metav1.Duration{Duration: keepaliveTime},
 			RouterID:      p.RouterID,
 			NodeSelectors: nodeSels,
 			Password:      p.Password,
 			BFDProfile:    p.BFDProfile,
 			EBGPMultiHop:  p.EBGPMultiHop,
 		},
-	}, nil
+	}
+	if p.KeepaliveTime != "" {
+		keepaliveTime, err := parseKeepaliveTime(holdTime, p.KeepaliveTime)
+		if err != nil {
+			return nil, err
+		}
+		res.Spec.KeepaliveTime = metav1.Duration{Duration: keepaliveTime}
+	}
+
+	return res, nil
 }
 
 func parseNodeSelector(sel nodeSelector) metav1.LabelSelector {
@@ -307,10 +311,6 @@ func parseHoldTime(ht string) (time.Duration, error) {
 }
 
 func parseKeepaliveTime(ht time.Duration, ka string) (time.Duration, error) {
-	// If keepalive time not set lets use 1/3 of holdtime.
-	if ka == "" {
-		return ht / 3, nil
-	}
 	d, err := time.ParseDuration(ka)
 	if err != nil {
 		return 0, fmt.Errorf("invalid keepalive time %q: %s", ka, err)


Test patch:
diff --git a/configmaptocrs/testdata/config.golden b/configmaptocrs/testdata/config.golden
index cd6134de..1bcabd2c 100644
--- a/configmaptocrs/testdata/config.golden
+++ b/configmaptocrs/testdata/config.golden
@@ -7,7 +7,7 @@ metadata:
   namespace: metallb-system
 spec:
   holdTime: 1m30s
-  keepaliveTime: 30s
+  keepaliveTime: 0s
   myASN: 64512
   passwordSecret: {}
   peerASN: 64512
@@ -22,7 +22,7 @@ metadata:
   namespace: metallb-system
 spec:
   holdTime: 1m30s
-  keepaliveTime: 30s
+  keepaliveTime: 0s
   myASN: 64512
   passwordSecret: {}
   peerASN: 64512